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.

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