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.

611 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
10 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)\nEnsure the genesis file is correct across all validators.",
  155. valAddr, lookupAddr, valIndex)
  156. }
  157. // If we already know of this vote, return false.
  158. if existing, ok := voteSet.getVote(valIndex, blockKey); ok {
  159. if bytes.Equal(existing.Signature, vote.Signature) {
  160. return false, nil // duplicate
  161. }
  162. return false, errors.Wrapf(ErrVoteNonDeterministicSignature, "Existing vote: %v; New vote: %v", existing, vote)
  163. }
  164. // Check signature.
  165. if err := vote.Verify(voteSet.chainID, val.PubKey); err != nil {
  166. return false, errors.Wrapf(err, "Failed to verify vote with ChainID %s and PubKey %s", voteSet.chainID, val.PubKey)
  167. }
  168. // Add vote and get conflicting vote if any.
  169. added, conflicting := voteSet.addVerifiedVote(vote, blockKey, val.VotingPower)
  170. if conflicting != nil {
  171. return added, NewConflictingVoteError(val, conflicting, vote)
  172. }
  173. if !added {
  174. panic("Expected to add non-conflicting vote")
  175. }
  176. return added, nil
  177. }
  178. // Returns (vote, true) if vote exists for valIndex and blockKey.
  179. func (voteSet *VoteSet) getVote(valIndex int, blockKey string) (vote *Vote, ok bool) {
  180. if existing := voteSet.votes[valIndex]; existing != nil && existing.BlockID.Key() == blockKey {
  181. return existing, true
  182. }
  183. if existing := voteSet.votesByBlock[blockKey].getByIndex(valIndex); existing != nil {
  184. return existing, true
  185. }
  186. return nil, false
  187. }
  188. // Assumes signature is valid.
  189. // If conflicting vote exists, returns it.
  190. func (voteSet *VoteSet) addVerifiedVote(vote *Vote, blockKey string, votingPower int64) (added bool, conflicting *Vote) {
  191. valIndex := vote.ValidatorIndex
  192. // Already exists in voteSet.votes?
  193. if existing := voteSet.votes[valIndex]; existing != nil {
  194. if existing.BlockID.Equals(vote.BlockID) {
  195. panic("addVerifiedVote does not expect duplicate votes")
  196. } else {
  197. conflicting = existing
  198. }
  199. // Replace vote if blockKey matches voteSet.maj23.
  200. if voteSet.maj23 != nil && voteSet.maj23.Key() == blockKey {
  201. voteSet.votes[valIndex] = vote
  202. voteSet.votesBitArray.SetIndex(valIndex, true)
  203. }
  204. // Otherwise don't add it to voteSet.votes
  205. } else {
  206. // Add to voteSet.votes and incr .sum
  207. voteSet.votes[valIndex] = vote
  208. voteSet.votesBitArray.SetIndex(valIndex, true)
  209. voteSet.sum += votingPower
  210. }
  211. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  212. if ok {
  213. if conflicting != nil && !votesByBlock.peerMaj23 {
  214. // There's a conflict and no peer claims that this block is special.
  215. return false, conflicting
  216. }
  217. // We'll add the vote in a bit.
  218. } else {
  219. // .votesByBlock doesn't exist...
  220. if conflicting != nil {
  221. // ... and there's a conflicting vote.
  222. // We're not even tracking this blockKey, so just forget it.
  223. return false, conflicting
  224. }
  225. // ... and there's no conflicting vote.
  226. // Start tracking this blockKey
  227. votesByBlock = newBlockVotes(false, voteSet.valSet.Size())
  228. voteSet.votesByBlock[blockKey] = votesByBlock
  229. // We'll add the vote in a bit.
  230. }
  231. // Before adding to votesByBlock, see if we'll exceed quorum
  232. origSum := votesByBlock.sum
  233. quorum := voteSet.valSet.TotalVotingPower()*2/3 + 1
  234. // Add vote to votesByBlock
  235. votesByBlock.addVerifiedVote(vote, votingPower)
  236. // If we just crossed the quorum threshold and have 2/3 majority...
  237. if origSum < quorum && quorum <= votesByBlock.sum {
  238. // Only consider the first quorum reached
  239. if voteSet.maj23 == nil {
  240. maj23BlockID := vote.BlockID
  241. voteSet.maj23 = &maj23BlockID
  242. // And also copy votes over to voteSet.votes
  243. for i, vote := range votesByBlock.votes {
  244. if vote != nil {
  245. voteSet.votes[i] = vote
  246. }
  247. }
  248. }
  249. }
  250. return true, conflicting
  251. }
  252. // If a peer claims that it has 2/3 majority for given blockKey, call this.
  253. // NOTE: if there are too many peers, or too much peer churn,
  254. // this can cause memory issues.
  255. // TODO: implement ability to remove peers too
  256. // NOTE: VoteSet must not be nil
  257. func (voteSet *VoteSet) SetPeerMaj23(peerID P2PID, blockID BlockID) error {
  258. if voteSet == nil {
  259. panic("SetPeerMaj23() on nil VoteSet")
  260. }
  261. voteSet.mtx.Lock()
  262. defer voteSet.mtx.Unlock()
  263. blockKey := blockID.Key()
  264. // Make sure peer hasn't already told us something.
  265. if existing, ok := voteSet.peerMaj23s[peerID]; ok {
  266. if existing.Equals(blockID) {
  267. return nil // Nothing to do
  268. }
  269. return fmt.Errorf("SetPeerMaj23: Received conflicting blockID from peer %v. Got %v, expected %v",
  270. peerID, blockID, existing)
  271. }
  272. voteSet.peerMaj23s[peerID] = blockID
  273. // Create .votesByBlock entry if needed.
  274. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  275. if ok {
  276. if votesByBlock.peerMaj23 {
  277. return nil // Nothing to do
  278. }
  279. votesByBlock.peerMaj23 = true
  280. // No need to copy votes, already there.
  281. } else {
  282. votesByBlock = newBlockVotes(true, voteSet.valSet.Size())
  283. voteSet.votesByBlock[blockKey] = votesByBlock
  284. // No need to copy votes, no votes to copy over.
  285. }
  286. return nil
  287. }
  288. func (voteSet *VoteSet) BitArray() *cmn.BitArray {
  289. if voteSet == nil {
  290. return nil
  291. }
  292. voteSet.mtx.Lock()
  293. defer voteSet.mtx.Unlock()
  294. return voteSet.votesBitArray.Copy()
  295. }
  296. func (voteSet *VoteSet) BitArrayByBlockID(blockID BlockID) *cmn.BitArray {
  297. if voteSet == nil {
  298. return nil
  299. }
  300. voteSet.mtx.Lock()
  301. defer voteSet.mtx.Unlock()
  302. votesByBlock, ok := voteSet.votesByBlock[blockID.Key()]
  303. if ok {
  304. return votesByBlock.bitArray.Copy()
  305. }
  306. return nil
  307. }
  308. // NOTE: if validator has conflicting votes, returns "canonical" vote
  309. func (voteSet *VoteSet) GetByIndex(valIndex int) *Vote {
  310. if voteSet == nil {
  311. return nil
  312. }
  313. voteSet.mtx.Lock()
  314. defer voteSet.mtx.Unlock()
  315. return voteSet.votes[valIndex]
  316. }
  317. func (voteSet *VoteSet) GetByAddress(address []byte) *Vote {
  318. if voteSet == nil {
  319. return nil
  320. }
  321. voteSet.mtx.Lock()
  322. defer voteSet.mtx.Unlock()
  323. valIndex, val := voteSet.valSet.GetByAddress(address)
  324. if val == nil {
  325. panic("GetByAddress(address) returned nil")
  326. }
  327. return voteSet.votes[valIndex]
  328. }
  329. func (voteSet *VoteSet) HasTwoThirdsMajority() bool {
  330. if voteSet == nil {
  331. return false
  332. }
  333. voteSet.mtx.Lock()
  334. defer voteSet.mtx.Unlock()
  335. return voteSet.maj23 != nil
  336. }
  337. func (voteSet *VoteSet) IsCommit() bool {
  338. if voteSet == nil {
  339. return false
  340. }
  341. if voteSet.type_ != PrecommitType {
  342. return false
  343. }
  344. voteSet.mtx.Lock()
  345. defer voteSet.mtx.Unlock()
  346. return voteSet.maj23 != nil
  347. }
  348. func (voteSet *VoteSet) HasTwoThirdsAny() bool {
  349. if voteSet == nil {
  350. return false
  351. }
  352. voteSet.mtx.Lock()
  353. defer voteSet.mtx.Unlock()
  354. return voteSet.sum > voteSet.valSet.TotalVotingPower()*2/3
  355. }
  356. func (voteSet *VoteSet) HasAll() bool {
  357. voteSet.mtx.Lock()
  358. defer voteSet.mtx.Unlock()
  359. return voteSet.sum == voteSet.valSet.TotalVotingPower()
  360. }
  361. // If there was a +2/3 majority for blockID, return blockID and true.
  362. // Else, return the empty BlockID{} and false.
  363. func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool) {
  364. if voteSet == nil {
  365. return BlockID{}, false
  366. }
  367. voteSet.mtx.Lock()
  368. defer voteSet.mtx.Unlock()
  369. if voteSet.maj23 != nil {
  370. return *voteSet.maj23, true
  371. }
  372. return BlockID{}, false
  373. }
  374. //--------------------------------------------------------------------------------
  375. // Strings and JSON
  376. func (voteSet *VoteSet) String() string {
  377. if voteSet == nil {
  378. return "nil-VoteSet"
  379. }
  380. return voteSet.StringIndented("")
  381. }
  382. func (voteSet *VoteSet) StringIndented(indent string) string {
  383. voteSet.mtx.Lock()
  384. defer voteSet.mtx.Unlock()
  385. voteStrings := make([]string, len(voteSet.votes))
  386. for i, vote := range voteSet.votes {
  387. if vote == nil {
  388. voteStrings[i] = nilVoteStr
  389. } else {
  390. voteStrings[i] = vote.String()
  391. }
  392. }
  393. return fmt.Sprintf(`VoteSet{
  394. %s H:%v R:%v T:%v
  395. %s %v
  396. %s %v
  397. %s %v
  398. %s}`,
  399. indent, voteSet.height, voteSet.round, voteSet.type_,
  400. indent, strings.Join(voteStrings, "\n"+indent+" "),
  401. indent, voteSet.votesBitArray,
  402. indent, voteSet.peerMaj23s,
  403. indent)
  404. }
  405. // Marshal the VoteSet to JSON. Same as String(), just in JSON,
  406. // and without the height/round/type_ (since its already included in the votes).
  407. func (voteSet *VoteSet) MarshalJSON() ([]byte, error) {
  408. voteSet.mtx.Lock()
  409. defer voteSet.mtx.Unlock()
  410. return cdc.MarshalJSON(VoteSetJSON{
  411. voteSet.voteStrings(),
  412. voteSet.bitArrayString(),
  413. voteSet.peerMaj23s,
  414. })
  415. }
  416. // More human readable JSON of the vote set
  417. // NOTE: insufficient for unmarshalling from (compressed votes)
  418. // TODO: make the peerMaj23s nicer to read (eg just the block hash)
  419. type VoteSetJSON struct {
  420. Votes []string `json:"votes"`
  421. VotesBitArray string `json:"votes_bit_array"`
  422. PeerMaj23s map[P2PID]BlockID `json:"peer_maj_23s"`
  423. }
  424. // Return the bit-array of votes including
  425. // the fraction of power that has voted like:
  426. // "BA{29:xx__x__x_x___x__x_______xxx__} 856/1304 = 0.66"
  427. func (voteSet *VoteSet) BitArrayString() string {
  428. voteSet.mtx.Lock()
  429. defer voteSet.mtx.Unlock()
  430. return voteSet.bitArrayString()
  431. }
  432. func (voteSet *VoteSet) bitArrayString() string {
  433. bAString := voteSet.votesBitArray.String()
  434. voted, total, fracVoted := voteSet.sumTotalFrac()
  435. return fmt.Sprintf("%s %d/%d = %.2f", bAString, voted, total, fracVoted)
  436. }
  437. // Returns a list of votes compressed to more readable strings.
  438. func (voteSet *VoteSet) VoteStrings() []string {
  439. voteSet.mtx.Lock()
  440. defer voteSet.mtx.Unlock()
  441. return voteSet.voteStrings()
  442. }
  443. func (voteSet *VoteSet) voteStrings() []string {
  444. voteStrings := make([]string, len(voteSet.votes))
  445. for i, vote := range voteSet.votes {
  446. if vote == nil {
  447. voteStrings[i] = nilVoteStr
  448. } else {
  449. voteStrings[i] = vote.String()
  450. }
  451. }
  452. return voteStrings
  453. }
  454. func (voteSet *VoteSet) StringShort() string {
  455. if voteSet == nil {
  456. return "nil-VoteSet"
  457. }
  458. voteSet.mtx.Lock()
  459. defer voteSet.mtx.Unlock()
  460. _, _, frac := voteSet.sumTotalFrac()
  461. return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v(%v) %v %v}`,
  462. voteSet.height, voteSet.round, voteSet.type_, voteSet.maj23, frac, voteSet.votesBitArray, voteSet.peerMaj23s)
  463. }
  464. // return the power voted, the total, and the fraction
  465. func (voteSet *VoteSet) sumTotalFrac() (int64, int64, float64) {
  466. voted, total := voteSet.sum, voteSet.valSet.TotalVotingPower()
  467. fracVoted := float64(voted) / float64(total)
  468. return voted, total, fracVoted
  469. }
  470. //--------------------------------------------------------------------------------
  471. // Commit
  472. // MakeCommit constructs a Commit from the VoteSet.
  473. // Panics if the vote type is not PrecommitType or if
  474. // there's no +2/3 votes for a single block.
  475. func (voteSet *VoteSet) MakeCommit() *Commit {
  476. if voteSet.type_ != PrecommitType {
  477. panic("Cannot MakeCommit() unless VoteSet.Type is PrecommitType")
  478. }
  479. voteSet.mtx.Lock()
  480. defer voteSet.mtx.Unlock()
  481. // Make sure we have a 2/3 majority
  482. if voteSet.maj23 == nil {
  483. panic("Cannot MakeCommit() unless a blockhash has +2/3")
  484. }
  485. // For every validator, get the precommit
  486. commitSigs := make([]*CommitSig, len(voteSet.votes))
  487. for i, v := range voteSet.votes {
  488. commitSigs[i] = v.CommitSig()
  489. }
  490. return NewCommit(*voteSet.maj23, commitSigs)
  491. }
  492. //--------------------------------------------------------------------------------
  493. /*
  494. Votes for a particular block
  495. There are two ways a *blockVotes gets created for a blockKey.
  496. 1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false)
  497. 2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true)
  498. */
  499. type blockVotes struct {
  500. peerMaj23 bool // peer claims to have maj23
  501. bitArray *cmn.BitArray // valIndex -> hasVote?
  502. votes []*Vote // valIndex -> *Vote
  503. sum int64 // vote sum
  504. }
  505. func newBlockVotes(peerMaj23 bool, numValidators int) *blockVotes {
  506. return &blockVotes{
  507. peerMaj23: peerMaj23,
  508. bitArray: cmn.NewBitArray(numValidators),
  509. votes: make([]*Vote, numValidators),
  510. sum: 0,
  511. }
  512. }
  513. func (vs *blockVotes) addVerifiedVote(vote *Vote, votingPower int64) {
  514. valIndex := vote.ValidatorIndex
  515. if existing := vs.votes[valIndex]; existing == nil {
  516. vs.bitArray.SetIndex(valIndex, true)
  517. vs.votes[valIndex] = vote
  518. vs.sum += votingPower
  519. }
  520. }
  521. func (vs *blockVotes) getByIndex(index int) *Vote {
  522. if vs == nil {
  523. return nil
  524. }
  525. return vs.votes[index]
  526. }
  527. //--------------------------------------------------------------------------------
  528. // Common interface between *consensus.VoteSet and types.Commit
  529. type VoteSetReader interface {
  530. Height() int64
  531. Round() int
  532. Type() byte
  533. Size() int
  534. BitArray() *cmn.BitArray
  535. GetByIndex(int) *Vote
  536. IsCommit() bool
  537. }