github.com/adoriasoft/tendermint@v0.34.0-dev1.0.20200722151356-96d84601a75a/types/evidence.go (about) 1 package types 2 3 import ( 4 "bytes" 5 "errors" 6 "fmt" 7 "strings" 8 "time" 9 10 "github.com/tendermint/tendermint/crypto" 11 cryptoenc "github.com/tendermint/tendermint/crypto/encoding" 12 "github.com/tendermint/tendermint/crypto/merkle" 13 "github.com/tendermint/tendermint/crypto/tmhash" 14 tmjson "github.com/tendermint/tendermint/libs/json" 15 tmmath "github.com/tendermint/tendermint/libs/math" 16 tmrand "github.com/tendermint/tendermint/libs/rand" 17 tmproto "github.com/tendermint/tendermint/proto/tendermint/types" 18 ) 19 20 const ( 21 // MaxEvidenceBytes is a maximum size of any evidence (including amino overhead). 22 MaxEvidenceBytes int64 = 444 23 24 // An invalid field in the header from LunaticValidatorEvidence. 25 // Must be a function of the ABCI application state. 26 ValidatorsHashField = "ValidatorsHash" 27 NextValidatorsHashField = "NextValidatorsHash" 28 ConsensusHashField = "ConsensusHash" 29 AppHashField = "AppHash" 30 LastResultsHashField = "LastResultsHash" 31 ) 32 33 // ErrEvidenceInvalid wraps a piece of evidence and the error denoting how or why it is invalid. 34 type ErrEvidenceInvalid struct { 35 Evidence Evidence 36 ErrorValue error 37 } 38 39 // NewErrEvidenceInvalid returns a new EvidenceInvalid with the given err. 40 func NewErrEvidenceInvalid(ev Evidence, err error) *ErrEvidenceInvalid { 41 return &ErrEvidenceInvalid{ev, err} 42 } 43 44 // Error returns a string representation of the error. 45 func (err *ErrEvidenceInvalid) Error() string { 46 return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.ErrorValue, err.Evidence) 47 } 48 49 // ErrEvidenceOverflow is for when there is too much evidence in a block. 50 type ErrEvidenceOverflow struct { 51 MaxNum int 52 GotNum int 53 } 54 55 // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max. 56 func NewErrEvidenceOverflow(max, got int) *ErrEvidenceOverflow { 57 return &ErrEvidenceOverflow{max, got} 58 } 59 60 // Error returns a string representation of the error. 61 func (err *ErrEvidenceOverflow) Error() string { 62 return fmt.Sprintf("Too much evidence: Max %d, got %d", err.MaxNum, err.GotNum) 63 } 64 65 //------------------------------------------- 66 67 // Evidence represents any provable malicious activity by a validator. 68 type Evidence interface { 69 Height() int64 // height of the equivocation 70 Time() time.Time // time of the equivocation 71 Address() []byte // address of the equivocating validator 72 Bytes() []byte // bytes which comprise the evidence 73 Hash() []byte // hash of the evidence 74 Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence 75 Equal(Evidence) bool // check equality of evidence 76 77 ValidateBasic() error 78 String() string 79 } 80 81 type CompositeEvidence interface { 82 VerifyComposite(committedHeader *Header, valSet *ValidatorSet) error 83 Split(committedHeader *Header, valSet *ValidatorSet, valToLastHeight map[string]int64) []Evidence 84 } 85 86 func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error) { 87 if evidence == nil { 88 return nil, errors.New("nil evidence") 89 } 90 91 switch evi := evidence.(type) { 92 case *DuplicateVoteEvidence: 93 pbevi := evi.ToProto() 94 tp := &tmproto.Evidence{ 95 Sum: &tmproto.Evidence_DuplicateVoteEvidence{ 96 DuplicateVoteEvidence: pbevi, 97 }, 98 } 99 return tp, nil 100 101 case *ConflictingHeadersEvidence: 102 pbevi := evi.ToProto() 103 104 tp := &tmproto.Evidence{ 105 Sum: &tmproto.Evidence_ConflictingHeadersEvidence{ 106 ConflictingHeadersEvidence: pbevi, 107 }, 108 } 109 110 return tp, nil 111 case *LunaticValidatorEvidence: 112 pbevi := evi.ToProto() 113 114 tp := &tmproto.Evidence{ 115 Sum: &tmproto.Evidence_LunaticValidatorEvidence{ 116 LunaticValidatorEvidence: pbevi, 117 }, 118 } 119 120 return tp, nil 121 122 case *PhantomValidatorEvidence: 123 pbevi := evi.ToProto() 124 125 tp := &tmproto.Evidence{ 126 Sum: &tmproto.Evidence_PhantomValidatorEvidence{ 127 PhantomValidatorEvidence: pbevi, 128 }, 129 } 130 131 return tp, nil 132 133 case *PotentialAmnesiaEvidence: 134 pbevi := evi.ToProto() 135 136 tp := &tmproto.Evidence{ 137 Sum: &tmproto.Evidence_PotentialAmnesiaEvidence{ 138 PotentialAmnesiaEvidence: pbevi, 139 }, 140 } 141 142 return tp, nil 143 144 case *AmnesiaEvidence: 145 aepb := evi.ToProto() 146 147 tp := &tmproto.Evidence{ 148 Sum: &tmproto.Evidence_AmnesiaEvidence{ 149 AmnesiaEvidence: aepb, 150 }, 151 } 152 153 return tp, nil 154 default: 155 return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi) 156 } 157 } 158 159 func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error) { 160 if evidence == nil { 161 return nil, errors.New("nil evidence") 162 } 163 164 switch evi := evidence.Sum.(type) { 165 case *tmproto.Evidence_DuplicateVoteEvidence: 166 return DuplicateVoteEvidenceFromProto(evi.DuplicateVoteEvidence) 167 case *tmproto.Evidence_ConflictingHeadersEvidence: 168 return ConflictingHeadersEvidenceFromProto(evi.ConflictingHeadersEvidence) 169 case *tmproto.Evidence_LunaticValidatorEvidence: 170 return LunaticValidatorEvidenceFromProto(evi.LunaticValidatorEvidence) 171 case *tmproto.Evidence_PotentialAmnesiaEvidence: 172 return PotentialAmnesiaEvidenceFromProto(evi.PotentialAmnesiaEvidence) 173 case *tmproto.Evidence_AmnesiaEvidence: 174 return AmnesiaEvidenceFromProto(evi.AmnesiaEvidence) 175 case *tmproto.Evidence_PhantomValidatorEvidence: 176 return PhantomValidatorEvidenceFromProto(evi.PhantomValidatorEvidence) 177 default: 178 return nil, errors.New("evidence is not recognized") 179 } 180 } 181 182 func init() { 183 tmjson.RegisterType(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence") 184 tmjson.RegisterType(&ConflictingHeadersEvidence{}, "tendermint/ConflictingHeadersEvidence") 185 tmjson.RegisterType(&PhantomValidatorEvidence{}, "tendermint/PhantomValidatorEvidence") 186 tmjson.RegisterType(&LunaticValidatorEvidence{}, "tendermint/LunaticValidatorEvidence") 187 tmjson.RegisterType(&PotentialAmnesiaEvidence{}, "tendermint/PotentialAmnesiaEvidence") 188 tmjson.RegisterType(&AmnesiaEvidence{}, "tendermint/AmnesiaEvidence") 189 } 190 191 //------------------------------------------- 192 193 // DuplicateVoteEvidence contains evidence a validator signed two conflicting 194 // votes. 195 type DuplicateVoteEvidence struct { 196 VoteA *Vote `json:"vote_a"` 197 VoteB *Vote `json:"vote_b"` 198 } 199 200 var _ Evidence = &DuplicateVoteEvidence{} 201 202 // NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given 203 // two conflicting votes. If one of the votes is nil, evidence returned is nil as well 204 func NewDuplicateVoteEvidence(vote1 *Vote, vote2 *Vote) *DuplicateVoteEvidence { 205 var voteA, voteB *Vote 206 if vote1 == nil || vote2 == nil { 207 return nil 208 } 209 if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 { 210 voteA = vote1 211 voteB = vote2 212 } else { 213 voteA = vote2 214 voteB = vote1 215 } 216 return &DuplicateVoteEvidence{ 217 VoteA: voteA, 218 VoteB: voteB, 219 } 220 } 221 222 // String returns a string representation of the evidence. 223 func (dve *DuplicateVoteEvidence) String() string { 224 return fmt.Sprintf("DuplicateVoteEvidence{VoteA: %v, VoteB: %v}", dve.VoteA, dve.VoteB) 225 226 } 227 228 // Height returns the height this evidence refers to. 229 func (dve *DuplicateVoteEvidence) Height() int64 { 230 return dve.VoteA.Height 231 } 232 233 // Time returns time of the latest vote. 234 func (dve *DuplicateVoteEvidence) Time() time.Time { 235 return maxTime(dve.VoteA.Timestamp, dve.VoteB.Timestamp) 236 } 237 238 // Address returns the address of the validator. 239 func (dve *DuplicateVoteEvidence) Address() []byte { 240 return dve.VoteA.ValidatorAddress 241 } 242 243 // Hash returns the hash of the evidence. 244 func (dve *DuplicateVoteEvidence) Bytes() []byte { 245 pbe := dve.ToProto() 246 bz, err := pbe.Marshal() 247 if err != nil { 248 panic(err) 249 } 250 251 return bz 252 } 253 254 // Hash returns the hash of the evidence. 255 func (dve *DuplicateVoteEvidence) Hash() []byte { 256 pbe := dve.ToProto() 257 bz, err := pbe.Marshal() 258 if err != nil { 259 panic(err) 260 } 261 262 return tmhash.Sum(bz) 263 } 264 265 // Verify returns an error if the two votes aren't conflicting. 266 // 267 // To be conflicting, they must be from the same validator, for the same H/R/S, 268 // but for different blocks. 269 func (dve *DuplicateVoteEvidence) Verify(chainID string, pubKey crypto.PubKey) error { 270 // H/R/S must be the same 271 if dve.VoteA.Height != dve.VoteB.Height || 272 dve.VoteA.Round != dve.VoteB.Round || 273 dve.VoteA.Type != dve.VoteB.Type { 274 return fmt.Errorf("h/r/s does not match: %d/%d/%v vs %d/%d/%v", 275 dve.VoteA.Height, dve.VoteA.Round, dve.VoteA.Type, 276 dve.VoteB.Height, dve.VoteB.Round, dve.VoteB.Type) 277 } 278 279 // Address must be the same 280 if !bytes.Equal(dve.VoteA.ValidatorAddress, dve.VoteB.ValidatorAddress) { 281 return fmt.Errorf("validator addresses do not match: %X vs %X", 282 dve.VoteA.ValidatorAddress, 283 dve.VoteB.ValidatorAddress, 284 ) 285 } 286 287 // Index must be the same 288 if dve.VoteA.ValidatorIndex != dve.VoteB.ValidatorIndex { 289 return fmt.Errorf( 290 "validator indices do not match: %d and %d", 291 dve.VoteA.ValidatorIndex, 292 dve.VoteB.ValidatorIndex, 293 ) 294 } 295 296 // BlockIDs must be different 297 if dve.VoteA.BlockID.Equals(dve.VoteB.BlockID) { 298 return fmt.Errorf( 299 "block IDs are the same (%v) - not a real duplicate vote", 300 dve.VoteA.BlockID, 301 ) 302 } 303 304 // pubkey must match address (this should already be true, sanity check) 305 addr := dve.VoteA.ValidatorAddress 306 if !bytes.Equal(pubKey.Address(), addr) { 307 return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)", 308 addr, pubKey, pubKey.Address()) 309 } 310 va := dve.VoteA.ToProto() 311 vb := dve.VoteB.ToProto() 312 // Signatures must be valid 313 if !pubKey.VerifyBytes(VoteSignBytes(chainID, va), dve.VoteA.Signature) { 314 return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature) 315 } 316 if !pubKey.VerifyBytes(VoteSignBytes(chainID, vb), dve.VoteB.Signature) { 317 return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature) 318 } 319 320 return nil 321 } 322 323 // Equal checks if two pieces of evidence are equal. 324 func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool { 325 if _, ok := ev.(*DuplicateVoteEvidence); !ok { 326 return false 327 } 328 pbdev := dve.ToProto() 329 bz, err := pbdev.Marshal() 330 if err != nil { 331 panic(err) 332 } 333 334 var evbz []byte 335 if ev, ok := ev.(*DuplicateVoteEvidence); ok { 336 evpb := ev.ToProto() 337 evbz, err = evpb.Marshal() 338 if err != nil { 339 panic(err) 340 } 341 } 342 343 // just check their hashes 344 dveHash := tmhash.Sum(bz) 345 evHash := tmhash.Sum(evbz) 346 return bytes.Equal(dveHash, evHash) 347 } 348 349 // ValidateBasic performs basic validation. 350 func (dve *DuplicateVoteEvidence) ValidateBasic() error { 351 if dve == nil { 352 return errors.New("empty duplicate vote evidence") 353 } 354 355 if dve.VoteA == nil || dve.VoteB == nil { 356 return fmt.Errorf("one or both of the votes are empty %v, %v", dve.VoteA, dve.VoteB) 357 } 358 if err := dve.VoteA.ValidateBasic(); err != nil { 359 return fmt.Errorf("invalid VoteA: %w", err) 360 } 361 if err := dve.VoteB.ValidateBasic(); err != nil { 362 return fmt.Errorf("invalid VoteB: %w", err) 363 } 364 // Enforce Votes are lexicographically sorted on blockID 365 if strings.Compare(dve.VoteA.BlockID.Key(), dve.VoteB.BlockID.Key()) >= 0 { 366 return errors.New("duplicate votes in invalid order") 367 } 368 return nil 369 } 370 371 func (dve *DuplicateVoteEvidence) ToProto() *tmproto.DuplicateVoteEvidence { 372 voteB := dve.VoteB.ToProto() 373 voteA := dve.VoteA.ToProto() 374 tp := tmproto.DuplicateVoteEvidence{ 375 VoteA: voteA, 376 VoteB: voteB, 377 } 378 return &tp 379 } 380 381 func DuplicateVoteEvidenceFromProto(pb *tmproto.DuplicateVoteEvidence) (*DuplicateVoteEvidence, error) { 382 if pb == nil { 383 return nil, errors.New("nil duplicate vote evidence") 384 } 385 386 vA, err := VoteFromProto(pb.VoteA) 387 if err != nil { 388 return nil, err 389 } 390 391 vB, err := VoteFromProto(pb.VoteB) 392 if err != nil { 393 return nil, err 394 } 395 396 dve := new(DuplicateVoteEvidence) 397 398 dve.VoteA = vA 399 dve.VoteB = vB 400 401 return dve, dve.ValidateBasic() 402 } 403 404 // ConflictingHeadersEvidence is primarily used by the light client when it 405 // observes two conflicting headers, both having 1/3+ of the voting power of 406 // the currently trusted validator set. 407 type ConflictingHeadersEvidence struct { 408 H1 *SignedHeader `json:"h_1"` 409 H2 *SignedHeader `json:"h_2"` 410 } 411 412 var _ Evidence = &ConflictingHeadersEvidence{} 413 var _ CompositeEvidence = &ConflictingHeadersEvidence{} 414 415 // NewConflictingHeadersEvidence creates a new instance of the respective evidence 416 func NewConflictingHeadersEvidence(h1, h2 *SignedHeader) *ConflictingHeadersEvidence { 417 return &ConflictingHeadersEvidence{H1: h1, H2: h2} 418 } 419 420 // Split breaks up evidence into smaller chunks (one per validator except for 421 // PotentialAmnesiaEvidence): PhantomValidatorEvidence, 422 // LunaticValidatorEvidence, DuplicateVoteEvidence and 423 // PotentialAmnesiaEvidence. 424 // 425 // committedHeader - header at height H1.Height == H2.Height 426 // valSet - validator set at height H1.Height == H2.Height 427 // valToLastHeight - map between active validators and respective last heights 428 func (ev *ConflictingHeadersEvidence) Split(committedHeader *Header, valSet *ValidatorSet, 429 valToLastHeight map[string]int64) []Evidence { 430 431 evList := make([]Evidence, 0) 432 433 var alternativeHeader *SignedHeader 434 if bytes.Equal(committedHeader.Hash(), ev.H1.Hash()) { 435 alternativeHeader = ev.H2 436 } else { 437 alternativeHeader = ev.H1 438 } 439 440 // If there are signers(alternativeHeader) that are not part of 441 // validators(committedHeader), they misbehaved as they are signing protocol 442 // messages in heights they are not validators => immediately slashable 443 // (#F4). 444 for i, sig := range alternativeHeader.Commit.Signatures { 445 if sig.Absent() { 446 continue 447 } 448 449 lastHeightValidatorWasInSet, ok := valToLastHeight[string(sig.ValidatorAddress)] 450 if !ok { 451 continue 452 } 453 454 if !valSet.HasAddress(sig.ValidatorAddress) { 455 evList = append(evList, &PhantomValidatorEvidence{ 456 Vote: alternativeHeader.Commit.GetVote(int32(i)), 457 LastHeightValidatorWasInSet: lastHeightValidatorWasInSet, 458 }) 459 } 460 } 461 462 // If ValidatorsHash, NextValidatorsHash, ConsensusHash, AppHash, and 463 // LastResultsHash in alternativeHeader are different (incorrect application 464 // state transition), then it is a lunatic misbehavior => immediately 465 // slashable (#F5). 466 var invalidField string 467 switch { 468 case !bytes.Equal(committedHeader.ValidatorsHash, alternativeHeader.ValidatorsHash): 469 invalidField = "ValidatorsHash" 470 case !bytes.Equal(committedHeader.NextValidatorsHash, alternativeHeader.NextValidatorsHash): 471 invalidField = "NextValidatorsHash" 472 case !bytes.Equal(committedHeader.ConsensusHash, alternativeHeader.ConsensusHash): 473 invalidField = "ConsensusHash" 474 case !bytes.Equal(committedHeader.AppHash, alternativeHeader.AppHash): 475 invalidField = "AppHash" 476 case !bytes.Equal(committedHeader.LastResultsHash, alternativeHeader.LastResultsHash): 477 invalidField = "LastResultsHash" 478 } 479 if invalidField != "" { 480 for i, sig := range alternativeHeader.Commit.Signatures { 481 if sig.Absent() { 482 continue 483 } 484 evList = append(evList, &LunaticValidatorEvidence{ 485 Header: alternativeHeader.Header, 486 Vote: alternativeHeader.Commit.GetVote(int32(i)), 487 InvalidHeaderField: invalidField, 488 }) 489 } 490 return evList 491 } 492 493 // Use the fact that signatures are sorted by ValidatorAddress. 494 var ( 495 i = 0 496 j = 0 497 ) 498 OUTER_LOOP: 499 for i < len(ev.H1.Commit.Signatures) { 500 sigA := ev.H1.Commit.Signatures[i] 501 if sigA.Absent() { 502 i++ 503 continue 504 } 505 // FIXME: Replace with HasAddress once DuplicateVoteEvidence#PubKey is 506 // removed. 507 _, val := valSet.GetByAddress(sigA.ValidatorAddress) 508 if val == nil { 509 i++ 510 continue 511 } 512 513 for j < len(ev.H2.Commit.Signatures) { 514 sigB := ev.H2.Commit.Signatures[j] 515 if sigB.Absent() { 516 j++ 517 continue 518 } 519 520 switch bytes.Compare(sigA.ValidatorAddress, sigB.ValidatorAddress) { 521 case 0: 522 // if H1.Round == H2.Round, and some signers signed different precommit 523 // messages in both commits, then it is an equivocation misbehavior => 524 // immediately slashable (#F1). 525 if ev.H1.Commit.Round == ev.H2.Commit.Round { 526 evList = append(evList, &DuplicateVoteEvidence{ 527 VoteA: ev.H1.Commit.GetVote(int32(i)), 528 VoteB: ev.H2.Commit.GetVote(int32(j)), 529 }) 530 } else { 531 // if H1.Round != H2.Round we need to run full detection procedure => not 532 // immediately slashable. 533 firstVote := ev.H1.Commit.GetVote(int32(i)) 534 secondVote := ev.H2.Commit.GetVote(int32(j)) 535 newEv := NewPotentialAmnesiaEvidence(firstVote, secondVote) 536 537 // has the validator incorrectly voted for a previous round 538 if newEv.VoteA.Round > newEv.VoteB.Round { 539 evList = append(evList, NewAmnesiaEvidence(newEv, NewEmptyPOLC())) 540 } else { 541 evList = append(evList, newEv) 542 } 543 } 544 545 i++ 546 j++ 547 continue OUTER_LOOP 548 case 1: 549 i++ 550 continue OUTER_LOOP 551 case -1: 552 j++ 553 } 554 } 555 } 556 557 return evList 558 } 559 560 func (ev *ConflictingHeadersEvidence) Height() int64 { return ev.H1.Height } 561 562 // Time returns time of the latest header. 563 func (ev *ConflictingHeadersEvidence) Time() time.Time { 564 return maxTime(ev.H1.Time, ev.H2.Time) 565 } 566 567 func (ev *ConflictingHeadersEvidence) Address() []byte { 568 panic("use ConflictingHeadersEvidence#Split to split evidence into individual pieces") 569 } 570 571 func (ev *ConflictingHeadersEvidence) Bytes() []byte { 572 pbe := ev.ToProto() 573 574 bz, err := pbe.Marshal() 575 if err != nil { 576 panic(err) 577 } 578 579 return bz 580 } 581 582 func (ev *ConflictingHeadersEvidence) Hash() []byte { 583 bz := make([]byte, tmhash.Size*2) 584 copy(bz[:tmhash.Size-1], ev.H1.Hash().Bytes()) 585 copy(bz[tmhash.Size:], ev.H2.Hash().Bytes()) 586 return tmhash.Sum(bz) 587 } 588 589 func (ev *ConflictingHeadersEvidence) Verify(chainID string, _ crypto.PubKey) error { 590 panic("use ConflictingHeadersEvidence#VerifyComposite to verify composite evidence") 591 } 592 593 // VerifyComposite verifies that both headers belong to the same chain, same 594 // height and signed by 1/3+ of validators at height H1.Height == H2.Height. 595 func (ev *ConflictingHeadersEvidence) VerifyComposite(committedHeader *Header, valSet *ValidatorSet) error { 596 var alternativeHeader *SignedHeader 597 switch { 598 case bytes.Equal(committedHeader.Hash(), ev.H1.Hash()): 599 alternativeHeader = ev.H2 600 case bytes.Equal(committedHeader.Hash(), ev.H2.Hash()): 601 alternativeHeader = ev.H1 602 default: 603 return errors.New("none of the headers are committed from this node's perspective") 604 } 605 606 // ChainID must be the same 607 if committedHeader.ChainID != alternativeHeader.ChainID { 608 return errors.New("alt header is from a different chain") 609 } 610 611 // Height must be the same 612 if committedHeader.Height != alternativeHeader.Height { 613 return errors.New("alt header is from a different height") 614 } 615 616 // Limit the number of signatures to avoid DoS attacks where a header 617 // contains too many signatures. 618 // 619 // Validator set size = 100 [node] 620 // Max validator set size = 100 * 2 = 200 [fork?] 621 maxNumValidators := valSet.Size() * 2 622 if len(alternativeHeader.Commit.Signatures) > maxNumValidators { 623 return fmt.Errorf("alt commit contains too many signatures: %d, expected no more than %d", 624 len(alternativeHeader.Commit.Signatures), 625 maxNumValidators) 626 } 627 628 // Header must be signed by at least 1/3+ of voting power of currently 629 // trusted validator set. 630 if err := valSet.VerifyCommitLightTrusting( 631 alternativeHeader.ChainID, 632 alternativeHeader.Commit, 633 tmmath.Fraction{Numerator: 1, Denominator: 3}); err != nil { 634 return fmt.Errorf("alt header does not have 1/3+ of voting power of our validator set: %w", err) 635 } 636 637 return nil 638 } 639 640 func (ev *ConflictingHeadersEvidence) Equal(ev2 Evidence) bool { 641 if e2, ok := ev2.(*ConflictingHeadersEvidence); ok { 642 return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash()) 643 } 644 645 return false 646 } 647 648 func (ev *ConflictingHeadersEvidence) ValidateBasic() error { 649 if ev == nil { 650 return errors.New("empty conflicting headers evidence") 651 } 652 653 if ev.H1 == nil { 654 return errors.New("first header is missing") 655 } 656 657 if ev.H2 == nil { 658 return errors.New("second header is missing") 659 } 660 661 if err := ev.H1.ValidateBasic(ev.H1.ChainID); err != nil { 662 return fmt.Errorf("h1: %w", err) 663 } 664 if err := ev.H2.ValidateBasic(ev.H2.ChainID); err != nil { 665 return fmt.Errorf("h2: %w", err) 666 } 667 return nil 668 } 669 670 func (ev *ConflictingHeadersEvidence) String() string { 671 return fmt.Sprintf("ConflictingHeadersEvidence{H1: %d#%X, H2: %d#%X}", 672 ev.H1.Height, ev.H1.Hash(), 673 ev.H2.Height, ev.H2.Hash()) 674 } 675 676 func (ev *ConflictingHeadersEvidence) ToProto() *tmproto.ConflictingHeadersEvidence { 677 pbh1 := ev.H1.ToProto() 678 pbh2 := ev.H2.ToProto() 679 680 tp := &tmproto.ConflictingHeadersEvidence{ 681 H1: pbh1, 682 H2: pbh2, 683 } 684 return tp 685 } 686 687 func ConflictingHeadersEvidenceFromProto(pb *tmproto.ConflictingHeadersEvidence) (*ConflictingHeadersEvidence, error) { 688 if pb == nil { 689 return &ConflictingHeadersEvidence{}, errors.New("nil ConflictingHeadersEvidence") 690 } 691 h1, err := SignedHeaderFromProto(pb.H1) 692 if err != nil { 693 return &ConflictingHeadersEvidence{}, fmt.Errorf("from proto err: %w", err) 694 } 695 h2, err := SignedHeaderFromProto(pb.H2) 696 if err != nil { 697 return &ConflictingHeadersEvidence{}, fmt.Errorf("from proto err: %w", err) 698 } 699 700 tp := &ConflictingHeadersEvidence{ 701 H1: h1, 702 H2: h2, 703 } 704 705 return tp, tp.ValidateBasic() 706 } 707 708 //------------------------------------------- 709 710 type PhantomValidatorEvidence struct { 711 Vote *Vote `json:"vote"` 712 LastHeightValidatorWasInSet int64 `json:"last_height_validator_was_in_set"` 713 } 714 715 var _ Evidence = &PhantomValidatorEvidence{} 716 717 // NewPhantomValidatorEvidence creates a new instance of the respective evidence 718 func NewPhantomValidatorEvidence(vote *Vote, lastHeightValidatorWasInSet int64) *PhantomValidatorEvidence { 719 return &PhantomValidatorEvidence{ 720 Vote: vote, 721 LastHeightValidatorWasInSet: lastHeightValidatorWasInSet, 722 } 723 } 724 725 func (e *PhantomValidatorEvidence) Height() int64 { 726 return e.Vote.Height 727 } 728 729 func (e *PhantomValidatorEvidence) Time() time.Time { 730 return e.Vote.Timestamp 731 } 732 733 func (e *PhantomValidatorEvidence) Address() []byte { 734 return e.Vote.ValidatorAddress 735 } 736 737 func (e *PhantomValidatorEvidence) Hash() []byte { 738 pbe := e.ToProto() 739 740 bz, err := pbe.Marshal() 741 if err != nil { 742 panic(err) 743 } 744 return tmhash.Sum(bz) 745 } 746 747 func (e *PhantomValidatorEvidence) Bytes() []byte { 748 pbe := e.ToProto() 749 750 bz, err := pbe.Marshal() 751 if err != nil { 752 panic(err) 753 } 754 755 return bz 756 } 757 758 func (e *PhantomValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error { 759 760 v := e.Vote.ToProto() 761 if !pubKey.VerifyBytes(VoteSignBytes(chainID, v), e.Vote.Signature) { 762 return errors.New("invalid signature") 763 } 764 765 return nil 766 } 767 768 func (e *PhantomValidatorEvidence) Equal(ev Evidence) bool { 769 if e2, ok := ev.(*PhantomValidatorEvidence); ok { 770 return e.Vote.Height == e2.Vote.Height && 771 bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress) 772 } 773 774 return false 775 } 776 777 func (e *PhantomValidatorEvidence) ValidateBasic() error { 778 if e == nil { 779 return errors.New("empty phantom validator evidence") 780 } 781 782 if e.Vote == nil { 783 return errors.New("empty vote") 784 } 785 786 if err := e.Vote.ValidateBasic(); err != nil { 787 return fmt.Errorf("invalid vote: %w", err) 788 } 789 790 if !e.Vote.BlockID.IsComplete() { 791 return errors.New("expected vote for block") 792 } 793 794 if e.LastHeightValidatorWasInSet <= 0 { 795 return errors.New("negative or zero LastHeightValidatorWasInSet") 796 } 797 798 return nil 799 } 800 801 func (e *PhantomValidatorEvidence) String() string { 802 return fmt.Sprintf("PhantomValidatorEvidence{%X voted at height %d}", 803 e.Vote.ValidatorAddress, e.Vote.Height) 804 } 805 806 func (e *PhantomValidatorEvidence) ToProto() *tmproto.PhantomValidatorEvidence { 807 vpb := e.Vote.ToProto() 808 809 tp := &tmproto.PhantomValidatorEvidence{ 810 Vote: vpb, 811 LastHeightValidatorWasInSet: e.LastHeightValidatorWasInSet, 812 } 813 814 return tp 815 } 816 817 func PhantomValidatorEvidenceFromProto(pb *tmproto.PhantomValidatorEvidence) (*PhantomValidatorEvidence, error) { 818 if pb == nil { 819 return nil, errors.New("nil PhantomValidatorEvidence") 820 } 821 822 vpb, err := VoteFromProto(pb.Vote) 823 if err != nil { 824 return nil, err 825 } 826 827 tp := &PhantomValidatorEvidence{ 828 Vote: vpb, 829 LastHeightValidatorWasInSet: pb.LastHeightValidatorWasInSet, 830 } 831 832 return tp, tp.ValidateBasic() 833 } 834 835 //------------------------------------------- 836 837 type LunaticValidatorEvidence struct { 838 Header *Header `json:"header"` 839 Vote *Vote `json:"vote"` 840 InvalidHeaderField string `json:"invalid_header_field"` 841 } 842 843 var _ Evidence = &LunaticValidatorEvidence{} 844 845 // NewLunaticValidatorEvidence creates a new instance of the respective evidence 846 func NewLunaticValidatorEvidence(header *Header, vote *Vote, invalidHeaderField string) *LunaticValidatorEvidence { 847 return &LunaticValidatorEvidence{ 848 Header: header, 849 Vote: vote, 850 InvalidHeaderField: invalidHeaderField, 851 } 852 } 853 854 func (e *LunaticValidatorEvidence) Height() int64 { 855 return e.Header.Height 856 } 857 858 // Time returns the maximum between the header's time and vote's time. 859 func (e *LunaticValidatorEvidence) Time() time.Time { 860 return maxTime(e.Header.Time, e.Vote.Timestamp) 861 } 862 863 func (e *LunaticValidatorEvidence) Address() []byte { 864 return e.Vote.ValidatorAddress 865 } 866 867 func (e *LunaticValidatorEvidence) Hash() []byte { 868 bz := make([]byte, tmhash.Size+crypto.AddressSize) 869 copy(bz[:tmhash.Size-1], e.Header.Hash().Bytes()) 870 copy(bz[tmhash.Size:], e.Vote.ValidatorAddress.Bytes()) 871 return tmhash.Sum(bz) 872 } 873 874 func (e *LunaticValidatorEvidence) Bytes() []byte { 875 pbe := e.ToProto() 876 877 bz, err := pbe.Marshal() 878 if err != nil { 879 panic(err) 880 } 881 882 return bz 883 } 884 885 func (e *LunaticValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error { 886 // chainID must be the same 887 if chainID != e.Header.ChainID { 888 return fmt.Errorf("chainID do not match: %s vs %s", 889 chainID, 890 e.Header.ChainID, 891 ) 892 } 893 894 v := e.Vote.ToProto() 895 if !pubKey.VerifyBytes(VoteSignBytes(chainID, v), e.Vote.Signature) { 896 return errors.New("invalid signature") 897 } 898 899 return nil 900 } 901 902 func (e *LunaticValidatorEvidence) Equal(ev Evidence) bool { 903 if e2, ok := ev.(*LunaticValidatorEvidence); ok { 904 return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) && 905 bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress) 906 } 907 return false 908 } 909 910 func (e *LunaticValidatorEvidence) ValidateBasic() error { 911 if e == nil { 912 return errors.New("empty lunatic validator evidence") 913 } 914 915 if e.Header == nil { 916 return errors.New("empty header") 917 } 918 919 if e.Vote == nil { 920 return errors.New("empty vote") 921 } 922 923 if err := e.Header.ValidateBasic(); err != nil { 924 return fmt.Errorf("invalid header: %v", err) 925 } 926 927 if err := e.Vote.ValidateBasic(); err != nil { 928 return fmt.Errorf("invalid signature: %v", err) 929 } 930 931 if !e.Vote.BlockID.IsComplete() { 932 return errors.New("expected vote for block") 933 } 934 935 if e.Header.Height != e.Vote.Height { 936 return fmt.Errorf("header and vote have different heights: %d vs %d", 937 e.Header.Height, 938 e.Vote.Height, 939 ) 940 } 941 942 switch e.InvalidHeaderField { 943 case "ValidatorsHash", "NextValidatorsHash", "ConsensusHash", "AppHash", "LastResultsHash": 944 break 945 default: 946 return errors.New("unknown invalid header field") 947 } 948 949 if !bytes.Equal(e.Header.Hash(), e.Vote.BlockID.Hash) { 950 return fmt.Errorf("vote was not for header: %X != %X", 951 e.Vote.BlockID.Hash, 952 e.Header.Hash(), 953 ) 954 } 955 956 return nil 957 } 958 959 func (e *LunaticValidatorEvidence) String() string { 960 return fmt.Sprintf("LunaticValidatorEvidence{%X voted for %d/%X, which contains invalid %s}", 961 e.Vote.ValidatorAddress, e.Header.Height, e.Header.Hash(), e.InvalidHeaderField) 962 } 963 964 func (e *LunaticValidatorEvidence) VerifyHeader(committedHeader *Header) error { 965 matchErr := func(field string) error { 966 return fmt.Errorf("%s matches committed hash", field) 967 } 968 969 if committedHeader == nil { 970 return errors.New("committed header is nil") 971 } 972 973 switch e.InvalidHeaderField { 974 case ValidatorsHashField: 975 if bytes.Equal(committedHeader.ValidatorsHash, e.Header.ValidatorsHash) { 976 return matchErr(ValidatorsHashField) 977 } 978 case NextValidatorsHashField: 979 if bytes.Equal(committedHeader.NextValidatorsHash, e.Header.NextValidatorsHash) { 980 return matchErr(NextValidatorsHashField) 981 } 982 case ConsensusHashField: 983 if bytes.Equal(committedHeader.ConsensusHash, e.Header.ConsensusHash) { 984 return matchErr(ConsensusHashField) 985 } 986 case AppHashField: 987 if bytes.Equal(committedHeader.AppHash, e.Header.AppHash) { 988 return matchErr(AppHashField) 989 } 990 case LastResultsHashField: 991 if bytes.Equal(committedHeader.LastResultsHash, e.Header.LastResultsHash) { 992 return matchErr(LastResultsHashField) 993 } 994 default: 995 return errors.New("unknown InvalidHeaderField") 996 } 997 998 return nil 999 } 1000 1001 func (e *LunaticValidatorEvidence) ToProto() *tmproto.LunaticValidatorEvidence { 1002 h := e.Header.ToProto() 1003 v := e.Vote.ToProto() 1004 1005 tp := &tmproto.LunaticValidatorEvidence{ 1006 Header: h, 1007 Vote: v, 1008 InvalidHeaderField: e.InvalidHeaderField, 1009 } 1010 1011 return tp 1012 } 1013 1014 func LunaticValidatorEvidenceFromProto(pb *tmproto.LunaticValidatorEvidence) (*LunaticValidatorEvidence, error) { 1015 if pb == nil { 1016 return nil, errors.New("nil LunaticValidatorEvidence") 1017 } 1018 1019 h, err := HeaderFromProto(pb.GetHeader()) 1020 if err != nil { 1021 return nil, err 1022 } 1023 1024 v, err := VoteFromProto(pb.GetVote()) 1025 if err != nil { 1026 return nil, err 1027 } 1028 1029 tp := LunaticValidatorEvidence{ 1030 Header: &h, 1031 Vote: v, 1032 InvalidHeaderField: pb.InvalidHeaderField, 1033 } 1034 1035 return &tp, tp.ValidateBasic() 1036 } 1037 1038 //------------------------------------------- 1039 1040 // PotentialAmnesiaEvidence is constructed when a validator votes on two different blocks at different rounds 1041 // in the same height. PotentialAmnesiaEvidence can then evolve into AmnesiaEvidence if the indicted validator 1042 // is incapable of providing the proof of lock change that validates voting twice in the allotted trial period. 1043 // Heightstamp is used for each node to keep a track of how much time has passed so as to know when the trial period 1044 // is finished and is set when the node first receives the evidence. 1045 type PotentialAmnesiaEvidence struct { 1046 VoteA *Vote `json:"vote_a"` 1047 VoteB *Vote `json:"vote_b"` 1048 1049 HeightStamp int64 1050 } 1051 1052 var _ Evidence = &PotentialAmnesiaEvidence{} 1053 1054 // NewPotentialAmnesiaEvidence creates a new instance of the evidence and orders the votes correctly 1055 func NewPotentialAmnesiaEvidence(voteA *Vote, voteB *Vote) *PotentialAmnesiaEvidence { 1056 if voteA == nil || voteB == nil { 1057 return nil 1058 } 1059 1060 if voteA.Timestamp.Before(voteB.Timestamp) { 1061 return &PotentialAmnesiaEvidence{VoteA: voteA, VoteB: voteB} 1062 } 1063 return &PotentialAmnesiaEvidence{VoteA: voteB, VoteB: voteA} 1064 } 1065 1066 func (e *PotentialAmnesiaEvidence) Height() int64 { 1067 return e.VoteA.Height 1068 } 1069 1070 func (e *PotentialAmnesiaEvidence) Time() time.Time { 1071 return e.VoteB.Timestamp 1072 } 1073 1074 func (e *PotentialAmnesiaEvidence) Address() []byte { 1075 return e.VoteA.ValidatorAddress 1076 } 1077 1078 // NOTE: Heightstamp must not be included in hash 1079 func (e *PotentialAmnesiaEvidence) Hash() []byte { 1080 v1, err := e.VoteA.ToProto().Marshal() 1081 if err != nil { 1082 panic(fmt.Errorf("trying to hash potential amnesia evidence, err: %w", err)) 1083 } 1084 1085 v2, err := e.VoteB.ToProto().Marshal() 1086 if err != nil { 1087 panic(fmt.Errorf("trying to hash potential amnesia evidence, err: %w", err)) 1088 } 1089 1090 return tmhash.Sum(append(v1, v2...)) 1091 } 1092 1093 func (e *PotentialAmnesiaEvidence) Bytes() []byte { 1094 pbe := e.ToProto() 1095 1096 bz, err := pbe.Marshal() 1097 if err != nil { 1098 panic(err) 1099 } 1100 1101 return bz 1102 } 1103 1104 func (e *PotentialAmnesiaEvidence) Verify(chainID string, pubKey crypto.PubKey) error { 1105 // pubkey must match address (this should already be true, sanity check) 1106 addr := e.VoteA.ValidatorAddress 1107 if !bytes.Equal(pubKey.Address(), addr) { 1108 return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)", 1109 addr, pubKey, pubKey.Address()) 1110 } 1111 1112 va := e.VoteA.ToProto() 1113 vb := e.VoteB.ToProto() 1114 1115 // Signatures must be valid 1116 if !pubKey.VerifyBytes(VoteSignBytes(chainID, va), e.VoteA.Signature) { 1117 return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature) 1118 } 1119 if !pubKey.VerifyBytes(VoteSignBytes(chainID, vb), e.VoteB.Signature) { 1120 return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature) 1121 } 1122 1123 return nil 1124 } 1125 1126 func (e *PotentialAmnesiaEvidence) Equal(ev Evidence) bool { 1127 if e2, ok := ev.(*PotentialAmnesiaEvidence); ok { 1128 return e.Height() == e2.Height() && e.VoteA.Round == e2.VoteA.Round && e.VoteB.Round == e2.VoteB.Round && 1129 bytes.Equal(e.Address(), e2.Address()) 1130 } 1131 return false 1132 } 1133 1134 func (e *PotentialAmnesiaEvidence) ValidateBasic() error { 1135 if e == nil { 1136 return errors.New("empty potential amnesia evidence") 1137 } 1138 1139 if e.VoteA == nil || e.VoteB == nil { 1140 return fmt.Errorf("one or both of the votes are empty %v, %v", e.VoteA, e.VoteB) 1141 } 1142 1143 if err := e.VoteA.ValidateBasic(); err != nil { 1144 return fmt.Errorf("invalid VoteA: %v", err) 1145 } 1146 if err := e.VoteB.ValidateBasic(); err != nil { 1147 return fmt.Errorf("invalid VoteB: %v", err) 1148 } 1149 1150 // H/S must be the same 1151 if e.VoteA.Height != e.VoteB.Height || 1152 e.VoteA.Type != e.VoteB.Type { 1153 return fmt.Errorf("h/s do not match: %d/%v vs %d/%v", 1154 e.VoteA.Height, e.VoteA.Type, e.VoteB.Height, e.VoteB.Type) 1155 } 1156 1157 // Enforce that vote A came before vote B 1158 if e.VoteA.Timestamp.After(e.VoteB.Timestamp) { 1159 return fmt.Errorf("vote A should have a timestamp before vote B, but got %s > %s", 1160 e.VoteA.Timestamp, e.VoteB.Timestamp) 1161 } 1162 1163 // Address must be the same 1164 if !bytes.Equal(e.VoteA.ValidatorAddress, e.VoteB.ValidatorAddress) { 1165 return fmt.Errorf("validator addresses do not match: %X vs %X", 1166 e.VoteA.ValidatorAddress, 1167 e.VoteB.ValidatorAddress, 1168 ) 1169 } 1170 1171 // Index must be the same 1172 // https://github.com/tendermint/tendermint/issues/4619 1173 if e.VoteA.ValidatorIndex != e.VoteB.ValidatorIndex { 1174 return fmt.Errorf( 1175 "duplicateVoteEvidence Error: Validator indices do not match. Got %d and %d", 1176 e.VoteA.ValidatorIndex, 1177 e.VoteB.ValidatorIndex, 1178 ) 1179 } 1180 1181 // BlockIDs must be different 1182 if e.VoteA.BlockID.Equals(e.VoteB.BlockID) { 1183 return fmt.Errorf( 1184 "block IDs are the same (%v) - not a real duplicate vote", 1185 e.VoteA.BlockID, 1186 ) 1187 } 1188 1189 return nil 1190 } 1191 1192 func (e *PotentialAmnesiaEvidence) String() string { 1193 return fmt.Sprintf("PotentialAmnesiaEvidence{VoteA: %v, VoteB: %v}", e.VoteA, e.VoteB) 1194 } 1195 1196 // Primed finds whether the PotentialAmnesiaEvidence is ready to be upgraded to Amnesia Evidence. It is decided if 1197 // either the prosecuted node voted in the past or if the allocated trial period has expired without a proof of lock 1198 // change having been provided. 1199 func (e *PotentialAmnesiaEvidence) Primed(trialPeriod, currentHeight int64) bool { 1200 // voted in the past can be instantly punishable 1201 if e.VoteA.Round > e.VoteB.Round { 1202 return true 1203 } 1204 // has the trial period expired 1205 if e.HeightStamp > 0 { 1206 return e.HeightStamp+trialPeriod <= currentHeight 1207 } 1208 return false 1209 } 1210 1211 func (e *PotentialAmnesiaEvidence) ToProto() *tmproto.PotentialAmnesiaEvidence { 1212 voteB := e.VoteB.ToProto() 1213 voteA := e.VoteA.ToProto() 1214 1215 tp := &tmproto.PotentialAmnesiaEvidence{ 1216 VoteA: voteA, 1217 VoteB: voteB, 1218 HeightStamp: e.HeightStamp, 1219 } 1220 1221 return tp 1222 } 1223 1224 // ------------------ 1225 1226 // ProofOfLockChange (POLC) proves that a node followed the consensus protocol and voted for a precommit in two 1227 // different rounds because the node received a majority of votes for a different block in the latter round. In cases of 1228 // amnesia evidence, a suspected node will need ProofOfLockChange to prove that the node did not break protocol. 1229 type ProofOfLockChange struct { 1230 Votes []*Vote `json:"votes"` 1231 PubKey crypto.PubKey `json:"pubkey"` 1232 } 1233 1234 // MakePOLCFromVoteSet can be used when a majority of prevotes or precommits for a block is seen 1235 // that the node has itself not yet voted for in order to process the vote set into a proof of lock change 1236 func NewPOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) (*ProofOfLockChange, error) { 1237 polc := newPOLCFromVoteSet(voteSet, pubKey, blockID) 1238 return polc, polc.ValidateBasic() 1239 } 1240 1241 func newPOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) *ProofOfLockChange { 1242 if voteSet == nil { 1243 return nil 1244 } 1245 var votes []*Vote 1246 valSetSize := voteSet.Size() 1247 for valIdx := int32(0); int(valIdx) < valSetSize; valIdx++ { 1248 vote := voteSet.GetByIndex(valIdx) 1249 if vote != nil && vote.BlockID.Equals(blockID) { 1250 votes = append(votes, vote) 1251 } 1252 } 1253 return NewPOLC(votes, pubKey) 1254 } 1255 1256 // NewPOLC creates a POLC 1257 func NewPOLC(votes []*Vote, pubKey crypto.PubKey) *ProofOfLockChange { 1258 return &ProofOfLockChange{ 1259 Votes: votes, 1260 PubKey: pubKey, 1261 } 1262 } 1263 1264 // EmptyPOLC returns an empty polc. This is used when no polc has been provided in the allocated trial period time 1265 // and the node now needs to move to upgrading to AmnesiaEvidence and hence uses an empty polc 1266 func NewEmptyPOLC() *ProofOfLockChange { 1267 return &ProofOfLockChange{ 1268 nil, 1269 nil, 1270 } 1271 } 1272 1273 func (e *ProofOfLockChange) Height() int64 { 1274 return e.Votes[0].Height 1275 } 1276 1277 // Time returns time of the latest vote. 1278 func (e *ProofOfLockChange) Time() time.Time { 1279 latest := e.Votes[0].Timestamp 1280 for _, vote := range e.Votes { 1281 if vote.Timestamp.After(latest) { 1282 latest = vote.Timestamp 1283 } 1284 } 1285 return latest 1286 } 1287 1288 func (e *ProofOfLockChange) Round() int32 { 1289 return e.Votes[0].Round 1290 } 1291 1292 func (e *ProofOfLockChange) Address() []byte { 1293 return e.PubKey.Address() 1294 } 1295 1296 func (e *ProofOfLockChange) BlockID() BlockID { 1297 return e.Votes[0].BlockID 1298 } 1299 1300 // ValidateVotes checks the polc against the validator set of that height. The function makes sure that the polc 1301 // contains a majority of votes and that each 1302 func (e *ProofOfLockChange) ValidateVotes(valSet *ValidatorSet, chainID string) error { 1303 if e.IsAbsent() { 1304 return errors.New("polc is empty") 1305 } 1306 talliedVotingPower := int64(0) 1307 votingPowerNeeded := valSet.TotalVotingPower() * 2 / 3 1308 for _, vote := range e.Votes { 1309 exists := false 1310 for _, validator := range valSet.Validators { 1311 if bytes.Equal(validator.Address, vote.ValidatorAddress) { 1312 exists = true 1313 v := vote.ToProto() 1314 if !validator.PubKey.VerifyBytes(VoteSignBytes(chainID, v), vote.Signature) { 1315 return fmt.Errorf("cannot verify vote (from validator: %d) against signature: %v", 1316 vote.ValidatorIndex, vote.Signature) 1317 } 1318 1319 talliedVotingPower += validator.VotingPower 1320 } 1321 } 1322 if !exists { 1323 return fmt.Errorf("vote was not from a validator in this set: %v", vote.String()) 1324 } 1325 } 1326 if talliedVotingPower <= votingPowerNeeded { 1327 return ErrNotEnoughVotingPowerSigned{ 1328 Got: talliedVotingPower, 1329 Needed: votingPowerNeeded + 1, 1330 } 1331 } 1332 return nil 1333 } 1334 1335 func (e *ProofOfLockChange) Equal(e2 *ProofOfLockChange) bool { 1336 return bytes.Equal(e.Address(), e2.Address()) && e.Height() == e2.Height() && 1337 e.Round() == e2.Round() 1338 } 1339 1340 func (e *ProofOfLockChange) ValidateBasic() error { 1341 if e == nil { 1342 return errors.New("empty proof of lock change") 1343 } 1344 1345 // first check if the polc is absent / empty 1346 if e.IsAbsent() { 1347 return nil 1348 } 1349 1350 if e.PubKey == nil { 1351 return errors.New("missing public key") 1352 } 1353 // validate basic doesn't count the number of votes and their voting power, this is to be done by VerifyEvidence 1354 if e.Votes == nil || len(e.Votes) == 0 { 1355 return errors.New("missing votes") 1356 } 1357 // height, round and vote type must be the same for all votes 1358 height := e.Height() 1359 round := e.Round() 1360 if round == 0 { 1361 return errors.New("can't have a polc for the first round") 1362 } 1363 voteType := e.Votes[0].Type 1364 for idx, vote := range e.Votes { 1365 if vote == nil { 1366 return fmt.Errorf("nil vote at index: %d", idx) 1367 } 1368 1369 if err := vote.ValidateBasic(); err != nil { 1370 return fmt.Errorf("invalid vote#%d: %w", idx, err) 1371 } 1372 1373 if vote.Height != height { 1374 return fmt.Errorf("invalid height for vote#%d: %d instead of %d", idx, vote.Height, height) 1375 } 1376 1377 if vote.Round != round { 1378 return fmt.Errorf("invalid round for vote#%d: %d instead of %d", idx, vote.Round, round) 1379 } 1380 1381 if vote.Type != voteType { 1382 return fmt.Errorf("invalid vote type for vote#%d: %d instead of %d", idx, vote.Type, voteType) 1383 } 1384 1385 if !vote.BlockID.Equals(e.BlockID()) { 1386 return fmt.Errorf("vote must be for the same block id: %v instead of %v", e.BlockID(), vote.BlockID) 1387 } 1388 1389 if bytes.Equal(vote.ValidatorAddress.Bytes(), e.PubKey.Address().Bytes()) { 1390 return fmt.Errorf("vote validator address cannot be the same as the public key address: %X all votes %v", 1391 vote.ValidatorAddress.Bytes(), e.PubKey.Address().Bytes()) 1392 } 1393 1394 for i := idx + 1; i < len(e.Votes); i++ { 1395 if bytes.Equal(vote.ValidatorAddress.Bytes(), e.Votes[i].ValidatorAddress.Bytes()) { 1396 return fmt.Errorf("duplicate votes: %v", vote) 1397 } 1398 } 1399 1400 } 1401 return nil 1402 } 1403 1404 func (e *ProofOfLockChange) String() string { 1405 if e.IsAbsent() { 1406 return "Empty ProofOfLockChange" 1407 } 1408 return fmt.Sprintf("ProofOfLockChange {Address: %X, Height: %d, Round: %d", e.Address(), e.Height(), 1409 e.Votes[0].Round) 1410 } 1411 1412 // IsAbsent checks if the polc is empty 1413 func (e *ProofOfLockChange) IsAbsent() bool { 1414 return e.Votes == nil && e.PubKey == nil 1415 } 1416 1417 func (e *ProofOfLockChange) ToProto() (*tmproto.ProofOfLockChange, error) { 1418 plc := new(tmproto.ProofOfLockChange) 1419 vpb := make([]*tmproto.Vote, len(e.Votes)) 1420 1421 // if absent create empty proto polc 1422 if e.IsAbsent() { 1423 return plc, nil 1424 } 1425 1426 if e.Votes == nil { 1427 return plc, errors.New("invalid proof of lock change (no votes), did you forget to validate?") 1428 } 1429 for i, v := range e.Votes { 1430 pb := v.ToProto() 1431 if pb != nil { 1432 vpb[i] = pb 1433 } 1434 } 1435 1436 pk, err := cryptoenc.PubKeyToProto(e.PubKey) 1437 if err != nil { 1438 return plc, fmt.Errorf("invalid proof of lock change (err: %w), did you forget to validate?", err) 1439 } 1440 plc.PubKey = &pk 1441 plc.Votes = vpb 1442 1443 return plc, nil 1444 } 1445 1446 // AmnesiaEvidence is the progression of PotentialAmnesiaEvidence and is used to prove an infringement of the 1447 // Tendermint consensus when a validator incorrectly sends a vote in a later round without correctly changing the lock 1448 type AmnesiaEvidence struct { 1449 *PotentialAmnesiaEvidence 1450 Polc *ProofOfLockChange 1451 } 1452 1453 // Height, Time, Address, and Verify, and Hash functions are all inherited by the PotentialAmnesiaEvidence struct 1454 var _ Evidence = &AmnesiaEvidence{} 1455 1456 func NewAmnesiaEvidence(pe *PotentialAmnesiaEvidence, proof *ProofOfLockChange) *AmnesiaEvidence { 1457 return &AmnesiaEvidence{ 1458 pe, 1459 proof, 1460 } 1461 } 1462 1463 // Note: Amnesia evidence with or without a polc are considered the same 1464 func (e *AmnesiaEvidence) Equal(ev Evidence) bool { 1465 if e2, ok := ev.(*AmnesiaEvidence); ok { 1466 return e.PotentialAmnesiaEvidence.Equal(e2.PotentialAmnesiaEvidence) 1467 } 1468 return false 1469 } 1470 1471 func (e *AmnesiaEvidence) Bytes() []byte { 1472 pbe := e.ToProto() 1473 1474 bz, err := pbe.Marshal() 1475 if err != nil { 1476 panic(fmt.Errorf("converting amnesia evidence to bytes, err: %w", err)) 1477 } 1478 1479 return bz 1480 } 1481 1482 func (e *AmnesiaEvidence) ValidateBasic() error { 1483 if e == nil { 1484 return errors.New("empty amnesia evidence") 1485 } 1486 if e.Polc == nil || e.PotentialAmnesiaEvidence == nil { 1487 return errors.New("amnesia evidence is missing either the polc or the potential amnesia evidence") 1488 } 1489 1490 if err := e.PotentialAmnesiaEvidence.ValidateBasic(); err != nil { 1491 return fmt.Errorf("invalid potential amnesia evidence: %w", err) 1492 } 1493 if !e.Polc.IsAbsent() { 1494 if err := e.Polc.ValidateBasic(); err != nil { 1495 return fmt.Errorf("invalid proof of lock change: %w", err) 1496 } 1497 1498 if !bytes.Equal(e.PotentialAmnesiaEvidence.Address(), e.Polc.Address()) { 1499 return fmt.Errorf("validator addresses do not match (%X - %X)", e.PotentialAmnesiaEvidence.Address(), 1500 e.Polc.Address()) 1501 } 1502 1503 if e.PotentialAmnesiaEvidence.Height() != e.Polc.Height() { 1504 return fmt.Errorf("heights do not match (%d - %d)", e.PotentialAmnesiaEvidence.Height(), 1505 e.Polc.Height()) 1506 } 1507 1508 if e.Polc.Round() <= e.VoteA.Round || e.Polc.Round() > e.VoteB.Round { 1509 return fmt.Errorf("polc must be between %d and %d (inclusive)", e.VoteA.Round+1, e.VoteB.Round) 1510 } 1511 1512 if !e.Polc.BlockID().Equals(e.PotentialAmnesiaEvidence.VoteB.BlockID) && !e.Polc.BlockID().IsZero() { 1513 return fmt.Errorf("polc must be either for a nil block or for the same block as the second vote: %v != %v", 1514 e.Polc.BlockID(), e.PotentialAmnesiaEvidence.VoteB.BlockID) 1515 } 1516 1517 if e.Polc.Time().After(e.PotentialAmnesiaEvidence.VoteB.Timestamp) { 1518 return fmt.Errorf("validator voted again before receiving a majority of votes for the new block: %v is after %v", 1519 e.Polc.Time(), e.PotentialAmnesiaEvidence.VoteB.Timestamp) 1520 } 1521 } 1522 return nil 1523 } 1524 1525 // ViolatedConsensus assess on the basis of the AmnesiaEvidence whether the validator has violated the 1526 // Tendermint consensus. Evidence must be validated first (see ValidateBasic). 1527 // We are only interested in proving that the latter of the votes in terms of time was correctly done. 1528 func (e *AmnesiaEvidence) ViolatedConsensus() (bool, string) { 1529 // a validator having voted cannot go back and vote on an earlier round 1530 if e.PotentialAmnesiaEvidence.VoteA.Round > e.PotentialAmnesiaEvidence.VoteB.Round { 1531 return true, "validator went back and voted on a previous round" 1532 } 1533 1534 // if empty, then no proof was provided to defend the validators actions 1535 if e.Polc.IsAbsent() { 1536 return true, "no proof of lock was provided" 1537 } 1538 1539 return false, "" 1540 } 1541 1542 func (e *AmnesiaEvidence) String() string { 1543 return fmt.Sprintf("AmnesiaEvidence{ %v, polc: %v }", e.PotentialAmnesiaEvidence, e.Polc) 1544 } 1545 1546 func (e *AmnesiaEvidence) ToProto() *tmproto.AmnesiaEvidence { 1547 paepb := e.PotentialAmnesiaEvidence.ToProto() 1548 1549 polc, err := e.Polc.ToProto() 1550 if err != nil { 1551 polc, _ = NewEmptyPOLC().ToProto() 1552 } 1553 1554 return &tmproto.AmnesiaEvidence{ 1555 PotentialAmnesiaEvidence: paepb, 1556 Polc: polc, 1557 } 1558 } 1559 1560 func ProofOfLockChangeFromProto(pb *tmproto.ProofOfLockChange) (*ProofOfLockChange, error) { 1561 if pb == nil { 1562 return nil, errors.New("nil proof of lock change") 1563 } 1564 1565 plc := new(ProofOfLockChange) 1566 1567 // check if it is an empty polc 1568 if pb.PubKey == nil && pb.Votes == nil { 1569 return plc, nil 1570 } 1571 1572 if pb.Votes == nil { 1573 return nil, errors.New("proofOfLockChange: is not absent but has no votes") 1574 } 1575 1576 vpb := make([]*Vote, len(pb.Votes)) 1577 for i, v := range pb.Votes { 1578 vi, err := VoteFromProto(v) 1579 if err != nil { 1580 return nil, err 1581 } 1582 vpb[i] = vi 1583 } 1584 1585 if pb.PubKey == nil { 1586 return nil, errors.New("proofOfLockChange: is not absent but has nil PubKey") 1587 } 1588 pk, err := cryptoenc.PubKeyFromProto(*pb.PubKey) 1589 if err != nil { 1590 return nil, err 1591 } 1592 1593 plc.PubKey = pk 1594 plc.Votes = vpb 1595 1596 return plc, plc.ValidateBasic() 1597 } 1598 1599 func PotentialAmnesiaEvidenceFromProto(pb *tmproto.PotentialAmnesiaEvidence) (*PotentialAmnesiaEvidence, error) { 1600 voteA, err := VoteFromProto(pb.GetVoteA()) 1601 if err != nil { 1602 return nil, err 1603 } 1604 1605 voteB, err := VoteFromProto(pb.GetVoteB()) 1606 if err != nil { 1607 return nil, err 1608 } 1609 tp := PotentialAmnesiaEvidence{ 1610 VoteA: voteA, 1611 VoteB: voteB, 1612 HeightStamp: pb.GetHeightStamp(), 1613 } 1614 1615 return &tp, tp.ValidateBasic() 1616 } 1617 1618 func AmnesiaEvidenceFromProto(pb *tmproto.AmnesiaEvidence) (*AmnesiaEvidence, error) { 1619 if pb == nil { 1620 return nil, errors.New("nil amnesia evidence") 1621 } 1622 1623 pae, err := PotentialAmnesiaEvidenceFromProto(pb.PotentialAmnesiaEvidence) 1624 if err != nil { 1625 return nil, fmt.Errorf("decoding to amnesia evidence, err: %w", err) 1626 } 1627 polc, err := ProofOfLockChangeFromProto(pb.Polc) 1628 if err != nil { 1629 return nil, fmt.Errorf("decoding to amnesia evidence, err: %w", err) 1630 } 1631 1632 tp := &AmnesiaEvidence{ 1633 PotentialAmnesiaEvidence: pae, 1634 Polc: polc, 1635 } 1636 1637 return tp, tp.ValidateBasic() 1638 } 1639 1640 //-------------------------------------------------- 1641 1642 // EvidenceList is a list of Evidence. Evidences is not a word. 1643 type EvidenceList []Evidence 1644 1645 // Hash returns the simple merkle root hash of the EvidenceList. 1646 func (evl EvidenceList) Hash() []byte { 1647 // These allocations are required because Evidence is not of type Bytes, and 1648 // golang slices can't be typed cast. This shouldn't be a performance problem since 1649 // the Evidence size is capped. 1650 evidenceBzs := make([][]byte, len(evl)) 1651 for i := 0; i < len(evl); i++ { 1652 evidenceBzs[i] = evl[i].Bytes() 1653 } 1654 return merkle.HashFromByteSlices(evidenceBzs) 1655 } 1656 1657 func (evl EvidenceList) String() string { 1658 s := "" 1659 for _, e := range evl { 1660 s += fmt.Sprintf("%s\t\t", e) 1661 } 1662 return s 1663 } 1664 1665 // Has returns true if the evidence is in the EvidenceList. 1666 func (evl EvidenceList) Has(evidence Evidence) bool { 1667 for _, ev := range evl { 1668 if ev.Equal(evidence) { 1669 return true 1670 } 1671 } 1672 return false 1673 } 1674 1675 //-------------------------------------------- MOCKING -------------------------------------- 1676 1677 // unstable - use only for testing 1678 1679 // assumes the round to be 0 and the validator index to be 0 1680 func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence { 1681 val := NewMockPV() 1682 return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID) 1683 } 1684 1685 func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time, 1686 pv PrivValidator, chainID string) *DuplicateVoteEvidence { 1687 pubKey, _ := pv.GetPubKey() 1688 voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time) 1689 vA := voteA.ToProto() 1690 _ = pv.SignVote(chainID, vA) 1691 voteA.Signature = vA.Signature 1692 voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time) 1693 vB := voteB.ToProto() 1694 _ = pv.SignVote(chainID, vB) 1695 voteB.Signature = vB.Signature 1696 return NewDuplicateVoteEvidence(voteA, voteB) 1697 1698 } 1699 1700 func makeMockVote(height int64, round, index int32, addr Address, 1701 blockID BlockID, time time.Time) *Vote { 1702 return &Vote{ 1703 Type: tmproto.SignedMsgType(2), 1704 Height: height, 1705 Round: round, 1706 BlockID: blockID, 1707 Timestamp: time, 1708 ValidatorAddress: addr, 1709 ValidatorIndex: index, 1710 } 1711 } 1712 1713 func randBlockID() BlockID { 1714 return BlockID{ 1715 Hash: tmrand.Bytes(tmhash.Size), 1716 PartSetHeader: PartSetHeader{ 1717 Total: 1, 1718 Hash: tmrand.Bytes(tmhash.Size), 1719 }, 1720 } 1721 } 1722 1723 // mock polc - fails validate basic, not stable 1724 func NewMockPOLC(height int64, time time.Time, pubKey crypto.PubKey) ProofOfLockChange { 1725 voteVal := NewMockPV() 1726 pKey, _ := voteVal.GetPubKey() 1727 vote := Vote{Type: tmproto.PrecommitType, Height: height, Round: 1, BlockID: BlockID{}, 1728 Timestamp: time, ValidatorAddress: pKey.Address(), ValidatorIndex: 1, Signature: []byte{}} 1729 1730 v := vote.ToProto() 1731 if err := voteVal.SignVote("mock-chain-id", v); err != nil { 1732 panic(err) 1733 } 1734 vote.Signature = v.Signature 1735 1736 return ProofOfLockChange{ 1737 Votes: []*Vote{&vote}, 1738 PubKey: pubKey, 1739 } 1740 } 1741 1742 func maxTime(t1 time.Time, t2 time.Time) time.Time { 1743 if t1.After(t2) { 1744 return t1 1745 } 1746 return t2 1747 }