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.

1738 lines
49 KiB

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