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.

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