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.

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