You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

307 lines
8.8 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "github.com/tendermint/tendermint/account"
  8. . "github.com/tendermint/tendermint/common"
  9. "github.com/tendermint/tendermint/merkle"
  10. )
  11. // ValidatorSet represent a set of *Validator at a given height.
  12. // The validators can be fetched by address or index.
  13. // The index is in order of .Address, so the indices are fixed
  14. // for all rounds of a given blockchain height.
  15. // On the other hand, the .AccumPower of each validator and
  16. // the designated .Proposer() of a set changes every round,
  17. // upon calling .IncrementAccum().
  18. // NOTE: Not goroutine-safe.
  19. // NOTE: All get/set to validators should copy the value for safety.
  20. // TODO: consider validator Accum overflow
  21. // TODO: replace validators []*Validator with github.com/jaekwon/go-ibbs?
  22. type ValidatorSet struct {
  23. Validators []*Validator // NOTE: persisted via reflect, must be exported.
  24. // cached (unexported)
  25. proposer *Validator
  26. totalVotingPower int64
  27. }
  28. func NewValidatorSet(vals []*Validator) *ValidatorSet {
  29. validators := make([]*Validator, len(vals))
  30. for i, val := range vals {
  31. validators[i] = val.Copy()
  32. }
  33. sort.Sort(ValidatorsByAddress(validators))
  34. return &ValidatorSet{
  35. Validators: validators,
  36. }
  37. }
  38. // TODO: mind the overflow when times and votingPower shares too large.
  39. func (valSet *ValidatorSet) IncrementAccum(times int) {
  40. // Add VotingPower * times to each validator and order into heap.
  41. validatorsHeap := NewHeap()
  42. for _, val := range valSet.Validators {
  43. val.Accum += int64(val.VotingPower) * int64(times) // TODO: mind overflow
  44. validatorsHeap.Push(val, accumComparable(val.Accum))
  45. }
  46. // Decrement the validator with most accum, times times.
  47. for i := 0; i < times; i++ {
  48. mostest := validatorsHeap.Peek().(*Validator)
  49. if i == times-1 {
  50. valSet.proposer = mostest
  51. }
  52. mostest.Accum -= int64(valSet.TotalVotingPower())
  53. validatorsHeap.Update(mostest, accumComparable(mostest.Accum))
  54. }
  55. }
  56. func (valSet *ValidatorSet) Copy() *ValidatorSet {
  57. validators := make([]*Validator, len(valSet.Validators))
  58. for i, val := range valSet.Validators {
  59. // NOTE: must copy, since IncrementAccum updates in place.
  60. validators[i] = val.Copy()
  61. }
  62. return &ValidatorSet{
  63. Validators: validators,
  64. proposer: valSet.proposer,
  65. totalVotingPower: valSet.totalVotingPower,
  66. }
  67. }
  68. func (valSet *ValidatorSet) HasAddress(address []byte) bool {
  69. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  70. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  71. })
  72. return idx != len(valSet.Validators) && bytes.Compare(valSet.Validators[idx].Address, address) == 0
  73. }
  74. func (valSet *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator) {
  75. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  76. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  77. })
  78. if idx != len(valSet.Validators) && bytes.Compare(valSet.Validators[idx].Address, address) == 0 {
  79. return idx, valSet.Validators[idx].Copy()
  80. } else {
  81. return 0, nil
  82. }
  83. }
  84. func (valSet *ValidatorSet) GetByIndex(index int) (address []byte, val *Validator) {
  85. val = valSet.Validators[index]
  86. return val.Address, val.Copy()
  87. }
  88. func (valSet *ValidatorSet) Size() int {
  89. return len(valSet.Validators)
  90. }
  91. func (valSet *ValidatorSet) TotalVotingPower() int64 {
  92. if valSet.totalVotingPower == 0 {
  93. for _, val := range valSet.Validators {
  94. valSet.totalVotingPower += val.VotingPower
  95. }
  96. }
  97. return valSet.totalVotingPower
  98. }
  99. func (valSet *ValidatorSet) Proposer() (proposer *Validator) {
  100. if len(valSet.Validators) == 0 {
  101. return nil
  102. }
  103. if valSet.proposer == nil {
  104. for _, val := range valSet.Validators {
  105. valSet.proposer = valSet.proposer.CompareAccum(val)
  106. }
  107. }
  108. return valSet.proposer.Copy()
  109. }
  110. func (valSet *ValidatorSet) Hash() []byte {
  111. if len(valSet.Validators) == 0 {
  112. return nil
  113. }
  114. hashables := make([]merkle.Hashable, len(valSet.Validators))
  115. for i, val := range valSet.Validators {
  116. hashables[i] = val
  117. }
  118. return merkle.SimpleHashFromHashables(hashables)
  119. }
  120. func (valSet *ValidatorSet) Add(val *Validator) (added bool) {
  121. val = val.Copy()
  122. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  123. return bytes.Compare(val.Address, valSet.Validators[i].Address) <= 0
  124. })
  125. if idx == len(valSet.Validators) {
  126. valSet.Validators = append(valSet.Validators, val)
  127. // Invalidate cache
  128. valSet.proposer = nil
  129. valSet.totalVotingPower = 0
  130. return true
  131. } else if bytes.Compare(valSet.Validators[idx].Address, val.Address) == 0 {
  132. return false
  133. } else {
  134. newValidators := make([]*Validator, len(valSet.Validators)+1)
  135. copy(newValidators[:idx], valSet.Validators[:idx])
  136. newValidators[idx] = val
  137. copy(newValidators[idx+1:], valSet.Validators[idx:])
  138. valSet.Validators = newValidators
  139. // Invalidate cache
  140. valSet.proposer = nil
  141. valSet.totalVotingPower = 0
  142. return true
  143. }
  144. }
  145. func (valSet *ValidatorSet) Update(val *Validator) (updated bool) {
  146. index, sameVal := valSet.GetByAddress(val.Address)
  147. if sameVal == nil {
  148. return false
  149. } else {
  150. valSet.Validators[index] = val.Copy()
  151. // Invalidate cache
  152. valSet.proposer = nil
  153. valSet.totalVotingPower = 0
  154. return true
  155. }
  156. }
  157. func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) {
  158. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  159. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  160. })
  161. if idx == len(valSet.Validators) || bytes.Compare(valSet.Validators[idx].Address, address) != 0 {
  162. return nil, false
  163. } else {
  164. removedVal := valSet.Validators[idx]
  165. newValidators := valSet.Validators[:idx]
  166. if idx+1 < len(valSet.Validators) {
  167. newValidators = append(newValidators, valSet.Validators[idx+1:]...)
  168. }
  169. valSet.Validators = newValidators
  170. // Invalidate cache
  171. valSet.proposer = nil
  172. valSet.totalVotingPower = 0
  173. return removedVal, true
  174. }
  175. }
  176. func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
  177. for i, val := range valSet.Validators {
  178. stop := fn(i, val.Copy())
  179. if stop {
  180. break
  181. }
  182. }
  183. }
  184. // Verify that +2/3 of the set had signed the given signBytes
  185. func (valSet *ValidatorSet) VerifyValidation(chainID string,
  186. hash []byte, parts PartSetHeader, height int, v *Validation) error {
  187. if valSet.Size() != len(v.Precommits) {
  188. return fmt.Errorf("Invalid validation -- wrong set size: %v vs %v", valSet.Size(), len(v.Precommits))
  189. }
  190. if height != v.Height() {
  191. return fmt.Errorf("Invalid validation -- wrong height: %v vs %v", height, v.Height())
  192. }
  193. talliedVotingPower := int64(0)
  194. round := v.Round()
  195. for idx, precommit := range v.Precommits {
  196. // may be nil if validator skipped.
  197. if precommit == nil {
  198. continue
  199. }
  200. if precommit.Height != height {
  201. return fmt.Errorf("Invalid validation -- wrong height: %v vs %v", height, precommit.Height)
  202. }
  203. if precommit.Round != round {
  204. return fmt.Errorf("Invalid validation -- wrong round: %v vs %v", round, precommit.Round)
  205. }
  206. if precommit.Type != VoteTypePrecommit {
  207. return fmt.Errorf("Invalid validation -- not precommit @ index %v", idx)
  208. }
  209. _, val := valSet.GetByIndex(idx)
  210. // Validate signature
  211. precommitSignBytes := account.SignBytes(chainID, precommit)
  212. if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
  213. return fmt.Errorf("Invalid validation -- invalid signature: %v", precommit)
  214. }
  215. if !bytes.Equal(precommit.BlockHash, hash) {
  216. continue // Not an error, but doesn't count
  217. }
  218. if !parts.Equals(precommit.BlockPartsHeader) {
  219. continue // Not an error, but doesn't count
  220. }
  221. // Good precommit!
  222. talliedVotingPower += val.VotingPower
  223. }
  224. if talliedVotingPower > valSet.TotalVotingPower()*2/3 {
  225. return nil
  226. } else {
  227. return fmt.Errorf("Invalid validation -- insufficient voting power: got %v, needed %v",
  228. talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
  229. }
  230. }
  231. func (valSet *ValidatorSet) String() string {
  232. return valSet.StringIndented("")
  233. }
  234. func (valSet *ValidatorSet) StringIndented(indent string) string {
  235. if valSet == nil {
  236. return "nil-ValidatorSet"
  237. }
  238. valStrings := []string{}
  239. valSet.Iterate(func(index int, val *Validator) bool {
  240. valStrings = append(valStrings, val.String())
  241. return false
  242. })
  243. return fmt.Sprintf(`ValidatorSet{
  244. %s Proposer: %v
  245. %s Validators:
  246. %s %v
  247. %s}`,
  248. indent, valSet.Proposer().String(),
  249. indent,
  250. indent, strings.Join(valStrings, "\n"+indent+" "),
  251. indent)
  252. }
  253. //-------------------------------------
  254. // Implements sort for sorting validators by address.
  255. type ValidatorsByAddress []*Validator
  256. func (vs ValidatorsByAddress) Len() int {
  257. return len(vs)
  258. }
  259. func (vs ValidatorsByAddress) Less(i, j int) bool {
  260. return bytes.Compare(vs[i].Address, vs[j].Address) == -1
  261. }
  262. func (vs ValidatorsByAddress) Swap(i, j int) {
  263. it := vs[i]
  264. vs[i] = vs[j]
  265. vs[j] = it
  266. }
  267. //-------------------------------------
  268. // Use with Heap for sorting validators by accum
  269. type accumComparable int64
  270. // We want to find the validator with the greatest accum.
  271. func (ac accumComparable) Less(o interface{}) bool {
  272. return int64(ac) > int64(o.(accumComparable))
  273. }