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.

1772 lines
49 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/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 the time the evidence was created.
  266. func (dve *DuplicateVoteEvidence) Time() time.Time {
  267. return dve.VoteA.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. // XXX: this is not the time of equivocation
  589. func (ev ConflictingHeadersEvidence) Time() time.Time { return ev.H1.Time }
  590. func (ev ConflictingHeadersEvidence) Address() []byte {
  591. panic("use ConflictingHeadersEvidence#Split to split evidence into individual pieces")
  592. }
  593. func (ev ConflictingHeadersEvidence) Bytes() []byte {
  594. pbe := ev.ToProto()
  595. bz, err := pbe.Marshal()
  596. if err != nil {
  597. panic(err)
  598. }
  599. return bz
  600. }
  601. func (ev ConflictingHeadersEvidence) Hash() []byte {
  602. bz := make([]byte, tmhash.Size*2)
  603. copy(bz[:tmhash.Size-1], ev.H1.Hash().Bytes())
  604. copy(bz[tmhash.Size:], ev.H2.Hash().Bytes())
  605. return tmhash.Sum(bz)
  606. }
  607. func (ev ConflictingHeadersEvidence) Verify(chainID string, _ crypto.PubKey) error {
  608. panic("use ConflictingHeadersEvidence#VerifyComposite to verify composite evidence")
  609. }
  610. // VerifyComposite verifies that both headers belong to the same chain, same
  611. // height and signed by 1/3+ of validators at height H1.Height == H2.Height.
  612. func (ev ConflictingHeadersEvidence) VerifyComposite(committedHeader *Header, valSet *ValidatorSet) error {
  613. var alternativeHeader *SignedHeader
  614. switch {
  615. case bytes.Equal(committedHeader.Hash(), ev.H1.Hash()):
  616. alternativeHeader = ev.H2
  617. case bytes.Equal(committedHeader.Hash(), ev.H2.Hash()):
  618. alternativeHeader = ev.H1
  619. default:
  620. return errors.New("none of the headers are committed from this node's perspective")
  621. }
  622. // ChainID must be the same
  623. if committedHeader.ChainID != alternativeHeader.ChainID {
  624. return errors.New("alt header is from a different chain")
  625. }
  626. // Height must be the same
  627. if committedHeader.Height != alternativeHeader.Height {
  628. return errors.New("alt header is from a different height")
  629. }
  630. // Limit the number of signatures to avoid DoS attacks where a header
  631. // contains too many signatures.
  632. //
  633. // Validator set size = 100 [node]
  634. // Max validator set size = 100 * 2 = 200 [fork?]
  635. maxNumValidators := valSet.Size() * 2
  636. if len(alternativeHeader.Commit.Signatures) > maxNumValidators {
  637. return fmt.Errorf("alt commit contains too many signatures: %d, expected no more than %d",
  638. len(alternativeHeader.Commit.Signatures),
  639. maxNumValidators)
  640. }
  641. // Header must be signed by at least 1/3+ of voting power of currently
  642. // trusted validator set.
  643. if err := valSet.VerifyCommitTrusting(
  644. alternativeHeader.ChainID,
  645. alternativeHeader.Commit,
  646. tmmath.Fraction{Numerator: 1, Denominator: 3}); err != nil {
  647. return fmt.Errorf("alt header does not have 1/3+ of voting power of our validator set: %w", err)
  648. }
  649. return nil
  650. }
  651. func (ev ConflictingHeadersEvidence) Equal(ev2 Evidence) bool {
  652. switch e2 := ev2.(type) {
  653. case ConflictingHeadersEvidence:
  654. return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash())
  655. case *ConflictingHeadersEvidence:
  656. return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash())
  657. default:
  658. return false
  659. }
  660. }
  661. func (ev ConflictingHeadersEvidence) ValidateBasic() error {
  662. if ev.H1 == nil {
  663. return errors.New("first header is missing")
  664. }
  665. if ev.H2 == nil {
  666. return errors.New("second header is missing")
  667. }
  668. if err := ev.H1.ValidateBasic(ev.H1.ChainID); err != nil {
  669. return fmt.Errorf("h1: %w", err)
  670. }
  671. if err := ev.H2.ValidateBasic(ev.H2.ChainID); err != nil {
  672. return fmt.Errorf("h2: %w", err)
  673. }
  674. return nil
  675. }
  676. func (ev ConflictingHeadersEvidence) String() string {
  677. return fmt.Sprintf("ConflictingHeadersEvidence{H1: %d#%X, H2: %d#%X}",
  678. ev.H1.Height, ev.H1.Hash(),
  679. ev.H2.Height, ev.H2.Hash())
  680. }
  681. func (ev ConflictingHeadersEvidence) ToProto() tmproto.ConflictingHeadersEvidence {
  682. pbh1 := ev.H1.ToProto()
  683. pbh2 := ev.H2.ToProto()
  684. tp := tmproto.ConflictingHeadersEvidence{
  685. H1: pbh1,
  686. H2: pbh2,
  687. }
  688. return tp
  689. }
  690. func ConflictingHeadersEvidenceFromProto(pb *tmproto.ConflictingHeadersEvidence) (ConflictingHeadersEvidence, error) {
  691. if pb == nil {
  692. return ConflictingHeadersEvidence{}, errors.New("nil ConflictingHeadersEvidence")
  693. }
  694. h1, err := SignedHeaderFromProto(pb.H1)
  695. if err != nil {
  696. return ConflictingHeadersEvidence{}, fmt.Errorf("from proto err: %w", err)
  697. }
  698. h2, err := SignedHeaderFromProto(pb.H2)
  699. if err != nil {
  700. return ConflictingHeadersEvidence{}, fmt.Errorf("from proto err: %w", err)
  701. }
  702. tp := ConflictingHeadersEvidence{
  703. H1: h1,
  704. H2: h2,
  705. }
  706. return tp, tp.ValidateBasic()
  707. }
  708. //-------------------------------------------
  709. type PhantomValidatorEvidence struct {
  710. Vote *Vote `json:"vote"`
  711. LastHeightValidatorWasInSet int64 `json:"last_height_validator_was_in_set"`
  712. }
  713. var _ Evidence = PhantomValidatorEvidence{}
  714. func (e PhantomValidatorEvidence) Height() int64 {
  715. return e.Vote.Height
  716. }
  717. func (e PhantomValidatorEvidence) Time() time.Time {
  718. return e.Vote.Timestamp
  719. }
  720. func (e PhantomValidatorEvidence) Address() []byte {
  721. return e.Vote.ValidatorAddress
  722. }
  723. func (e PhantomValidatorEvidence) Hash() []byte {
  724. pbe := e.ToProto()
  725. bz, err := pbe.Marshal()
  726. if err != nil {
  727. panic(err)
  728. }
  729. return tmhash.Sum(bz)
  730. }
  731. func (e PhantomValidatorEvidence) Bytes() []byte {
  732. pbe := e.ToProto()
  733. bz, err := pbe.Marshal()
  734. if err != nil {
  735. panic(err)
  736. }
  737. return bz
  738. }
  739. func (e PhantomValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  740. v := e.Vote.ToProto()
  741. if !pubKey.VerifyBytes(VoteSignBytes(chainID, v), e.Vote.Signature) {
  742. return errors.New("invalid signature")
  743. }
  744. return nil
  745. }
  746. func (e PhantomValidatorEvidence) Equal(ev Evidence) bool {
  747. switch e2 := ev.(type) {
  748. case PhantomValidatorEvidence:
  749. return e.Vote.Height == e2.Vote.Height &&
  750. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  751. case *PhantomValidatorEvidence:
  752. return e.Vote.Height == e2.Vote.Height &&
  753. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  754. default:
  755. return false
  756. }
  757. }
  758. func (e PhantomValidatorEvidence) ValidateBasic() error {
  759. if e.Vote == nil {
  760. return errors.New("empty vote")
  761. }
  762. if err := e.Vote.ValidateBasic(); err != nil {
  763. return fmt.Errorf("invalid signature: %v", err)
  764. }
  765. if !e.Vote.BlockID.IsComplete() {
  766. return errors.New("expected vote for block")
  767. }
  768. if e.LastHeightValidatorWasInSet <= 0 {
  769. return errors.New("negative or zero LastHeightValidatorWasInSet")
  770. }
  771. return nil
  772. }
  773. func (e PhantomValidatorEvidence) String() string {
  774. return fmt.Sprintf("PhantomValidatorEvidence{%X voted at height %d}",
  775. e.Vote.ValidatorAddress, e.Vote.Height)
  776. }
  777. func (e PhantomValidatorEvidence) ToProto() tmproto.PhantomValidatorEvidence {
  778. vpb := e.Vote.ToProto()
  779. tp := tmproto.PhantomValidatorEvidence{
  780. Vote: vpb,
  781. LastHeightValidatorWasInSet: e.LastHeightValidatorWasInSet,
  782. }
  783. return tp
  784. }
  785. func PhantomValidatorEvidenceFromProto(pb *tmproto.PhantomValidatorEvidence) (PhantomValidatorEvidence, error) {
  786. if pb == nil {
  787. return PhantomValidatorEvidence{}, errors.New("nil PhantomValidatorEvidence")
  788. }
  789. vpb, err := VoteFromProto(pb.Vote)
  790. if err != nil {
  791. return PhantomValidatorEvidence{}, err
  792. }
  793. tp := PhantomValidatorEvidence{
  794. Vote: vpb,
  795. LastHeightValidatorWasInSet: pb.LastHeightValidatorWasInSet,
  796. }
  797. return tp, tp.ValidateBasic()
  798. }
  799. //-------------------------------------------
  800. type LunaticValidatorEvidence struct {
  801. Header *Header `json:"header"`
  802. Vote *Vote `json:"vote"`
  803. InvalidHeaderField string `json:"invalid_header_field"`
  804. }
  805. var _ Evidence = LunaticValidatorEvidence{}
  806. func (e LunaticValidatorEvidence) Height() int64 {
  807. return e.Header.Height
  808. }
  809. func (e LunaticValidatorEvidence) Time() time.Time {
  810. return e.Header.Time
  811. }
  812. func (e LunaticValidatorEvidence) Address() []byte {
  813. return e.Vote.ValidatorAddress
  814. }
  815. func (e LunaticValidatorEvidence) Hash() []byte {
  816. bz := make([]byte, tmhash.Size+crypto.AddressSize)
  817. copy(bz[:tmhash.Size-1], e.Header.Hash().Bytes())
  818. copy(bz[tmhash.Size:], e.Vote.ValidatorAddress.Bytes())
  819. return tmhash.Sum(bz)
  820. }
  821. func (e LunaticValidatorEvidence) Bytes() []byte {
  822. pbe := e.ToProto()
  823. bz, err := pbe.Marshal()
  824. if err != nil {
  825. panic(err)
  826. }
  827. return bz
  828. }
  829. func (e LunaticValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  830. // chainID must be the same
  831. if chainID != e.Header.ChainID {
  832. return fmt.Errorf("chainID do not match: %s vs %s",
  833. chainID,
  834. e.Header.ChainID,
  835. )
  836. }
  837. v := e.Vote.ToProto()
  838. if !pubKey.VerifyBytes(VoteSignBytes(chainID, v), e.Vote.Signature) {
  839. return errors.New("invalid signature")
  840. }
  841. return nil
  842. }
  843. func (e LunaticValidatorEvidence) Equal(ev Evidence) bool {
  844. switch e2 := ev.(type) {
  845. case LunaticValidatorEvidence:
  846. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  847. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  848. case *LunaticValidatorEvidence:
  849. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  850. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  851. default:
  852. return false
  853. }
  854. }
  855. func (e LunaticValidatorEvidence) ValidateBasic() error {
  856. if e.Header == nil {
  857. return errors.New("empty header")
  858. }
  859. if e.Vote == nil {
  860. return errors.New("empty vote")
  861. }
  862. if err := e.Header.ValidateBasic(); err != nil {
  863. return fmt.Errorf("invalid header: %v", err)
  864. }
  865. if err := e.Vote.ValidateBasic(); err != nil {
  866. return fmt.Errorf("invalid signature: %v", err)
  867. }
  868. if !e.Vote.BlockID.IsComplete() {
  869. return errors.New("expected vote for block")
  870. }
  871. if e.Header.Height != e.Vote.Height {
  872. return fmt.Errorf("header and vote have different heights: %d vs %d",
  873. e.Header.Height,
  874. e.Vote.Height,
  875. )
  876. }
  877. switch e.InvalidHeaderField {
  878. case "ValidatorsHash", "NextValidatorsHash", "ConsensusHash", "AppHash", "LastResultsHash":
  879. return nil
  880. default:
  881. return errors.New("unknown invalid header field")
  882. }
  883. }
  884. func (e LunaticValidatorEvidence) String() string {
  885. return fmt.Sprintf("LunaticValidatorEvidence{%X voted for %d/%X, which contains invalid %s}",
  886. e.Vote.ValidatorAddress, e.Header.Height, e.Header.Hash(), e.InvalidHeaderField)
  887. }
  888. func (e LunaticValidatorEvidence) VerifyHeader(committedHeader *Header) error {
  889. matchErr := func(field string) error {
  890. return fmt.Errorf("%s matches committed hash", field)
  891. }
  892. if committedHeader == nil {
  893. return errors.New("committed header is nil")
  894. }
  895. switch e.InvalidHeaderField {
  896. case ValidatorsHashField:
  897. if bytes.Equal(committedHeader.ValidatorsHash, e.Header.ValidatorsHash) {
  898. return matchErr(ValidatorsHashField)
  899. }
  900. case NextValidatorsHashField:
  901. if bytes.Equal(committedHeader.NextValidatorsHash, e.Header.NextValidatorsHash) {
  902. return matchErr(NextValidatorsHashField)
  903. }
  904. case ConsensusHashField:
  905. if bytes.Equal(committedHeader.ConsensusHash, e.Header.ConsensusHash) {
  906. return matchErr(ConsensusHashField)
  907. }
  908. case AppHashField:
  909. if bytes.Equal(committedHeader.AppHash, e.Header.AppHash) {
  910. return matchErr(AppHashField)
  911. }
  912. case LastResultsHashField:
  913. if bytes.Equal(committedHeader.LastResultsHash, e.Header.LastResultsHash) {
  914. return matchErr(LastResultsHashField)
  915. }
  916. default:
  917. return errors.New("unknown InvalidHeaderField")
  918. }
  919. return nil
  920. }
  921. func (e LunaticValidatorEvidence) ToProto() tmproto.LunaticValidatorEvidence {
  922. h := e.Header.ToProto()
  923. v := e.Vote.ToProto()
  924. tp := tmproto.LunaticValidatorEvidence{
  925. Header: h,
  926. Vote: v,
  927. InvalidHeaderField: e.InvalidHeaderField,
  928. }
  929. return tp
  930. }
  931. func LunaticValidatorEvidenceFromProto(pb *tmproto.LunaticValidatorEvidence) (*LunaticValidatorEvidence, error) {
  932. if pb == nil {
  933. return nil, errors.New("nil LunaticValidatorEvidence")
  934. }
  935. h, err := HeaderFromProto(pb.GetHeader())
  936. if err != nil {
  937. return nil, err
  938. }
  939. v, err := VoteFromProto(pb.GetVote())
  940. if err != nil {
  941. return nil, err
  942. }
  943. tp := LunaticValidatorEvidence{
  944. Header: &h,
  945. Vote: v,
  946. InvalidHeaderField: pb.InvalidHeaderField,
  947. }
  948. return &tp, tp.ValidateBasic()
  949. }
  950. //-------------------------------------------
  951. // PotentialAmnesiaEvidence is constructed when a validator votes on two different blocks at different rounds
  952. // in the same height. PotentialAmnesiaEvidence can then evolve into AmensiaEvidence if the indicted validator
  953. // is incapable of providing the proof of lock change that validates voting twice in the allotted trial period.
  954. // Heightstamp is used for each node to keep a track of how much time has passed so as to know when the trial period
  955. // is finished and is set when the node first receives the evidence.
  956. type PotentialAmnesiaEvidence struct {
  957. VoteA *Vote `json:"vote_a"`
  958. VoteB *Vote `json:"vote_b"`
  959. HeightStamp int64
  960. }
  961. var _ Evidence = PotentialAmnesiaEvidence{}
  962. func (e PotentialAmnesiaEvidence) Height() int64 {
  963. return e.VoteA.Height
  964. }
  965. func (e PotentialAmnesiaEvidence) Time() time.Time {
  966. return e.VoteA.Timestamp
  967. }
  968. func (e PotentialAmnesiaEvidence) Address() []byte {
  969. return e.VoteA.ValidatorAddress
  970. }
  971. func (e PotentialAmnesiaEvidence) Hash() []byte {
  972. pbe := e.ToProto()
  973. bz, err := pbe.Marshal()
  974. if err != nil {
  975. panic(err)
  976. }
  977. return tmhash.Sum(bz)
  978. }
  979. func (e PotentialAmnesiaEvidence) Bytes() []byte {
  980. pbe := e.ToProto()
  981. bz, err := pbe.Marshal()
  982. if err != nil {
  983. panic(err)
  984. }
  985. return bz
  986. }
  987. func (e PotentialAmnesiaEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  988. // pubkey must match address (this should already be true, sanity check)
  989. addr := e.VoteA.ValidatorAddress
  990. if !bytes.Equal(pubKey.Address(), addr) {
  991. return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)",
  992. addr, pubKey, pubKey.Address())
  993. }
  994. va := e.VoteA.ToProto()
  995. vb := e.VoteB.ToProto()
  996. // Signatures must be valid
  997. if !pubKey.VerifyBytes(VoteSignBytes(chainID, va), e.VoteA.Signature) {
  998. return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature)
  999. }
  1000. if !pubKey.VerifyBytes(VoteSignBytes(chainID, vb), e.VoteB.Signature) {
  1001. return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature)
  1002. }
  1003. return nil
  1004. }
  1005. func (e PotentialAmnesiaEvidence) Equal(ev Evidence) bool {
  1006. switch e2 := ev.(type) {
  1007. case PotentialAmnesiaEvidence:
  1008. return e.Height() == e2.Height() && e.VoteA.Round == e2.VoteA.Round && e.VoteB.Round == e2.VoteB.Round &&
  1009. bytes.Equal(e.Address(), e2.Address())
  1010. case *PotentialAmnesiaEvidence:
  1011. return e.Height() == e2.Height() && e.VoteA.Round == e2.VoteA.Round && e.VoteB.Round == e2.VoteB.Round &&
  1012. bytes.Equal(e.Address(), e2.Address())
  1013. default:
  1014. return false
  1015. }
  1016. }
  1017. func (e PotentialAmnesiaEvidence) ValidateBasic() error {
  1018. if e.VoteA == nil || e.VoteB == nil {
  1019. return fmt.Errorf("one or both of the votes are empty %v, %v", e.VoteA, e.VoteB)
  1020. }
  1021. if err := e.VoteA.ValidateBasic(); err != nil {
  1022. return fmt.Errorf("invalid VoteA: %v", err)
  1023. }
  1024. if err := e.VoteB.ValidateBasic(); err != nil {
  1025. return fmt.Errorf("invalid VoteB: %v", err)
  1026. }
  1027. // H/S must be the same
  1028. if e.VoteA.Height != e.VoteB.Height ||
  1029. e.VoteA.Type != e.VoteB.Type {
  1030. return fmt.Errorf("h/s do not match: %d/%v vs %d/%v",
  1031. e.VoteA.Height, e.VoteA.Type, e.VoteB.Height, e.VoteB.Type)
  1032. }
  1033. // Enforce that vote A came before vote B
  1034. if e.VoteA.Timestamp.After(e.VoteB.Timestamp) {
  1035. return fmt.Errorf("vote A should have a timestamp before vote B, but got %s > %s",
  1036. e.VoteA.Timestamp, e.VoteB.Timestamp)
  1037. }
  1038. // Address must be the same
  1039. if !bytes.Equal(e.VoteA.ValidatorAddress, e.VoteB.ValidatorAddress) {
  1040. return fmt.Errorf("validator addresses do not match: %X vs %X",
  1041. e.VoteA.ValidatorAddress,
  1042. e.VoteB.ValidatorAddress,
  1043. )
  1044. }
  1045. // Index must be the same
  1046. // https://github.com/tendermint/tendermint/issues/4619
  1047. if e.VoteA.ValidatorIndex != e.VoteB.ValidatorIndex {
  1048. return fmt.Errorf(
  1049. "duplicateVoteEvidence Error: Validator indices do not match. Got %d and %d",
  1050. e.VoteA.ValidatorIndex,
  1051. e.VoteB.ValidatorIndex,
  1052. )
  1053. }
  1054. // BlockIDs must be different
  1055. if e.VoteA.BlockID.Equals(e.VoteB.BlockID) {
  1056. return fmt.Errorf(
  1057. "block IDs are the same (%v) - not a real duplicate vote",
  1058. e.VoteA.BlockID,
  1059. )
  1060. }
  1061. return nil
  1062. }
  1063. func (e PotentialAmnesiaEvidence) String() string {
  1064. return fmt.Sprintf("PotentialAmnesiaEvidence{VoteA: %v, VoteB: %v}", e.VoteA, e.VoteB)
  1065. }
  1066. // Primed finds whether the PotentialAmnesiaEvidence is ready to be upgraded to Amnesia Evidence. It is decided if
  1067. // either the prosecuted node voted in the past or if the allocated trial period has expired without a proof of lock
  1068. // change having been provided.
  1069. func (e PotentialAmnesiaEvidence) Primed(trialPeriod, currentHeight int64) bool {
  1070. // voted in the past can be instantly punishable
  1071. if e.VoteA.Round > e.VoteB.Round {
  1072. return true
  1073. }
  1074. // has the trial period expired
  1075. if e.HeightStamp > 0 {
  1076. return e.HeightStamp+trialPeriod <= currentHeight
  1077. }
  1078. return false
  1079. }
  1080. func (e PotentialAmnesiaEvidence) ToProto() tmproto.PotentialAmnesiaEvidence {
  1081. voteB := e.VoteB.ToProto()
  1082. voteA := e.VoteA.ToProto()
  1083. tp := tmproto.PotentialAmnesiaEvidence{
  1084. VoteA: voteA,
  1085. VoteB: voteB,
  1086. HeightStamp: e.HeightStamp,
  1087. }
  1088. return tp
  1089. }
  1090. // ------------------
  1091. // ProofOfLockChange (POLC) proves that a node followed the consensus protocol and voted for a precommit in two
  1092. // different rounds because the node received a majority of votes for a different block in the latter round. In cases of
  1093. // amnesia evidence, a suspected node will need ProofOfLockChange to prove that the node did not break protocol.
  1094. type ProofOfLockChange struct {
  1095. Votes []Vote `json:"votes"`
  1096. PubKey crypto.PubKey `json:"pubkey"`
  1097. }
  1098. // MakePOLCFromVoteSet can be used when a majority of prevotes or precommits for a block is seen
  1099. // that the node has itself not yet voted for in order to process the vote set into a proof of lock change
  1100. func MakePOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) (ProofOfLockChange, error) {
  1101. polc := makePOLCFromVoteSet(voteSet, pubKey, blockID)
  1102. return polc, polc.ValidateBasic()
  1103. }
  1104. func makePOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) ProofOfLockChange {
  1105. var votes []Vote
  1106. valSetSize := voteSet.Size()
  1107. for valIdx := int32(0); int(valIdx) < valSetSize; valIdx++ {
  1108. vote := voteSet.GetByIndex(valIdx)
  1109. if vote != nil && vote.BlockID.Equals(blockID) {
  1110. votes = append(votes, *vote)
  1111. }
  1112. }
  1113. return ProofOfLockChange{
  1114. Votes: votes,
  1115. PubKey: pubKey,
  1116. }
  1117. }
  1118. // EmptyPOLC returns an empty polc. This is used when no polc has been provided in the allocated trial period time
  1119. // and the node now needs to move to upgrading to AmnesiaEvidence and hence uses an empty polc
  1120. func EmptyPOLC() ProofOfLockChange {
  1121. return ProofOfLockChange{
  1122. nil,
  1123. nil,
  1124. }
  1125. }
  1126. func (e ProofOfLockChange) Height() int64 {
  1127. return e.Votes[0].Height
  1128. }
  1129. // returns the time of the last vote
  1130. func (e ProofOfLockChange) Time() time.Time {
  1131. latest := e.Votes[0].Timestamp
  1132. for _, vote := range e.Votes {
  1133. if vote.Timestamp.After(latest) {
  1134. latest = vote.Timestamp
  1135. }
  1136. }
  1137. return latest
  1138. }
  1139. func (e ProofOfLockChange) Round() int32 {
  1140. return e.Votes[0].Round
  1141. }
  1142. func (e ProofOfLockChange) Address() []byte {
  1143. return e.PubKey.Address()
  1144. }
  1145. func (e ProofOfLockChange) BlockID() BlockID {
  1146. return e.Votes[0].BlockID
  1147. }
  1148. // ValidateVotes checks the polc against the validator set of that height. The function makes sure that the polc
  1149. // contains a majority of votes and that each
  1150. func (e ProofOfLockChange) ValidateVotes(valSet *ValidatorSet, chainID string) error {
  1151. if e.IsAbsent() {
  1152. return errors.New("polc is empty")
  1153. }
  1154. talliedVotingPower := int64(0)
  1155. votingPowerNeeded := valSet.TotalVotingPower() * 2 / 3
  1156. for _, vote := range e.Votes {
  1157. exists := false
  1158. for _, validator := range valSet.Validators {
  1159. if bytes.Equal(validator.Address, vote.ValidatorAddress) {
  1160. exists = true
  1161. v := vote.ToProto()
  1162. if !validator.PubKey.VerifyBytes(VoteSignBytes(chainID, v), vote.Signature) {
  1163. return fmt.Errorf("cannot verify vote (from validator: %d) against signature: %v",
  1164. vote.ValidatorIndex, vote.Signature)
  1165. }
  1166. talliedVotingPower += validator.VotingPower
  1167. }
  1168. }
  1169. if !exists {
  1170. return fmt.Errorf("vote was not from a validator in this set: %v", vote.String())
  1171. }
  1172. }
  1173. if talliedVotingPower <= votingPowerNeeded {
  1174. return ErrNotEnoughVotingPowerSigned{
  1175. Got: talliedVotingPower,
  1176. Needed: votingPowerNeeded + 1,
  1177. }
  1178. }
  1179. return nil
  1180. }
  1181. func (e ProofOfLockChange) Equal(e2 ProofOfLockChange) bool {
  1182. return bytes.Equal(e.Address(), e2.Address()) && e.Height() == e2.Height() &&
  1183. e.Round() == e2.Round()
  1184. }
  1185. func (e ProofOfLockChange) ValidateBasic() error {
  1186. // first check if the polc is absent / empty
  1187. if e.IsAbsent() {
  1188. return nil
  1189. }
  1190. if e.PubKey == nil {
  1191. return errors.New("missing public key")
  1192. }
  1193. // validate basic doesn't count the number of votes and their voting power, this is to be done by VerifyEvidence
  1194. if e.Votes == nil {
  1195. return errors.New("missing votes")
  1196. }
  1197. // height, round and vote type must be the same for all votes
  1198. height := e.Height()
  1199. round := e.Round()
  1200. if round == 0 {
  1201. return errors.New("can't have a polc for the first round")
  1202. }
  1203. voteType := e.Votes[0].Type
  1204. for idx, vote := range e.Votes {
  1205. if err := vote.ValidateBasic(); err != nil {
  1206. return fmt.Errorf("invalid vote#%d: %w", idx, err)
  1207. }
  1208. if vote.Height != height {
  1209. return fmt.Errorf("invalid height for vote#%d: %d instead of %d", idx, vote.Height, height)
  1210. }
  1211. if vote.Round != round {
  1212. return fmt.Errorf("invalid round for vote#%d: %d instead of %d", idx, vote.Round, round)
  1213. }
  1214. if vote.Type != voteType {
  1215. return fmt.Errorf("invalid vote type for vote#%d: %d instead of %d", idx, vote.Type, voteType)
  1216. }
  1217. if !vote.BlockID.Equals(e.BlockID()) {
  1218. return fmt.Errorf("vote must be for the same block id: %v instead of %v", e.BlockID(), vote.BlockID)
  1219. }
  1220. if bytes.Equal(vote.ValidatorAddress.Bytes(), e.PubKey.Address().Bytes()) {
  1221. return fmt.Errorf("vote validator address cannot be the same as the public key address: %X all votes %v",
  1222. vote.ValidatorAddress.Bytes(), e.PubKey.Address().Bytes())
  1223. }
  1224. for i := idx + 1; i < len(e.Votes); i++ {
  1225. if bytes.Equal(vote.ValidatorAddress.Bytes(), e.Votes[i].ValidatorAddress.Bytes()) {
  1226. return fmt.Errorf("duplicate votes: %v", vote)
  1227. }
  1228. }
  1229. }
  1230. return nil
  1231. }
  1232. func (e ProofOfLockChange) String() string {
  1233. if e.IsAbsent() {
  1234. return "Empty ProofOfLockChange"
  1235. }
  1236. return fmt.Sprintf("ProofOfLockChange {Address: %X, Height: %d, Round: %d", e.Address(), e.Height(),
  1237. e.Votes[0].Round)
  1238. }
  1239. // IsAbsent checks if the polc is empty
  1240. func (e ProofOfLockChange) IsAbsent() bool {
  1241. return e.Votes == nil && e.PubKey == nil
  1242. }
  1243. func (e *ProofOfLockChange) ToProto() (*tmproto.ProofOfLockChange, error) {
  1244. if e == nil {
  1245. return nil, errors.New("nil proof of lock change")
  1246. }
  1247. plc := new(tmproto.ProofOfLockChange)
  1248. vpb := make([]*tmproto.Vote, len(e.Votes))
  1249. // if absent create empty proto polc
  1250. if e.IsAbsent() {
  1251. return plc, nil
  1252. }
  1253. if e.Votes == nil {
  1254. return nil, errors.New("polc is not absent but has no votes")
  1255. }
  1256. for i, v := range e.Votes {
  1257. pb := v.ToProto()
  1258. if pb != nil {
  1259. vpb[i] = pb
  1260. }
  1261. }
  1262. pk, err := cryptoenc.PubKeyToProto(e.PubKey)
  1263. if err != nil {
  1264. return nil, err
  1265. }
  1266. plc.PubKey = &pk
  1267. plc.Votes = vpb
  1268. return plc, nil
  1269. }
  1270. // AmnesiaEvidence is the progression of PotentialAmnesiaEvidence and is used to prove an infringement of the
  1271. // Tendermint consensus when a validator incorrectly sends a vote in a later round without correctly changing the lock
  1272. type AmnesiaEvidence struct {
  1273. PotentialAmnesiaEvidence
  1274. Polc ProofOfLockChange
  1275. }
  1276. // Height, Time, Address and Verify functions are all inherited by the PotentialAmnesiaEvidence struct
  1277. var _ Evidence = &AmnesiaEvidence{}
  1278. var _ Evidence = AmnesiaEvidence{}
  1279. func MakeAmnesiaEvidence(pe PotentialAmnesiaEvidence, proof ProofOfLockChange) AmnesiaEvidence {
  1280. return AmnesiaEvidence{
  1281. pe,
  1282. proof,
  1283. }
  1284. }
  1285. func (e AmnesiaEvidence) Equal(ev Evidence) bool {
  1286. e2, ok := ev.(AmnesiaEvidence)
  1287. if !ok {
  1288. return false
  1289. }
  1290. return e.PotentialAmnesiaEvidence.Equal(e2.PotentialAmnesiaEvidence)
  1291. }
  1292. func (e AmnesiaEvidence) ValidateBasic() error {
  1293. if err := e.PotentialAmnesiaEvidence.ValidateBasic(); err != nil {
  1294. return fmt.Errorf("invalid potential amnesia evidence: %w", err)
  1295. }
  1296. if !e.Polc.IsAbsent() {
  1297. if err := e.Polc.ValidateBasic(); err != nil {
  1298. return fmt.Errorf("invalid proof of lock change: %w", err)
  1299. }
  1300. if !bytes.Equal(e.PotentialAmnesiaEvidence.Address(), e.Polc.Address()) {
  1301. return fmt.Errorf("validator addresses do not match (%X - %X)", e.PotentialAmnesiaEvidence.Address(),
  1302. e.Polc.Address())
  1303. }
  1304. if e.PotentialAmnesiaEvidence.Height() != e.Polc.Height() {
  1305. return fmt.Errorf("heights do not match (%d - %d)", e.PotentialAmnesiaEvidence.Height(),
  1306. e.Polc.Height())
  1307. }
  1308. if e.Polc.Round() <= e.VoteA.Round || e.Polc.Round() > e.VoteB.Round {
  1309. return fmt.Errorf("polc must be between %d and %d (inclusive)", e.VoteA.Round+1, e.VoteB.Round)
  1310. }
  1311. if !e.Polc.BlockID().Equals(e.PotentialAmnesiaEvidence.VoteB.BlockID) && !e.Polc.BlockID().IsZero() {
  1312. return fmt.Errorf("polc must be either for a nil block or for the same block as the second vote: %v != %v",
  1313. e.Polc.BlockID(), e.PotentialAmnesiaEvidence.VoteB.BlockID)
  1314. }
  1315. if e.Polc.Time().After(e.PotentialAmnesiaEvidence.VoteB.Timestamp) {
  1316. return fmt.Errorf("validator voted again before receiving a majority of votes for the new block: %v is after %v",
  1317. e.Polc.Time(), e.PotentialAmnesiaEvidence.VoteB.Timestamp)
  1318. }
  1319. }
  1320. return nil
  1321. }
  1322. // ViolatedConsensus assess on the basis of the AmensiaEvidence whether the validator has violated the
  1323. // Tendermint consensus. Evidence must be validated first (see ValidateBasic).
  1324. // We are only interested in proving that the latter of the votes in terms of time was correctly done.
  1325. func (e AmnesiaEvidence) ViolatedConsensus() (bool, string) {
  1326. // a validator having voted cannot go back and vote on an earlier round
  1327. if e.PotentialAmnesiaEvidence.VoteA.Round > e.PotentialAmnesiaEvidence.VoteB.Round {
  1328. return true, "validator went back and voted on a previous round"
  1329. }
  1330. // if empty, then no proof was provided to defend the validators actions
  1331. if e.Polc.IsAbsent() {
  1332. return true, "no proof of lock was provided"
  1333. }
  1334. return false, ""
  1335. }
  1336. func (e AmnesiaEvidence) String() string {
  1337. return fmt.Sprintf("AmnesiaEvidence{ %v, polc: %v }", e.PotentialAmnesiaEvidence, e.Polc)
  1338. }
  1339. func ProofOfLockChangeFromProto(pb *tmproto.ProofOfLockChange) (*ProofOfLockChange, error) {
  1340. if pb == nil {
  1341. return nil, errors.New("nil proof of lock change")
  1342. }
  1343. plc := new(ProofOfLockChange)
  1344. // check if it is an empty polc
  1345. if pb.PubKey == nil && pb.Votes == nil {
  1346. return plc, nil
  1347. }
  1348. if pb.Votes == nil {
  1349. return nil, errors.New("proofOfLockChange: is not absent but has no votes")
  1350. }
  1351. vpb := make([]Vote, len(pb.Votes))
  1352. for i, v := range pb.Votes {
  1353. vi, err := VoteFromProto(v)
  1354. if err != nil {
  1355. return nil, err
  1356. }
  1357. vpb[i] = *vi
  1358. }
  1359. if pb.PubKey == nil {
  1360. return nil, errors.New("proofOfLockChange: is not abest but has nil PubKey")
  1361. }
  1362. pk, err := cryptoenc.PubKeyFromProto(*pb.PubKey)
  1363. if err != nil {
  1364. return nil, err
  1365. }
  1366. plc.PubKey = pk
  1367. plc.Votes = vpb
  1368. return plc, nil
  1369. }
  1370. func PotentialAmnesiaEvidenceFromProto(pb *tmproto.PotentialAmnesiaEvidence) (*PotentialAmnesiaEvidence, error) {
  1371. voteA, err := VoteFromProto(pb.GetVoteA())
  1372. if err != nil {
  1373. return nil, err
  1374. }
  1375. voteB, err := VoteFromProto(pb.GetVoteB())
  1376. if err != nil {
  1377. return nil, err
  1378. }
  1379. tp := PotentialAmnesiaEvidence{
  1380. VoteA: voteA,
  1381. VoteB: voteB,
  1382. HeightStamp: pb.GetHeightStamp(),
  1383. }
  1384. return &tp, tp.ValidateBasic()
  1385. }
  1386. func AmnesiaEvidenceToProto(evi AmnesiaEvidence) (*tmproto.Evidence, error) {
  1387. paepb := evi.PotentialAmnesiaEvidence.ToProto()
  1388. polc, err := evi.Polc.ToProto()
  1389. if err != nil {
  1390. return nil, err
  1391. }
  1392. tp := &tmproto.Evidence{
  1393. Sum: &tmproto.Evidence_AmnesiaEvidence{
  1394. AmnesiaEvidence: &tmproto.AmnesiaEvidence{
  1395. PotentialAmnesiaEvidence: &paepb,
  1396. Polc: polc,
  1397. },
  1398. },
  1399. }
  1400. return tp, nil
  1401. }
  1402. func AmensiaEvidenceFromProto(pb *tmproto.AmnesiaEvidence) (AmnesiaEvidence, error) {
  1403. if pb == nil {
  1404. return AmnesiaEvidence{}, errors.New("nil duplicate vote evidence")
  1405. }
  1406. pae, err := PotentialAmnesiaEvidenceFromProto(pb.PotentialAmnesiaEvidence)
  1407. if err != nil {
  1408. return AmnesiaEvidence{}, err
  1409. }
  1410. polc, err := ProofOfLockChangeFromProto(pb.Polc)
  1411. if err != nil {
  1412. return AmnesiaEvidence{}, err
  1413. }
  1414. tp := AmnesiaEvidence{
  1415. PotentialAmnesiaEvidence: *pae,
  1416. Polc: *polc,
  1417. }
  1418. return tp, tp.ValidateBasic()
  1419. }
  1420. //-----------------------------------------------------------------
  1421. // UNSTABLE
  1422. type MockRandomEvidence struct {
  1423. MockEvidence
  1424. randBytes []byte
  1425. }
  1426. var _ Evidence = &MockRandomEvidence{}
  1427. // UNSTABLE
  1428. func NewMockRandomEvidence(height int64, eTime time.Time, address []byte, randBytes []byte) MockRandomEvidence {
  1429. return MockRandomEvidence{
  1430. MockEvidence{
  1431. EvidenceHeight: height,
  1432. EvidenceTime: eTime,
  1433. EvidenceAddress: address}, randBytes,
  1434. }
  1435. }
  1436. func (e MockRandomEvidence) Hash() []byte {
  1437. return []byte(fmt.Sprintf("%d-%x", e.EvidenceHeight, e.randBytes))
  1438. }
  1439. func (e MockRandomEvidence) Equal(ev Evidence) bool { return false }
  1440. // UNSTABLE
  1441. type MockEvidence struct {
  1442. EvidenceHeight int64
  1443. EvidenceTime time.Time
  1444. EvidenceAddress []byte
  1445. }
  1446. var _ Evidence = &MockEvidence{}
  1447. // UNSTABLE
  1448. func NewMockEvidence(height int64, eTime time.Time, address []byte) MockEvidence {
  1449. return MockEvidence{
  1450. EvidenceHeight: height,
  1451. EvidenceTime: eTime,
  1452. EvidenceAddress: address,
  1453. }
  1454. }
  1455. func (e MockEvidence) Height() int64 { return e.EvidenceHeight }
  1456. func (e MockEvidence) Time() time.Time { return e.EvidenceTime }
  1457. func (e MockEvidence) Address() []byte { return e.EvidenceAddress }
  1458. func (e MockEvidence) Hash() []byte {
  1459. return []byte(fmt.Sprintf("%d-%x-%s",
  1460. e.EvidenceHeight, e.EvidenceAddress, e.EvidenceTime))
  1461. }
  1462. func (e MockEvidence) Bytes() []byte {
  1463. return []byte(fmt.Sprintf("%d-%x-%s",
  1464. e.EvidenceHeight, e.EvidenceAddress, e.EvidenceTime))
  1465. }
  1466. func (e MockEvidence) Verify(chainID string, pubKey crypto.PubKey) error { return nil }
  1467. func (e MockEvidence) Equal(ev Evidence) bool {
  1468. return e.EvidenceHeight == ev.Height() &&
  1469. bytes.Equal(e.EvidenceAddress, ev.Address())
  1470. }
  1471. func (e MockEvidence) ValidateBasic() error { return nil }
  1472. func (e MockEvidence) String() string {
  1473. return fmt.Sprintf("Evidence: %d/%s/%s", e.EvidenceHeight, e.Time(), e.EvidenceAddress)
  1474. }
  1475. // mock polc - fails validate basic, not stable
  1476. func NewMockPOLC(height int64, time time.Time, pubKey crypto.PubKey) ProofOfLockChange {
  1477. voteVal := NewMockPV()
  1478. pKey, _ := voteVal.GetPubKey()
  1479. vote := Vote{Type: tmproto.PrecommitType, Height: height, Round: 1, BlockID: BlockID{},
  1480. Timestamp: time, ValidatorAddress: pKey.Address(), ValidatorIndex: 1, Signature: []byte{}}
  1481. v := vote.ToProto()
  1482. if err := voteVal.SignVote("mock-chain-id", v); err != nil {
  1483. panic(err)
  1484. }
  1485. vote.Signature = v.Signature
  1486. return ProofOfLockChange{
  1487. Votes: []Vote{vote},
  1488. PubKey: pubKey,
  1489. }
  1490. }