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.

1581 lines
45 KiB

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