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.

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