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.

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