github.com/project-88388/tendermint-v0.34.14-terra.2@v1.0.0/types/vote_set.go (about) 1 package types 2 3 import ( 4 "bytes" 5 "fmt" 6 "strings" 7 8 "github.com/tendermint/tendermint/libs/bits" 9 tmjson "github.com/tendermint/tendermint/libs/json" 10 tmsync "github.com/tendermint/tendermint/libs/sync" 11 tmproto "github.com/tendermint/tendermint/proto/tendermint/types" 12 ) 13 14 const ( 15 // MaxVotesCount is the maximum number of votes in a set. Used in ValidateBasic funcs for 16 // protection against DOS attacks. Note this implies a corresponding equal limit to 17 // the number of validators. 18 MaxVotesCount = 10000 19 ) 20 21 // UNSTABLE 22 // XXX: duplicate of p2p.ID to avoid dependence between packages. 23 // Perhaps we can have a minimal types package containing this (and other things?) 24 // that both `types` and `p2p` import ? 25 type P2PID string 26 27 /* 28 VoteSet helps collect signatures from validators at each height+round for a 29 predefined vote type. 30 31 We need VoteSet to be able to keep track of conflicting votes when validators 32 double-sign. Yet, we can't keep track of *all* the votes seen, as that could 33 be a DoS attack vector. 34 35 There are two storage areas for votes. 36 1. voteSet.votes 37 2. voteSet.votesByBlock 38 39 `.votes` is the "canonical" list of votes. It always has at least one vote, 40 if a vote from a validator had been seen at all. Usually it keeps track of 41 the first vote seen, but when a 2/3 majority is found, votes for that get 42 priority and are copied over from `.votesByBlock`. 43 44 `.votesByBlock` keeps track of a list of votes for a particular block. There 45 are two ways a &blockVotes{} gets created in `.votesByBlock`. 46 1. the first vote seen by a validator was for the particular block. 47 2. a peer claims to have seen 2/3 majority for the particular block. 48 49 Since the first vote from a validator will always get added in `.votesByBlock` 50 , all votes in `.votes` will have a corresponding entry in `.votesByBlock`. 51 52 When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its 53 votes are copied into `.votes`. 54 55 All this is memory bounded because conflicting votes only get added if a peer 56 told us to track that block, each peer only gets to tell us 1 such block, and, 57 there's only a limited number of peers. 58 59 NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64. 60 */ 61 type VoteSet struct { 62 chainID string 63 height int64 64 round int32 65 signedMsgType tmproto.SignedMsgType 66 valSet *ValidatorSet 67 68 mtx tmsync.Mutex 69 votesBitArray *bits.BitArray 70 votes []*Vote // Primary votes to share 71 sum int64 // Sum of voting power for seen votes, discounting conflicts 72 maj23 *BlockID // First 2/3 majority seen 73 votesByBlock map[string]*blockVotes // string(blockHash|blockParts) -> blockVotes 74 peerMaj23s map[P2PID]BlockID // Maj23 for each peer 75 } 76 77 // Constructs a new VoteSet struct used to accumulate votes for given height/round. 78 func NewVoteSet(chainID string, height int64, round int32, 79 signedMsgType tmproto.SignedMsgType, valSet *ValidatorSet) *VoteSet { 80 if height == 0 { 81 panic("Cannot make VoteSet for height == 0, doesn't make sense.") 82 } 83 return &VoteSet{ 84 chainID: chainID, 85 height: height, 86 round: round, 87 signedMsgType: signedMsgType, 88 valSet: valSet, 89 votesBitArray: bits.NewBitArray(valSet.Size()), 90 votes: make([]*Vote, valSet.Size()), 91 sum: 0, 92 maj23: nil, 93 votesByBlock: make(map[string]*blockVotes, valSet.Size()), 94 peerMaj23s: make(map[P2PID]BlockID), 95 } 96 } 97 98 func (voteSet *VoteSet) ChainID() string { 99 return voteSet.chainID 100 } 101 102 // Implements VoteSetReader. 103 func (voteSet *VoteSet) GetHeight() int64 { 104 if voteSet == nil { 105 return 0 106 } 107 return voteSet.height 108 } 109 110 // Implements VoteSetReader. 111 func (voteSet *VoteSet) GetRound() int32 { 112 if voteSet == nil { 113 return -1 114 } 115 return voteSet.round 116 } 117 118 // Implements VoteSetReader. 119 func (voteSet *VoteSet) Type() byte { 120 if voteSet == nil { 121 return 0x00 122 } 123 return byte(voteSet.signedMsgType) 124 } 125 126 // Implements VoteSetReader. 127 func (voteSet *VoteSet) Size() int { 128 if voteSet == nil { 129 return 0 130 } 131 return voteSet.valSet.Size() 132 } 133 134 // Returns added=true if vote is valid and new. 135 // Otherwise returns err=ErrVote[ 136 // UnexpectedStep | InvalidIndex | InvalidAddress | 137 // InvalidSignature | InvalidBlockHash | ConflictingVotes ] 138 // Duplicate votes return added=false, err=nil. 139 // Conflicting votes return added=*, err=ErrVoteConflictingVotes. 140 // NOTE: vote should not be mutated after adding. 141 // NOTE: VoteSet must not be nil 142 // NOTE: Vote must not be nil 143 func (voteSet *VoteSet) AddVote(vote *Vote) (added bool, err error) { 144 if voteSet == nil { 145 panic("AddVote() on nil VoteSet") 146 } 147 voteSet.mtx.Lock() 148 defer voteSet.mtx.Unlock() 149 150 return voteSet.addVote(vote) 151 } 152 153 // NOTE: Validates as much as possible before attempting to verify the signature. 154 func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) { 155 if vote == nil { 156 return false, ErrVoteNil 157 } 158 valIndex := vote.ValidatorIndex 159 valAddr := vote.ValidatorAddress 160 blockKey := vote.BlockID.Key() 161 162 // Ensure that validator index was set 163 if valIndex < 0 { 164 return false, fmt.Errorf("index < 0: %w", ErrVoteInvalidValidatorIndex) 165 } else if len(valAddr) == 0 { 166 return false, fmt.Errorf("empty address: %w", ErrVoteInvalidValidatorAddress) 167 } 168 169 // Make sure the step matches. 170 if (vote.Height != voteSet.height) || 171 (vote.Round != voteSet.round) || 172 (vote.Type != voteSet.signedMsgType) { 173 return false, fmt.Errorf("expected %d/%d/%d, but got %d/%d/%d: %w", 174 voteSet.height, voteSet.round, voteSet.signedMsgType, 175 vote.Height, vote.Round, vote.Type, ErrVoteUnexpectedStep) 176 } 177 178 // Ensure that signer is a validator. 179 lookupAddr, val := voteSet.valSet.GetByIndex(valIndex) 180 if val == nil { 181 return false, fmt.Errorf( 182 "cannot find validator %d in valSet of size %d: %w", 183 valIndex, voteSet.valSet.Size(), ErrVoteInvalidValidatorIndex) 184 } 185 186 // Ensure that the signer has the right address. 187 if !bytes.Equal(valAddr, lookupAddr) { 188 return false, fmt.Errorf( 189 "vote.ValidatorAddress (%X) does not match address (%X) for vote.ValidatorIndex (%d)\n"+ 190 "Ensure the genesis file is correct across all validators: %w", 191 valAddr, lookupAddr, valIndex, ErrVoteInvalidValidatorAddress) 192 } 193 194 // If we already know of this vote, return false. 195 if existing, ok := voteSet.getVote(valIndex, blockKey); ok { 196 if bytes.Equal(existing.Signature, vote.Signature) { 197 return false, nil // duplicate 198 } 199 return false, fmt.Errorf("existing vote: %v; new vote: %v: %w", existing, vote, ErrVoteNonDeterministicSignature) 200 } 201 202 // Check signature. 203 if err := vote.Verify(voteSet.chainID, val.PubKey); err != nil { 204 return false, fmt.Errorf("failed to verify vote with ChainID %s and PubKey %s: %w", voteSet.chainID, val.PubKey, err) 205 } 206 207 // Add vote and get conflicting vote if any. 208 added, conflicting := voteSet.addVerifiedVote(vote, blockKey, val.VotingPower) 209 if conflicting != nil { 210 return added, NewConflictingVoteError(conflicting, vote) 211 } 212 if !added { 213 panic("Expected to add non-conflicting vote") 214 } 215 return added, nil 216 } 217 218 // Returns (vote, true) if vote exists for valIndex and blockKey. 219 func (voteSet *VoteSet) getVote(valIndex int32, blockKey string) (vote *Vote, ok bool) { 220 if existing := voteSet.votes[valIndex]; existing != nil && existing.BlockID.Key() == blockKey { 221 return existing, true 222 } 223 if existing := voteSet.votesByBlock[blockKey].getByIndex(valIndex); existing != nil { 224 return existing, true 225 } 226 return nil, false 227 } 228 229 // Assumes signature is valid. 230 // If conflicting vote exists, returns it. 231 func (voteSet *VoteSet) addVerifiedVote( 232 vote *Vote, 233 blockKey string, 234 votingPower int64, 235 ) (added bool, conflicting *Vote) { 236 valIndex := vote.ValidatorIndex 237 238 // Already exists in voteSet.votes? 239 if existing := voteSet.votes[valIndex]; existing != nil { 240 if existing.BlockID.Equals(vote.BlockID) { 241 panic("addVerifiedVote does not expect duplicate votes") 242 } else { 243 conflicting = existing 244 } 245 // Replace vote if blockKey matches voteSet.maj23. 246 if voteSet.maj23 != nil && voteSet.maj23.Key() == blockKey { 247 voteSet.votes[valIndex] = vote 248 voteSet.votesBitArray.SetIndex(int(valIndex), true) 249 } 250 // Otherwise don't add it to voteSet.votes 251 } else { 252 // Add to voteSet.votes and incr .sum 253 voteSet.votes[valIndex] = vote 254 voteSet.votesBitArray.SetIndex(int(valIndex), true) 255 voteSet.sum += votingPower 256 } 257 258 votesByBlock, ok := voteSet.votesByBlock[blockKey] 259 if ok { 260 if conflicting != nil && !votesByBlock.peerMaj23 { 261 // There's a conflict and no peer claims that this block is special. 262 return false, conflicting 263 } 264 // We'll add the vote in a bit. 265 } else { 266 // .votesByBlock doesn't exist... 267 if conflicting != nil { 268 // ... and there's a conflicting vote. 269 // We're not even tracking this blockKey, so just forget it. 270 return false, conflicting 271 } 272 // ... and there's no conflicting vote. 273 // Start tracking this blockKey 274 votesByBlock = newBlockVotes(false, voteSet.valSet.Size()) 275 voteSet.votesByBlock[blockKey] = votesByBlock 276 // We'll add the vote in a bit. 277 } 278 279 // Before adding to votesByBlock, see if we'll exceed quorum 280 origSum := votesByBlock.sum 281 quorum := voteSet.valSet.TotalVotingPower()*2/3 + 1 282 283 // Add vote to votesByBlock 284 votesByBlock.addVerifiedVote(vote, votingPower) 285 286 // If we just crossed the quorum threshold and have 2/3 majority... 287 if origSum < quorum && quorum <= votesByBlock.sum { 288 // Only consider the first quorum reached 289 if voteSet.maj23 == nil { 290 maj23BlockID := vote.BlockID 291 voteSet.maj23 = &maj23BlockID 292 // And also copy votes over to voteSet.votes 293 for i, vote := range votesByBlock.votes { 294 if vote != nil { 295 voteSet.votes[i] = vote 296 } 297 } 298 } 299 } 300 301 return true, conflicting 302 } 303 304 // If a peer claims that it has 2/3 majority for given blockKey, call this. 305 // NOTE: if there are too many peers, or too much peer churn, 306 // this can cause memory issues. 307 // TODO: implement ability to remove peers too 308 // NOTE: VoteSet must not be nil 309 func (voteSet *VoteSet) SetPeerMaj23(peerID P2PID, blockID BlockID) error { 310 if voteSet == nil { 311 panic("SetPeerMaj23() on nil VoteSet") 312 } 313 voteSet.mtx.Lock() 314 defer voteSet.mtx.Unlock() 315 316 blockKey := blockID.Key() 317 318 // Make sure peer hasn't already told us something. 319 if existing, ok := voteSet.peerMaj23s[peerID]; ok { 320 if existing.Equals(blockID) { 321 return nil // Nothing to do 322 } 323 return fmt.Errorf("setPeerMaj23: Received conflicting blockID from peer %v. Got %v, expected %v", 324 peerID, blockID, existing) 325 } 326 voteSet.peerMaj23s[peerID] = blockID 327 328 // Create .votesByBlock entry if needed. 329 votesByBlock, ok := voteSet.votesByBlock[blockKey] 330 if ok { 331 if votesByBlock.peerMaj23 { 332 return nil // Nothing to do 333 } 334 votesByBlock.peerMaj23 = true 335 // No need to copy votes, already there. 336 } else { 337 votesByBlock = newBlockVotes(true, voteSet.valSet.Size()) 338 voteSet.votesByBlock[blockKey] = votesByBlock 339 // No need to copy votes, no votes to copy over. 340 } 341 return nil 342 } 343 344 // Implements VoteSetReader. 345 func (voteSet *VoteSet) BitArray() *bits.BitArray { 346 if voteSet == nil { 347 return nil 348 } 349 voteSet.mtx.Lock() 350 defer voteSet.mtx.Unlock() 351 return voteSet.votesBitArray.Copy() 352 } 353 354 func (voteSet *VoteSet) BitArrayByBlockID(blockID BlockID) *bits.BitArray { 355 if voteSet == nil { 356 return nil 357 } 358 voteSet.mtx.Lock() 359 defer voteSet.mtx.Unlock() 360 votesByBlock, ok := voteSet.votesByBlock[blockID.Key()] 361 if ok { 362 return votesByBlock.bitArray.Copy() 363 } 364 return nil 365 } 366 367 // NOTE: if validator has conflicting votes, returns "canonical" vote 368 // Implements VoteSetReader. 369 func (voteSet *VoteSet) GetByIndex(valIndex int32) *Vote { 370 if voteSet == nil { 371 return nil 372 } 373 voteSet.mtx.Lock() 374 defer voteSet.mtx.Unlock() 375 return voteSet.votes[valIndex] 376 } 377 378 func (voteSet *VoteSet) GetByAddress(address []byte) *Vote { 379 if voteSet == nil { 380 return nil 381 } 382 voteSet.mtx.Lock() 383 defer voteSet.mtx.Unlock() 384 valIndex, val := voteSet.valSet.GetByAddress(address) 385 if val == nil { 386 panic("GetByAddress(address) returned nil") 387 } 388 return voteSet.votes[valIndex] 389 } 390 391 func (voteSet *VoteSet) HasTwoThirdsMajority() bool { 392 if voteSet == nil { 393 return false 394 } 395 voteSet.mtx.Lock() 396 defer voteSet.mtx.Unlock() 397 return voteSet.maj23 != nil 398 } 399 400 // Implements VoteSetReader. 401 func (voteSet *VoteSet) IsCommit() bool { 402 if voteSet == nil { 403 return false 404 } 405 if voteSet.signedMsgType != tmproto.PrecommitType { 406 return false 407 } 408 voteSet.mtx.Lock() 409 defer voteSet.mtx.Unlock() 410 return voteSet.maj23 != nil 411 } 412 413 func (voteSet *VoteSet) HasTwoThirdsAny() bool { 414 if voteSet == nil { 415 return false 416 } 417 voteSet.mtx.Lock() 418 defer voteSet.mtx.Unlock() 419 return voteSet.sum > voteSet.valSet.TotalVotingPower()*2/3 420 } 421 422 func (voteSet *VoteSet) HasAll() bool { 423 voteSet.mtx.Lock() 424 defer voteSet.mtx.Unlock() 425 return voteSet.sum == voteSet.valSet.TotalVotingPower() 426 } 427 428 // If there was a +2/3 majority for blockID, return blockID and true. 429 // Else, return the empty BlockID{} and false. 430 func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool) { 431 if voteSet == nil { 432 return BlockID{}, false 433 } 434 voteSet.mtx.Lock() 435 defer voteSet.mtx.Unlock() 436 if voteSet.maj23 != nil { 437 return *voteSet.maj23, true 438 } 439 return BlockID{}, false 440 } 441 442 //-------------------------------------------------------------------------------- 443 // Strings and JSON 444 445 const nilVoteSetString = "nil-VoteSet" 446 447 // String returns a string representation of VoteSet. 448 // 449 // See StringIndented. 450 func (voteSet *VoteSet) String() string { 451 if voteSet == nil { 452 return nilVoteSetString 453 } 454 return voteSet.StringIndented("") 455 } 456 457 // StringIndented returns an indented String. 458 // 459 // Height Round Type 460 // Votes 461 // Votes bit array 462 // 2/3+ majority 463 // 464 // See Vote#String. 465 func (voteSet *VoteSet) StringIndented(indent string) string { 466 voteSet.mtx.Lock() 467 defer voteSet.mtx.Unlock() 468 469 voteStrings := make([]string, len(voteSet.votes)) 470 for i, vote := range voteSet.votes { 471 if vote == nil { 472 voteStrings[i] = nilVoteStr 473 } else { 474 voteStrings[i] = vote.String() 475 } 476 } 477 return fmt.Sprintf(`VoteSet{ 478 %s H:%v R:%v T:%v 479 %s %v 480 %s %v 481 %s %v 482 %s}`, 483 indent, voteSet.height, voteSet.round, voteSet.signedMsgType, 484 indent, strings.Join(voteStrings, "\n"+indent+" "), 485 indent, voteSet.votesBitArray, 486 indent, voteSet.peerMaj23s, 487 indent) 488 } 489 490 // Marshal the VoteSet to JSON. Same as String(), just in JSON, 491 // and without the height/round/signedMsgType (since its already included in the votes). 492 func (voteSet *VoteSet) MarshalJSON() ([]byte, error) { 493 voteSet.mtx.Lock() 494 defer voteSet.mtx.Unlock() 495 return tmjson.Marshal(VoteSetJSON{ 496 voteSet.voteStrings(), 497 voteSet.bitArrayString(), 498 voteSet.peerMaj23s, 499 }) 500 } 501 502 // More human readable JSON of the vote set 503 // NOTE: insufficient for unmarshalling from (compressed votes) 504 // TODO: make the peerMaj23s nicer to read (eg just the block hash) 505 type VoteSetJSON struct { 506 Votes []string `json:"votes"` 507 VotesBitArray string `json:"votes_bit_array"` 508 PeerMaj23s map[P2PID]BlockID `json:"peer_maj_23s"` 509 } 510 511 // Return the bit-array of votes including 512 // the fraction of power that has voted like: 513 // "BA{29:xx__x__x_x___x__x_______xxx__} 856/1304 = 0.66" 514 func (voteSet *VoteSet) BitArrayString() string { 515 voteSet.mtx.Lock() 516 defer voteSet.mtx.Unlock() 517 return voteSet.bitArrayString() 518 } 519 520 func (voteSet *VoteSet) bitArrayString() string { 521 bAString := voteSet.votesBitArray.String() 522 voted, total, fracVoted := voteSet.sumTotalFrac() 523 return fmt.Sprintf("%s %d/%d = %.2f", bAString, voted, total, fracVoted) 524 } 525 526 // Returns a list of votes compressed to more readable strings. 527 func (voteSet *VoteSet) VoteStrings() []string { 528 voteSet.mtx.Lock() 529 defer voteSet.mtx.Unlock() 530 return voteSet.voteStrings() 531 } 532 533 func (voteSet *VoteSet) voteStrings() []string { 534 voteStrings := make([]string, len(voteSet.votes)) 535 for i, vote := range voteSet.votes { 536 if vote == nil { 537 voteStrings[i] = nilVoteStr 538 } else { 539 voteStrings[i] = vote.String() 540 } 541 } 542 return voteStrings 543 } 544 545 // StringShort returns a short representation of VoteSet. 546 // 547 // 1. height 548 // 2. round 549 // 3. signed msg type 550 // 4. first 2/3+ majority 551 // 5. fraction of voted power 552 // 6. votes bit array 553 // 7. 2/3+ majority for each peer 554 func (voteSet *VoteSet) StringShort() string { 555 if voteSet == nil { 556 return nilVoteSetString 557 } 558 voteSet.mtx.Lock() 559 defer voteSet.mtx.Unlock() 560 _, _, frac := voteSet.sumTotalFrac() 561 return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v(%v) %v %v}`, 562 voteSet.height, voteSet.round, voteSet.signedMsgType, voteSet.maj23, frac, voteSet.votesBitArray, voteSet.peerMaj23s) 563 } 564 565 // LogString produces a logging suitable string representation of the 566 // vote set. 567 func (voteSet *VoteSet) LogString() string { 568 if voteSet == nil { 569 return nilVoteSetString 570 } 571 voteSet.mtx.Lock() 572 defer voteSet.mtx.Unlock() 573 voted, total, frac := voteSet.sumTotalFrac() 574 575 return fmt.Sprintf("Votes:%d/%d(%.3f)", voted, total, frac) 576 } 577 578 // return the power voted, the total, and the fraction 579 func (voteSet *VoteSet) sumTotalFrac() (int64, int64, float64) { 580 voted, total := voteSet.sum, voteSet.valSet.TotalVotingPower() 581 fracVoted := float64(voted) / float64(total) 582 return voted, total, fracVoted 583 } 584 585 //-------------------------------------------------------------------------------- 586 // Commit 587 588 // MakeCommit constructs a Commit from the VoteSet. It only includes precommits 589 // for the block, which has 2/3+ majority, and nil. 590 // 591 // Panics if the vote type is not PrecommitType or if there's no +2/3 votes for 592 // a single block. 593 func (voteSet *VoteSet) MakeCommit() *Commit { 594 if voteSet.signedMsgType != tmproto.PrecommitType { 595 panic("Cannot MakeCommit() unless VoteSet.Type is PrecommitType") 596 } 597 voteSet.mtx.Lock() 598 defer voteSet.mtx.Unlock() 599 600 // Make sure we have a 2/3 majority 601 if voteSet.maj23 == nil { 602 panic("Cannot MakeCommit() unless a blockhash has +2/3") 603 } 604 605 // For every validator, get the precommit 606 commitSigs := make([]CommitSig, len(voteSet.votes)) 607 for i, v := range voteSet.votes { 608 commitSig := v.CommitSig() 609 // if block ID exists but doesn't match, exclude sig 610 if commitSig.ForBlock() && !v.BlockID.Equals(*voteSet.maj23) { 611 commitSig = NewCommitSigAbsent() 612 } 613 commitSigs[i] = commitSig 614 } 615 616 return NewCommit(voteSet.GetHeight(), voteSet.GetRound(), *voteSet.maj23, commitSigs) 617 } 618 619 //-------------------------------------------------------------------------------- 620 621 /* 622 Votes for a particular block 623 There are two ways a *blockVotes gets created for a blockKey. 624 1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false) 625 2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true) 626 */ 627 type blockVotes struct { 628 peerMaj23 bool // peer claims to have maj23 629 bitArray *bits.BitArray // valIndex -> hasVote? 630 votes []*Vote // valIndex -> *Vote 631 sum int64 // vote sum 632 } 633 634 func newBlockVotes(peerMaj23 bool, numValidators int) *blockVotes { 635 return &blockVotes{ 636 peerMaj23: peerMaj23, 637 bitArray: bits.NewBitArray(numValidators), 638 votes: make([]*Vote, numValidators), 639 sum: 0, 640 } 641 } 642 643 func (vs *blockVotes) addVerifiedVote(vote *Vote, votingPower int64) { 644 valIndex := vote.ValidatorIndex 645 if existing := vs.votes[valIndex]; existing == nil { 646 vs.bitArray.SetIndex(int(valIndex), true) 647 vs.votes[valIndex] = vote 648 vs.sum += votingPower 649 } 650 } 651 652 func (vs *blockVotes) getByIndex(index int32) *Vote { 653 if vs == nil { 654 return nil 655 } 656 return vs.votes[index] 657 } 658 659 //-------------------------------------------------------------------------------- 660 661 // Common interface between *consensus.VoteSet and types.Commit 662 type VoteSetReader interface { 663 GetHeight() int64 664 GetRound() int32 665 Type() byte 666 Size() int 667 BitArray() *bits.BitArray 668 GetByIndex(int32) *Vote 669 IsCommit() bool 670 }