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.

1747 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.
  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. e.VoteA.Type != e.VoteB.Type {
  954. return fmt.Errorf("h/s do not match: %d/%v vs %d/%v",
  955. e.VoteA.Height, e.VoteA.Type, e.VoteB.Height, e.VoteB.Type)
  956. }
  957. // Enforce that vote A came before vote B
  958. if e.VoteA.Timestamp.After(e.VoteB.Timestamp) {
  959. return fmt.Errorf("vote A should have a timestamp before vote B, but got %s > %s",
  960. e.VoteA.Timestamp, e.VoteB.Timestamp)
  961. }
  962. // Address must be the same
  963. if !bytes.Equal(e.VoteA.ValidatorAddress, e.VoteB.ValidatorAddress) {
  964. return fmt.Errorf("validator addresses do not match: %X vs %X",
  965. e.VoteA.ValidatorAddress,
  966. e.VoteB.ValidatorAddress,
  967. )
  968. }
  969. // Index must be the same
  970. // https://github.com/tendermint/tendermint/issues/4619
  971. if e.VoteA.ValidatorIndex != e.VoteB.ValidatorIndex {
  972. return fmt.Errorf(
  973. "duplicateVoteEvidence Error: Validator indices do not match. Got %d and %d",
  974. e.VoteA.ValidatorIndex,
  975. e.VoteB.ValidatorIndex,
  976. )
  977. }
  978. // BlockIDs must be different
  979. if e.VoteA.BlockID.Equals(e.VoteB.BlockID) {
  980. return fmt.Errorf(
  981. "block IDs are the same (%v) - not a real duplicate vote",
  982. e.VoteA.BlockID,
  983. )
  984. }
  985. return nil
  986. }
  987. func (e *PotentialAmnesiaEvidence) String() string {
  988. return fmt.Sprintf("PotentialAmnesiaEvidence{VoteA: %v, VoteB: %v}", e.VoteA, e.VoteB)
  989. }
  990. // Primed finds whether the PotentialAmnesiaEvidence is ready to be upgraded to Amnesia Evidence. It is decided if
  991. // either the prosecuted node voted in the past or if the allocated trial period has expired without a proof of lock
  992. // change having been provided.
  993. func (e *PotentialAmnesiaEvidence) Primed(trialPeriod, currentHeight int64) bool {
  994. // voted in the past can be instantly punishable
  995. if e.VoteA.Round > e.VoteB.Round {
  996. return true
  997. }
  998. // has the trial period expired
  999. if e.HeightStamp > 0 {
  1000. return e.HeightStamp+trialPeriod <= currentHeight
  1001. }
  1002. return false
  1003. }
  1004. func (e *PotentialAmnesiaEvidence) ToProto() *tmproto.PotentialAmnesiaEvidence {
  1005. voteB := e.VoteB.ToProto()
  1006. voteA := e.VoteA.ToProto()
  1007. tp := &tmproto.PotentialAmnesiaEvidence{
  1008. VoteA: voteA,
  1009. VoteB: voteB,
  1010. HeightStamp: e.HeightStamp,
  1011. }
  1012. return tp
  1013. }
  1014. // ------------------
  1015. // ProofOfLockChange (POLC) proves that a node followed the consensus protocol and voted for a precommit in two
  1016. // different rounds because the node received a majority of votes for a different block in the latter round. In cases of
  1017. // amnesia evidence, a suspected node will need ProofOfLockChange to prove that the node did not break protocol.
  1018. type ProofOfLockChange struct {
  1019. Votes []*Vote `json:"votes"`
  1020. PubKey crypto.PubKey `json:"pubkey"`
  1021. }
  1022. // MakePOLCFromVoteSet can be used when a majority of prevotes or precommits for a block is seen
  1023. // that the node has itself not yet voted for in order to process the vote set into a proof of lock change
  1024. func NewPOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) (*ProofOfLockChange, error) {
  1025. polc := newPOLCFromVoteSet(voteSet, pubKey, blockID)
  1026. return polc, polc.ValidateBasic()
  1027. }
  1028. func newPOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) *ProofOfLockChange {
  1029. if voteSet == nil {
  1030. return nil
  1031. }
  1032. var votes []*Vote
  1033. valSetSize := voteSet.Size()
  1034. for valIdx := int32(0); int(valIdx) < valSetSize; valIdx++ {
  1035. vote := voteSet.GetByIndex(valIdx)
  1036. if vote != nil && vote.BlockID.Equals(blockID) {
  1037. votes = append(votes, vote)
  1038. }
  1039. }
  1040. return NewPOLC(votes, pubKey)
  1041. }
  1042. // NewPOLC creates a POLC
  1043. func NewPOLC(votes []*Vote, pubKey crypto.PubKey) *ProofOfLockChange {
  1044. return &ProofOfLockChange{
  1045. Votes: votes,
  1046. PubKey: pubKey,
  1047. }
  1048. }
  1049. // EmptyPOLC returns an empty polc. This is used when no polc has been provided in the allocated trial period time
  1050. // and the node now needs to move to upgrading to AmnesiaEvidence and hence uses an empty polc
  1051. func NewEmptyPOLC() *ProofOfLockChange {
  1052. return &ProofOfLockChange{
  1053. nil,
  1054. nil,
  1055. }
  1056. }
  1057. func (e *ProofOfLockChange) Height() int64 {
  1058. return e.Votes[0].Height
  1059. }
  1060. // Time returns time of the latest vote.
  1061. func (e *ProofOfLockChange) Time() time.Time {
  1062. latest := e.Votes[0].Timestamp
  1063. for _, vote := range e.Votes {
  1064. if vote.Timestamp.After(latest) {
  1065. latest = vote.Timestamp
  1066. }
  1067. }
  1068. return latest
  1069. }
  1070. func (e *ProofOfLockChange) Round() int32 {
  1071. return e.Votes[0].Round
  1072. }
  1073. func (e *ProofOfLockChange) Address() []byte {
  1074. return e.PubKey.Address()
  1075. }
  1076. func (e *ProofOfLockChange) BlockID() BlockID {
  1077. return e.Votes[0].BlockID
  1078. }
  1079. // ValidateVotes checks the polc against the validator set of that height. The function makes sure that the polc
  1080. // contains a majority of votes and that each
  1081. func (e *ProofOfLockChange) ValidateVotes(valSet *ValidatorSet, chainID string) error {
  1082. if e.IsAbsent() {
  1083. return errors.New("polc is empty")
  1084. }
  1085. talliedVotingPower := int64(0)
  1086. votingPowerNeeded := valSet.TotalVotingPower() * 2 / 3
  1087. for _, vote := range e.Votes {
  1088. exists := false
  1089. for _, validator := range valSet.Validators {
  1090. if bytes.Equal(validator.Address, vote.ValidatorAddress) {
  1091. exists = true
  1092. v := vote.ToProto()
  1093. if !validator.PubKey.VerifyBytes(VoteSignBytes(chainID, v), vote.Signature) {
  1094. return fmt.Errorf("cannot verify vote (from validator: %d) against signature: %v",
  1095. vote.ValidatorIndex, vote.Signature)
  1096. }
  1097. talliedVotingPower += validator.VotingPower
  1098. }
  1099. }
  1100. if !exists {
  1101. return fmt.Errorf("vote was not from a validator in this set: %v", vote.String())
  1102. }
  1103. }
  1104. if talliedVotingPower <= votingPowerNeeded {
  1105. return ErrNotEnoughVotingPowerSigned{
  1106. Got: talliedVotingPower,
  1107. Needed: votingPowerNeeded + 1,
  1108. }
  1109. }
  1110. return nil
  1111. }
  1112. func (e *ProofOfLockChange) Equal(e2 *ProofOfLockChange) bool {
  1113. return bytes.Equal(e.Address(), e2.Address()) && e.Height() == e2.Height() &&
  1114. e.Round() == e2.Round()
  1115. }
  1116. func (e *ProofOfLockChange) ValidateBasic() error {
  1117. if e == nil {
  1118. return errors.New("empty proof of lock change")
  1119. }
  1120. // first check if the polc is absent / empty
  1121. if e.IsAbsent() {
  1122. return nil
  1123. }
  1124. if e.PubKey == nil {
  1125. return errors.New("missing public key")
  1126. }
  1127. // validate basic doesn't count the number of votes and their voting power, this is to be done by VerifyEvidence
  1128. if e.Votes == nil || len(e.Votes) == 0 {
  1129. return errors.New("missing votes")
  1130. }
  1131. // height, round and vote type must be the same for all votes
  1132. height := e.Height()
  1133. round := e.Round()
  1134. if round == 0 {
  1135. return errors.New("can't have a polc for the first round")
  1136. }
  1137. voteType := e.Votes[0].Type
  1138. for idx, vote := range e.Votes {
  1139. if vote == nil {
  1140. return fmt.Errorf("nil vote at index: %d", idx)
  1141. }
  1142. if err := vote.ValidateBasic(); err != nil {
  1143. return fmt.Errorf("invalid vote#%d: %w", idx, err)
  1144. }
  1145. if vote.Height != height {
  1146. return fmt.Errorf("invalid height for vote#%d: %d instead of %d", idx, vote.Height, height)
  1147. }
  1148. if vote.Round != round {
  1149. return fmt.Errorf("invalid round for vote#%d: %d instead of %d", idx, vote.Round, round)
  1150. }
  1151. if vote.Type != voteType {
  1152. return fmt.Errorf("invalid vote type for vote#%d: %d instead of %d", idx, vote.Type, voteType)
  1153. }
  1154. if !vote.BlockID.Equals(e.BlockID()) {
  1155. return fmt.Errorf("vote must be for the same block id: %v instead of %v", e.BlockID(), vote.BlockID)
  1156. }
  1157. if bytes.Equal(vote.ValidatorAddress.Bytes(), e.PubKey.Address().Bytes()) {
  1158. return fmt.Errorf("vote validator address cannot be the same as the public key address: %X all votes %v",
  1159. vote.ValidatorAddress.Bytes(), e.PubKey.Address().Bytes())
  1160. }
  1161. for i := idx + 1; i < len(e.Votes); i++ {
  1162. if bytes.Equal(vote.ValidatorAddress.Bytes(), e.Votes[i].ValidatorAddress.Bytes()) {
  1163. return fmt.Errorf("duplicate votes: %v", vote)
  1164. }
  1165. }
  1166. }
  1167. return nil
  1168. }
  1169. func (e *ProofOfLockChange) String() string {
  1170. if e.IsAbsent() {
  1171. return "Empty ProofOfLockChange"
  1172. }
  1173. return fmt.Sprintf("ProofOfLockChange {Address: %X, Height: %d, Round: %d", e.Address(), e.Height(),
  1174. e.Votes[0].Round)
  1175. }
  1176. // IsAbsent checks if the polc is empty
  1177. func (e *ProofOfLockChange) IsAbsent() bool {
  1178. return e.Votes == nil && e.PubKey == nil
  1179. }
  1180. func (e *ProofOfLockChange) ToProto() (*tmproto.ProofOfLockChange, error) {
  1181. plc := new(tmproto.ProofOfLockChange)
  1182. vpb := make([]*tmproto.Vote, len(e.Votes))
  1183. // if absent create empty proto polc
  1184. if e.IsAbsent() {
  1185. return plc, nil
  1186. }
  1187. if e.Votes == nil {
  1188. return plc, errors.New("invalid proof of lock change (no votes), did you forget to validate?")
  1189. }
  1190. for i, v := range e.Votes {
  1191. pb := v.ToProto()
  1192. if pb != nil {
  1193. vpb[i] = pb
  1194. }
  1195. }
  1196. pk, err := cryptoenc.PubKeyToProto(e.PubKey)
  1197. if err != nil {
  1198. return plc, fmt.Errorf("invalid proof of lock change (err: %w), did you forget to validate?", err)
  1199. }
  1200. plc.PubKey = &pk
  1201. plc.Votes = vpb
  1202. return plc, nil
  1203. }
  1204. // AmnesiaEvidence is the progression of PotentialAmnesiaEvidence and is used to prove an infringement of the
  1205. // Tendermint consensus when a validator incorrectly sends a vote in a later round without correctly changing the lock
  1206. type AmnesiaEvidence struct {
  1207. *PotentialAmnesiaEvidence
  1208. Polc *ProofOfLockChange
  1209. }
  1210. // Height, Time, Address, and Verify, and Hash functions are all inherited by the PotentialAmnesiaEvidence struct
  1211. var _ Evidence = &AmnesiaEvidence{}
  1212. func NewAmnesiaEvidence(pe *PotentialAmnesiaEvidence, proof *ProofOfLockChange) *AmnesiaEvidence {
  1213. return &AmnesiaEvidence{
  1214. pe,
  1215. proof,
  1216. }
  1217. }
  1218. // Note: Amnesia evidence with or without a polc are considered the same
  1219. func (e *AmnesiaEvidence) Equal(ev Evidence) bool {
  1220. if e2, ok := ev.(*AmnesiaEvidence); ok {
  1221. return e.PotentialAmnesiaEvidence.Equal(e2.PotentialAmnesiaEvidence)
  1222. }
  1223. return false
  1224. }
  1225. func (e *AmnesiaEvidence) Bytes() []byte {
  1226. pbe := e.ToProto()
  1227. bz, err := pbe.Marshal()
  1228. if err != nil {
  1229. panic(fmt.Errorf("converting amnesia evidence to bytes, err: %w", err))
  1230. }
  1231. return bz
  1232. }
  1233. func (e *AmnesiaEvidence) ValidateBasic() error {
  1234. if e == nil {
  1235. return errors.New("empty amnesia evidence")
  1236. }
  1237. if e.Polc == nil || e.PotentialAmnesiaEvidence == nil {
  1238. return errors.New("amnesia evidence is missing either the polc or the potential amnesia evidence")
  1239. }
  1240. if err := e.PotentialAmnesiaEvidence.ValidateBasic(); err != nil {
  1241. return fmt.Errorf("invalid potential amnesia evidence: %w", err)
  1242. }
  1243. if !e.Polc.IsAbsent() {
  1244. if err := e.Polc.ValidateBasic(); err != nil {
  1245. return fmt.Errorf("invalid proof of lock change: %w", err)
  1246. }
  1247. if !bytes.Equal(e.PotentialAmnesiaEvidence.Address(), e.Polc.Address()) {
  1248. return fmt.Errorf("validator addresses do not match (%X - %X)", e.PotentialAmnesiaEvidence.Address(),
  1249. e.Polc.Address())
  1250. }
  1251. if e.PotentialAmnesiaEvidence.Height() != e.Polc.Height() {
  1252. return fmt.Errorf("heights do not match (%d - %d)", e.PotentialAmnesiaEvidence.Height(),
  1253. e.Polc.Height())
  1254. }
  1255. if e.Polc.Round() <= e.VoteA.Round || e.Polc.Round() > e.VoteB.Round {
  1256. return fmt.Errorf("polc must be between %d and %d (inclusive)", e.VoteA.Round+1, e.VoteB.Round)
  1257. }
  1258. if !e.Polc.BlockID().Equals(e.PotentialAmnesiaEvidence.VoteB.BlockID) && !e.Polc.BlockID().IsZero() {
  1259. return fmt.Errorf("polc must be either for a nil block or for the same block as the second vote: %v != %v",
  1260. e.Polc.BlockID(), e.PotentialAmnesiaEvidence.VoteB.BlockID)
  1261. }
  1262. if e.Polc.Time().After(e.PotentialAmnesiaEvidence.VoteB.Timestamp) {
  1263. return fmt.Errorf("validator voted again before receiving a majority of votes for the new block: %v is after %v",
  1264. e.Polc.Time(), e.PotentialAmnesiaEvidence.VoteB.Timestamp)
  1265. }
  1266. }
  1267. return nil
  1268. }
  1269. // ViolatedConsensus assess on the basis of the AmnesiaEvidence whether the validator has violated the
  1270. // Tendermint consensus. Evidence must be validated first (see ValidateBasic).
  1271. // We are only interested in proving that the latter of the votes in terms of time was correctly done.
  1272. func (e *AmnesiaEvidence) ViolatedConsensus() (bool, string) {
  1273. // a validator having voted cannot go back and vote on an earlier round
  1274. if e.PotentialAmnesiaEvidence.VoteA.Round > e.PotentialAmnesiaEvidence.VoteB.Round {
  1275. return true, "validator went back and voted on a previous round"
  1276. }
  1277. // if empty, then no proof was provided to defend the validators actions
  1278. if e.Polc.IsAbsent() {
  1279. return true, "no proof of lock was provided"
  1280. }
  1281. return false, ""
  1282. }
  1283. func (e *AmnesiaEvidence) String() string {
  1284. return fmt.Sprintf("AmnesiaEvidence{ %v, polc: %v }", e.PotentialAmnesiaEvidence, e.Polc)
  1285. }
  1286. func (e *AmnesiaEvidence) ToProto() *tmproto.AmnesiaEvidence {
  1287. paepb := e.PotentialAmnesiaEvidence.ToProto()
  1288. polc, err := e.Polc.ToProto()
  1289. if err != nil {
  1290. polc, _ = NewEmptyPOLC().ToProto()
  1291. }
  1292. return &tmproto.AmnesiaEvidence{
  1293. PotentialAmnesiaEvidence: paepb,
  1294. Polc: polc,
  1295. }
  1296. }
  1297. func ProofOfLockChangeFromProto(pb *tmproto.ProofOfLockChange) (*ProofOfLockChange, error) {
  1298. if pb == nil {
  1299. return nil, errors.New("nil proof of lock change")
  1300. }
  1301. plc := new(ProofOfLockChange)
  1302. // check if it is an empty polc
  1303. if pb.PubKey == nil && pb.Votes == nil {
  1304. return plc, nil
  1305. }
  1306. if pb.Votes == nil {
  1307. return nil, errors.New("proofOfLockChange: is not absent but has no votes")
  1308. }
  1309. vpb := make([]*Vote, len(pb.Votes))
  1310. for i, v := range pb.Votes {
  1311. vi, err := VoteFromProto(v)
  1312. if err != nil {
  1313. return nil, err
  1314. }
  1315. vpb[i] = vi
  1316. }
  1317. if pb.PubKey == nil {
  1318. return nil, errors.New("proofOfLockChange: is not absent but has nil PubKey")
  1319. }
  1320. pk, err := cryptoenc.PubKeyFromProto(*pb.PubKey)
  1321. if err != nil {
  1322. return nil, err
  1323. }
  1324. plc.PubKey = pk
  1325. plc.Votes = vpb
  1326. return plc, plc.ValidateBasic()
  1327. }
  1328. func PotentialAmnesiaEvidenceFromProto(pb *tmproto.PotentialAmnesiaEvidence) (*PotentialAmnesiaEvidence, error) {
  1329. voteA, err := VoteFromProto(pb.GetVoteA())
  1330. if err != nil {
  1331. return nil, err
  1332. }
  1333. voteB, err := VoteFromProto(pb.GetVoteB())
  1334. if err != nil {
  1335. return nil, err
  1336. }
  1337. tp := PotentialAmnesiaEvidence{
  1338. VoteA: voteA,
  1339. VoteB: voteB,
  1340. HeightStamp: pb.GetHeightStamp(),
  1341. }
  1342. return &tp, tp.ValidateBasic()
  1343. }
  1344. func AmnesiaEvidenceFromProto(pb *tmproto.AmnesiaEvidence) (*AmnesiaEvidence, error) {
  1345. if pb == nil {
  1346. return nil, errors.New("nil amnesia evidence")
  1347. }
  1348. pae, err := PotentialAmnesiaEvidenceFromProto(pb.PotentialAmnesiaEvidence)
  1349. if err != nil {
  1350. return nil, fmt.Errorf("decoding to amnesia evidence, err: %w", err)
  1351. }
  1352. polc, err := ProofOfLockChangeFromProto(pb.Polc)
  1353. if err != nil {
  1354. return nil, fmt.Errorf("decoding to amnesia evidence, err: %w", err)
  1355. }
  1356. tp := &AmnesiaEvidence{
  1357. PotentialAmnesiaEvidence: pae,
  1358. Polc: polc,
  1359. }
  1360. return tp, tp.ValidateBasic()
  1361. }
  1362. //--------------------------------------------------
  1363. // EvidenceList is a list of Evidence. Evidences is not a word.
  1364. type EvidenceList []Evidence
  1365. // Hash returns the simple merkle root hash of the EvidenceList.
  1366. func (evl EvidenceList) Hash() []byte {
  1367. // These allocations are required because Evidence is not of type Bytes, and
  1368. // golang slices can't be typed cast. This shouldn't be a performance problem since
  1369. // the Evidence size is capped.
  1370. evidenceBzs := make([][]byte, len(evl))
  1371. for i := 0; i < len(evl); i++ {
  1372. evidenceBzs[i] = evl[i].Bytes()
  1373. }
  1374. return merkle.HashFromByteSlices(evidenceBzs)
  1375. }
  1376. func (evl EvidenceList) String() string {
  1377. s := ""
  1378. for _, e := range evl {
  1379. s += fmt.Sprintf("%s\t\t", e)
  1380. }
  1381. return s
  1382. }
  1383. // Has returns true if the evidence is in the EvidenceList.
  1384. func (evl EvidenceList) Has(evidence Evidence) bool {
  1385. for _, ev := range evl {
  1386. if ev.Equal(evidence) {
  1387. return true
  1388. }
  1389. }
  1390. return false
  1391. }
  1392. //-------------------------------------------- MOCKING --------------------------------------
  1393. // unstable - use only for testing
  1394. // assumes the round to be 0 and the validator index to be 0
  1395. func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence {
  1396. val := NewMockPV()
  1397. return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID)
  1398. }
  1399. func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time,
  1400. pv PrivValidator, chainID string) *DuplicateVoteEvidence {
  1401. pubKey, _ := pv.GetPubKey()
  1402. voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  1403. vA := voteA.ToProto()
  1404. _ = pv.SignVote(chainID, vA)
  1405. voteA.Signature = vA.Signature
  1406. voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  1407. vB := voteB.ToProto()
  1408. _ = pv.SignVote(chainID, vB)
  1409. voteB.Signature = vB.Signature
  1410. return NewDuplicateVoteEvidence(voteA, voteB)
  1411. }
  1412. func makeMockVote(height int64, round, index int32, addr Address,
  1413. blockID BlockID, time time.Time) *Vote {
  1414. return &Vote{
  1415. Type: tmproto.SignedMsgType(2),
  1416. Height: height,
  1417. Round: round,
  1418. BlockID: blockID,
  1419. Timestamp: time,
  1420. ValidatorAddress: addr,
  1421. ValidatorIndex: index,
  1422. }
  1423. }
  1424. func randBlockID() BlockID {
  1425. return BlockID{
  1426. Hash: tmrand.Bytes(tmhash.Size),
  1427. PartSetHeader: PartSetHeader{
  1428. Total: 1,
  1429. Hash: tmrand.Bytes(tmhash.Size),
  1430. },
  1431. }
  1432. }
  1433. // mock polc - fails validate basic, not stable
  1434. func NewMockPOLC(height int64, time time.Time, pubKey crypto.PubKey) ProofOfLockChange {
  1435. voteVal := NewMockPV()
  1436. pKey, _ := voteVal.GetPubKey()
  1437. vote := Vote{Type: tmproto.PrecommitType, Height: height, Round: 1, BlockID: BlockID{},
  1438. Timestamp: time, ValidatorAddress: pKey.Address(), ValidatorIndex: 1, Signature: []byte{}}
  1439. v := vote.ToProto()
  1440. if err := voteVal.SignVote("mock-chain-id", v); err != nil {
  1441. panic(err)
  1442. }
  1443. vote.Signature = v.Signature
  1444. return ProofOfLockChange{
  1445. Votes: []*Vote{&vote},
  1446. PubKey: pubKey,
  1447. }
  1448. }
  1449. func maxTime(t1 time.Time, t2 time.Time) time.Time {
  1450. if t1.After(t2) {
  1451. return t1
  1452. }
  1453. return t2
  1454. }