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.

987 lines
29 KiB

lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/pkg/errors"
  8. "github.com/tendermint/tendermint/crypto/tmhash"
  9. tmmath "github.com/tendermint/tendermint/libs/math"
  10. amino "github.com/tendermint/go-amino"
  11. "github.com/tendermint/tendermint/crypto"
  12. "github.com/tendermint/tendermint/crypto/merkle"
  13. )
  14. const (
  15. // MaxEvidenceBytes is a maximum size of any evidence (including amino overhead).
  16. MaxEvidenceBytes int64 = 484
  17. // An invalid field in the header from LunaticValidatorEvidence.
  18. // Must be a function of the ABCI application state.
  19. ValidatorsHashField = "ValidatorsHash"
  20. NextValidatorsHashField = "NextValidatorsHash"
  21. ConsensusHashField = "ConsensusHash"
  22. AppHashField = "AppHash"
  23. LastResultsHashField = "LastResultsHash"
  24. )
  25. // ErrEvidenceInvalid wraps a piece of evidence and the error denoting how or why it is invalid.
  26. type ErrEvidenceInvalid struct {
  27. Evidence Evidence
  28. ErrorValue error
  29. }
  30. // NewErrEvidenceInvalid returns a new EvidenceInvalid with the given err.
  31. func NewErrEvidenceInvalid(ev Evidence, err error) *ErrEvidenceInvalid {
  32. return &ErrEvidenceInvalid{ev, err}
  33. }
  34. // Error returns a string representation of the error.
  35. func (err *ErrEvidenceInvalid) Error() string {
  36. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.ErrorValue, err.Evidence)
  37. }
  38. // ErrEvidenceOverflow is for when there is too much evidence in a block.
  39. type ErrEvidenceOverflow struct {
  40. MaxNum int64
  41. GotNum int64
  42. }
  43. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  44. func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow {
  45. return &ErrEvidenceOverflow{max, got}
  46. }
  47. // Error returns a string representation of the error.
  48. func (err *ErrEvidenceOverflow) Error() string {
  49. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.MaxNum, err.GotNum)
  50. }
  51. //-------------------------------------------
  52. // Evidence represents any provable malicious activity by a validator.
  53. type Evidence interface {
  54. Height() int64 // height of the equivocation
  55. Time() time.Time // time of the equivocation
  56. Address() []byte // address of the equivocating validator
  57. Bytes() []byte // bytes which comprise the evidence
  58. Hash() []byte // hash of the evidence
  59. Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence
  60. Equal(Evidence) bool // check equality of evidence
  61. ValidateBasic() error
  62. String() string
  63. }
  64. type CompositeEvidence interface {
  65. VerifyComposite(committedHeader *Header, valSet *ValidatorSet) error
  66. Split(committedHeader *Header, valSet *ValidatorSet, valToLastHeight map[string]int64) []Evidence
  67. }
  68. func RegisterEvidences(cdc *amino.Codec) {
  69. cdc.RegisterInterface((*Evidence)(nil), nil)
  70. cdc.RegisterConcrete(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence", nil)
  71. cdc.RegisterConcrete(&ConflictingHeadersEvidence{}, "tendermint/ConflictingHeadersEvidence", nil)
  72. cdc.RegisterConcrete(&PhantomValidatorEvidence{}, "tendermint/PhantomValidatorEvidence", nil)
  73. cdc.RegisterConcrete(&LunaticValidatorEvidence{}, "tendermint/LunaticValidatorEvidence", nil)
  74. cdc.RegisterConcrete(&PotentialAmnesiaEvidence{}, "tendermint/PotentialAmnesiaEvidence", nil)
  75. }
  76. func RegisterMockEvidences(cdc *amino.Codec) {
  77. cdc.RegisterConcrete(MockEvidence{}, "tendermint/MockEvidence", nil)
  78. cdc.RegisterConcrete(MockRandomEvidence{}, "tendermint/MockRandomEvidence", nil)
  79. }
  80. const (
  81. MaxEvidenceBytesDenominator = 10
  82. )
  83. // MaxEvidencePerBlock returns the maximum number of evidences
  84. // allowed in the block and their maximum total size (limitted to 1/10th
  85. // of the maximum block size).
  86. // TODO: change to a constant, or to a fraction of the validator set size.
  87. // See https://github.com/tendermint/tendermint/issues/2590
  88. func MaxEvidencePerBlock(blockMaxBytes int64) (int64, int64) {
  89. maxBytes := blockMaxBytes / MaxEvidenceBytesDenominator
  90. maxNum := maxBytes / MaxEvidenceBytes
  91. return maxNum, maxBytes
  92. }
  93. //-------------------------------------------
  94. // DuplicateVoteEvidence contains evidence a validator signed two conflicting
  95. // votes.
  96. type DuplicateVoteEvidence struct {
  97. PubKey crypto.PubKey
  98. VoteA *Vote
  99. VoteB *Vote
  100. }
  101. var _ Evidence = &DuplicateVoteEvidence{}
  102. // NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given
  103. // two conflicting votes. If one of the votes is nil, evidence returned is nil as well
  104. func NewDuplicateVoteEvidence(pubkey crypto.PubKey, vote1 *Vote, vote2 *Vote) *DuplicateVoteEvidence {
  105. var voteA, voteB *Vote
  106. if vote1 == nil || vote2 == nil {
  107. return nil
  108. }
  109. if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 {
  110. voteA = vote1
  111. voteB = vote2
  112. } else {
  113. voteA = vote2
  114. voteB = vote1
  115. }
  116. return &DuplicateVoteEvidence{
  117. PubKey: pubkey,
  118. VoteA: voteA,
  119. VoteB: voteB,
  120. }
  121. }
  122. // String returns a string representation of the evidence.
  123. func (dve *DuplicateVoteEvidence) String() string {
  124. return fmt.Sprintf("DuplicateVoteEvidence{VoteA: %v, VoteB: %v}", dve.VoteA, dve.VoteB)
  125. }
  126. // Height returns the height this evidence refers to.
  127. func (dve *DuplicateVoteEvidence) Height() int64 {
  128. return dve.VoteA.Height
  129. }
  130. // Time returns the time the evidence was created.
  131. func (dve *DuplicateVoteEvidence) Time() time.Time {
  132. return dve.VoteA.Timestamp
  133. }
  134. // Address returns the address of the validator.
  135. func (dve *DuplicateVoteEvidence) Address() []byte {
  136. return dve.PubKey.Address()
  137. }
  138. // Hash returns the hash of the evidence.
  139. func (dve *DuplicateVoteEvidence) Bytes() []byte {
  140. return cdcEncode(dve)
  141. }
  142. // Hash returns the hash of the evidence.
  143. func (dve *DuplicateVoteEvidence) Hash() []byte {
  144. return tmhash.Sum(cdcEncode(dve))
  145. }
  146. // Verify returns an error if the two votes aren't conflicting.
  147. //
  148. // To be conflicting, they must be from the same validator, for the same H/R/S,
  149. // but for different blocks.
  150. func (dve *DuplicateVoteEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  151. // H/R/S must be the same
  152. if dve.VoteA.Height != dve.VoteB.Height ||
  153. dve.VoteA.Round != dve.VoteB.Round ||
  154. dve.VoteA.Type != dve.VoteB.Type {
  155. return fmt.Errorf("h/r/s does not match: %d/%d/%v vs %d/%d/%v",
  156. dve.VoteA.Height, dve.VoteA.Round, dve.VoteA.Type,
  157. dve.VoteB.Height, dve.VoteB.Round, dve.VoteB.Type)
  158. }
  159. // Address must be the same
  160. if !bytes.Equal(dve.VoteA.ValidatorAddress, dve.VoteB.ValidatorAddress) {
  161. return fmt.Errorf("validator addresses do not match: %X vs %X",
  162. dve.VoteA.ValidatorAddress,
  163. dve.VoteB.ValidatorAddress,
  164. )
  165. }
  166. // Index must be the same
  167. if dve.VoteA.ValidatorIndex != dve.VoteB.ValidatorIndex {
  168. return fmt.Errorf(
  169. "validator indices do not match: %d and %d",
  170. dve.VoteA.ValidatorIndex,
  171. dve.VoteB.ValidatorIndex,
  172. )
  173. }
  174. // BlockIDs must be different
  175. if dve.VoteA.BlockID.Equals(dve.VoteB.BlockID) {
  176. return fmt.Errorf(
  177. "block IDs are the same (%v) - not a real duplicate vote",
  178. dve.VoteA.BlockID,
  179. )
  180. }
  181. // pubkey must match address (this should already be true, sanity check)
  182. addr := dve.VoteA.ValidatorAddress
  183. if !bytes.Equal(pubKey.Address(), addr) {
  184. return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)",
  185. addr, pubKey, pubKey.Address())
  186. }
  187. // Signatures must be valid
  188. if !pubKey.VerifyBytes(dve.VoteA.SignBytes(chainID), dve.VoteA.Signature) {
  189. return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature)
  190. }
  191. if !pubKey.VerifyBytes(dve.VoteB.SignBytes(chainID), dve.VoteB.Signature) {
  192. return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature)
  193. }
  194. return nil
  195. }
  196. // Equal checks if two pieces of evidence are equal.
  197. func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool {
  198. if _, ok := ev.(*DuplicateVoteEvidence); !ok {
  199. return false
  200. }
  201. // just check their hashes
  202. dveHash := tmhash.Sum(cdcEncode(dve))
  203. evHash := tmhash.Sum(cdcEncode(ev))
  204. return bytes.Equal(dveHash, evHash)
  205. }
  206. // ValidateBasic performs basic validation.
  207. func (dve *DuplicateVoteEvidence) ValidateBasic() error {
  208. if len(dve.PubKey.Bytes()) == 0 {
  209. return errors.New("empty PubKey")
  210. }
  211. if dve.VoteA == nil || dve.VoteB == nil {
  212. return fmt.Errorf("one or both of the votes are empty %v, %v", dve.VoteA, dve.VoteB)
  213. }
  214. if err := dve.VoteA.ValidateBasic(); err != nil {
  215. return fmt.Errorf("invalid VoteA: %w", err)
  216. }
  217. if err := dve.VoteB.ValidateBasic(); err != nil {
  218. return fmt.Errorf("invalid VoteB: %w", err)
  219. }
  220. // Enforce Votes are lexicographically sorted on blockID
  221. if strings.Compare(dve.VoteA.BlockID.Key(), dve.VoteB.BlockID.Key()) >= 0 {
  222. return errors.New("duplicate votes in invalid order")
  223. }
  224. return nil
  225. }
  226. //-------------------------------------------
  227. // EvidenceList is a list of Evidence. Evidences is not a word.
  228. type EvidenceList []Evidence
  229. // Hash returns the simple merkle root hash of the EvidenceList.
  230. func (evl EvidenceList) Hash() []byte {
  231. // These allocations are required because Evidence is not of type Bytes, and
  232. // golang slices can't be typed cast. This shouldn't be a performance problem since
  233. // the Evidence size is capped.
  234. evidenceBzs := make([][]byte, len(evl))
  235. for i := 0; i < len(evl); i++ {
  236. evidenceBzs[i] = evl[i].Bytes()
  237. }
  238. return merkle.SimpleHashFromByteSlices(evidenceBzs)
  239. }
  240. func (evl EvidenceList) String() string {
  241. s := ""
  242. for _, e := range evl {
  243. s += fmt.Sprintf("%s\t\t", e)
  244. }
  245. return s
  246. }
  247. // Has returns true if the evidence is in the EvidenceList.
  248. func (evl EvidenceList) Has(evidence Evidence) bool {
  249. for _, ev := range evl {
  250. if ev.Equal(evidence) {
  251. return true
  252. }
  253. }
  254. return false
  255. }
  256. //-------------------------------------------
  257. // ConflictingHeadersEvidence is primarily used by the light client when it
  258. // observes two conflicting headers, both having 1/3+ of the voting power of
  259. // the currently trusted validator set.
  260. type ConflictingHeadersEvidence struct {
  261. H1 *SignedHeader `json:"h_1"`
  262. H2 *SignedHeader `json:"h_2"`
  263. }
  264. var _ Evidence = &ConflictingHeadersEvidence{}
  265. var _ CompositeEvidence = &ConflictingHeadersEvidence{}
  266. var _ Evidence = ConflictingHeadersEvidence{}
  267. var _ CompositeEvidence = ConflictingHeadersEvidence{}
  268. // Split breaks up eviddence into smaller chunks (one per validator except for
  269. // PotentialAmnesiaEvidence): PhantomValidatorEvidence,
  270. // LunaticValidatorEvidence, DuplicateVoteEvidence and
  271. // PotentialAmnesiaEvidence.
  272. //
  273. // committedHeader - header at height H1.Height == H2.Height
  274. // valSet - validator set at height H1.Height == H2.Height
  275. // valToLastHeight - map between active validators and respective last heights
  276. func (ev ConflictingHeadersEvidence) Split(committedHeader *Header, valSet *ValidatorSet,
  277. valToLastHeight map[string]int64) []Evidence {
  278. evList := make([]Evidence, 0)
  279. var alternativeHeader *SignedHeader
  280. if bytes.Equal(committedHeader.Hash(), ev.H1.Hash()) {
  281. alternativeHeader = ev.H2
  282. } else {
  283. alternativeHeader = ev.H1
  284. }
  285. // If there are signers(alternativeHeader) that are not part of
  286. // validators(committedHeader), they misbehaved as they are signing protocol
  287. // messages in heights they are not validators => immediately slashable
  288. // (#F4).
  289. for i, sig := range alternativeHeader.Commit.Signatures {
  290. if sig.Absent() {
  291. continue
  292. }
  293. lastHeightValidatorWasInSet, ok := valToLastHeight[string(sig.ValidatorAddress)]
  294. if !ok {
  295. continue
  296. }
  297. if !valSet.HasAddress(sig.ValidatorAddress) {
  298. evList = append(evList, &PhantomValidatorEvidence{
  299. Header: alternativeHeader.Header,
  300. Vote: alternativeHeader.Commit.GetVote(i),
  301. LastHeightValidatorWasInSet: lastHeightValidatorWasInSet,
  302. })
  303. }
  304. }
  305. // If ValidatorsHash, NextValidatorsHash, ConsensusHash, AppHash, and
  306. // LastResultsHash in alternativeHeader are different (incorrect application
  307. // state transition), then it is a lunatic misbehavior => immediately
  308. // slashable (#F5).
  309. var invalidField string
  310. switch {
  311. case !bytes.Equal(committedHeader.ValidatorsHash, alternativeHeader.ValidatorsHash):
  312. invalidField = "ValidatorsHash"
  313. case !bytes.Equal(committedHeader.NextValidatorsHash, alternativeHeader.NextValidatorsHash):
  314. invalidField = "NextValidatorsHash"
  315. case !bytes.Equal(committedHeader.ConsensusHash, alternativeHeader.ConsensusHash):
  316. invalidField = "ConsensusHash"
  317. case !bytes.Equal(committedHeader.AppHash, alternativeHeader.AppHash):
  318. invalidField = "AppHash"
  319. case !bytes.Equal(committedHeader.LastResultsHash, alternativeHeader.LastResultsHash):
  320. invalidField = "LastResultsHash"
  321. }
  322. if invalidField != "" {
  323. for i, sig := range alternativeHeader.Commit.Signatures {
  324. if sig.Absent() {
  325. continue
  326. }
  327. evList = append(evList, &LunaticValidatorEvidence{
  328. Header: alternativeHeader.Header,
  329. Vote: alternativeHeader.Commit.GetVote(i),
  330. InvalidHeaderField: invalidField,
  331. })
  332. }
  333. return evList
  334. }
  335. // Use the fact that signatures are sorted by ValidatorAddress.
  336. var (
  337. i = 0
  338. j = 0
  339. )
  340. OUTER_LOOP:
  341. for i < len(ev.H1.Commit.Signatures) {
  342. sigA := ev.H1.Commit.Signatures[i]
  343. if sigA.Absent() {
  344. i++
  345. continue
  346. }
  347. // FIXME: Replace with HasAddress once DuplicateVoteEvidence#PubKey is
  348. // removed.
  349. _, val := valSet.GetByAddress(sigA.ValidatorAddress)
  350. if val == nil {
  351. i++
  352. continue
  353. }
  354. for j < len(ev.H2.Commit.Signatures) {
  355. sigB := ev.H2.Commit.Signatures[j]
  356. if sigB.Absent() {
  357. j++
  358. continue
  359. }
  360. switch bytes.Compare(sigA.ValidatorAddress, sigB.ValidatorAddress) {
  361. case 0:
  362. // if H1.Round == H2.Round, and some signers signed different precommit
  363. // messages in both commits, then it is an equivocation misbehavior =>
  364. // immediately slashable (#F1).
  365. if ev.H1.Commit.Round == ev.H2.Commit.Round {
  366. evList = append(evList, &DuplicateVoteEvidence{
  367. PubKey: val.PubKey,
  368. VoteA: ev.H1.Commit.GetVote(i),
  369. VoteB: ev.H2.Commit.GetVote(j),
  370. })
  371. } else {
  372. // if H1.Round != H2.Round we need to run full detection procedure => not
  373. // immediately slashable.
  374. evList = append(evList, &PotentialAmnesiaEvidence{
  375. VoteA: ev.H1.Commit.GetVote(i),
  376. VoteB: ev.H2.Commit.GetVote(j),
  377. })
  378. }
  379. i++
  380. j++
  381. continue OUTER_LOOP
  382. case 1:
  383. i++
  384. continue OUTER_LOOP
  385. case -1:
  386. j++
  387. }
  388. }
  389. }
  390. return evList
  391. }
  392. func (ev ConflictingHeadersEvidence) Height() int64 { return ev.H1.Height }
  393. // XXX: this is not the time of equivocation
  394. func (ev ConflictingHeadersEvidence) Time() time.Time { return ev.H1.Time }
  395. func (ev ConflictingHeadersEvidence) Address() []byte {
  396. panic("use ConflictingHeadersEvidence#Split to split evidence into individual pieces")
  397. }
  398. func (ev ConflictingHeadersEvidence) Bytes() []byte {
  399. return cdcEncode(ev)
  400. }
  401. func (ev ConflictingHeadersEvidence) Hash() []byte {
  402. bz := make([]byte, tmhash.Size*2)
  403. copy(bz[:tmhash.Size-1], ev.H1.Hash().Bytes())
  404. copy(bz[tmhash.Size:], ev.H2.Hash().Bytes())
  405. return tmhash.Sum(bz)
  406. }
  407. func (ev ConflictingHeadersEvidence) Verify(chainID string, _ crypto.PubKey) error {
  408. panic("use ConflictingHeadersEvidence#VerifyComposite to verify composite evidence")
  409. }
  410. // VerifyComposite verifies that both headers belong to the same chain, same
  411. // height and signed by 1/3+ of validators at height H1.Height == H2.Height.
  412. func (ev ConflictingHeadersEvidence) VerifyComposite(committedHeader *Header, valSet *ValidatorSet) error {
  413. var alternativeHeader *SignedHeader
  414. switch {
  415. case bytes.Equal(committedHeader.Hash(), ev.H1.Hash()):
  416. alternativeHeader = ev.H2
  417. case bytes.Equal(committedHeader.Hash(), ev.H2.Hash()):
  418. alternativeHeader = ev.H1
  419. default:
  420. return errors.New("none of the headers are committed from this node's perspective")
  421. }
  422. // ChainID must be the same
  423. if committedHeader.ChainID != alternativeHeader.ChainID {
  424. return errors.New("alt header is from a different chain")
  425. }
  426. // Height must be the same
  427. if committedHeader.Height != alternativeHeader.Height {
  428. return errors.New("alt header is from a different height")
  429. }
  430. // Limit the number of signatures to avoid DoS attacks where a header
  431. // contains too many signatures.
  432. //
  433. // Validator set size = 100 [node]
  434. // Max validator set size = 100 * 2 = 200 [fork?]
  435. maxNumValidators := valSet.Size() * 2
  436. if len(alternativeHeader.Commit.Signatures) > maxNumValidators {
  437. return errors.Errorf("alt commit contains too many signatures: %d, expected no more than %d",
  438. len(alternativeHeader.Commit.Signatures),
  439. maxNumValidators)
  440. }
  441. // Header must be signed by at least 1/3+ of voting power of currently
  442. // trusted validator set.
  443. if err := valSet.VerifyCommitTrusting(
  444. alternativeHeader.ChainID,
  445. alternativeHeader.Commit.BlockID,
  446. alternativeHeader.Height,
  447. alternativeHeader.Commit,
  448. tmmath.Fraction{Numerator: 1, Denominator: 3}); err != nil {
  449. return errors.Wrap(err, "alt header does not have 1/3+ of voting power of our validator set")
  450. }
  451. return nil
  452. }
  453. func (ev ConflictingHeadersEvidence) Equal(ev2 Evidence) bool {
  454. switch e2 := ev2.(type) {
  455. case ConflictingHeadersEvidence:
  456. return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash())
  457. case *ConflictingHeadersEvidence:
  458. return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash())
  459. default:
  460. return false
  461. }
  462. }
  463. func (ev ConflictingHeadersEvidence) ValidateBasic() error {
  464. if ev.H1 == nil {
  465. return errors.New("first header is missing")
  466. }
  467. if ev.H2 == nil {
  468. return errors.New("second header is missing")
  469. }
  470. if err := ev.H1.ValidateBasic(ev.H1.ChainID); err != nil {
  471. return fmt.Errorf("h1: %w", err)
  472. }
  473. if err := ev.H2.ValidateBasic(ev.H2.ChainID); err != nil {
  474. return fmt.Errorf("h2: %w", err)
  475. }
  476. return nil
  477. }
  478. func (ev ConflictingHeadersEvidence) String() string {
  479. return fmt.Sprintf("ConflictingHeadersEvidence{H1: %d#%X, H2: %d#%X}",
  480. ev.H1.Height, ev.H1.Hash(),
  481. ev.H2.Height, ev.H2.Hash())
  482. }
  483. //-------------------------------------------
  484. type PhantomValidatorEvidence struct {
  485. Header *Header `json:"header"`
  486. Vote *Vote `json:"vote"`
  487. LastHeightValidatorWasInSet int64 `json:"last_height_validator_was_in_set"`
  488. }
  489. var _ Evidence = &PhantomValidatorEvidence{}
  490. var _ Evidence = PhantomValidatorEvidence{}
  491. func (e PhantomValidatorEvidence) Height() int64 {
  492. return e.Header.Height
  493. }
  494. func (e PhantomValidatorEvidence) Time() time.Time {
  495. return e.Header.Time
  496. }
  497. func (e PhantomValidatorEvidence) Address() []byte {
  498. return e.Vote.ValidatorAddress
  499. }
  500. func (e PhantomValidatorEvidence) Hash() []byte {
  501. bz := make([]byte, tmhash.Size+crypto.AddressSize)
  502. copy(bz[:tmhash.Size-1], e.Header.Hash().Bytes())
  503. copy(bz[tmhash.Size:], e.Vote.ValidatorAddress.Bytes())
  504. return tmhash.Sum(bz)
  505. }
  506. func (e PhantomValidatorEvidence) Bytes() []byte {
  507. return cdcEncode(e)
  508. }
  509. func (e PhantomValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  510. // chainID must be the same
  511. if chainID != e.Header.ChainID {
  512. return fmt.Errorf("chainID do not match: %s vs %s",
  513. chainID,
  514. e.Header.ChainID,
  515. )
  516. }
  517. if !pubKey.VerifyBytes(e.Vote.SignBytes(chainID), e.Vote.Signature) {
  518. return errors.New("invalid signature")
  519. }
  520. return nil
  521. }
  522. func (e PhantomValidatorEvidence) Equal(ev Evidence) bool {
  523. switch e2 := ev.(type) {
  524. case PhantomValidatorEvidence:
  525. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  526. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  527. case *PhantomValidatorEvidence:
  528. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  529. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  530. default:
  531. return false
  532. }
  533. }
  534. func (e PhantomValidatorEvidence) ValidateBasic() error {
  535. if e.Header == nil {
  536. return errors.New("empty header")
  537. }
  538. if e.Vote == nil {
  539. return errors.New("empty vote")
  540. }
  541. // if err := e.Header.ValidateBasic(); err != nil {
  542. // return fmt.Errorf("invalid header: %v", err)
  543. // }
  544. if err := e.Vote.ValidateBasic(); err != nil {
  545. return fmt.Errorf("invalid signature: %v", err)
  546. }
  547. if !e.Vote.BlockID.IsComplete() {
  548. return errors.New("expected vote for block")
  549. }
  550. if e.Header.Height != e.Vote.Height {
  551. return fmt.Errorf("header and vote have different heights: %d vs %d",
  552. e.Header.Height,
  553. e.Vote.Height,
  554. )
  555. }
  556. if e.LastHeightValidatorWasInSet <= 0 {
  557. return errors.New("negative or zero LastHeightValidatorWasInSet")
  558. }
  559. return nil
  560. }
  561. func (e PhantomValidatorEvidence) String() string {
  562. return fmt.Sprintf("PhantomValidatorEvidence{%X voted for %d/%X}",
  563. e.Vote.ValidatorAddress, e.Header.Height, e.Header.Hash())
  564. }
  565. //-------------------------------------------
  566. type LunaticValidatorEvidence struct {
  567. Header *Header `json:"header"`
  568. Vote *Vote `json:"vote"`
  569. InvalidHeaderField string `json:"invalid_header_field"`
  570. }
  571. var _ Evidence = &LunaticValidatorEvidence{}
  572. var _ Evidence = LunaticValidatorEvidence{}
  573. func (e LunaticValidatorEvidence) Height() int64 {
  574. return e.Header.Height
  575. }
  576. func (e LunaticValidatorEvidence) Time() time.Time {
  577. return e.Header.Time
  578. }
  579. func (e LunaticValidatorEvidence) Address() []byte {
  580. return e.Vote.ValidatorAddress
  581. }
  582. func (e LunaticValidatorEvidence) Hash() []byte {
  583. bz := make([]byte, tmhash.Size+crypto.AddressSize)
  584. copy(bz[:tmhash.Size-1], e.Header.Hash().Bytes())
  585. copy(bz[tmhash.Size:], e.Vote.ValidatorAddress.Bytes())
  586. return tmhash.Sum(bz)
  587. }
  588. func (e LunaticValidatorEvidence) Bytes() []byte {
  589. return cdcEncode(e)
  590. }
  591. func (e LunaticValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  592. // chainID must be the same
  593. if chainID != e.Header.ChainID {
  594. return fmt.Errorf("chainID do not match: %s vs %s",
  595. chainID,
  596. e.Header.ChainID,
  597. )
  598. }
  599. if !pubKey.VerifyBytes(e.Vote.SignBytes(chainID), e.Vote.Signature) {
  600. return errors.New("invalid signature")
  601. }
  602. return nil
  603. }
  604. func (e LunaticValidatorEvidence) Equal(ev Evidence) bool {
  605. switch e2 := ev.(type) {
  606. case LunaticValidatorEvidence:
  607. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  608. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  609. case *LunaticValidatorEvidence:
  610. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  611. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  612. default:
  613. return false
  614. }
  615. }
  616. func (e LunaticValidatorEvidence) ValidateBasic() error {
  617. if e.Header == nil {
  618. return errors.New("empty header")
  619. }
  620. if e.Vote == nil {
  621. return errors.New("empty vote")
  622. }
  623. // if err := e.Header.ValidateBasic(); err != nil {
  624. // return fmt.Errorf("invalid header: %v", err)
  625. // }
  626. if err := e.Vote.ValidateBasic(); err != nil {
  627. return fmt.Errorf("invalid signature: %v", err)
  628. }
  629. if !e.Vote.BlockID.IsComplete() {
  630. return errors.New("expected vote for block")
  631. }
  632. if e.Header.Height != e.Vote.Height {
  633. return fmt.Errorf("header and vote have different heights: %d vs %d",
  634. e.Header.Height,
  635. e.Vote.Height,
  636. )
  637. }
  638. switch e.InvalidHeaderField {
  639. case "ValidatorsHash", "NextValidatorsHash", "ConsensusHash", "AppHash", "LastResultsHash":
  640. return nil
  641. default:
  642. return errors.New("unknown invalid header field")
  643. }
  644. }
  645. func (e LunaticValidatorEvidence) String() string {
  646. return fmt.Sprintf("LunaticValidatorEvidence{%X voted for %d/%X, which contains invalid %s}",
  647. e.Vote.ValidatorAddress, e.Header.Height, e.Header.Hash(), e.InvalidHeaderField)
  648. }
  649. func (e LunaticValidatorEvidence) VerifyHeader(committedHeader *Header) error {
  650. matchErr := func(field string) error {
  651. return fmt.Errorf("%s matches committed hash", field)
  652. }
  653. switch e.InvalidHeaderField {
  654. case ValidatorsHashField:
  655. if bytes.Equal(committedHeader.ValidatorsHash, e.Header.ValidatorsHash) {
  656. return matchErr(ValidatorsHashField)
  657. }
  658. case NextValidatorsHashField:
  659. if bytes.Equal(committedHeader.NextValidatorsHash, e.Header.NextValidatorsHash) {
  660. return matchErr(NextValidatorsHashField)
  661. }
  662. case ConsensusHashField:
  663. if bytes.Equal(committedHeader.ConsensusHash, e.Header.ConsensusHash) {
  664. return matchErr(ConsensusHashField)
  665. }
  666. case AppHashField:
  667. if bytes.Equal(committedHeader.AppHash, e.Header.AppHash) {
  668. return matchErr(AppHashField)
  669. }
  670. case LastResultsHashField:
  671. if bytes.Equal(committedHeader.LastResultsHash, e.Header.LastResultsHash) {
  672. return matchErr(LastResultsHashField)
  673. }
  674. default:
  675. return errors.New("unknown InvalidHeaderField")
  676. }
  677. return nil
  678. }
  679. //-------------------------------------------
  680. type PotentialAmnesiaEvidence struct {
  681. VoteA *Vote `json:"vote_a"`
  682. VoteB *Vote `json:"vote_b"`
  683. }
  684. var _ Evidence = &PotentialAmnesiaEvidence{}
  685. var _ Evidence = PotentialAmnesiaEvidence{}
  686. func (e PotentialAmnesiaEvidence) Height() int64 {
  687. return e.VoteA.Height
  688. }
  689. func (e PotentialAmnesiaEvidence) Time() time.Time {
  690. if e.VoteA.Timestamp.Before(e.VoteB.Timestamp) {
  691. return e.VoteA.Timestamp
  692. }
  693. return e.VoteB.Timestamp
  694. }
  695. func (e PotentialAmnesiaEvidence) Address() []byte {
  696. return e.VoteA.ValidatorAddress
  697. }
  698. func (e PotentialAmnesiaEvidence) Hash() []byte {
  699. return tmhash.Sum(cdcEncode(e))
  700. }
  701. func (e PotentialAmnesiaEvidence) Bytes() []byte {
  702. return cdcEncode(e)
  703. }
  704. func (e PotentialAmnesiaEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  705. // pubkey must match address (this should already be true, sanity check)
  706. addr := e.VoteA.ValidatorAddress
  707. if !bytes.Equal(pubKey.Address(), addr) {
  708. return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)",
  709. addr, pubKey, pubKey.Address())
  710. }
  711. // Signatures must be valid
  712. if !pubKey.VerifyBytes(e.VoteA.SignBytes(chainID), e.VoteA.Signature) {
  713. return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature)
  714. }
  715. if !pubKey.VerifyBytes(e.VoteB.SignBytes(chainID), e.VoteB.Signature) {
  716. return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature)
  717. }
  718. return nil
  719. }
  720. func (e PotentialAmnesiaEvidence) Equal(ev Evidence) bool {
  721. switch e2 := ev.(type) {
  722. case PotentialAmnesiaEvidence:
  723. return bytes.Equal(e.Hash(), e2.Hash())
  724. case *PotentialAmnesiaEvidence:
  725. return bytes.Equal(e.Hash(), e2.Hash())
  726. default:
  727. return false
  728. }
  729. }
  730. func (e PotentialAmnesiaEvidence) ValidateBasic() error {
  731. if e.VoteA == nil || e.VoteB == nil {
  732. return fmt.Errorf("one or both of the votes are empty %v, %v", e.VoteA, e.VoteB)
  733. }
  734. if err := e.VoteA.ValidateBasic(); err != nil {
  735. return fmt.Errorf("invalid VoteA: %v", err)
  736. }
  737. if err := e.VoteB.ValidateBasic(); err != nil {
  738. return fmt.Errorf("invalid VoteB: %v", err)
  739. }
  740. // Enforce Votes are lexicographically sorted on blockID
  741. if strings.Compare(e.VoteA.BlockID.Key(), e.VoteB.BlockID.Key()) >= 0 {
  742. return errors.New("amnesia votes in invalid order")
  743. }
  744. // H/S must be the same
  745. if e.VoteA.Height != e.VoteB.Height ||
  746. e.VoteA.Type != e.VoteB.Type {
  747. return fmt.Errorf("h/s do not match: %d/%v vs %d/%v",
  748. e.VoteA.Height, e.VoteA.Type, e.VoteB.Height, e.VoteB.Type)
  749. }
  750. // R must be different
  751. if e.VoteA.Round == e.VoteB.Round {
  752. return fmt.Errorf("expected votes from different rounds, got %d", e.VoteA.Round)
  753. }
  754. // Address must be the same
  755. if !bytes.Equal(e.VoteA.ValidatorAddress, e.VoteB.ValidatorAddress) {
  756. return fmt.Errorf("validator addresses do not match: %X vs %X",
  757. e.VoteA.ValidatorAddress,
  758. e.VoteB.ValidatorAddress,
  759. )
  760. }
  761. // Index must be the same
  762. // https://github.com/tendermint/tendermint/issues/4619
  763. if e.VoteA.ValidatorIndex != e.VoteB.ValidatorIndex {
  764. return fmt.Errorf(
  765. "duplicateVoteEvidence Error: Validator indices do not match. Got %d and %d",
  766. e.VoteA.ValidatorIndex,
  767. e.VoteB.ValidatorIndex,
  768. )
  769. }
  770. // BlockIDs must be different
  771. if e.VoteA.BlockID.Equals(e.VoteB.BlockID) {
  772. return fmt.Errorf(
  773. "block IDs are the same (%v) - not a real duplicate vote",
  774. e.VoteA.BlockID,
  775. )
  776. }
  777. return nil
  778. }
  779. func (e PotentialAmnesiaEvidence) String() string {
  780. return fmt.Sprintf("PotentialAmnesiaEvidence{VoteA: %v, VoteB: %v}", e.VoteA, e.VoteB)
  781. }
  782. //-----------------------------------------------------------------
  783. // UNSTABLE
  784. type MockRandomEvidence struct {
  785. MockEvidence
  786. randBytes []byte
  787. }
  788. var _ Evidence = &MockRandomEvidence{}
  789. // UNSTABLE
  790. func NewMockRandomEvidence(height int64, eTime time.Time, address []byte, randBytes []byte) MockRandomEvidence {
  791. return MockRandomEvidence{
  792. MockEvidence{
  793. EvidenceHeight: height,
  794. EvidenceTime: eTime,
  795. EvidenceAddress: address}, randBytes,
  796. }
  797. }
  798. func (e MockRandomEvidence) Hash() []byte {
  799. return []byte(fmt.Sprintf("%d-%x", e.EvidenceHeight, e.randBytes))
  800. }
  801. // UNSTABLE
  802. type MockEvidence struct {
  803. EvidenceHeight int64
  804. EvidenceTime time.Time
  805. EvidenceAddress []byte
  806. }
  807. var _ Evidence = &MockEvidence{}
  808. // UNSTABLE
  809. func NewMockEvidence(height int64, eTime time.Time, idx int, address []byte) MockEvidence {
  810. return MockEvidence{
  811. EvidenceHeight: height,
  812. EvidenceTime: eTime,
  813. EvidenceAddress: address}
  814. }
  815. func (e MockEvidence) Height() int64 { return e.EvidenceHeight }
  816. func (e MockEvidence) Time() time.Time { return e.EvidenceTime }
  817. func (e MockEvidence) Address() []byte { return e.EvidenceAddress }
  818. func (e MockEvidence) Hash() []byte {
  819. return []byte(fmt.Sprintf("%d-%x-%s",
  820. e.EvidenceHeight, e.EvidenceAddress, e.EvidenceTime))
  821. }
  822. func (e MockEvidence) Bytes() []byte {
  823. return []byte(fmt.Sprintf("%d-%x-%s",
  824. e.EvidenceHeight, e.EvidenceAddress, e.EvidenceTime))
  825. }
  826. func (e MockEvidence) Verify(chainID string, pubKey crypto.PubKey) error { return nil }
  827. func (e MockEvidence) Equal(ev Evidence) bool {
  828. e2 := ev.(MockEvidence)
  829. return e.EvidenceHeight == e2.EvidenceHeight &&
  830. bytes.Equal(e.EvidenceAddress, e2.EvidenceAddress)
  831. }
  832. func (e MockEvidence) ValidateBasic() error { return nil }
  833. func (e MockEvidence) String() string {
  834. return fmt.Sprintf("Evidence: %d/%s/%s", e.EvidenceHeight, e.Time(), e.EvidenceAddress)
  835. }