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.

527 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
10 years ago
10 years ago
10 years ago
10 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/tendermint/go-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 *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. 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: 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. func (voteSet *VoteSet) AddVote(vote *Vote) (added bool, err error) {
  108. if voteSet == nil {
  109. PanicSanity("AddVote() on nil VoteSet")
  110. }
  111. voteSet.mtx.Lock()
  112. defer voteSet.mtx.Unlock()
  113. return voteSet.addVote(vote)
  114. }
  115. // NOTE: Validates as much as possible before attempting to verify the signature.
  116. func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) {
  117. valIndex := vote.ValidatorIndex
  118. valAddr := vote.ValidatorAddress
  119. blockKey := vote.BlockID.Key()
  120. // Ensure that validator index was set
  121. if valIndex < 0 || len(valAddr) == 0 {
  122. panic("Validator index or address was not set in vote.")
  123. }
  124. // Make sure the step matches.
  125. if (vote.Height != voteSet.height) ||
  126. (vote.Round != voteSet.round) ||
  127. (vote.Type != voteSet.type_) {
  128. return false, ErrVoteUnexpectedStep
  129. }
  130. // Ensure that signer is a validator.
  131. lookupAddr, val := voteSet.valSet.GetByIndex(valIndex)
  132. if val == nil {
  133. return false, ErrVoteInvalidValidatorIndex
  134. }
  135. // Ensure that the signer has the right address
  136. if !bytes.Equal(valAddr, lookupAddr) {
  137. return false, ErrVoteInvalidValidatorAddress
  138. }
  139. // If we already know of this vote, return false.
  140. if existing, ok := voteSet.getVote(valIndex, blockKey); ok {
  141. if existing.Signature.Equals(vote.Signature) {
  142. return false, nil // duplicate
  143. } else {
  144. return false, ErrVoteInvalidSignature // NOTE: assumes deterministic signatures
  145. }
  146. }
  147. // Check signature.
  148. if !val.PubKey.VerifyBytes(SignBytes(voteSet.chainID, vote), vote.Signature) {
  149. // Bad signature.
  150. return false, ErrVoteInvalidSignature
  151. }
  152. // Add vote and get conflicting vote if any
  153. added, conflicting := voteSet.addVerifiedVote(vote, blockKey, val.VotingPower)
  154. if conflicting != nil {
  155. return added, &ErrVoteConflictingVotes{
  156. VoteA: conflicting,
  157. VoteB: vote,
  158. }
  159. } else {
  160. if !added {
  161. PanicSanity("Expected to add non-conflicting vote")
  162. }
  163. return added, nil
  164. }
  165. }
  166. // Returns (vote, true) if vote exists for valIndex and blockKey
  167. func (voteSet *VoteSet) getVote(valIndex int, blockKey string) (vote *Vote, ok bool) {
  168. if existing := voteSet.votes[valIndex]; existing != nil && existing.BlockID.Key() == blockKey {
  169. return existing, true
  170. }
  171. if existing := voteSet.votesByBlock[blockKey].getByIndex(valIndex); existing != nil {
  172. return existing, true
  173. }
  174. return nil, false
  175. }
  176. // Assumes signature is valid.
  177. // If conflicting vote exists, returns it.
  178. func (voteSet *VoteSet) addVerifiedVote(vote *Vote, blockKey string, votingPower int64) (added bool, conflicting *Vote) {
  179. valIndex := vote.ValidatorIndex
  180. // Already exists in voteSet.votes?
  181. if existing := voteSet.votes[valIndex]; existing != nil {
  182. if existing.BlockID.Equals(vote.BlockID) {
  183. PanicSanity("addVerifiedVote does not expect duplicate votes")
  184. } else {
  185. conflicting = existing
  186. }
  187. // Replace vote if blockKey matches voteSet.maj23.
  188. if voteSet.maj23 != nil && voteSet.maj23.Key() == blockKey {
  189. voteSet.votes[valIndex] = vote
  190. voteSet.votesBitArray.SetIndex(valIndex, true)
  191. }
  192. // Otherwise don't add it to voteSet.votes
  193. } else {
  194. // Add to voteSet.votes and incr .sum
  195. voteSet.votes[valIndex] = vote
  196. voteSet.votesBitArray.SetIndex(valIndex, true)
  197. voteSet.sum += votingPower
  198. }
  199. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  200. if ok {
  201. if conflicting != nil && !votesByBlock.peerMaj23 {
  202. // There's a conflict and no peer claims that this block is special.
  203. return false, conflicting
  204. }
  205. // We'll add the vote in a bit.
  206. } else {
  207. // .votesByBlock doesn't exist...
  208. if conflicting != nil {
  209. // ... and there's a conflicting vote.
  210. // We're not even tracking this blockKey, so just forget it.
  211. return false, conflicting
  212. } else {
  213. // ... and there's no conflicting vote.
  214. // Start tracking this blockKey
  215. votesByBlock = newBlockVotes(false, voteSet.valSet.Size())
  216. voteSet.votesByBlock[blockKey] = votesByBlock
  217. // We'll add the vote in a bit.
  218. }
  219. }
  220. // Before adding to votesByBlock, see if we'll exceed quorum
  221. origSum := votesByBlock.sum
  222. quorum := voteSet.valSet.TotalVotingPower()*2/3 + 1
  223. // Add vote to votesByBlock
  224. votesByBlock.addVerifiedVote(vote, votingPower)
  225. // If we just crossed the quorum threshold and have 2/3 majority...
  226. if origSum < quorum && quorum <= votesByBlock.sum {
  227. // Only consider the first quorum reached
  228. if voteSet.maj23 == nil {
  229. maj23BlockID := vote.BlockID
  230. voteSet.maj23 = &maj23BlockID
  231. // And also copy votes over to voteSet.votes
  232. for i, vote := range votesByBlock.votes {
  233. if vote != nil {
  234. voteSet.votes[i] = vote
  235. }
  236. }
  237. }
  238. }
  239. return true, conflicting
  240. }
  241. // If a peer claims that it has 2/3 majority for given blockKey, call this.
  242. // NOTE: if there are too many peers, or too much peer churn,
  243. // this can cause memory issues.
  244. // TODO: implement ability to remove peers too
  245. // NOTE: VoteSet must not be nil
  246. func (voteSet *VoteSet) SetPeerMaj23(peerID string, blockID BlockID) {
  247. if voteSet == nil {
  248. PanicSanity("SetPeerMaj23() on nil VoteSet")
  249. }
  250. voteSet.mtx.Lock()
  251. defer voteSet.mtx.Unlock()
  252. blockKey := blockID.Key()
  253. // Make sure peer hasn't already told us something.
  254. if existing, ok := voteSet.peerMaj23s[peerID]; ok {
  255. if existing.Equals(blockID) {
  256. return // Nothing to do
  257. } else {
  258. return // TODO bad peer!
  259. }
  260. }
  261. voteSet.peerMaj23s[peerID] = blockID
  262. // Create .votesByBlock entry if needed.
  263. votesByBlock, ok := voteSet.votesByBlock[blockKey]
  264. if ok {
  265. if votesByBlock.peerMaj23 {
  266. return // Nothing to do
  267. } else {
  268. votesByBlock.peerMaj23 = true
  269. // No need to copy votes, already there.
  270. }
  271. } else {
  272. votesByBlock = newBlockVotes(true, voteSet.valSet.Size())
  273. voteSet.votesByBlock[blockKey] = votesByBlock
  274. // No need to copy votes, no votes to copy over.
  275. }
  276. }
  277. func (voteSet *VoteSet) BitArray() *BitArray {
  278. if voteSet == nil {
  279. return nil
  280. }
  281. voteSet.mtx.Lock()
  282. defer voteSet.mtx.Unlock()
  283. return voteSet.votesBitArray.Copy()
  284. }
  285. func (voteSet *VoteSet) BitArrayByBlockID(blockID BlockID) *BitArray {
  286. if voteSet == nil {
  287. return nil
  288. }
  289. voteSet.mtx.Lock()
  290. defer voteSet.mtx.Unlock()
  291. votesByBlock, ok := voteSet.votesByBlock[blockID.Key()]
  292. if ok {
  293. return votesByBlock.bitArray.Copy()
  294. }
  295. return nil
  296. }
  297. // NOTE: if validator has conflicting votes, returns "canonical" vote
  298. func (voteSet *VoteSet) GetByIndex(valIndex int) *Vote {
  299. if voteSet == nil {
  300. return nil
  301. }
  302. voteSet.mtx.Lock()
  303. defer voteSet.mtx.Unlock()
  304. return voteSet.votes[valIndex]
  305. }
  306. func (voteSet *VoteSet) GetByAddress(address []byte) *Vote {
  307. if voteSet == nil {
  308. return nil
  309. }
  310. voteSet.mtx.Lock()
  311. defer voteSet.mtx.Unlock()
  312. valIndex, val := voteSet.valSet.GetByAddress(address)
  313. if val == nil {
  314. PanicSanity("GetByAddress(address) returned nil")
  315. }
  316. return voteSet.votes[valIndex]
  317. }
  318. func (voteSet *VoteSet) HasTwoThirdsMajority() bool {
  319. if voteSet == nil {
  320. return false
  321. }
  322. voteSet.mtx.Lock()
  323. defer voteSet.mtx.Unlock()
  324. return voteSet.maj23 != nil
  325. }
  326. func (voteSet *VoteSet) IsCommit() bool {
  327. if voteSet == nil {
  328. return false
  329. }
  330. if voteSet.type_ != VoteTypePrecommit {
  331. return false
  332. }
  333. voteSet.mtx.Lock()
  334. defer voteSet.mtx.Unlock()
  335. return voteSet.maj23 != nil
  336. }
  337. func (voteSet *VoteSet) HasTwoThirdsAny() bool {
  338. if voteSet == nil {
  339. return false
  340. }
  341. voteSet.mtx.Lock()
  342. defer voteSet.mtx.Unlock()
  343. return voteSet.sum > voteSet.valSet.TotalVotingPower()*2/3
  344. }
  345. func (voteSet *VoteSet) HasAll() bool {
  346. return voteSet.sum == voteSet.valSet.TotalVotingPower()
  347. }
  348. // Returns either a blockhash (or nil) that received +2/3 majority.
  349. // If there exists no such majority, returns (nil, PartSetHeader{}, false).
  350. func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool) {
  351. if voteSet == nil {
  352. return BlockID{}, false
  353. }
  354. voteSet.mtx.Lock()
  355. defer voteSet.mtx.Unlock()
  356. if voteSet.maj23 != nil {
  357. return *voteSet.maj23, true
  358. } else {
  359. return BlockID{}, false
  360. }
  361. }
  362. func (voteSet *VoteSet) String() string {
  363. if voteSet == nil {
  364. return "nil-VoteSet"
  365. }
  366. return voteSet.StringIndented("")
  367. }
  368. func (voteSet *VoteSet) StringIndented(indent string) string {
  369. voteStrings := make([]string, len(voteSet.votes))
  370. for i, vote := range voteSet.votes {
  371. if vote == nil {
  372. voteStrings[i] = "nil-Vote"
  373. } else {
  374. voteStrings[i] = vote.String()
  375. }
  376. }
  377. return fmt.Sprintf(`VoteSet{
  378. %s H:%v R:%v T:%v
  379. %s %v
  380. %s %v
  381. %s %v
  382. %s}`,
  383. indent, voteSet.height, voteSet.round, voteSet.type_,
  384. indent, strings.Join(voteStrings, "\n"+indent+" "),
  385. indent, voteSet.votesBitArray,
  386. indent, voteSet.peerMaj23s,
  387. indent)
  388. }
  389. func (voteSet *VoteSet) StringShort() string {
  390. if voteSet == nil {
  391. return "nil-VoteSet"
  392. }
  393. voteSet.mtx.Lock()
  394. defer voteSet.mtx.Unlock()
  395. return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v %v %v}`,
  396. voteSet.height, voteSet.round, voteSet.type_, voteSet.maj23, voteSet.votesBitArray, voteSet.peerMaj23s)
  397. }
  398. //--------------------------------------------------------------------------------
  399. // Commit
  400. func (voteSet *VoteSet) MakeCommit() *Commit {
  401. if voteSet.type_ != VoteTypePrecommit {
  402. PanicSanity("Cannot MakeCommit() unless VoteSet.Type is VoteTypePrecommit")
  403. }
  404. voteSet.mtx.Lock()
  405. defer voteSet.mtx.Unlock()
  406. // Make sure we have a 2/3 majority
  407. if voteSet.maj23 == nil {
  408. PanicSanity("Cannot MakeCommit() unless a blockhash has +2/3")
  409. }
  410. // For every validator, get the precommit
  411. votesCopy := make([]*Vote, len(voteSet.votes))
  412. copy(votesCopy, voteSet.votes)
  413. return &Commit{
  414. BlockID: *voteSet.maj23,
  415. Precommits: votesCopy,
  416. }
  417. }
  418. //--------------------------------------------------------------------------------
  419. /*
  420. Votes for a particular block
  421. There are two ways a *blockVotes gets created for a blockKey.
  422. 1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false)
  423. 2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true)
  424. */
  425. type blockVotes struct {
  426. peerMaj23 bool // peer claims to have maj23
  427. bitArray *BitArray // valIndex -> hasVote?
  428. votes []*Vote // valIndex -> *Vote
  429. sum int64 // vote sum
  430. }
  431. func newBlockVotes(peerMaj23 bool, numValidators int) *blockVotes {
  432. return &blockVotes{
  433. peerMaj23: peerMaj23,
  434. bitArray: NewBitArray(numValidators),
  435. votes: make([]*Vote, numValidators),
  436. sum: 0,
  437. }
  438. }
  439. func (vs *blockVotes) addVerifiedVote(vote *Vote, votingPower int64) {
  440. valIndex := vote.ValidatorIndex
  441. if existing := vs.votes[valIndex]; existing == nil {
  442. vs.bitArray.SetIndex(valIndex, true)
  443. vs.votes[valIndex] = vote
  444. vs.sum += votingPower
  445. }
  446. }
  447. func (vs *blockVotes) getByIndex(index int) *Vote {
  448. if vs == nil {
  449. return nil
  450. }
  451. return vs.votes[index]
  452. }
  453. //--------------------------------------------------------------------------------
  454. // Common interface between *consensus.VoteSet and types.Commit
  455. type VoteSetReader interface {
  456. Height() int
  457. Round() int
  458. Type() byte
  459. Size() int
  460. BitArray() *BitArray
  461. GetByIndex(int) *Vote
  462. IsCommit() bool
  463. }