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.

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