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.

539 lines
15 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
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
10 years ago
8 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. "github.com/tendermint/tendermint/p2p"
  9. cmn "github.com/tendermint/tmlibs/common"
  10. )
  11. /*
  12. VoteSet helps collect signatures from validators at each height+round for a
  13. predefined vote type.
  14. We need VoteSet to be able to keep track of conflicting votes when validators
  15. double-sign. Yet, we can't keep track of *all* the votes seen, as that could
  16. be a DoS attack vector.
  17. There are two storage areas for votes.
  18. 1. voteSet.votes
  19. 2. voteSet.votesByBlock
  20. `.votes` is the "canonical" list of votes. It always has at least one vote,
  21. if a vote from a validator had been seen at all. Usually it keeps track of
  22. the first vote seen, but when a 2/3 majority is found, votes for that get
  23. priority and are copied over from `.votesByBlock`.
  24. `.votesByBlock` keeps track of a list of votes for a particular block. There
  25. are two ways a &blockVotes{} gets created in `.votesByBlock`.
  26. 1. the first vote seen by a validator was for the particular block.
  27. 2. a peer claims to have seen 2/3 majority for the particular block.
  28. Since the first vote from a validator will always get added in `.votesByBlock`
  29. , all votes in `.votes` will have a corresponding entry in `.votesByBlock`.
  30. When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its
  31. votes are copied into `.votes`.
  32. All this is memory bounded because conflicting votes only get added if a peer
  33. told us to track that block, each peer only gets to tell us 1 such block, and,
  34. there's only a limited number of peers.
  35. NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64.
  36. */
  37. type VoteSet struct {
  38. chainID string
  39. height int64
  40. round int
  41. type_ byte
  42. mtx sync.Mutex
  43. valSet *ValidatorSet
  44. votesBitArray *cmn.BitArray
  45. votes []*Vote // Primary votes to share
  46. sum int64 // Sum of voting power for seen votes, discounting conflicts
  47. maj23 *BlockID // First 2/3 majority seen
  48. votesByBlock map[string]*blockVotes // string(blockHash|blockParts) -> blockVotes
  49. peerMaj23s map[p2p.ID]BlockID // Maj23 for each peer
  50. }
  51. // Constructs a new VoteSet struct used to accumulate votes for given height/round.
  52. func NewVoteSet(chainID string, height int64, round int, type_ byte, valSet *ValidatorSet) *VoteSet {
  53. if height == 0 {
  54. cmn.PanicSanity("Cannot make VoteSet for height == 0, doesn't make sense.")
  55. }
  56. return &VoteSet{
  57. chainID: chainID,
  58. height: height,
  59. round: round,
  60. type_: type_,
  61. valSet: valSet,
  62. votesBitArray: cmn.NewBitArray(valSet.Size()),
  63. votes: make([]*Vote, valSet.Size()),
  64. sum: 0,
  65. maj23: nil,
  66. votesByBlock: make(map[string]*blockVotes, valSet.Size()),
  67. peerMaj23s: make(map[p2p.ID]BlockID),
  68. }
  69. }
  70. func (voteSet *VoteSet) ChainID() string {
  71. return voteSet.chainID
  72. }
  73. func (voteSet *VoteSet) Height() int64 {
  74. if voteSet == nil {
  75. return 0
  76. } else {
  77. return voteSet.height
  78. }
  79. }
  80. func (voteSet *VoteSet) Round() int {
  81. if voteSet == nil {
  82. return -1
  83. } else {
  84. return voteSet.round
  85. }
  86. }
  87. func (voteSet *VoteSet) Type() byte {
  88. if voteSet == nil {
  89. return 0x00
  90. } else {
  91. return voteSet.type_
  92. }
  93. }
  94. func (voteSet *VoteSet) Size() int {
  95. if voteSet == nil {
  96. return 0
  97. } else {
  98. return voteSet.valSet.Size()
  99. }
  100. }
  101. // Returns added=true if vote is valid and new.
  102. // Otherwise returns err=ErrVote[
  103. // UnexpectedStep | InvalidIndex | InvalidAddress |
  104. // InvalidSignature | InvalidBlockHash | ConflictingVotes ]
  105. // Duplicate votes return added=false, err=nil.
  106. // Conflicting votes return added=*, err=ErrVoteConflictingVotes.
  107. // NOTE: vote should not be mutated after adding.
  108. // NOTE: VoteSet must not be nil
  109. // NOTE: Vote must not be nil
  110. func (voteSet *VoteSet) AddVote(vote *Vote) (added bool, err error) {
  111. if voteSet == nil {
  112. cmn.PanicSanity("AddVote() on nil VoteSet")
  113. }
  114. voteSet.mtx.Lock()
  115. defer voteSet.mtx.Unlock()
  116. return voteSet.addVote(vote)
  117. }
  118. // NOTE: Validates as much as possible before attempting to verify the signature.
  119. func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) {
  120. if vote == nil {
  121. return false, ErrVoteNil
  122. }
  123. valIndex := vote.ValidatorIndex
  124. valAddr := vote.ValidatorAddress
  125. blockKey := vote.BlockID.Key()
  126. // Ensure that validator index was set
  127. if valIndex < 0 {
  128. return false, errors.Wrap(ErrVoteInvalidValidatorIndex, "Index < 0")
  129. } else if len(valAddr) == 0 {
  130. return false, errors.Wrap(ErrVoteInvalidValidatorAddress, "Empty address")
  131. }
  132. // Make sure the step matches.
  133. if (vote.Height != voteSet.height) ||
  134. (vote.Round != voteSet.round) ||
  135. (vote.Type != voteSet.type_) {
  136. return false, errors.Wrapf(ErrVoteUnexpectedStep, "Got %d/%d/%d, expected %d/%d/%d",
  137. voteSet.height, voteSet.round, voteSet.type_,
  138. vote.Height, vote.Round, vote.Type)
  139. }
  140. // Ensure that signer is a validator.
  141. lookupAddr, val := voteSet.valSet.GetByIndex(valIndex)
  142. if val == nil {
  143. return false, errors.Wrapf(ErrVoteInvalidValidatorIndex,
  144. "Cannot find validator %d in valSet of size %d", valIndex, voteSet.valSet.Size())
  145. }
  146. // Ensure that the signer has the right address
  147. if !bytes.Equal(valAddr, lookupAddr) {
  148. return false, errors.Wrapf(ErrVoteInvalidValidatorAddress,
  149. "vote.ValidatorAddress (%X) does not match address (%X) for vote.ValidatorIndex (%d)\nEnsure the genesis file is correct across all validators.",
  150. valAddr, lookupAddr, valIndex)
  151. }
  152. // If we already know of this vote, return false.
  153. if existing, ok := voteSet.getVote(valIndex, blockKey); ok {
  154. if existing.Signature.Equals(vote.Signature) {
  155. return false, nil // duplicate
  156. } else {
  157. return false, errors.Wrapf(ErrVoteNonDeterministicSignature, "Existing vote: %v; New vote: %v", existing, vote)
  158. }
  159. }
  160. // Check signature.
  161. if err := vote.Verify(voteSet.chainID, val.PubKey); err != nil {
  162. return false, errors.Wrapf(err, "Failed to verify vote with ChainID %s and PubKey %s", voteSet.chainID, val.PubKey)
  163. }
  164. // Add vote and get conflicting vote if any
  165. added, conflicting := voteSet.addVerifiedVote(vote, blockKey, val.VotingPower)
  166. if conflicting != nil {
  167. return added, NewConflictingVoteError(val, conflicting, vote)
  168. } else {
  169. if !added {
  170. cmn.PanicSanity("Expected to add non-conflicting vote")
  171. }
  172. return added, nil
  173. }
  174. }
  175. // Returns (vote, true) if vote exists for valIndex and blockKey
  176. func (voteSet *VoteSet) getVote(valIndex int, blockKey string) (vote *Vote, ok bool) {
  177. if existing := voteSet.votes[valIndex]; existing != nil && existing.BlockID.Key() == blockKey {
  178. return existing, true
  179. }
  180. if existing := voteSet.votesByBlock[blockKey].getByIndex(valIndex); existing != nil {
  181. return existing, true
  182. }
  183. return nil, false
  184. }
  185. // Assumes signature is valid.
  186. // If conflicting vote exists, returns it.
  187. func (voteSet *VoteSet) addVerifiedVote(vote *Vote, blockKey string, votingPower int64) (added bool, conflicting *Vote) {
  188. valIndex := vote.ValidatorIndex
  189. // Already exists in voteSet.votes?
  190. if existing := voteSet.votes[valIndex]; existing != nil {
  191. if existing.BlockID.Equals(vote.BlockID) {
  192. cmn.PanicSanity("addVerifiedVote does not expect duplicate votes")
  193. } else {
  194. conflicting = existing
  195. }
  196. // Replace vote if blockKey matches voteSet.maj23.
  197. if voteSet.maj23 != nil && voteSet.maj23.Key() == blockKey {
  198. voteSet.votes[valIndex] = vote
  199. voteSet.votesBitArray.SetIndex(valIndex, true)
  200. }
  201. // Otherwise don't add it to voteSet.votes
  202. } else {
  203. // Add to voteSet.votes and incr .sum
  204. voteSet.votes[valIndex] = vote
  205. voteSet.votesBitArray.SetIndex(valIndex, true)
  206. voteSet.sum += votingPower
  207. }
  208. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  209. if ok {
  210. if conflicting != nil && !votesByBlock.peerMaj23 {
  211. // There's a conflict and no peer claims that this block is special.
  212. return false, conflicting
  213. }
  214. // We'll add the vote in a bit.
  215. } else {
  216. // .votesByBlock doesn't exist...
  217. if conflicting != nil {
  218. // ... and there's a conflicting vote.
  219. // We're not even tracking this blockKey, so just forget it.
  220. return false, conflicting
  221. } else {
  222. // ... and there's no conflicting vote.
  223. // Start tracking this blockKey
  224. votesByBlock = newBlockVotes(false, voteSet.valSet.Size())
  225. voteSet.votesByBlock[blockKey] = votesByBlock
  226. // We'll add the vote in a bit.
  227. }
  228. }
  229. // Before adding to votesByBlock, see if we'll exceed quorum
  230. origSum := votesByBlock.sum
  231. quorum := voteSet.valSet.TotalVotingPower()*2/3 + 1
  232. // Add vote to votesByBlock
  233. votesByBlock.addVerifiedVote(vote, votingPower)
  234. // If we just crossed the quorum threshold and have 2/3 majority...
  235. if origSum < quorum && quorum <= votesByBlock.sum {
  236. // Only consider the first quorum reached
  237. if voteSet.maj23 == nil {
  238. maj23BlockID := vote.BlockID
  239. voteSet.maj23 = &maj23BlockID
  240. // And also copy votes over to voteSet.votes
  241. for i, vote := range votesByBlock.votes {
  242. if vote != nil {
  243. voteSet.votes[i] = vote
  244. }
  245. }
  246. }
  247. }
  248. return true, conflicting
  249. }
  250. // If a peer claims that it has 2/3 majority for given blockKey, call this.
  251. // NOTE: if there are too many peers, or too much peer churn,
  252. // this can cause memory issues.
  253. // TODO: implement ability to remove peers too
  254. // NOTE: VoteSet must not be nil
  255. func (voteSet *VoteSet) SetPeerMaj23(peerID p2p.ID, blockID BlockID) error {
  256. if voteSet == nil {
  257. cmn.PanicSanity("SetPeerMaj23() on nil VoteSet")
  258. }
  259. voteSet.mtx.Lock()
  260. defer voteSet.mtx.Unlock()
  261. blockKey := blockID.Key()
  262. // Make sure peer hasn't already told us something.
  263. if existing, ok := voteSet.peerMaj23s[peerID]; ok {
  264. if existing.Equals(blockID) {
  265. return nil // Nothing to do
  266. } else {
  267. return fmt.Errorf("SetPeerMaj23: Received conflicting blockID from peer %v. Got %v, expected %v",
  268. peerID, blockID, existing)
  269. }
  270. }
  271. voteSet.peerMaj23s[peerID] = blockID
  272. // Create .votesByBlock entry if needed.
  273. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  274. if ok {
  275. if votesByBlock.peerMaj23 {
  276. return nil // Nothing to do
  277. } else {
  278. votesByBlock.peerMaj23 = true
  279. // No need to copy votes, already there.
  280. }
  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. cmn.PanicSanity("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_ != VoteTypePrecommit {
  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. return voteSet.sum == voteSet.valSet.TotalVotingPower()
  358. }
  359. // Returns either a blockhash (or nil) that received +2/3 majority.
  360. // If there exists no such majority, returns (nil, PartSetHeader{}, false).
  361. func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool) {
  362. if voteSet == nil {
  363. return BlockID{}, false
  364. }
  365. voteSet.mtx.Lock()
  366. defer voteSet.mtx.Unlock()
  367. if voteSet.maj23 != nil {
  368. return *voteSet.maj23, true
  369. } else {
  370. return BlockID{}, false
  371. }
  372. }
  373. func (voteSet *VoteSet) String() string {
  374. if voteSet == nil {
  375. return "nil-VoteSet"
  376. }
  377. return voteSet.StringIndented("")
  378. }
  379. func (voteSet *VoteSet) StringIndented(indent string) string {
  380. voteStrings := make([]string, len(voteSet.votes))
  381. for i, vote := range voteSet.votes {
  382. if vote == nil {
  383. voteStrings[i] = "nil-Vote"
  384. } else {
  385. voteStrings[i] = vote.String()
  386. }
  387. }
  388. return fmt.Sprintf(`VoteSet{
  389. %s H:%v R:%v T:%v
  390. %s %v
  391. %s %v
  392. %s %v
  393. %s}`,
  394. indent, voteSet.height, voteSet.round, voteSet.type_,
  395. indent, strings.Join(voteStrings, "\n"+indent+" "),
  396. indent, voteSet.votesBitArray,
  397. indent, voteSet.peerMaj23s,
  398. indent)
  399. }
  400. func (voteSet *VoteSet) StringShort() string {
  401. if voteSet == nil {
  402. return "nil-VoteSet"
  403. }
  404. voteSet.mtx.Lock()
  405. defer voteSet.mtx.Unlock()
  406. return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v %v %v}`,
  407. voteSet.height, voteSet.round, voteSet.type_, voteSet.maj23, voteSet.votesBitArray, voteSet.peerMaj23s)
  408. }
  409. //--------------------------------------------------------------------------------
  410. // Commit
  411. func (voteSet *VoteSet) MakeCommit() *Commit {
  412. if voteSet.type_ != VoteTypePrecommit {
  413. cmn.PanicSanity("Cannot MakeCommit() unless VoteSet.Type is VoteTypePrecommit")
  414. }
  415. voteSet.mtx.Lock()
  416. defer voteSet.mtx.Unlock()
  417. // Make sure we have a 2/3 majority
  418. if voteSet.maj23 == nil {
  419. cmn.PanicSanity("Cannot MakeCommit() unless a blockhash has +2/3")
  420. }
  421. // For every validator, get the precommit
  422. votesCopy := make([]*Vote, len(voteSet.votes))
  423. copy(votesCopy, voteSet.votes)
  424. return &Commit{
  425. BlockID: *voteSet.maj23,
  426. Precommits: votesCopy,
  427. }
  428. }
  429. //--------------------------------------------------------------------------------
  430. /*
  431. Votes for a particular block
  432. There are two ways a *blockVotes gets created for a blockKey.
  433. 1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false)
  434. 2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true)
  435. */
  436. type blockVotes struct {
  437. peerMaj23 bool // peer claims to have maj23
  438. bitArray *cmn.BitArray // valIndex -> hasVote?
  439. votes []*Vote // valIndex -> *Vote
  440. sum int64 // vote sum
  441. }
  442. func newBlockVotes(peerMaj23 bool, numValidators int) *blockVotes {
  443. return &blockVotes{
  444. peerMaj23: peerMaj23,
  445. bitArray: cmn.NewBitArray(numValidators),
  446. votes: make([]*Vote, numValidators),
  447. sum: 0,
  448. }
  449. }
  450. func (vs *blockVotes) addVerifiedVote(vote *Vote, votingPower int64) {
  451. valIndex := vote.ValidatorIndex
  452. if existing := vs.votes[valIndex]; existing == nil {
  453. vs.bitArray.SetIndex(valIndex, true)
  454. vs.votes[valIndex] = vote
  455. vs.sum += votingPower
  456. }
  457. }
  458. func (vs *blockVotes) getByIndex(index int) *Vote {
  459. if vs == nil {
  460. return nil
  461. }
  462. return vs.votes[index]
  463. }
  464. //--------------------------------------------------------------------------------
  465. // Common interface between *consensus.VoteSet and types.Commit
  466. type VoteSetReader interface {
  467. Height() int64
  468. Round() int
  469. Type() byte
  470. Size() int
  471. BitArray() *cmn.BitArray
  472. GetByIndex(int) *Vote
  473. IsCommit() bool
  474. }