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.

543 lines
16 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
6 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
6 years ago
6 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
7 years ago
7 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "sort"
  7. "strings"
  8. "github.com/tendermint/tendermint/crypto/merkle"
  9. cmn "github.com/tendermint/tendermint/libs/common"
  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. type ValidatorSet struct {
  21. // NOTE: persisted via reflect, must be exported.
  22. Validators []*Validator `json:"validators"`
  23. Proposer *Validator `json:"proposer"`
  24. // cached (unexported)
  25. totalVotingPower int64
  26. }
  27. func NewValidatorSet(valz []*Validator) *ValidatorSet {
  28. if valz != nil && len(valz) == 0 {
  29. panic("validator set initialization slice cannot be an empty slice (but it can be nil)")
  30. }
  31. validators := make([]*Validator, len(valz))
  32. for i, val := range valz {
  33. validators[i] = val.Copy()
  34. }
  35. sort.Sort(ValidatorsByAddress(validators))
  36. vals := &ValidatorSet{
  37. Validators: validators,
  38. }
  39. if len(valz) > 0 {
  40. vals.IncrementAccum(1)
  41. }
  42. return vals
  43. }
  44. // Nil or empty validator sets are invalid.
  45. func (vals *ValidatorSet) IsNilOrEmpty() bool {
  46. return vals == nil || len(vals.Validators) == 0
  47. }
  48. // Increment Accum and update the proposer on a copy, and return it.
  49. func (vals *ValidatorSet) CopyIncrementAccum(times int) *ValidatorSet {
  50. copy := vals.Copy()
  51. copy.IncrementAccum(times)
  52. return copy
  53. }
  54. // IncrementAccum increments accum of each validator and updates the
  55. // proposer. Panics if validator set is empty.
  56. func (vals *ValidatorSet) IncrementAccum(times int) {
  57. // Add VotingPower * times to each validator and order into heap.
  58. validatorsHeap := cmn.NewHeap()
  59. for _, val := range vals.Validators {
  60. // Check for overflow both multiplication and sum.
  61. val.Accum = safeAddClip(val.Accum, safeMulClip(val.VotingPower, int64(times)))
  62. validatorsHeap.PushComparable(val, accumComparable{val})
  63. }
  64. // Decrement the validator with most accum times times.
  65. for i := 0; i < times; i++ {
  66. mostest := validatorsHeap.Peek().(*Validator)
  67. // mind underflow
  68. mostest.Accum = safeSubClip(mostest.Accum, vals.TotalVotingPower())
  69. if i == times-1 {
  70. vals.Proposer = mostest
  71. } else {
  72. validatorsHeap.Update(mostest, accumComparable{mostest})
  73. }
  74. }
  75. }
  76. // Copy each validator into a new ValidatorSet
  77. func (vals *ValidatorSet) Copy() *ValidatorSet {
  78. validators := make([]*Validator, len(vals.Validators))
  79. for i, val := range vals.Validators {
  80. // NOTE: must copy, since IncrementAccum updates in place.
  81. validators[i] = val.Copy()
  82. }
  83. return &ValidatorSet{
  84. Validators: validators,
  85. Proposer: vals.Proposer,
  86. totalVotingPower: vals.totalVotingPower,
  87. }
  88. }
  89. // HasAddress returns true if address given is in the validator set, false -
  90. // otherwise.
  91. func (vals *ValidatorSet) HasAddress(address []byte) bool {
  92. idx := sort.Search(len(vals.Validators), func(i int) bool {
  93. return bytes.Compare(address, vals.Validators[i].Address) <= 0
  94. })
  95. return idx < len(vals.Validators) && bytes.Equal(vals.Validators[idx].Address, address)
  96. }
  97. // GetByAddress returns an index of the validator with address and validator
  98. // itself if found. Otherwise, -1 and nil are returned.
  99. func (vals *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator) {
  100. idx := sort.Search(len(vals.Validators), func(i int) bool {
  101. return bytes.Compare(address, vals.Validators[i].Address) <= 0
  102. })
  103. if idx < len(vals.Validators) && bytes.Equal(vals.Validators[idx].Address, address) {
  104. return idx, vals.Validators[idx].Copy()
  105. }
  106. return -1, nil
  107. }
  108. // GetByIndex returns the validator's address and validator itself by index.
  109. // It returns nil values if index is less than 0 or greater or equal to
  110. // len(ValidatorSet.Validators).
  111. func (vals *ValidatorSet) GetByIndex(index int) (address []byte, val *Validator) {
  112. if index < 0 || index >= len(vals.Validators) {
  113. return nil, nil
  114. }
  115. val = vals.Validators[index]
  116. return val.Address, val.Copy()
  117. }
  118. // Size returns the length of the validator set.
  119. func (vals *ValidatorSet) Size() int {
  120. return len(vals.Validators)
  121. }
  122. // TotalVotingPower returns the sum of the voting powers of all validators.
  123. func (vals *ValidatorSet) TotalVotingPower() int64 {
  124. if vals.totalVotingPower == 0 {
  125. for _, val := range vals.Validators {
  126. // mind overflow
  127. vals.totalVotingPower = safeAddClip(vals.totalVotingPower, val.VotingPower)
  128. }
  129. }
  130. return vals.totalVotingPower
  131. }
  132. // GetProposer returns the current proposer. If the validator set is empty, nil
  133. // is returned.
  134. func (vals *ValidatorSet) GetProposer() (proposer *Validator) {
  135. if len(vals.Validators) == 0 {
  136. return nil
  137. }
  138. if vals.Proposer == nil {
  139. vals.Proposer = vals.findProposer()
  140. }
  141. return vals.Proposer.Copy()
  142. }
  143. func (vals *ValidatorSet) findProposer() *Validator {
  144. var proposer *Validator
  145. for _, val := range vals.Validators {
  146. if proposer == nil || !bytes.Equal(val.Address, proposer.Address) {
  147. proposer = proposer.CompareAccum(val)
  148. }
  149. }
  150. return proposer
  151. }
  152. // Hash returns the Merkle root hash build using validators (as leaves) in the
  153. // set.
  154. func (vals *ValidatorSet) Hash() []byte {
  155. if len(vals.Validators) == 0 {
  156. return nil
  157. }
  158. hashers := make([]merkle.Hasher, len(vals.Validators))
  159. for i, val := range vals.Validators {
  160. hashers[i] = val
  161. }
  162. return merkle.SimpleHashFromHashers(hashers)
  163. }
  164. // Add adds val to the validator set and returns true. It returns false if val
  165. // is already in the set.
  166. func (vals *ValidatorSet) Add(val *Validator) (added bool) {
  167. val = val.Copy()
  168. idx := sort.Search(len(vals.Validators), func(i int) bool {
  169. return bytes.Compare(val.Address, vals.Validators[i].Address) <= 0
  170. })
  171. if idx >= len(vals.Validators) {
  172. vals.Validators = append(vals.Validators, val)
  173. // Invalidate cache
  174. vals.Proposer = nil
  175. vals.totalVotingPower = 0
  176. return true
  177. } else if bytes.Equal(vals.Validators[idx].Address, val.Address) {
  178. return false
  179. } else {
  180. newValidators := make([]*Validator, len(vals.Validators)+1)
  181. copy(newValidators[:idx], vals.Validators[:idx])
  182. newValidators[idx] = val
  183. copy(newValidators[idx+1:], vals.Validators[idx:])
  184. vals.Validators = newValidators
  185. // Invalidate cache
  186. vals.Proposer = nil
  187. vals.totalVotingPower = 0
  188. return true
  189. }
  190. }
  191. // Update updates val and returns true. It returns false if val is not present
  192. // in the set.
  193. func (vals *ValidatorSet) Update(val *Validator) (updated bool) {
  194. index, sameVal := vals.GetByAddress(val.Address)
  195. if sameVal == nil {
  196. return false
  197. }
  198. vals.Validators[index] = val.Copy()
  199. // Invalidate cache
  200. vals.Proposer = nil
  201. vals.totalVotingPower = 0
  202. return true
  203. }
  204. // Remove deletes the validator with address. It returns the validator removed
  205. // and true. If returns nil and false if validator is not present in the set.
  206. func (vals *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) {
  207. idx := sort.Search(len(vals.Validators), func(i int) bool {
  208. return bytes.Compare(address, vals.Validators[i].Address) <= 0
  209. })
  210. if idx >= len(vals.Validators) || !bytes.Equal(vals.Validators[idx].Address, address) {
  211. return nil, false
  212. }
  213. removedVal := vals.Validators[idx]
  214. newValidators := vals.Validators[:idx]
  215. if idx+1 < len(vals.Validators) {
  216. newValidators = append(newValidators, vals.Validators[idx+1:]...)
  217. }
  218. vals.Validators = newValidators
  219. // Invalidate cache
  220. vals.Proposer = nil
  221. vals.totalVotingPower = 0
  222. return removedVal, true
  223. }
  224. // Iterate will run the given function over the set.
  225. func (vals *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
  226. for i, val := range vals.Validators {
  227. stop := fn(i, val.Copy())
  228. if stop {
  229. break
  230. }
  231. }
  232. }
  233. // Verify that +2/3 of the set had signed the given signBytes.
  234. func (vals *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height int64, commit *Commit) error {
  235. if vals.Size() != len(commit.Precommits) {
  236. return fmt.Errorf("Invalid commit -- wrong set size: %v vs %v", vals.Size(), len(commit.Precommits))
  237. }
  238. if height != commit.Height() {
  239. return fmt.Errorf("Invalid commit -- wrong height: %v vs %v", height, commit.Height())
  240. }
  241. if !blockID.Equals(commit.BlockID) {
  242. return fmt.Errorf("Invalid commit -- wrong block id: want %v got %v",
  243. blockID, commit.BlockID)
  244. }
  245. talliedVotingPower := int64(0)
  246. round := commit.Round()
  247. for idx, precommit := range commit.Precommits {
  248. if precommit == nil {
  249. continue // OK, some precommits can be missing.
  250. }
  251. if precommit.Height != height {
  252. return fmt.Errorf("Invalid commit -- wrong height: want %v got %v", height, precommit.Height)
  253. }
  254. if precommit.Round != round {
  255. return fmt.Errorf("Invalid commit -- wrong round: want %v got %v", round, precommit.Round)
  256. }
  257. if precommit.Type != VoteTypePrecommit {
  258. return fmt.Errorf("Invalid commit -- not precommit @ index %v", idx)
  259. }
  260. _, val := vals.GetByIndex(idx)
  261. // Validate signature.
  262. precommitSignBytes := precommit.SignBytes(chainID)
  263. if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
  264. return fmt.Errorf("Invalid commit -- invalid signature: %v", precommit)
  265. }
  266. // Good precommit!
  267. if blockID.Equals(precommit.BlockID) {
  268. talliedVotingPower += val.VotingPower
  269. } else {
  270. // It's OK that the BlockID doesn't match. We include stray
  271. // precommits to measure validator availability.
  272. }
  273. }
  274. if talliedVotingPower > vals.TotalVotingPower()*2/3 {
  275. return nil
  276. }
  277. return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
  278. talliedVotingPower, (vals.TotalVotingPower()*2/3 + 1))
  279. }
  280. // VerifyFutureCommit will check to see if the set would be valid with a different
  281. // validator set.
  282. //
  283. // vals is the old validator set that we know. Over 2/3 of the power in old
  284. // signed this block.
  285. //
  286. // In Tendermint, 1/3 of the voting power can halt or fork the chain, but 1/3
  287. // can't make arbitrary state transitions. You still need > 2/3 Byzantine to
  288. // make arbitrary state transitions.
  289. //
  290. // To preserve this property in the light client, we also require > 2/3 of the
  291. // old vals to sign the future commit at H, that way we preserve the property
  292. // that if they weren't being truthful about the validator set at H (block hash
  293. // -> vals hash) or about the app state (block hash -> app hash) we can slash
  294. // > 2/3. Otherwise, the lite client isn't providing the same security
  295. // guarantees.
  296. //
  297. // Even if we added a slashing condition that if you sign a block header with
  298. // the wrong validator set, then we would only need > 1/3 of signatures from
  299. // the old vals on the new commit, it wouldn't be sufficient because the new
  300. // vals can be arbitrary and commit some arbitrary app hash.
  301. //
  302. // newSet is the validator set that signed this block. Only votes from new are
  303. // sufficient for 2/3 majority in the new set as well, for it to be a valid
  304. // commit.
  305. //
  306. // NOTE: This doesn't check whether the commit is a future commit, because the
  307. // current height isn't part of the ValidatorSet. Caller must check that the
  308. // commit height is greater than the height for this validator set.
  309. func (vals *ValidatorSet) VerifyFutureCommit(newSet *ValidatorSet, chainID string,
  310. blockID BlockID, height int64, commit *Commit) error {
  311. oldVals := vals
  312. // Commit must be a valid commit for newSet.
  313. err := newSet.VerifyCommit(chainID, blockID, height, commit)
  314. if err != nil {
  315. return err
  316. }
  317. // Check old voting power.
  318. oldVotingPower := int64(0)
  319. seen := map[int]bool{}
  320. round := commit.Round()
  321. for idx, precommit := range commit.Precommits {
  322. if precommit == nil {
  323. continue
  324. }
  325. if precommit.Height != height {
  326. return cmn.NewError("Blocks don't match - %d vs %d", round, precommit.Round)
  327. }
  328. if precommit.Round != round {
  329. return cmn.NewError("Invalid commit -- wrong round: %v vs %v", round, precommit.Round)
  330. }
  331. if precommit.Type != VoteTypePrecommit {
  332. return cmn.NewError("Invalid commit -- not precommit @ index %v", idx)
  333. }
  334. // See if this validator is in oldVals.
  335. idx, val := oldVals.GetByAddress(precommit.ValidatorAddress)
  336. if val == nil || seen[idx] {
  337. continue // missing or double vote...
  338. }
  339. seen[idx] = true
  340. // Validate signature.
  341. precommitSignBytes := precommit.SignBytes(chainID)
  342. if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
  343. return cmn.NewError("Invalid commit -- invalid signature: %v", precommit)
  344. }
  345. // Good precommit!
  346. if blockID.Equals(precommit.BlockID) {
  347. oldVotingPower += val.VotingPower
  348. } else {
  349. // It's OK that the BlockID doesn't match. We include stray
  350. // precommits to measure validator availability.
  351. }
  352. }
  353. if oldVotingPower <= oldVals.TotalVotingPower()*2/3 {
  354. return cmn.NewError("Invalid commit -- insufficient old voting power: got %v, needed %v",
  355. oldVotingPower, (oldVals.TotalVotingPower()*2/3 + 1))
  356. }
  357. return nil
  358. }
  359. func (vals *ValidatorSet) String() string {
  360. return vals.StringIndented("")
  361. }
  362. // String
  363. func (vals *ValidatorSet) StringIndented(indent string) string {
  364. if vals == nil {
  365. return "nil-ValidatorSet"
  366. }
  367. valStrings := []string{}
  368. vals.Iterate(func(index int, val *Validator) bool {
  369. valStrings = append(valStrings, val.String())
  370. return false
  371. })
  372. return fmt.Sprintf(`ValidatorSet{
  373. %s Proposer: %v
  374. %s Validators:
  375. %s %v
  376. %s}`,
  377. indent, vals.GetProposer().String(),
  378. indent,
  379. indent, strings.Join(valStrings, "\n"+indent+" "),
  380. indent)
  381. }
  382. //-------------------------------------
  383. // Implements sort for sorting validators by address.
  384. // Sort validators by address
  385. type ValidatorsByAddress []*Validator
  386. func (valz ValidatorsByAddress) Len() int {
  387. return len(valz)
  388. }
  389. func (valz ValidatorsByAddress) Less(i, j int) bool {
  390. return bytes.Compare(valz[i].Address, valz[j].Address) == -1
  391. }
  392. func (valz ValidatorsByAddress) Swap(i, j int) {
  393. it := valz[i]
  394. valz[i] = valz[j]
  395. valz[j] = it
  396. }
  397. //-------------------------------------
  398. // Use with Heap for sorting validators by accum
  399. type accumComparable struct {
  400. *Validator
  401. }
  402. // We want to find the validator with the greatest accum.
  403. func (ac accumComparable) Less(o interface{}) bool {
  404. other := o.(accumComparable).Validator
  405. larger := ac.CompareAccum(other)
  406. return bytes.Equal(larger.Address, ac.Address)
  407. }
  408. //----------------------------------------
  409. // For testing
  410. // RandValidatorSet returns a randomized validator set, useful for testing.
  411. // NOTE: PrivValidator are in order.
  412. // UNSTABLE
  413. func RandValidatorSet(numValidators int, votingPower int64) (*ValidatorSet, []PrivValidator) {
  414. valz := make([]*Validator, numValidators)
  415. privValidators := make([]PrivValidator, numValidators)
  416. for i := 0; i < numValidators; i++ {
  417. val, privValidator := RandValidator(false, votingPower)
  418. valz[i] = val
  419. privValidators[i] = privValidator
  420. }
  421. vals := NewValidatorSet(valz)
  422. sort.Sort(PrivValidatorsByAddress(privValidators))
  423. return vals, privValidators
  424. }
  425. ///////////////////////////////////////////////////////////////////////////////
  426. // Safe multiplication and addition/subtraction
  427. func safeMul(a, b int64) (int64, bool) {
  428. if a == 0 || b == 0 {
  429. return 0, false
  430. }
  431. if a == 1 {
  432. return b, false
  433. }
  434. if b == 1 {
  435. return a, false
  436. }
  437. if a == math.MinInt64 || b == math.MinInt64 {
  438. return -1, true
  439. }
  440. c := a * b
  441. return c, c/b != a
  442. }
  443. func safeAdd(a, b int64) (int64, bool) {
  444. if b > 0 && a > math.MaxInt64-b {
  445. return -1, true
  446. } else if b < 0 && a < math.MinInt64-b {
  447. return -1, true
  448. }
  449. return a + b, false
  450. }
  451. func safeSub(a, b int64) (int64, bool) {
  452. if b > 0 && a < math.MinInt64+b {
  453. return -1, true
  454. } else if b < 0 && a > math.MaxInt64+b {
  455. return -1, true
  456. }
  457. return a - b, false
  458. }
  459. func safeMulClip(a, b int64) int64 {
  460. c, overflow := safeMul(a, b)
  461. if overflow {
  462. if (a < 0 || b < 0) && !(a < 0 && b < 0) {
  463. return math.MinInt64
  464. }
  465. return math.MaxInt64
  466. }
  467. return c
  468. }
  469. func safeAddClip(a, b int64) int64 {
  470. c, overflow := safeAdd(a, b)
  471. if overflow {
  472. if b < 0 {
  473. return math.MinInt64
  474. }
  475. return math.MaxInt64
  476. }
  477. return c
  478. }
  479. func safeSubClip(a, b int64) int64 {
  480. c, overflow := safeSub(a, b)
  481. if overflow {
  482. if b > 0 {
  483. return math.MinInt64
  484. }
  485. return math.MaxInt64
  486. }
  487. return c
  488. }