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.

537 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
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. "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)",
  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) {
  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 // Nothing to do
  266. } else {
  267. return // TODO bad peer!
  268. }
  269. }
  270. voteSet.peerMaj23s[peerID] = blockID
  271. // Create .votesByBlock entry if needed.
  272. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  273. if ok {
  274. if votesByBlock.peerMaj23 {
  275. return // Nothing to do
  276. } else {
  277. votesByBlock.peerMaj23 = true
  278. // No need to copy votes, already there.
  279. }
  280. } else {
  281. votesByBlock = newBlockVotes(true, voteSet.valSet.Size())
  282. voteSet.votesByBlock[blockKey] = votesByBlock
  283. // No need to copy votes, no votes to copy over.
  284. }
  285. }
  286. func (voteSet *VoteSet) BitArray() *cmn.BitArray {
  287. if voteSet == nil {
  288. return nil
  289. }
  290. voteSet.mtx.Lock()
  291. defer voteSet.mtx.Unlock()
  292. return voteSet.votesBitArray.Copy()
  293. }
  294. func (voteSet *VoteSet) BitArrayByBlockID(blockID BlockID) *cmn.BitArray {
  295. if voteSet == nil {
  296. return nil
  297. }
  298. voteSet.mtx.Lock()
  299. defer voteSet.mtx.Unlock()
  300. votesByBlock, ok := voteSet.votesByBlock[blockID.Key()]
  301. if ok {
  302. return votesByBlock.bitArray.Copy()
  303. }
  304. return nil
  305. }
  306. // NOTE: if validator has conflicting votes, returns "canonical" vote
  307. func (voteSet *VoteSet) GetByIndex(valIndex int) *Vote {
  308. if voteSet == nil {
  309. return nil
  310. }
  311. voteSet.mtx.Lock()
  312. defer voteSet.mtx.Unlock()
  313. return voteSet.votes[valIndex]
  314. }
  315. func (voteSet *VoteSet) GetByAddress(address []byte) *Vote {
  316. if voteSet == nil {
  317. return nil
  318. }
  319. voteSet.mtx.Lock()
  320. defer voteSet.mtx.Unlock()
  321. valIndex, val := voteSet.valSet.GetByAddress(address)
  322. if val == nil {
  323. cmn.PanicSanity("GetByAddress(address) returned nil")
  324. }
  325. return voteSet.votes[valIndex]
  326. }
  327. func (voteSet *VoteSet) HasTwoThirdsMajority() bool {
  328. if voteSet == nil {
  329. return false
  330. }
  331. voteSet.mtx.Lock()
  332. defer voteSet.mtx.Unlock()
  333. return voteSet.maj23 != nil
  334. }
  335. func (voteSet *VoteSet) IsCommit() bool {
  336. if voteSet == nil {
  337. return false
  338. }
  339. if voteSet.type_ != VoteTypePrecommit {
  340. return false
  341. }
  342. voteSet.mtx.Lock()
  343. defer voteSet.mtx.Unlock()
  344. return voteSet.maj23 != nil
  345. }
  346. func (voteSet *VoteSet) HasTwoThirdsAny() bool {
  347. if voteSet == nil {
  348. return false
  349. }
  350. voteSet.mtx.Lock()
  351. defer voteSet.mtx.Unlock()
  352. return voteSet.sum > voteSet.valSet.TotalVotingPower()*2/3
  353. }
  354. func (voteSet *VoteSet) HasAll() bool {
  355. return voteSet.sum == voteSet.valSet.TotalVotingPower()
  356. }
  357. // Returns either a blockhash (or nil) that received +2/3 majority.
  358. // If there exists no such majority, returns (nil, PartSetHeader{}, false).
  359. func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool) {
  360. if voteSet == nil {
  361. return BlockID{}, false
  362. }
  363. voteSet.mtx.Lock()
  364. defer voteSet.mtx.Unlock()
  365. if voteSet.maj23 != nil {
  366. return *voteSet.maj23, true
  367. } else {
  368. return BlockID{}, false
  369. }
  370. }
  371. func (voteSet *VoteSet) String() string {
  372. if voteSet == nil {
  373. return "nil-VoteSet"
  374. }
  375. return voteSet.StringIndented("")
  376. }
  377. func (voteSet *VoteSet) StringIndented(indent string) string {
  378. voteStrings := make([]string, len(voteSet.votes))
  379. for i, vote := range voteSet.votes {
  380. if vote == nil {
  381. voteStrings[i] = "nil-Vote"
  382. } else {
  383. voteStrings[i] = vote.String()
  384. }
  385. }
  386. return fmt.Sprintf(`VoteSet{
  387. %s H:%v R:%v T:%v
  388. %s %v
  389. %s %v
  390. %s %v
  391. %s}`,
  392. indent, voteSet.height, voteSet.round, voteSet.type_,
  393. indent, strings.Join(voteStrings, "\n"+indent+" "),
  394. indent, voteSet.votesBitArray,
  395. indent, voteSet.peerMaj23s,
  396. indent)
  397. }
  398. func (voteSet *VoteSet) StringShort() string {
  399. if voteSet == nil {
  400. return "nil-VoteSet"
  401. }
  402. voteSet.mtx.Lock()
  403. defer voteSet.mtx.Unlock()
  404. return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v %v %v}`,
  405. voteSet.height, voteSet.round, voteSet.type_, voteSet.maj23, voteSet.votesBitArray, voteSet.peerMaj23s)
  406. }
  407. //--------------------------------------------------------------------------------
  408. // Commit
  409. func (voteSet *VoteSet) MakeCommit() *Commit {
  410. if voteSet.type_ != VoteTypePrecommit {
  411. cmn.PanicSanity("Cannot MakeCommit() unless VoteSet.Type is VoteTypePrecommit")
  412. }
  413. voteSet.mtx.Lock()
  414. defer voteSet.mtx.Unlock()
  415. // Make sure we have a 2/3 majority
  416. if voteSet.maj23 == nil {
  417. cmn.PanicSanity("Cannot MakeCommit() unless a blockhash has +2/3")
  418. }
  419. // For every validator, get the precommit
  420. votesCopy := make([]*Vote, len(voteSet.votes))
  421. copy(votesCopy, voteSet.votes)
  422. return &Commit{
  423. BlockID: *voteSet.maj23,
  424. Precommits: votesCopy,
  425. }
  426. }
  427. //--------------------------------------------------------------------------------
  428. /*
  429. Votes for a particular block
  430. There are two ways a *blockVotes gets created for a blockKey.
  431. 1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false)
  432. 2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true)
  433. */
  434. type blockVotes struct {
  435. peerMaj23 bool // peer claims to have maj23
  436. bitArray *cmn.BitArray // valIndex -> hasVote?
  437. votes []*Vote // valIndex -> *Vote
  438. sum int64 // vote sum
  439. }
  440. func newBlockVotes(peerMaj23 bool, numValidators int) *blockVotes {
  441. return &blockVotes{
  442. peerMaj23: peerMaj23,
  443. bitArray: cmn.NewBitArray(numValidators),
  444. votes: make([]*Vote, numValidators),
  445. sum: 0,
  446. }
  447. }
  448. func (vs *blockVotes) addVerifiedVote(vote *Vote, votingPower int64) {
  449. valIndex := vote.ValidatorIndex
  450. if existing := vs.votes[valIndex]; existing == nil {
  451. vs.bitArray.SetIndex(valIndex, true)
  452. vs.votes[valIndex] = vote
  453. vs.sum += votingPower
  454. }
  455. }
  456. func (vs *blockVotes) getByIndex(index int) *Vote {
  457. if vs == nil {
  458. return nil
  459. }
  460. return vs.votes[index]
  461. }
  462. //--------------------------------------------------------------------------------
  463. // Common interface between *consensus.VoteSet and types.Commit
  464. type VoteSetReader interface {
  465. Height() int64
  466. Round() int
  467. Type() byte
  468. Size() int
  469. BitArray() *cmn.BitArray
  470. GetByIndex(int) *Vote
  471. IsCommit() bool
  472. }