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.

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