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.

383 lines
11 KiB

10 years ago
10 years ago
7 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-wire"
  8. cmn "github.com/tendermint/tmlibs/common"
  9. "github.com/tendermint/tmlibs/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 .GetProposer() 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. type ValidatorSet struct {
  22. // NOTE: persisted via reflect, must be exported.
  23. Validators []*Validator `json:"validators"`
  24. Proposer *Validator `json:"proposer"`
  25. // cached (unexported)
  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. vs := &ValidatorSet{
  35. Validators: validators,
  36. }
  37. if vals != nil {
  38. vs.IncrementAccum(1)
  39. }
  40. return vs
  41. }
  42. // incrementAccum and update the proposer
  43. // TODO: mind the overflow when times and votingPower shares too large.
  44. func (valSet *ValidatorSet) IncrementAccum(times int) {
  45. // Add VotingPower * times to each validator and order into heap.
  46. validatorsHeap := cmn.NewHeap()
  47. for _, val := range valSet.Validators {
  48. val.Accum += int64(val.VotingPower) * int64(times) // TODO: mind overflow
  49. validatorsHeap.Push(val, accumComparable{val})
  50. }
  51. // Decrement the validator with most accum times times
  52. for i := 0; i < times; i++ {
  53. mostest := validatorsHeap.Peek().(*Validator)
  54. if i == times-1 {
  55. valSet.Proposer = mostest
  56. }
  57. mostest.Accum -= int64(valSet.TotalVotingPower())
  58. validatorsHeap.Update(mostest, accumComparable{mostest})
  59. }
  60. }
  61. func (valSet *ValidatorSet) Copy() *ValidatorSet {
  62. validators := make([]*Validator, len(valSet.Validators))
  63. for i, val := range valSet.Validators {
  64. // NOTE: must copy, since IncrementAccum updates in place.
  65. validators[i] = val.Copy()
  66. }
  67. return &ValidatorSet{
  68. Validators: validators,
  69. Proposer: valSet.Proposer,
  70. totalVotingPower: valSet.totalVotingPower,
  71. }
  72. }
  73. func (valSet *ValidatorSet) HasAddress(address []byte) bool {
  74. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  75. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  76. })
  77. return idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address)
  78. }
  79. func (valSet *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator) {
  80. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  81. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  82. })
  83. if idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address) {
  84. return idx, valSet.Validators[idx].Copy()
  85. } else {
  86. return 0, nil
  87. }
  88. }
  89. func (valSet *ValidatorSet) GetByIndex(index int) (address []byte, val *Validator) {
  90. val = valSet.Validators[index]
  91. return val.Address, val.Copy()
  92. }
  93. func (valSet *ValidatorSet) Size() int {
  94. return len(valSet.Validators)
  95. }
  96. func (valSet *ValidatorSet) TotalVotingPower() int64 {
  97. if valSet.totalVotingPower == 0 {
  98. for _, val := range valSet.Validators {
  99. valSet.totalVotingPower += val.VotingPower
  100. }
  101. }
  102. return valSet.totalVotingPower
  103. }
  104. func (valSet *ValidatorSet) GetProposer() (proposer *Validator) {
  105. if len(valSet.Validators) == 0 {
  106. return nil
  107. }
  108. if valSet.Proposer == nil {
  109. valSet.Proposer = valSet.findProposer()
  110. }
  111. return valSet.Proposer.Copy()
  112. }
  113. func (valSet *ValidatorSet) findProposer() *Validator {
  114. var proposer *Validator
  115. for _, val := range valSet.Validators {
  116. if proposer == nil || !bytes.Equal(val.Address, proposer.Address) {
  117. proposer = proposer.CompareAccum(val)
  118. }
  119. }
  120. return proposer
  121. }
  122. func (valSet *ValidatorSet) Hash() []byte {
  123. if len(valSet.Validators) == 0 {
  124. return nil
  125. }
  126. hashables := make([]merkle.Hashable, len(valSet.Validators))
  127. for i, val := range valSet.Validators {
  128. hashables[i] = val
  129. }
  130. return merkle.SimpleHashFromHashables(hashables)
  131. }
  132. func (valSet *ValidatorSet) Add(val *Validator) (added bool) {
  133. val = val.Copy()
  134. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  135. return bytes.Compare(val.Address, valSet.Validators[i].Address) <= 0
  136. })
  137. if idx == len(valSet.Validators) {
  138. valSet.Validators = append(valSet.Validators, val)
  139. // Invalidate cache
  140. valSet.Proposer = nil
  141. valSet.totalVotingPower = 0
  142. return true
  143. } else if bytes.Equal(valSet.Validators[idx].Address, val.Address) {
  144. return false
  145. } else {
  146. newValidators := make([]*Validator, len(valSet.Validators)+1)
  147. copy(newValidators[:idx], valSet.Validators[:idx])
  148. newValidators[idx] = val
  149. copy(newValidators[idx+1:], valSet.Validators[idx:])
  150. valSet.Validators = newValidators
  151. // Invalidate cache
  152. valSet.Proposer = nil
  153. valSet.totalVotingPower = 0
  154. return true
  155. }
  156. }
  157. func (valSet *ValidatorSet) Update(val *Validator) (updated bool) {
  158. index, sameVal := valSet.GetByAddress(val.Address)
  159. if sameVal == nil {
  160. return false
  161. } else {
  162. valSet.Validators[index] = val.Copy()
  163. // Invalidate cache
  164. valSet.Proposer = nil
  165. valSet.totalVotingPower = 0
  166. return true
  167. }
  168. }
  169. func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) {
  170. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  171. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  172. })
  173. if idx == len(valSet.Validators) || !bytes.Equal(valSet.Validators[idx].Address, address) {
  174. return nil, false
  175. } else {
  176. removedVal := valSet.Validators[idx]
  177. newValidators := valSet.Validators[:idx]
  178. if idx+1 < len(valSet.Validators) {
  179. newValidators = append(newValidators, valSet.Validators[idx+1:]...)
  180. }
  181. valSet.Validators = newValidators
  182. // Invalidate cache
  183. valSet.Proposer = nil
  184. valSet.totalVotingPower = 0
  185. return removedVal, true
  186. }
  187. }
  188. func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
  189. for i, val := range valSet.Validators {
  190. stop := fn(i, val.Copy())
  191. if stop {
  192. break
  193. }
  194. }
  195. }
  196. // Verify that +2/3 of the set had signed the given signBytes
  197. func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height int, commit *Commit) error {
  198. if valSet.Size() != len(commit.Precommits) {
  199. return fmt.Errorf("Invalid commit -- wrong set size: %v vs %v", valSet.Size(), len(commit.Precommits))
  200. }
  201. if height != commit.Height() {
  202. return fmt.Errorf("Invalid commit -- wrong height: %v vs %v", height, commit.Height())
  203. }
  204. talliedVotingPower := int64(0)
  205. round := commit.Round()
  206. for idx, precommit := range commit.Precommits {
  207. // may be nil if validator skipped.
  208. if precommit == nil {
  209. continue
  210. }
  211. if precommit.Height != height {
  212. return fmt.Errorf("Invalid commit -- wrong height: %v vs %v", height, precommit.Height)
  213. }
  214. if precommit.Round != round {
  215. return fmt.Errorf("Invalid commit -- wrong round: %v vs %v", round, precommit.Round)
  216. }
  217. if precommit.Type != VoteTypePrecommit {
  218. return fmt.Errorf("Invalid commit -- not precommit @ index %v", idx)
  219. }
  220. _, val := valSet.GetByIndex(idx)
  221. // Validate signature
  222. precommitSignBytes := SignBytes(chainID, precommit)
  223. if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
  224. return fmt.Errorf("Invalid commit -- invalid signature: %v", precommit)
  225. }
  226. if !blockID.Equals(precommit.BlockID) {
  227. continue // Not an error, but doesn't count
  228. }
  229. // Good precommit!
  230. talliedVotingPower += val.VotingPower
  231. }
  232. if talliedVotingPower > valSet.TotalVotingPower()*2/3 {
  233. return nil
  234. } else {
  235. return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
  236. talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
  237. }
  238. }
  239. // Verify that +2/3 of this set had signed the given signBytes.
  240. // Unlike VerifyCommit(), this function can verify commits with differeent sets.
  241. func (valSet *ValidatorSet) VerifyCommitAny(chainID string, blockID BlockID, height int, commit *Commit) error {
  242. panic("Not yet implemented")
  243. /*
  244. Start like:
  245. FOR_LOOP:
  246. for _, val := range vals {
  247. if len(precommits) == 0 {
  248. break FOR_LOOP
  249. }
  250. next := precommits[0]
  251. switch bytes.Compare(val.Address(), next.ValidatorAddress) {
  252. case -1:
  253. continue FOR_LOOP
  254. case 0:
  255. signBytes := tm.SignBytes(next)
  256. ...
  257. case 1:
  258. ... // error?
  259. }
  260. }
  261. */
  262. }
  263. func (valSet *ValidatorSet) ToBytes() []byte {
  264. buf, n, err := new(bytes.Buffer), new(int), new(error)
  265. wire.WriteBinary(valSet, buf, n, err)
  266. if *err != nil {
  267. cmn.PanicCrisis(*err)
  268. }
  269. return buf.Bytes()
  270. }
  271. func (valSet *ValidatorSet) FromBytes(b []byte) {
  272. r, n, err := bytes.NewReader(b), new(int), new(error)
  273. wire.ReadBinary(valSet, r, 0, n, err)
  274. if *err != nil {
  275. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  276. cmn.PanicCrisis(*err)
  277. }
  278. }
  279. func (valSet *ValidatorSet) String() string {
  280. return valSet.StringIndented("")
  281. }
  282. func (valSet *ValidatorSet) StringIndented(indent string) string {
  283. if valSet == nil {
  284. return "nil-ValidatorSet"
  285. }
  286. valStrings := []string{}
  287. valSet.Iterate(func(index int, val *Validator) bool {
  288. valStrings = append(valStrings, val.String())
  289. return false
  290. })
  291. return fmt.Sprintf(`ValidatorSet{
  292. %s Proposer: %v
  293. %s Validators:
  294. %s %v
  295. %s}`,
  296. indent, valSet.GetProposer().String(),
  297. indent,
  298. indent, strings.Join(valStrings, "\n"+indent+" "),
  299. indent)
  300. }
  301. //-------------------------------------
  302. // Implements sort for sorting validators by address.
  303. type ValidatorsByAddress []*Validator
  304. func (vs ValidatorsByAddress) Len() int {
  305. return len(vs)
  306. }
  307. func (vs ValidatorsByAddress) Less(i, j int) bool {
  308. return bytes.Compare(vs[i].Address, vs[j].Address) == -1
  309. }
  310. func (vs ValidatorsByAddress) Swap(i, j int) {
  311. it := vs[i]
  312. vs[i] = vs[j]
  313. vs[j] = it
  314. }
  315. //-------------------------------------
  316. // Use with Heap for sorting validators by accum
  317. type accumComparable struct {
  318. *Validator
  319. }
  320. // We want to find the validator with the greatest accum.
  321. func (ac accumComparable) Less(o interface{}) bool {
  322. other := o.(accumComparable).Validator
  323. larger := ac.CompareAccum(other)
  324. return bytes.Equal(larger.Address, ac.Address)
  325. }
  326. //----------------------------------------
  327. // For testing
  328. // NOTE: PrivValidator are in order.
  329. func RandValidatorSet(numValidators int, votingPower int64) (*ValidatorSet, []*PrivValidator) {
  330. vals := make([]*Validator, numValidators)
  331. privValidators := make([]*PrivValidator, numValidators)
  332. for i := 0; i < numValidators; i++ {
  333. val, privValidator := RandValidator(false, votingPower)
  334. vals[i] = val
  335. privValidators[i] = privValidator
  336. }
  337. valSet := NewValidatorSet(vals)
  338. sort.Sort(PrivValidatorsByAddress(privValidators))
  339. return valSet, privValidators
  340. }