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.

616 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
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "github.com/pkg/errors"
  8. cmn "github.com/tendermint/tendermint/libs/common"
  9. )
  10. const (
  11. // MaxVotesCount is the maximum votes count. Used in ValidateBasic funcs for
  12. // protection against DOS attacks.
  13. MaxVotesCount = 10000
  14. )
  15. // UNSTABLE
  16. // XXX: duplicate of p2p.ID to avoid dependence between packages.
  17. // Perhaps we can have a minimal types package containing this (and other things?)
  18. // that both `types` and `p2p` import ?
  19. type P2PID string
  20. /*
  21. VoteSet helps collect signatures from validators at each height+round for a
  22. predefined vote type.
  23. We need VoteSet to be able to keep track of conflicting votes when validators
  24. double-sign. Yet, we can't keep track of *all* the votes seen, as that could
  25. be a DoS attack vector.
  26. There are two storage areas for votes.
  27. 1. voteSet.votes
  28. 2. voteSet.votesByBlock
  29. `.votes` is the "canonical" list of votes. It always has at least one vote,
  30. if a vote from a validator had been seen at all. Usually it keeps track of
  31. the first vote seen, but when a 2/3 majority is found, votes for that get
  32. priority and are copied over from `.votesByBlock`.
  33. `.votesByBlock` keeps track of a list of votes for a particular block. There
  34. are two ways a &blockVotes{} gets created in `.votesByBlock`.
  35. 1. the first vote seen by a validator was for the particular block.
  36. 2. a peer claims to have seen 2/3 majority for the particular block.
  37. Since the first vote from a validator will always get added in `.votesByBlock`
  38. , all votes in `.votes` will have a corresponding entry in `.votesByBlock`.
  39. When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its
  40. votes are copied into `.votes`.
  41. All this is memory bounded because conflicting votes only get added if a peer
  42. told us to track that block, each peer only gets to tell us 1 such block, and,
  43. there's only a limited number of peers.
  44. NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64.
  45. */
  46. type VoteSet struct {
  47. chainID string
  48. height int64
  49. round int
  50. type_ SignedMsgType
  51. valSet *ValidatorSet
  52. mtx sync.Mutex
  53. votesBitArray *cmn.BitArray
  54. votes []*Vote // Primary votes to share
  55. sum int64 // Sum of voting power for seen votes, discounting conflicts
  56. maj23 *BlockID // First 2/3 majority seen
  57. votesByBlock map[string]*blockVotes // string(blockHash|blockParts) -> blockVotes
  58. peerMaj23s map[P2PID]BlockID // Maj23 for each peer
  59. }
  60. // Constructs a new VoteSet struct used to accumulate votes for given height/round.
  61. func NewVoteSet(chainID string, height int64, round int, type_ SignedMsgType, valSet *ValidatorSet) *VoteSet {
  62. if height == 0 {
  63. panic("Cannot make VoteSet for height == 0, doesn't make sense.")
  64. }
  65. return &VoteSet{
  66. chainID: chainID,
  67. height: height,
  68. round: round,
  69. type_: type_,
  70. valSet: valSet,
  71. votesBitArray: cmn.NewBitArray(valSet.Size()),
  72. votes: make([]*Vote, valSet.Size()),
  73. sum: 0,
  74. maj23: nil,
  75. votesByBlock: make(map[string]*blockVotes, valSet.Size()),
  76. peerMaj23s: make(map[P2PID]BlockID),
  77. }
  78. }
  79. func (voteSet *VoteSet) ChainID() string {
  80. return voteSet.chainID
  81. }
  82. func (voteSet *VoteSet) Height() int64 {
  83. if voteSet == nil {
  84. return 0
  85. }
  86. return voteSet.height
  87. }
  88. func (voteSet *VoteSet) Round() int {
  89. if voteSet == nil {
  90. return -1
  91. }
  92. return voteSet.round
  93. }
  94. func (voteSet *VoteSet) Type() byte {
  95. if voteSet == nil {
  96. return 0x00
  97. }
  98. return byte(voteSet.type_)
  99. }
  100. func (voteSet *VoteSet) Size() int {
  101. if voteSet == nil {
  102. return 0
  103. }
  104. return voteSet.valSet.Size()
  105. }
  106. // Returns added=true if vote is valid and new.
  107. // Otherwise returns err=ErrVote[
  108. // UnexpectedStep | InvalidIndex | InvalidAddress |
  109. // InvalidSignature | InvalidBlockHash | ConflictingVotes ]
  110. // Duplicate votes return added=false, err=nil.
  111. // Conflicting votes return added=*, err=ErrVoteConflictingVotes.
  112. // NOTE: vote should not be mutated after adding.
  113. // NOTE: VoteSet must not be nil
  114. // NOTE: Vote must not be nil
  115. func (voteSet *VoteSet) AddVote(vote *Vote) (added bool, err error) {
  116. if voteSet == nil {
  117. panic("AddVote() on nil VoteSet")
  118. }
  119. voteSet.mtx.Lock()
  120. defer voteSet.mtx.Unlock()
  121. return voteSet.addVote(vote)
  122. }
  123. // NOTE: Validates as much as possible before attempting to verify the signature.
  124. func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) {
  125. if vote == nil {
  126. return false, ErrVoteNil
  127. }
  128. valIndex := vote.ValidatorIndex
  129. valAddr := vote.ValidatorAddress
  130. blockKey := vote.BlockID.Key()
  131. // Ensure that validator index was set
  132. if valIndex < 0 {
  133. return false, errors.Wrap(ErrVoteInvalidValidatorIndex, "Index < 0")
  134. } else if len(valAddr) == 0 {
  135. return false, errors.Wrap(ErrVoteInvalidValidatorAddress, "Empty address")
  136. }
  137. // Make sure the step matches.
  138. if (vote.Height != voteSet.height) ||
  139. (vote.Round != voteSet.round) ||
  140. (vote.Type != voteSet.type_) {
  141. return false, errors.Wrapf(ErrVoteUnexpectedStep, "Expected %d/%d/%d, but got %d/%d/%d",
  142. voteSet.height, voteSet.round, voteSet.type_,
  143. vote.Height, vote.Round, vote.Type)
  144. }
  145. // Ensure that signer is a validator.
  146. lookupAddr, val := voteSet.valSet.GetByIndex(valIndex)
  147. if val == nil {
  148. return false, errors.Wrapf(ErrVoteInvalidValidatorIndex,
  149. "Cannot find validator %d in valSet of size %d", valIndex, voteSet.valSet.Size())
  150. }
  151. // Ensure that the signer has the right address.
  152. if !bytes.Equal(valAddr, lookupAddr) {
  153. return false, errors.Wrapf(ErrVoteInvalidValidatorAddress,
  154. "vote.ValidatorAddress (%X) does not match address (%X) for vote.ValidatorIndex (%d)\n"+
  155. "Ensure the genesis file is correct across all validators.",
  156. valAddr, lookupAddr, valIndex)
  157. }
  158. // If we already know of this vote, return false.
  159. if existing, ok := voteSet.getVote(valIndex, blockKey); ok {
  160. if bytes.Equal(existing.Signature, vote.Signature) {
  161. return false, nil // duplicate
  162. }
  163. return false, errors.Wrapf(ErrVoteNonDeterministicSignature, "Existing vote: %v; New vote: %v", existing, vote)
  164. }
  165. // Check signature.
  166. if err := vote.Verify(voteSet.chainID, val.PubKey); err != nil {
  167. return false, errors.Wrapf(err, "Failed to verify vote with ChainID %s and PubKey %s", voteSet.chainID, val.PubKey)
  168. }
  169. // Add vote and get conflicting vote if any.
  170. added, conflicting := voteSet.addVerifiedVote(vote, blockKey, val.VotingPower)
  171. if conflicting != nil {
  172. return added, NewConflictingVoteError(val, conflicting, vote)
  173. }
  174. if !added {
  175. panic("Expected to add non-conflicting vote")
  176. }
  177. return added, nil
  178. }
  179. // Returns (vote, true) if vote exists for valIndex and blockKey.
  180. func (voteSet *VoteSet) getVote(valIndex int, blockKey string) (vote *Vote, ok bool) {
  181. if existing := voteSet.votes[valIndex]; existing != nil && existing.BlockID.Key() == blockKey {
  182. return existing, true
  183. }
  184. if existing := voteSet.votesByBlock[blockKey].getByIndex(valIndex); existing != nil {
  185. return existing, true
  186. }
  187. return nil, false
  188. }
  189. // Assumes signature is valid.
  190. // If conflicting vote exists, returns it.
  191. func (voteSet *VoteSet) addVerifiedVote(
  192. vote *Vote,
  193. blockKey string,
  194. votingPower int64,
  195. ) (added bool, conflicting *Vote) {
  196. valIndex := vote.ValidatorIndex
  197. // Already exists in voteSet.votes?
  198. if existing := voteSet.votes[valIndex]; existing != nil {
  199. if existing.BlockID.Equals(vote.BlockID) {
  200. panic("addVerifiedVote does not expect duplicate votes")
  201. } else {
  202. conflicting = existing
  203. }
  204. // Replace vote if blockKey matches voteSet.maj23.
  205. if voteSet.maj23 != nil && voteSet.maj23.Key() == blockKey {
  206. voteSet.votes[valIndex] = vote
  207. voteSet.votesBitArray.SetIndex(valIndex, true)
  208. }
  209. // Otherwise don't add it to voteSet.votes
  210. } else {
  211. // Add to voteSet.votes and incr .sum
  212. voteSet.votes[valIndex] = vote
  213. voteSet.votesBitArray.SetIndex(valIndex, true)
  214. voteSet.sum += votingPower
  215. }
  216. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  217. if ok {
  218. if conflicting != nil && !votesByBlock.peerMaj23 {
  219. // There's a conflict and no peer claims that this block is special.
  220. return false, conflicting
  221. }
  222. // We'll add the vote in a bit.
  223. } else {
  224. // .votesByBlock doesn't exist...
  225. if conflicting != nil {
  226. // ... and there's a conflicting vote.
  227. // We're not even tracking this blockKey, so just forget it.
  228. return false, conflicting
  229. }
  230. // ... and there's no conflicting vote.
  231. // Start tracking this blockKey
  232. votesByBlock = newBlockVotes(false, voteSet.valSet.Size())
  233. voteSet.votesByBlock[blockKey] = votesByBlock
  234. // We'll add the vote in a bit.
  235. }
  236. // Before adding to votesByBlock, see if we'll exceed quorum
  237. origSum := votesByBlock.sum
  238. quorum := voteSet.valSet.TotalVotingPower()*2/3 + 1
  239. // Add vote to votesByBlock
  240. votesByBlock.addVerifiedVote(vote, votingPower)
  241. // If we just crossed the quorum threshold and have 2/3 majority...
  242. if origSum < quorum && quorum <= votesByBlock.sum {
  243. // Only consider the first quorum reached
  244. if voteSet.maj23 == nil {
  245. maj23BlockID := vote.BlockID
  246. voteSet.maj23 = &maj23BlockID
  247. // And also copy votes over to voteSet.votes
  248. for i, vote := range votesByBlock.votes {
  249. if vote != nil {
  250. voteSet.votes[i] = vote
  251. }
  252. }
  253. }
  254. }
  255. return true, conflicting
  256. }
  257. // If a peer claims that it has 2/3 majority for given blockKey, call this.
  258. // NOTE: if there are too many peers, or too much peer churn,
  259. // this can cause memory issues.
  260. // TODO: implement ability to remove peers too
  261. // NOTE: VoteSet must not be nil
  262. func (voteSet *VoteSet) SetPeerMaj23(peerID P2PID, blockID BlockID) error {
  263. if voteSet == nil {
  264. panic("SetPeerMaj23() on nil VoteSet")
  265. }
  266. voteSet.mtx.Lock()
  267. defer voteSet.mtx.Unlock()
  268. blockKey := blockID.Key()
  269. // Make sure peer hasn't already told us something.
  270. if existing, ok := voteSet.peerMaj23s[peerID]; ok {
  271. if existing.Equals(blockID) {
  272. return nil // Nothing to do
  273. }
  274. return fmt.Errorf("SetPeerMaj23: Received conflicting blockID from peer %v. Got %v, expected %v",
  275. peerID, blockID, existing)
  276. }
  277. voteSet.peerMaj23s[peerID] = blockID
  278. // Create .votesByBlock entry if needed.
  279. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  280. if ok {
  281. if votesByBlock.peerMaj23 {
  282. return nil // Nothing to do
  283. }
  284. votesByBlock.peerMaj23 = true
  285. // No need to copy votes, already there.
  286. } else {
  287. votesByBlock = newBlockVotes(true, voteSet.valSet.Size())
  288. voteSet.votesByBlock[blockKey] = votesByBlock
  289. // No need to copy votes, no votes to copy over.
  290. }
  291. return nil
  292. }
  293. func (voteSet *VoteSet) BitArray() *cmn.BitArray {
  294. if voteSet == nil {
  295. return nil
  296. }
  297. voteSet.mtx.Lock()
  298. defer voteSet.mtx.Unlock()
  299. return voteSet.votesBitArray.Copy()
  300. }
  301. func (voteSet *VoteSet) BitArrayByBlockID(blockID BlockID) *cmn.BitArray {
  302. if voteSet == nil {
  303. return nil
  304. }
  305. voteSet.mtx.Lock()
  306. defer voteSet.mtx.Unlock()
  307. votesByBlock, ok := voteSet.votesByBlock[blockID.Key()]
  308. if ok {
  309. return votesByBlock.bitArray.Copy()
  310. }
  311. return nil
  312. }
  313. // NOTE: if validator has conflicting votes, returns "canonical" vote
  314. func (voteSet *VoteSet) GetByIndex(valIndex int) *Vote {
  315. if voteSet == nil {
  316. return nil
  317. }
  318. voteSet.mtx.Lock()
  319. defer voteSet.mtx.Unlock()
  320. return voteSet.votes[valIndex]
  321. }
  322. func (voteSet *VoteSet) GetByAddress(address []byte) *Vote {
  323. if voteSet == nil {
  324. return nil
  325. }
  326. voteSet.mtx.Lock()
  327. defer voteSet.mtx.Unlock()
  328. valIndex, val := voteSet.valSet.GetByAddress(address)
  329. if val == nil {
  330. panic("GetByAddress(address) returned nil")
  331. }
  332. return voteSet.votes[valIndex]
  333. }
  334. func (voteSet *VoteSet) HasTwoThirdsMajority() bool {
  335. if voteSet == nil {
  336. return false
  337. }
  338. voteSet.mtx.Lock()
  339. defer voteSet.mtx.Unlock()
  340. return voteSet.maj23 != nil
  341. }
  342. func (voteSet *VoteSet) IsCommit() bool {
  343. if voteSet == nil {
  344. return false
  345. }
  346. if voteSet.type_ != PrecommitType {
  347. return false
  348. }
  349. voteSet.mtx.Lock()
  350. defer voteSet.mtx.Unlock()
  351. return voteSet.maj23 != nil
  352. }
  353. func (voteSet *VoteSet) HasTwoThirdsAny() bool {
  354. if voteSet == nil {
  355. return false
  356. }
  357. voteSet.mtx.Lock()
  358. defer voteSet.mtx.Unlock()
  359. return voteSet.sum > voteSet.valSet.TotalVotingPower()*2/3
  360. }
  361. func (voteSet *VoteSet) HasAll() bool {
  362. voteSet.mtx.Lock()
  363. defer voteSet.mtx.Unlock()
  364. return voteSet.sum == voteSet.valSet.TotalVotingPower()
  365. }
  366. // If there was a +2/3 majority for blockID, return blockID and true.
  367. // Else, return the empty BlockID{} and false.
  368. func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool) {
  369. if voteSet == nil {
  370. return BlockID{}, false
  371. }
  372. voteSet.mtx.Lock()
  373. defer voteSet.mtx.Unlock()
  374. if voteSet.maj23 != nil {
  375. return *voteSet.maj23, true
  376. }
  377. return BlockID{}, false
  378. }
  379. //--------------------------------------------------------------------------------
  380. // Strings and JSON
  381. func (voteSet *VoteSet) String() string {
  382. if voteSet == nil {
  383. return "nil-VoteSet"
  384. }
  385. return voteSet.StringIndented("")
  386. }
  387. func (voteSet *VoteSet) StringIndented(indent string) string {
  388. voteSet.mtx.Lock()
  389. defer voteSet.mtx.Unlock()
  390. voteStrings := make([]string, len(voteSet.votes))
  391. for i, vote := range voteSet.votes {
  392. if vote == nil {
  393. voteStrings[i] = nilVoteStr
  394. } else {
  395. voteStrings[i] = vote.String()
  396. }
  397. }
  398. return fmt.Sprintf(`VoteSet{
  399. %s H:%v R:%v T:%v
  400. %s %v
  401. %s %v
  402. %s %v
  403. %s}`,
  404. indent, voteSet.height, voteSet.round, voteSet.type_,
  405. indent, strings.Join(voteStrings, "\n"+indent+" "),
  406. indent, voteSet.votesBitArray,
  407. indent, voteSet.peerMaj23s,
  408. indent)
  409. }
  410. // Marshal the VoteSet to JSON. Same as String(), just in JSON,
  411. // and without the height/round/type_ (since its already included in the votes).
  412. func (voteSet *VoteSet) MarshalJSON() ([]byte, error) {
  413. voteSet.mtx.Lock()
  414. defer voteSet.mtx.Unlock()
  415. return cdc.MarshalJSON(VoteSetJSON{
  416. voteSet.voteStrings(),
  417. voteSet.bitArrayString(),
  418. voteSet.peerMaj23s,
  419. })
  420. }
  421. // More human readable JSON of the vote set
  422. // NOTE: insufficient for unmarshalling from (compressed votes)
  423. // TODO: make the peerMaj23s nicer to read (eg just the block hash)
  424. type VoteSetJSON struct {
  425. Votes []string `json:"votes"`
  426. VotesBitArray string `json:"votes_bit_array"`
  427. PeerMaj23s map[P2PID]BlockID `json:"peer_maj_23s"`
  428. }
  429. // Return the bit-array of votes including
  430. // the fraction of power that has voted like:
  431. // "BA{29:xx__x__x_x___x__x_______xxx__} 856/1304 = 0.66"
  432. func (voteSet *VoteSet) BitArrayString() string {
  433. voteSet.mtx.Lock()
  434. defer voteSet.mtx.Unlock()
  435. return voteSet.bitArrayString()
  436. }
  437. func (voteSet *VoteSet) bitArrayString() string {
  438. bAString := voteSet.votesBitArray.String()
  439. voted, total, fracVoted := voteSet.sumTotalFrac()
  440. return fmt.Sprintf("%s %d/%d = %.2f", bAString, voted, total, fracVoted)
  441. }
  442. // Returns a list of votes compressed to more readable strings.
  443. func (voteSet *VoteSet) VoteStrings() []string {
  444. voteSet.mtx.Lock()
  445. defer voteSet.mtx.Unlock()
  446. return voteSet.voteStrings()
  447. }
  448. func (voteSet *VoteSet) voteStrings() []string {
  449. voteStrings := make([]string, len(voteSet.votes))
  450. for i, vote := range voteSet.votes {
  451. if vote == nil {
  452. voteStrings[i] = nilVoteStr
  453. } else {
  454. voteStrings[i] = vote.String()
  455. }
  456. }
  457. return voteStrings
  458. }
  459. func (voteSet *VoteSet) StringShort() string {
  460. if voteSet == nil {
  461. return "nil-VoteSet"
  462. }
  463. voteSet.mtx.Lock()
  464. defer voteSet.mtx.Unlock()
  465. _, _, frac := voteSet.sumTotalFrac()
  466. return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v(%v) %v %v}`,
  467. voteSet.height, voteSet.round, voteSet.type_, voteSet.maj23, frac, voteSet.votesBitArray, voteSet.peerMaj23s)
  468. }
  469. // return the power voted, the total, and the fraction
  470. func (voteSet *VoteSet) sumTotalFrac() (int64, int64, float64) {
  471. voted, total := voteSet.sum, voteSet.valSet.TotalVotingPower()
  472. fracVoted := float64(voted) / float64(total)
  473. return voted, total, fracVoted
  474. }
  475. //--------------------------------------------------------------------------------
  476. // Commit
  477. // MakeCommit constructs a Commit from the VoteSet.
  478. // Panics if the vote type is not PrecommitType or if
  479. // there's no +2/3 votes for a single block.
  480. func (voteSet *VoteSet) MakeCommit() *Commit {
  481. if voteSet.type_ != PrecommitType {
  482. panic("Cannot MakeCommit() unless VoteSet.Type is PrecommitType")
  483. }
  484. voteSet.mtx.Lock()
  485. defer voteSet.mtx.Unlock()
  486. // Make sure we have a 2/3 majority
  487. if voteSet.maj23 == nil {
  488. panic("Cannot MakeCommit() unless a blockhash has +2/3")
  489. }
  490. // For every validator, get the precommit
  491. commitSigs := make([]*CommitSig, len(voteSet.votes))
  492. for i, v := range voteSet.votes {
  493. commitSigs[i] = v.CommitSig()
  494. }
  495. return NewCommit(*voteSet.maj23, commitSigs)
  496. }
  497. //--------------------------------------------------------------------------------
  498. /*
  499. Votes for a particular block
  500. There are two ways a *blockVotes gets created for a blockKey.
  501. 1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false)
  502. 2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true)
  503. */
  504. type blockVotes struct {
  505. peerMaj23 bool // peer claims to have maj23
  506. bitArray *cmn.BitArray // valIndex -> hasVote?
  507. votes []*Vote // valIndex -> *Vote
  508. sum int64 // vote sum
  509. }
  510. func newBlockVotes(peerMaj23 bool, numValidators int) *blockVotes {
  511. return &blockVotes{
  512. peerMaj23: peerMaj23,
  513. bitArray: cmn.NewBitArray(numValidators),
  514. votes: make([]*Vote, numValidators),
  515. sum: 0,
  516. }
  517. }
  518. func (vs *blockVotes) addVerifiedVote(vote *Vote, votingPower int64) {
  519. valIndex := vote.ValidatorIndex
  520. if existing := vs.votes[valIndex]; existing == nil {
  521. vs.bitArray.SetIndex(valIndex, true)
  522. vs.votes[valIndex] = vote
  523. vs.sum += votingPower
  524. }
  525. }
  526. func (vs *blockVotes) getByIndex(index int) *Vote {
  527. if vs == nil {
  528. return nil
  529. }
  530. return vs.votes[index]
  531. }
  532. //--------------------------------------------------------------------------------
  533. // Common interface between *consensus.VoteSet and types.Commit
  534. type VoteSetReader interface {
  535. Height() int64
  536. Round() int
  537. Type() byte
  538. Size() int
  539. BitArray() *cmn.BitArray
  540. GetByIndex(int) *Vote
  541. IsCommit() bool
  542. }