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.

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