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.

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