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.

505 lines
14 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
7 years ago
7 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "sort"
  7. "strings"
  8. "github.com/pkg/errors"
  9. cmn "github.com/tendermint/tmlibs/common"
  10. "github.com/tendermint/tmlibs/merkle"
  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 .GetProposer() 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. type ValidatorSet struct {
  23. // NOTE: persisted via reflect, must be exported.
  24. Validators []*Validator `json:"validators"`
  25. Proposer *Validator `json:"proposer"`
  26. // cached (unexported)
  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. vs := &ValidatorSet{
  36. Validators: validators,
  37. }
  38. if vals != nil {
  39. vs.IncrementAccum(1)
  40. }
  41. return vs
  42. }
  43. // incrementAccum and update the proposer
  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. // check for overflow both multiplication and sum
  49. val.Accum = safeAddClip(val.Accum, safeMulClip(val.VotingPower, int64(times)))
  50. validatorsHeap.Push(val, accumComparable{val})
  51. }
  52. // Decrement the validator with most accum times times
  53. for i := 0; i < times; i++ {
  54. mostest := validatorsHeap.Peek().(*Validator)
  55. if i == times-1 {
  56. valSet.Proposer = mostest
  57. }
  58. // mind underflow
  59. mostest.Accum = safeSubClip(mostest.Accum, valSet.TotalVotingPower())
  60. validatorsHeap.Update(mostest, accumComparable{mostest})
  61. }
  62. }
  63. func (valSet *ValidatorSet) Copy() *ValidatorSet {
  64. validators := make([]*Validator, len(valSet.Validators))
  65. for i, val := range valSet.Validators {
  66. // NOTE: must copy, since IncrementAccum updates in place.
  67. validators[i] = val.Copy()
  68. }
  69. return &ValidatorSet{
  70. Validators: validators,
  71. Proposer: valSet.Proposer,
  72. totalVotingPower: valSet.totalVotingPower,
  73. }
  74. }
  75. func (valSet *ValidatorSet) HasAddress(address []byte) bool {
  76. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  77. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  78. })
  79. return idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address)
  80. }
  81. func (valSet *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator) {
  82. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  83. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  84. })
  85. if idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address) {
  86. return idx, valSet.Validators[idx].Copy()
  87. } else {
  88. return 0, nil
  89. }
  90. }
  91. // GetByIndex returns the validator by index.
  92. // It returns nil values if index < 0 or
  93. // index >= len(ValidatorSet.Validators)
  94. func (valSet *ValidatorSet) GetByIndex(index int) (address []byte, val *Validator) {
  95. if index < 0 || index >= len(valSet.Validators) {
  96. return nil, nil
  97. }
  98. val = valSet.Validators[index]
  99. return val.Address, val.Copy()
  100. }
  101. func (valSet *ValidatorSet) Size() int {
  102. return len(valSet.Validators)
  103. }
  104. func (valSet *ValidatorSet) TotalVotingPower() int64 {
  105. if valSet.totalVotingPower == 0 {
  106. for _, val := range valSet.Validators {
  107. // mind overflow
  108. valSet.totalVotingPower = safeAddClip(valSet.totalVotingPower, val.VotingPower)
  109. }
  110. }
  111. return valSet.totalVotingPower
  112. }
  113. func (valSet *ValidatorSet) GetProposer() (proposer *Validator) {
  114. if len(valSet.Validators) == 0 {
  115. return nil
  116. }
  117. if valSet.Proposer == nil {
  118. valSet.Proposer = valSet.findProposer()
  119. }
  120. return valSet.Proposer.Copy()
  121. }
  122. func (valSet *ValidatorSet) findProposer() *Validator {
  123. var proposer *Validator
  124. for _, val := range valSet.Validators {
  125. if proposer == nil || !bytes.Equal(val.Address, proposer.Address) {
  126. proposer = proposer.CompareAccum(val)
  127. }
  128. }
  129. return proposer
  130. }
  131. func (valSet *ValidatorSet) Hash() []byte {
  132. if len(valSet.Validators) == 0 {
  133. return nil
  134. }
  135. hashables := make([]merkle.Hashable, len(valSet.Validators))
  136. for i, val := range valSet.Validators {
  137. hashables[i] = val
  138. }
  139. return merkle.SimpleHashFromHashables(hashables)
  140. }
  141. func (valSet *ValidatorSet) Add(val *Validator) (added bool) {
  142. val = val.Copy()
  143. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  144. return bytes.Compare(val.Address, valSet.Validators[i].Address) <= 0
  145. })
  146. if idx == len(valSet.Validators) {
  147. valSet.Validators = append(valSet.Validators, val)
  148. // Invalidate cache
  149. valSet.Proposer = nil
  150. valSet.totalVotingPower = 0
  151. return true
  152. } else if bytes.Equal(valSet.Validators[idx].Address, val.Address) {
  153. return false
  154. } else {
  155. newValidators := make([]*Validator, len(valSet.Validators)+1)
  156. copy(newValidators[:idx], valSet.Validators[:idx])
  157. newValidators[idx] = val
  158. copy(newValidators[idx+1:], valSet.Validators[idx:])
  159. valSet.Validators = newValidators
  160. // Invalidate cache
  161. valSet.Proposer = nil
  162. valSet.totalVotingPower = 0
  163. return true
  164. }
  165. }
  166. func (valSet *ValidatorSet) Update(val *Validator) (updated bool) {
  167. index, sameVal := valSet.GetByAddress(val.Address)
  168. if sameVal == nil {
  169. return false
  170. } else {
  171. valSet.Validators[index] = val.Copy()
  172. // Invalidate cache
  173. valSet.Proposer = nil
  174. valSet.totalVotingPower = 0
  175. return true
  176. }
  177. }
  178. func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) {
  179. idx := sort.Search(len(valSet.Validators), func(i int) bool {
  180. return bytes.Compare(address, valSet.Validators[i].Address) <= 0
  181. })
  182. if idx == len(valSet.Validators) || !bytes.Equal(valSet.Validators[idx].Address, address) {
  183. return nil, false
  184. } else {
  185. removedVal := valSet.Validators[idx]
  186. newValidators := valSet.Validators[:idx]
  187. if idx+1 < len(valSet.Validators) {
  188. newValidators = append(newValidators, valSet.Validators[idx+1:]...)
  189. }
  190. valSet.Validators = newValidators
  191. // Invalidate cache
  192. valSet.Proposer = nil
  193. valSet.totalVotingPower = 0
  194. return removedVal, true
  195. }
  196. }
  197. func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
  198. for i, val := range valSet.Validators {
  199. stop := fn(i, val.Copy())
  200. if stop {
  201. break
  202. }
  203. }
  204. }
  205. // Verify that +2/3 of the set had signed the given signBytes
  206. func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height int64, commit *Commit) error {
  207. if valSet.Size() != len(commit.Precommits) {
  208. return fmt.Errorf("Invalid commit -- wrong set size: %v vs %v", valSet.Size(), len(commit.Precommits))
  209. }
  210. if height != commit.Height() {
  211. return fmt.Errorf("Invalid commit -- wrong height: %v vs %v", height, commit.Height())
  212. }
  213. talliedVotingPower := int64(0)
  214. round := commit.Round()
  215. for idx, precommit := range commit.Precommits {
  216. // may be nil if validator skipped.
  217. if precommit == nil {
  218. continue
  219. }
  220. if precommit.Height != height {
  221. return fmt.Errorf("Invalid commit -- wrong height: %v vs %v", height, precommit.Height)
  222. }
  223. if precommit.Round != round {
  224. return fmt.Errorf("Invalid commit -- wrong round: %v vs %v", round, precommit.Round)
  225. }
  226. if precommit.Type != VoteTypePrecommit {
  227. return fmt.Errorf("Invalid commit -- not precommit @ index %v", idx)
  228. }
  229. _, val := valSet.GetByIndex(idx)
  230. // Validate signature
  231. precommitSignBytes := SignBytes(chainID, precommit)
  232. if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
  233. return fmt.Errorf("Invalid commit -- invalid signature: %v", precommit)
  234. }
  235. if !blockID.Equals(precommit.BlockID) {
  236. continue // Not an error, but doesn't count
  237. }
  238. // Good precommit!
  239. talliedVotingPower += val.VotingPower
  240. }
  241. if talliedVotingPower > valSet.TotalVotingPower()*2/3 {
  242. return nil
  243. } else {
  244. return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
  245. talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
  246. }
  247. }
  248. // VerifyCommitAny will check to see if the set would
  249. // be valid with a different validator set.
  250. //
  251. // valSet is the validator set that we know
  252. // * over 2/3 of the power in old signed this block
  253. //
  254. // newSet is the validator set that signed this block
  255. // * only votes from old are sufficient for 2/3 majority
  256. // in the new set as well
  257. //
  258. // That means that:
  259. // * 10% of the valset can't just declare themselves kings
  260. // * If the validator set is 3x old size, we need more proof to trust
  261. func (valSet *ValidatorSet) VerifyCommitAny(newSet *ValidatorSet, chainID string,
  262. blockID BlockID, height int64, commit *Commit) error {
  263. if newSet.Size() != len(commit.Precommits) {
  264. return errors.Errorf("Invalid commit -- wrong set size: %v vs %v", newSet.Size(), len(commit.Precommits))
  265. }
  266. if height != commit.Height() {
  267. return errors.Errorf("Invalid commit -- wrong height: %v vs %v", height, commit.Height())
  268. }
  269. oldVotingPower := int64(0)
  270. newVotingPower := int64(0)
  271. seen := map[int]bool{}
  272. round := commit.Round()
  273. for idx, precommit := range commit.Precommits {
  274. // first check as in VerifyCommit
  275. if precommit == nil {
  276. continue
  277. }
  278. if precommit.Height != height {
  279. // return certerr.ErrHeightMismatch(height, precommit.Height)
  280. return errors.Errorf("Blocks don't match - %d vs %d", round, precommit.Round)
  281. }
  282. if precommit.Round != round {
  283. return errors.Errorf("Invalid commit -- wrong round: %v vs %v", round, precommit.Round)
  284. }
  285. if precommit.Type != VoteTypePrecommit {
  286. return errors.Errorf("Invalid commit -- not precommit @ index %v", idx)
  287. }
  288. if !blockID.Equals(precommit.BlockID) {
  289. continue // Not an error, but doesn't count
  290. }
  291. // we only grab by address, ignoring unknown validators
  292. vi, ov := valSet.GetByAddress(precommit.ValidatorAddress)
  293. if ov == nil || seen[vi] {
  294. continue // missing or double vote...
  295. }
  296. seen[vi] = true
  297. // Validate signature old school
  298. precommitSignBytes := SignBytes(chainID, precommit)
  299. if !ov.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
  300. return errors.Errorf("Invalid commit -- invalid signature: %v", precommit)
  301. }
  302. // Good precommit!
  303. oldVotingPower += ov.VotingPower
  304. // check new school
  305. _, cv := newSet.GetByIndex(idx)
  306. if cv.PubKey.Equals(ov.PubKey) {
  307. // make sure this is properly set in the current block as well
  308. newVotingPower += cv.VotingPower
  309. }
  310. }
  311. if oldVotingPower <= valSet.TotalVotingPower()*2/3 {
  312. return errors.Errorf("Invalid commit -- insufficient old voting power: got %v, needed %v",
  313. oldVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
  314. } else if newVotingPower <= newSet.TotalVotingPower()*2/3 {
  315. return errors.Errorf("Invalid commit -- insufficient cur voting power: got %v, needed %v",
  316. newVotingPower, (newSet.TotalVotingPower()*2/3 + 1))
  317. }
  318. return nil
  319. }
  320. func (valSet *ValidatorSet) String() string {
  321. return valSet.StringIndented("")
  322. }
  323. func (valSet *ValidatorSet) StringIndented(indent string) string {
  324. if valSet == nil {
  325. return "nil-ValidatorSet"
  326. }
  327. valStrings := []string{}
  328. valSet.Iterate(func(index int, val *Validator) bool {
  329. valStrings = append(valStrings, val.String())
  330. return false
  331. })
  332. return fmt.Sprintf(`ValidatorSet{
  333. %s Proposer: %v
  334. %s Validators:
  335. %s %v
  336. %s}`,
  337. indent, valSet.GetProposer().String(),
  338. indent,
  339. indent, strings.Join(valStrings, "\n"+indent+" "),
  340. indent)
  341. }
  342. //-------------------------------------
  343. // Implements sort for sorting validators by address.
  344. type ValidatorsByAddress []*Validator
  345. func (vs ValidatorsByAddress) Len() int {
  346. return len(vs)
  347. }
  348. func (vs ValidatorsByAddress) Less(i, j int) bool {
  349. return bytes.Compare(vs[i].Address, vs[j].Address) == -1
  350. }
  351. func (vs ValidatorsByAddress) Swap(i, j int) {
  352. it := vs[i]
  353. vs[i] = vs[j]
  354. vs[j] = it
  355. }
  356. //-------------------------------------
  357. // Use with Heap for sorting validators by accum
  358. type accumComparable struct {
  359. *Validator
  360. }
  361. // We want to find the validator with the greatest accum.
  362. func (ac accumComparable) Less(o interface{}) bool {
  363. other := o.(accumComparable).Validator
  364. larger := ac.CompareAccum(other)
  365. return bytes.Equal(larger.Address, ac.Address)
  366. }
  367. //----------------------------------------
  368. // For testing
  369. // RandValidatorSet returns a randomized validator set, useful for testing.
  370. // NOTE: PrivValidator are in order.
  371. // UNSTABLE
  372. func RandValidatorSet(numValidators int, votingPower int64) (*ValidatorSet, []*PrivValidatorFS) {
  373. vals := make([]*Validator, numValidators)
  374. privValidators := make([]*PrivValidatorFS, numValidators)
  375. for i := 0; i < numValidators; i++ {
  376. val, privValidator := RandValidator(false, votingPower)
  377. vals[i] = val
  378. privValidators[i] = privValidator
  379. }
  380. valSet := NewValidatorSet(vals)
  381. sort.Sort(PrivValidatorsByAddress(privValidators))
  382. return valSet, privValidators
  383. }
  384. ///////////////////////////////////////////////////////////////////////////////
  385. // Safe multiplication and addition/subtraction
  386. func safeMul(a, b int64) (int64, bool) {
  387. if a == 0 || b == 0 {
  388. return 0, false
  389. }
  390. if a == 1 {
  391. return b, false
  392. }
  393. if b == 1 {
  394. return a, false
  395. }
  396. if a == math.MinInt64 || b == math.MinInt64 {
  397. return -1, true
  398. }
  399. c := a * b
  400. return c, c/b != a
  401. }
  402. func safeAdd(a, b int64) (int64, bool) {
  403. if b > 0 && a > math.MaxInt64-b {
  404. return -1, true
  405. } else if b < 0 && a < math.MinInt64-b {
  406. return -1, true
  407. }
  408. return a + b, false
  409. }
  410. func safeSub(a, b int64) (int64, bool) {
  411. if b > 0 && a < math.MinInt64+b {
  412. return -1, true
  413. } else if b < 0 && a > math.MaxInt64+b {
  414. return -1, true
  415. }
  416. return a - b, false
  417. }
  418. func safeMulClip(a, b int64) int64 {
  419. c, overflow := safeMul(a, b)
  420. if overflow {
  421. if (a < 0 || b < 0) && !(a < 0 && b < 0) {
  422. return math.MinInt64
  423. } else {
  424. return math.MaxInt64
  425. }
  426. }
  427. return c
  428. }
  429. func safeAddClip(a, b int64) int64 {
  430. c, overflow := safeAdd(a, b)
  431. if overflow {
  432. if b < 0 {
  433. return math.MinInt64
  434. } else {
  435. return math.MaxInt64
  436. }
  437. }
  438. return c
  439. }
  440. func safeSubClip(a, b int64) int64 {
  441. c, overflow := safeSub(a, b)
  442. if overflow {
  443. if b > 0 {
  444. return math.MinInt64
  445. } else {
  446. return math.MaxInt64
  447. }
  448. }
  449. return c
  450. }