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.

1326 lines
38 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. amino "github.com/tendermint/go-amino"
  9. "github.com/tendermint/tendermint/crypto"
  10. "github.com/tendermint/tendermint/crypto/merkle"
  11. "github.com/tendermint/tendermint/crypto/tmhash"
  12. tmmath "github.com/tendermint/tendermint/libs/math"
  13. tmproto "github.com/tendermint/tendermint/proto/types"
  14. )
  15. const (
  16. // MaxEvidenceBytes is a maximum size of any evidence (including amino overhead).
  17. MaxEvidenceBytes int64 = 444
  18. // An invalid field in the header from LunaticValidatorEvidence.
  19. // Must be a function of the ABCI application state.
  20. ValidatorsHashField = "ValidatorsHash"
  21. NextValidatorsHashField = "NextValidatorsHash"
  22. ConsensusHashField = "ConsensusHash"
  23. AppHashField = "AppHash"
  24. LastResultsHashField = "LastResultsHash"
  25. )
  26. // ErrEvidenceInvalid wraps a piece of evidence and the error denoting how or why it is invalid.
  27. type ErrEvidenceInvalid struct {
  28. Evidence Evidence
  29. ErrorValue error
  30. }
  31. // NewErrEvidenceInvalid returns a new EvidenceInvalid with the given err.
  32. func NewErrEvidenceInvalid(ev Evidence, err error) *ErrEvidenceInvalid {
  33. return &ErrEvidenceInvalid{ev, err}
  34. }
  35. // Error returns a string representation of the error.
  36. func (err *ErrEvidenceInvalid) Error() string {
  37. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.ErrorValue, err.Evidence)
  38. }
  39. // ErrEvidenceOverflow is for when there is too much evidence in a block.
  40. type ErrEvidenceOverflow struct {
  41. MaxNum int
  42. GotNum int
  43. }
  44. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  45. func NewErrEvidenceOverflow(max, got int) *ErrEvidenceOverflow {
  46. return &ErrEvidenceOverflow{max, got}
  47. }
  48. // Error returns a string representation of the error.
  49. func (err *ErrEvidenceOverflow) Error() string {
  50. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.MaxNum, err.GotNum)
  51. }
  52. //-------------------------------------------
  53. // Evidence represents any provable malicious activity by a validator.
  54. type Evidence interface {
  55. Height() int64 // height of the equivocation
  56. Time() time.Time // time of the equivocation
  57. Address() []byte // address of the equivocating validator
  58. Bytes() []byte // bytes which comprise the evidence
  59. Hash() []byte // hash of the evidence
  60. Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence
  61. Equal(Evidence) bool // check equality of evidence
  62. ValidateBasic() error
  63. String() string
  64. }
  65. type CompositeEvidence interface {
  66. VerifyComposite(committedHeader *Header, valSet *ValidatorSet) error
  67. Split(committedHeader *Header, valSet *ValidatorSet, valToLastHeight map[string]int64) []Evidence
  68. }
  69. func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error) {
  70. if evidence == nil {
  71. return nil, errors.New("nil evidence")
  72. }
  73. switch evi := evidence.(type) {
  74. case *DuplicateVoteEvidence:
  75. voteB := evi.VoteB.ToProto()
  76. voteA := evi.VoteA.ToProto()
  77. tp := &tmproto.Evidence{
  78. Sum: &tmproto.Evidence_DuplicateVoteEvidence{
  79. DuplicateVoteEvidence: &tmproto.DuplicateVoteEvidence{
  80. VoteA: voteA,
  81. VoteB: voteB,
  82. },
  83. },
  84. }
  85. return tp, nil
  86. case ConflictingHeadersEvidence:
  87. pbh1 := evi.H1.ToProto()
  88. pbh2 := evi.H2.ToProto()
  89. tp := &tmproto.Evidence{
  90. Sum: &tmproto.Evidence_ConflictingHeadersEvidence{
  91. ConflictingHeadersEvidence: &tmproto.ConflictingHeadersEvidence{
  92. H1: pbh1,
  93. H2: pbh2,
  94. },
  95. },
  96. }
  97. return tp, nil
  98. case *ConflictingHeadersEvidence:
  99. pbh1 := evi.H1.ToProto()
  100. pbh2 := evi.H2.ToProto()
  101. tp := &tmproto.Evidence{
  102. Sum: &tmproto.Evidence_ConflictingHeadersEvidence{
  103. ConflictingHeadersEvidence: &tmproto.ConflictingHeadersEvidence{
  104. H1: pbh1,
  105. H2: pbh2,
  106. },
  107. },
  108. }
  109. return tp, nil
  110. case *LunaticValidatorEvidence:
  111. h := evi.Header.ToProto()
  112. v := evi.Vote.ToProto()
  113. tp := &tmproto.Evidence{
  114. Sum: &tmproto.Evidence_LunaticValidatorEvidence{
  115. LunaticValidatorEvidence: &tmproto.LunaticValidatorEvidence{
  116. Header: h,
  117. Vote: v,
  118. InvalidHeaderField: evi.InvalidHeaderField,
  119. },
  120. },
  121. }
  122. return tp, nil
  123. case LunaticValidatorEvidence:
  124. h := evi.Header.ToProto()
  125. v := evi.Vote.ToProto()
  126. tp := &tmproto.Evidence{
  127. Sum: &tmproto.Evidence_LunaticValidatorEvidence{
  128. LunaticValidatorEvidence: &tmproto.LunaticValidatorEvidence{
  129. Header: h,
  130. Vote: v,
  131. InvalidHeaderField: evi.InvalidHeaderField,
  132. },
  133. },
  134. }
  135. return tp, nil
  136. case *PotentialAmnesiaEvidence:
  137. voteB := evi.VoteB.ToProto()
  138. voteA := evi.VoteA.ToProto()
  139. tp := &tmproto.Evidence{
  140. Sum: &tmproto.Evidence_PotentialAmnesiaEvidence{
  141. PotentialAmnesiaEvidence: &tmproto.PotentialAmnesiaEvidence{
  142. VoteA: voteA,
  143. VoteB: voteB,
  144. },
  145. },
  146. }
  147. return tp, nil
  148. case PotentialAmnesiaEvidence:
  149. voteB := evi.VoteB.ToProto()
  150. voteA := evi.VoteA.ToProto()
  151. tp := &tmproto.Evidence{
  152. Sum: &tmproto.Evidence_PotentialAmnesiaEvidence{
  153. PotentialAmnesiaEvidence: &tmproto.PotentialAmnesiaEvidence{
  154. VoteA: voteA,
  155. VoteB: voteB,
  156. },
  157. },
  158. }
  159. return tp, nil
  160. case MockEvidence:
  161. if err := evi.ValidateBasic(); err != nil {
  162. return nil, err
  163. }
  164. tp := &tmproto.Evidence{
  165. Sum: &tmproto.Evidence_MockEvidence{
  166. MockEvidence: &tmproto.MockEvidence{
  167. EvidenceHeight: evi.Height(),
  168. EvidenceTime: evi.Time(),
  169. EvidenceAddress: evi.Address(),
  170. },
  171. },
  172. }
  173. return tp, nil
  174. case MockRandomEvidence:
  175. if err := evi.ValidateBasic(); err != nil {
  176. return nil, err
  177. }
  178. tp := &tmproto.Evidence{
  179. Sum: &tmproto.Evidence_MockRandomEvidence{
  180. MockRandomEvidence: &tmproto.MockRandomEvidence{
  181. EvidenceHeight: evi.Height(),
  182. EvidenceTime: evi.Time(),
  183. EvidenceAddress: evi.Address(),
  184. RandBytes: evi.randBytes,
  185. },
  186. },
  187. }
  188. return tp, nil
  189. default:
  190. return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi)
  191. }
  192. }
  193. func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error) {
  194. if evidence == nil {
  195. return nil, errors.New("nil evidence")
  196. }
  197. switch evi := evidence.Sum.(type) {
  198. case *tmproto.Evidence_DuplicateVoteEvidence:
  199. vA, err := VoteFromProto(evi.DuplicateVoteEvidence.VoteA)
  200. if err != nil {
  201. return nil, err
  202. }
  203. vB, err := VoteFromProto(evi.DuplicateVoteEvidence.VoteB)
  204. if err != nil {
  205. return nil, err
  206. }
  207. dve := DuplicateVoteEvidence{
  208. VoteA: vA,
  209. VoteB: vB,
  210. }
  211. return &dve, dve.ValidateBasic()
  212. case *tmproto.Evidence_ConflictingHeadersEvidence:
  213. h1, err := SignedHeaderFromProto(evi.ConflictingHeadersEvidence.H1)
  214. if err != nil {
  215. return nil, fmt.Errorf("from proto err: %w", err)
  216. }
  217. h2, err := SignedHeaderFromProto(evi.ConflictingHeadersEvidence.H2)
  218. if err != nil {
  219. return nil, fmt.Errorf("from proto err: %w", err)
  220. }
  221. tp := ConflictingHeadersEvidence{
  222. H1: h1,
  223. H2: h2,
  224. }
  225. return tp, tp.ValidateBasic()
  226. case *tmproto.Evidence_LunaticValidatorEvidence:
  227. h, err := HeaderFromProto(evi.LunaticValidatorEvidence.GetHeader())
  228. if err != nil {
  229. return nil, err
  230. }
  231. v, err := VoteFromProto(evi.LunaticValidatorEvidence.GetVote())
  232. if err != nil {
  233. return nil, err
  234. }
  235. tp := LunaticValidatorEvidence{
  236. Header: &h,
  237. Vote: v,
  238. InvalidHeaderField: evi.LunaticValidatorEvidence.InvalidHeaderField,
  239. }
  240. return &tp, tp.ValidateBasic()
  241. case *tmproto.Evidence_PotentialAmnesiaEvidence:
  242. voteA, err := VoteFromProto(evi.PotentialAmnesiaEvidence.GetVoteA())
  243. if err != nil {
  244. return nil, err
  245. }
  246. voteB, err := VoteFromProto(evi.PotentialAmnesiaEvidence.GetVoteB())
  247. if err != nil {
  248. return nil, err
  249. }
  250. tp := PotentialAmnesiaEvidence{
  251. VoteA: voteA,
  252. VoteB: voteB,
  253. }
  254. return &tp, tp.ValidateBasic()
  255. case *tmproto.Evidence_MockEvidence:
  256. me := MockEvidence{
  257. EvidenceHeight: evi.MockEvidence.GetEvidenceHeight(),
  258. EvidenceAddress: evi.MockEvidence.GetEvidenceAddress(),
  259. EvidenceTime: evi.MockEvidence.GetEvidenceTime(),
  260. }
  261. return me, me.ValidateBasic()
  262. case *tmproto.Evidence_MockRandomEvidence:
  263. mre := MockRandomEvidence{
  264. MockEvidence: MockEvidence{
  265. EvidenceHeight: evi.MockRandomEvidence.GetEvidenceHeight(),
  266. EvidenceAddress: evi.MockRandomEvidence.GetEvidenceAddress(),
  267. EvidenceTime: evi.MockRandomEvidence.GetEvidenceTime(),
  268. },
  269. randBytes: evi.MockRandomEvidence.RandBytes,
  270. }
  271. return mre, mre.ValidateBasic()
  272. default:
  273. return nil, errors.New("evidence is not recognized")
  274. }
  275. }
  276. func RegisterEvidences(cdc *amino.Codec) {
  277. cdc.RegisterInterface((*Evidence)(nil), nil)
  278. cdc.RegisterConcrete(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence", nil)
  279. cdc.RegisterConcrete(&ConflictingHeadersEvidence{}, "tendermint/ConflictingHeadersEvidence", nil)
  280. cdc.RegisterConcrete(&PhantomValidatorEvidence{}, "tendermint/PhantomValidatorEvidence", nil)
  281. cdc.RegisterConcrete(&LunaticValidatorEvidence{}, "tendermint/LunaticValidatorEvidence", nil)
  282. cdc.RegisterConcrete(&PotentialAmnesiaEvidence{}, "tendermint/PotentialAmnesiaEvidence", nil)
  283. }
  284. func RegisterMockEvidences(cdc *amino.Codec) {
  285. cdc.RegisterConcrete(MockEvidence{}, "tendermint/MockEvidence", nil)
  286. cdc.RegisterConcrete(MockRandomEvidence{}, "tendermint/MockRandomEvidence", nil)
  287. }
  288. //-------------------------------------------
  289. // DuplicateVoteEvidence contains evidence a validator signed two conflicting
  290. // votes.
  291. type DuplicateVoteEvidence struct {
  292. VoteA *Vote `json:"vote_a"`
  293. VoteB *Vote `json:"vote_b"`
  294. }
  295. var _ Evidence = &DuplicateVoteEvidence{}
  296. // NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given
  297. // two conflicting votes. If one of the votes is nil, evidence returned is nil as well
  298. func NewDuplicateVoteEvidence(vote1 *Vote, vote2 *Vote) *DuplicateVoteEvidence {
  299. var voteA, voteB *Vote
  300. if vote1 == nil || vote2 == nil {
  301. return nil
  302. }
  303. if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 {
  304. voteA = vote1
  305. voteB = vote2
  306. } else {
  307. voteA = vote2
  308. voteB = vote1
  309. }
  310. return &DuplicateVoteEvidence{
  311. VoteA: voteA,
  312. VoteB: voteB,
  313. }
  314. }
  315. // String returns a string representation of the evidence.
  316. func (dve *DuplicateVoteEvidence) String() string {
  317. return fmt.Sprintf("DuplicateVoteEvidence{VoteA: %v, VoteB: %v}", dve.VoteA, dve.VoteB)
  318. }
  319. // Height returns the height this evidence refers to.
  320. func (dve *DuplicateVoteEvidence) Height() int64 {
  321. return dve.VoteA.Height
  322. }
  323. // Time returns the time the evidence was created.
  324. func (dve *DuplicateVoteEvidence) Time() time.Time {
  325. return dve.VoteA.Timestamp
  326. }
  327. // Address returns the address of the validator.
  328. func (dve *DuplicateVoteEvidence) Address() []byte {
  329. return dve.VoteA.ValidatorAddress
  330. }
  331. // Hash returns the hash of the evidence.
  332. func (dve *DuplicateVoteEvidence) Bytes() []byte {
  333. return cdcEncode(dve)
  334. }
  335. // Hash returns the hash of the evidence.
  336. func (dve *DuplicateVoteEvidence) Hash() []byte {
  337. return tmhash.Sum(cdcEncode(dve))
  338. }
  339. // Verify returns an error if the two votes aren't conflicting.
  340. //
  341. // To be conflicting, they must be from the same validator, for the same H/R/S,
  342. // but for different blocks.
  343. func (dve *DuplicateVoteEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  344. // H/R/S must be the same
  345. if dve.VoteA.Height != dve.VoteB.Height ||
  346. dve.VoteA.Round != dve.VoteB.Round ||
  347. dve.VoteA.Type != dve.VoteB.Type {
  348. return fmt.Errorf("h/r/s does not match: %d/%d/%v vs %d/%d/%v",
  349. dve.VoteA.Height, dve.VoteA.Round, dve.VoteA.Type,
  350. dve.VoteB.Height, dve.VoteB.Round, dve.VoteB.Type)
  351. }
  352. // Address must be the same
  353. if !bytes.Equal(dve.VoteA.ValidatorAddress, dve.VoteB.ValidatorAddress) {
  354. return fmt.Errorf("validator addresses do not match: %X vs %X",
  355. dve.VoteA.ValidatorAddress,
  356. dve.VoteB.ValidatorAddress,
  357. )
  358. }
  359. // Index must be the same
  360. if dve.VoteA.ValidatorIndex != dve.VoteB.ValidatorIndex {
  361. return fmt.Errorf(
  362. "validator indices do not match: %d and %d",
  363. dve.VoteA.ValidatorIndex,
  364. dve.VoteB.ValidatorIndex,
  365. )
  366. }
  367. // BlockIDs must be different
  368. if dve.VoteA.BlockID.Equals(dve.VoteB.BlockID) {
  369. return fmt.Errorf(
  370. "block IDs are the same (%v) - not a real duplicate vote",
  371. dve.VoteA.BlockID,
  372. )
  373. }
  374. // pubkey must match address (this should already be true, sanity check)
  375. addr := dve.VoteA.ValidatorAddress
  376. if !bytes.Equal(pubKey.Address(), addr) {
  377. return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)",
  378. addr, pubKey, pubKey.Address())
  379. }
  380. // Signatures must be valid
  381. if !pubKey.VerifyBytes(dve.VoteA.SignBytes(chainID), dve.VoteA.Signature) {
  382. return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature)
  383. }
  384. if !pubKey.VerifyBytes(dve.VoteB.SignBytes(chainID), dve.VoteB.Signature) {
  385. return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature)
  386. }
  387. return nil
  388. }
  389. // Equal checks if two pieces of evidence are equal.
  390. func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool {
  391. if _, ok := ev.(*DuplicateVoteEvidence); !ok {
  392. return false
  393. }
  394. // just check their hashes
  395. dveHash := tmhash.Sum(cdcEncode(dve))
  396. evHash := tmhash.Sum(cdcEncode(ev))
  397. fmt.Println(dveHash, evHash)
  398. return bytes.Equal(dveHash, evHash)
  399. }
  400. // ValidateBasic performs basic validation.
  401. func (dve *DuplicateVoteEvidence) ValidateBasic() error {
  402. if dve.VoteA == nil || dve.VoteB == nil {
  403. return fmt.Errorf("one or both of the votes are empty %v, %v", dve.VoteA, dve.VoteB)
  404. }
  405. if err := dve.VoteA.ValidateBasic(); err != nil {
  406. return fmt.Errorf("invalid VoteA: %w", err)
  407. }
  408. if err := dve.VoteB.ValidateBasic(); err != nil {
  409. return fmt.Errorf("invalid VoteB: %w", err)
  410. }
  411. // Enforce Votes are lexicographically sorted on blockID
  412. if strings.Compare(dve.VoteA.BlockID.Key(), dve.VoteB.BlockID.Key()) >= 0 {
  413. return errors.New("duplicate votes in invalid order")
  414. }
  415. return nil
  416. }
  417. //-------------------------------------------
  418. // EvidenceList is a list of Evidence. Evidences is not a word.
  419. type EvidenceList []Evidence
  420. // Hash returns the simple merkle root hash of the EvidenceList.
  421. func (evl EvidenceList) Hash() []byte {
  422. // These allocations are required because Evidence is not of type Bytes, and
  423. // golang slices can't be typed cast. This shouldn't be a performance problem since
  424. // the Evidence size is capped.
  425. evidenceBzs := make([][]byte, len(evl))
  426. for i := 0; i < len(evl); i++ {
  427. evidenceBzs[i] = evl[i].Bytes()
  428. }
  429. return merkle.SimpleHashFromByteSlices(evidenceBzs)
  430. }
  431. func (evl EvidenceList) String() string {
  432. s := ""
  433. for _, e := range evl {
  434. s += fmt.Sprintf("%s\t\t", e)
  435. }
  436. return s
  437. }
  438. // Has returns true if the evidence is in the EvidenceList.
  439. func (evl EvidenceList) Has(evidence Evidence) bool {
  440. for _, ev := range evl {
  441. if ev.Equal(evidence) {
  442. return true
  443. }
  444. }
  445. return false
  446. }
  447. //-------------------------------------------
  448. // ConflictingHeadersEvidence is primarily used by the light client when it
  449. // observes two conflicting headers, both having 1/3+ of the voting power of
  450. // the currently trusted validator set.
  451. type ConflictingHeadersEvidence struct {
  452. H1 *SignedHeader `json:"h_1"`
  453. H2 *SignedHeader `json:"h_2"`
  454. }
  455. var _ Evidence = ConflictingHeadersEvidence{}
  456. var _ CompositeEvidence = ConflictingHeadersEvidence{}
  457. // Split breaks up eviddence into smaller chunks (one per validator except for
  458. // PotentialAmnesiaEvidence): PhantomValidatorEvidence,
  459. // LunaticValidatorEvidence, DuplicateVoteEvidence and
  460. // PotentialAmnesiaEvidence.
  461. //
  462. // committedHeader - header at height H1.Height == H2.Height
  463. // valSet - validator set at height H1.Height == H2.Height
  464. // valToLastHeight - map between active validators and respective last heights
  465. func (ev ConflictingHeadersEvidence) Split(committedHeader *Header, valSet *ValidatorSet,
  466. valToLastHeight map[string]int64) []Evidence {
  467. evList := make([]Evidence, 0)
  468. var alternativeHeader *SignedHeader
  469. if bytes.Equal(committedHeader.Hash(), ev.H1.Hash()) {
  470. alternativeHeader = ev.H2
  471. } else {
  472. alternativeHeader = ev.H1
  473. }
  474. // If there are signers(alternativeHeader) that are not part of
  475. // validators(committedHeader), they misbehaved as they are signing protocol
  476. // messages in heights they are not validators => immediately slashable
  477. // (#F4).
  478. for i, sig := range alternativeHeader.Commit.Signatures {
  479. if sig.Absent() {
  480. continue
  481. }
  482. lastHeightValidatorWasInSet, ok := valToLastHeight[string(sig.ValidatorAddress)]
  483. if !ok {
  484. continue
  485. }
  486. if !valSet.HasAddress(sig.ValidatorAddress) {
  487. evList = append(evList, &PhantomValidatorEvidence{
  488. Vote: alternativeHeader.Commit.GetVote(int32(i)),
  489. LastHeightValidatorWasInSet: lastHeightValidatorWasInSet,
  490. })
  491. }
  492. }
  493. // If ValidatorsHash, NextValidatorsHash, ConsensusHash, AppHash, and
  494. // LastResultsHash in alternativeHeader are different (incorrect application
  495. // state transition), then it is a lunatic misbehavior => immediately
  496. // slashable (#F5).
  497. var invalidField string
  498. switch {
  499. case !bytes.Equal(committedHeader.ValidatorsHash, alternativeHeader.ValidatorsHash):
  500. invalidField = "ValidatorsHash"
  501. case !bytes.Equal(committedHeader.NextValidatorsHash, alternativeHeader.NextValidatorsHash):
  502. invalidField = "NextValidatorsHash"
  503. case !bytes.Equal(committedHeader.ConsensusHash, alternativeHeader.ConsensusHash):
  504. invalidField = "ConsensusHash"
  505. case !bytes.Equal(committedHeader.AppHash, alternativeHeader.AppHash):
  506. invalidField = "AppHash"
  507. case !bytes.Equal(committedHeader.LastResultsHash, alternativeHeader.LastResultsHash):
  508. invalidField = "LastResultsHash"
  509. }
  510. if invalidField != "" {
  511. for i, sig := range alternativeHeader.Commit.Signatures {
  512. if sig.Absent() {
  513. continue
  514. }
  515. evList = append(evList, &LunaticValidatorEvidence{
  516. Header: alternativeHeader.Header,
  517. Vote: alternativeHeader.Commit.GetVote(int32(i)),
  518. InvalidHeaderField: invalidField,
  519. })
  520. }
  521. return evList
  522. }
  523. // Use the fact that signatures are sorted by ValidatorAddress.
  524. var (
  525. i = 0
  526. j = 0
  527. )
  528. OUTER_LOOP:
  529. for i < len(ev.H1.Commit.Signatures) {
  530. sigA := ev.H1.Commit.Signatures[i]
  531. if sigA.Absent() {
  532. i++
  533. continue
  534. }
  535. // FIXME: Replace with HasAddress once DuplicateVoteEvidence#PubKey is
  536. // removed.
  537. _, val := valSet.GetByAddress(sigA.ValidatorAddress)
  538. if val == nil {
  539. i++
  540. continue
  541. }
  542. for j < len(ev.H2.Commit.Signatures) {
  543. sigB := ev.H2.Commit.Signatures[j]
  544. if sigB.Absent() {
  545. j++
  546. continue
  547. }
  548. switch bytes.Compare(sigA.ValidatorAddress, sigB.ValidatorAddress) {
  549. case 0:
  550. // if H1.Round == H2.Round, and some signers signed different precommit
  551. // messages in both commits, then it is an equivocation misbehavior =>
  552. // immediately slashable (#F1).
  553. if ev.H1.Commit.Round == ev.H2.Commit.Round {
  554. evList = append(evList, &DuplicateVoteEvidence{
  555. VoteA: ev.H1.Commit.GetVote(int32(i)),
  556. VoteB: ev.H2.Commit.GetVote(int32(j)),
  557. })
  558. } else {
  559. // if H1.Round != H2.Round we need to run full detection procedure => not
  560. // immediately slashable.
  561. evList = append(evList, &PotentialAmnesiaEvidence{
  562. VoteA: ev.H1.Commit.GetVote(int32(i)),
  563. VoteB: ev.H2.Commit.GetVote(int32(j)),
  564. })
  565. }
  566. i++
  567. j++
  568. continue OUTER_LOOP
  569. case 1:
  570. i++
  571. continue OUTER_LOOP
  572. case -1:
  573. j++
  574. }
  575. }
  576. }
  577. return evList
  578. }
  579. func (ev ConflictingHeadersEvidence) Height() int64 { return ev.H1.Height }
  580. // XXX: this is not the time of equivocation
  581. func (ev ConflictingHeadersEvidence) Time() time.Time { return ev.H1.Time }
  582. func (ev ConflictingHeadersEvidence) Address() []byte {
  583. panic("use ConflictingHeadersEvidence#Split to split evidence into individual pieces")
  584. }
  585. func (ev ConflictingHeadersEvidence) Bytes() []byte {
  586. return cdcEncode(ev)
  587. }
  588. func (ev ConflictingHeadersEvidence) Hash() []byte {
  589. bz := make([]byte, tmhash.Size*2)
  590. copy(bz[:tmhash.Size-1], ev.H1.Hash().Bytes())
  591. copy(bz[tmhash.Size:], ev.H2.Hash().Bytes())
  592. return tmhash.Sum(bz)
  593. }
  594. func (ev ConflictingHeadersEvidence) Verify(chainID string, _ crypto.PubKey) error {
  595. panic("use ConflictingHeadersEvidence#VerifyComposite to verify composite evidence")
  596. }
  597. // VerifyComposite verifies that both headers belong to the same chain, same
  598. // height and signed by 1/3+ of validators at height H1.Height == H2.Height.
  599. func (ev ConflictingHeadersEvidence) VerifyComposite(committedHeader *Header, valSet *ValidatorSet) error {
  600. var alternativeHeader *SignedHeader
  601. switch {
  602. case bytes.Equal(committedHeader.Hash(), ev.H1.Hash()):
  603. alternativeHeader = ev.H2
  604. case bytes.Equal(committedHeader.Hash(), ev.H2.Hash()):
  605. alternativeHeader = ev.H1
  606. default:
  607. return errors.New("none of the headers are committed from this node's perspective")
  608. }
  609. // ChainID must be the same
  610. if committedHeader.ChainID != alternativeHeader.ChainID {
  611. return errors.New("alt header is from a different chain")
  612. }
  613. // Height must be the same
  614. if committedHeader.Height != alternativeHeader.Height {
  615. return errors.New("alt header is from a different height")
  616. }
  617. // Limit the number of signatures to avoid DoS attacks where a header
  618. // contains too many signatures.
  619. //
  620. // Validator set size = 100 [node]
  621. // Max validator set size = 100 * 2 = 200 [fork?]
  622. maxNumValidators := valSet.Size() * 2
  623. if len(alternativeHeader.Commit.Signatures) > maxNumValidators {
  624. return fmt.Errorf("alt commit contains too many signatures: %d, expected no more than %d",
  625. len(alternativeHeader.Commit.Signatures),
  626. maxNumValidators)
  627. }
  628. // Header must be signed by at least 1/3+ of voting power of currently
  629. // trusted validator set.
  630. if err := valSet.VerifyCommitTrusting(
  631. alternativeHeader.ChainID,
  632. alternativeHeader.Commit,
  633. tmmath.Fraction{Numerator: 1, Denominator: 3}); err != nil {
  634. return fmt.Errorf("alt header does not have 1/3+ of voting power of our validator set: %w", err)
  635. }
  636. return nil
  637. }
  638. func (ev ConflictingHeadersEvidence) Equal(ev2 Evidence) bool {
  639. switch e2 := ev2.(type) {
  640. case ConflictingHeadersEvidence:
  641. return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash())
  642. case *ConflictingHeadersEvidence:
  643. return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash())
  644. default:
  645. return false
  646. }
  647. }
  648. func (ev ConflictingHeadersEvidence) ValidateBasic() error {
  649. if ev.H1 == nil {
  650. return errors.New("first header is missing")
  651. }
  652. if ev.H2 == nil {
  653. return errors.New("second header is missing")
  654. }
  655. if err := ev.H1.ValidateBasic(ev.H1.ChainID); err != nil {
  656. return fmt.Errorf("h1: %w", err)
  657. }
  658. if err := ev.H2.ValidateBasic(ev.H2.ChainID); err != nil {
  659. return fmt.Errorf("h2: %w", err)
  660. }
  661. return nil
  662. }
  663. func (ev ConflictingHeadersEvidence) String() string {
  664. return fmt.Sprintf("ConflictingHeadersEvidence{H1: %d#%X, H2: %d#%X}",
  665. ev.H1.Height, ev.H1.Hash(),
  666. ev.H2.Height, ev.H2.Hash())
  667. }
  668. //-------------------------------------------
  669. type PhantomValidatorEvidence struct {
  670. Vote *Vote `json:"vote"`
  671. LastHeightValidatorWasInSet int64 `json:"last_height_validator_was_in_set"`
  672. }
  673. var _ Evidence = PhantomValidatorEvidence{}
  674. func (e PhantomValidatorEvidence) Height() int64 {
  675. return e.Vote.Height
  676. }
  677. func (e PhantomValidatorEvidence) Time() time.Time {
  678. return e.Vote.Timestamp
  679. }
  680. func (e PhantomValidatorEvidence) Address() []byte {
  681. return e.Vote.ValidatorAddress
  682. }
  683. func (e PhantomValidatorEvidence) Hash() []byte {
  684. return tmhash.Sum(cdcEncode(e))
  685. }
  686. func (e PhantomValidatorEvidence) Bytes() []byte {
  687. return cdcEncode(e)
  688. }
  689. func (e PhantomValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  690. // signature must be verified to the chain ID
  691. if !pubKey.VerifyBytes(e.Vote.SignBytes(chainID), e.Vote.Signature) {
  692. return errors.New("invalid signature")
  693. }
  694. return nil
  695. }
  696. func (e PhantomValidatorEvidence) Equal(ev Evidence) bool {
  697. switch e2 := ev.(type) {
  698. case PhantomValidatorEvidence:
  699. return e.Vote.Height == e2.Vote.Height &&
  700. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  701. case *PhantomValidatorEvidence:
  702. return e.Vote.Height == e2.Vote.Height &&
  703. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  704. default:
  705. return false
  706. }
  707. }
  708. func (e PhantomValidatorEvidence) ValidateBasic() error {
  709. if e.Vote == nil {
  710. return errors.New("empty vote")
  711. }
  712. if err := e.Vote.ValidateBasic(); err != nil {
  713. return fmt.Errorf("invalid signature: %v", err)
  714. }
  715. if !e.Vote.BlockID.IsComplete() {
  716. return errors.New("expected vote for block")
  717. }
  718. if e.LastHeightValidatorWasInSet <= 0 {
  719. return errors.New("negative or zero LastHeightValidatorWasInSet")
  720. }
  721. return nil
  722. }
  723. func (e PhantomValidatorEvidence) String() string {
  724. return fmt.Sprintf("PhantomValidatorEvidence{%X voted at height %d}",
  725. e.Vote.ValidatorAddress, e.Vote.Height)
  726. }
  727. //-------------------------------------------
  728. type LunaticValidatorEvidence struct {
  729. Header *Header `json:"header"`
  730. Vote *Vote `json:"vote"`
  731. InvalidHeaderField string `json:"invalid_header_field"`
  732. }
  733. var _ Evidence = LunaticValidatorEvidence{}
  734. func (e LunaticValidatorEvidence) Height() int64 {
  735. return e.Header.Height
  736. }
  737. func (e LunaticValidatorEvidence) Time() time.Time {
  738. return e.Header.Time
  739. }
  740. func (e LunaticValidatorEvidence) Address() []byte {
  741. return e.Vote.ValidatorAddress
  742. }
  743. func (e LunaticValidatorEvidence) Hash() []byte {
  744. bz := make([]byte, tmhash.Size+crypto.AddressSize)
  745. copy(bz[:tmhash.Size-1], e.Header.Hash().Bytes())
  746. copy(bz[tmhash.Size:], e.Vote.ValidatorAddress.Bytes())
  747. return tmhash.Sum(bz)
  748. }
  749. func (e LunaticValidatorEvidence) Bytes() []byte {
  750. return cdcEncode(e)
  751. }
  752. func (e LunaticValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  753. // chainID must be the same
  754. if chainID != e.Header.ChainID {
  755. return fmt.Errorf("chainID do not match: %s vs %s",
  756. chainID,
  757. e.Header.ChainID,
  758. )
  759. }
  760. if !pubKey.VerifyBytes(e.Vote.SignBytes(chainID), e.Vote.Signature) {
  761. return errors.New("invalid signature")
  762. }
  763. return nil
  764. }
  765. func (e LunaticValidatorEvidence) Equal(ev Evidence) bool {
  766. switch e2 := ev.(type) {
  767. case LunaticValidatorEvidence:
  768. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  769. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  770. case *LunaticValidatorEvidence:
  771. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  772. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  773. default:
  774. return false
  775. }
  776. }
  777. func (e LunaticValidatorEvidence) ValidateBasic() error {
  778. if e.Header == nil {
  779. return errors.New("empty header")
  780. }
  781. if e.Vote == nil {
  782. return errors.New("empty vote")
  783. }
  784. if err := e.Header.ValidateBasic(); err != nil {
  785. return fmt.Errorf("invalid header: %v", err)
  786. }
  787. if err := e.Vote.ValidateBasic(); err != nil {
  788. return fmt.Errorf("invalid signature: %v", err)
  789. }
  790. if !e.Vote.BlockID.IsComplete() {
  791. return errors.New("expected vote for block")
  792. }
  793. if e.Header.Height != e.Vote.Height {
  794. return fmt.Errorf("header and vote have different heights: %d vs %d",
  795. e.Header.Height,
  796. e.Vote.Height,
  797. )
  798. }
  799. switch e.InvalidHeaderField {
  800. case "ValidatorsHash", "NextValidatorsHash", "ConsensusHash", "AppHash", "LastResultsHash":
  801. return nil
  802. default:
  803. return errors.New("unknown invalid header field")
  804. }
  805. }
  806. func (e LunaticValidatorEvidence) String() string {
  807. return fmt.Sprintf("LunaticValidatorEvidence{%X voted for %d/%X, which contains invalid %s}",
  808. e.Vote.ValidatorAddress, e.Header.Height, e.Header.Hash(), e.InvalidHeaderField)
  809. }
  810. func (e LunaticValidatorEvidence) VerifyHeader(committedHeader *Header) error {
  811. matchErr := func(field string) error {
  812. return fmt.Errorf("%s matches committed hash", field)
  813. }
  814. if committedHeader == nil {
  815. return errors.New("committed header is nil")
  816. }
  817. switch e.InvalidHeaderField {
  818. case ValidatorsHashField:
  819. if bytes.Equal(committedHeader.ValidatorsHash, e.Header.ValidatorsHash) {
  820. return matchErr(ValidatorsHashField)
  821. }
  822. case NextValidatorsHashField:
  823. if bytes.Equal(committedHeader.NextValidatorsHash, e.Header.NextValidatorsHash) {
  824. return matchErr(NextValidatorsHashField)
  825. }
  826. case ConsensusHashField:
  827. if bytes.Equal(committedHeader.ConsensusHash, e.Header.ConsensusHash) {
  828. return matchErr(ConsensusHashField)
  829. }
  830. case AppHashField:
  831. if bytes.Equal(committedHeader.AppHash, e.Header.AppHash) {
  832. return matchErr(AppHashField)
  833. }
  834. case LastResultsHashField:
  835. if bytes.Equal(committedHeader.LastResultsHash, e.Header.LastResultsHash) {
  836. return matchErr(LastResultsHashField)
  837. }
  838. default:
  839. return errors.New("unknown InvalidHeaderField")
  840. }
  841. return nil
  842. }
  843. //-------------------------------------------
  844. type PotentialAmnesiaEvidence struct {
  845. VoteA *Vote `json:"vote_a"`
  846. VoteB *Vote `json:"vote_b"`
  847. }
  848. var _ Evidence = PotentialAmnesiaEvidence{}
  849. func (e PotentialAmnesiaEvidence) Height() int64 {
  850. return e.VoteA.Height
  851. }
  852. func (e PotentialAmnesiaEvidence) Time() time.Time {
  853. if e.VoteA.Timestamp.Before(e.VoteB.Timestamp) {
  854. return e.VoteA.Timestamp
  855. }
  856. return e.VoteB.Timestamp
  857. }
  858. func (e PotentialAmnesiaEvidence) Address() []byte {
  859. return e.VoteA.ValidatorAddress
  860. }
  861. func (e PotentialAmnesiaEvidence) Hash() []byte {
  862. return tmhash.Sum(cdcEncode(e))
  863. }
  864. func (e PotentialAmnesiaEvidence) Bytes() []byte {
  865. return cdcEncode(e)
  866. }
  867. func (e PotentialAmnesiaEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  868. // pubkey must match address (this should already be true, sanity check)
  869. addr := e.VoteA.ValidatorAddress
  870. if !bytes.Equal(pubKey.Address(), addr) {
  871. return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)",
  872. addr, pubKey, pubKey.Address())
  873. }
  874. // Signatures must be valid
  875. if !pubKey.VerifyBytes(e.VoteA.SignBytes(chainID), e.VoteA.Signature) {
  876. return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature)
  877. }
  878. if !pubKey.VerifyBytes(e.VoteB.SignBytes(chainID), e.VoteB.Signature) {
  879. return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature)
  880. }
  881. return nil
  882. }
  883. func (e PotentialAmnesiaEvidence) Equal(ev Evidence) bool {
  884. switch e2 := ev.(type) {
  885. case PotentialAmnesiaEvidence:
  886. return bytes.Equal(e.Hash(), e2.Hash())
  887. case *PotentialAmnesiaEvidence:
  888. return bytes.Equal(e.Hash(), e2.Hash())
  889. default:
  890. return false
  891. }
  892. }
  893. func (e PotentialAmnesiaEvidence) ValidateBasic() error {
  894. if e.VoteA == nil || e.VoteB == nil {
  895. return fmt.Errorf("one or both of the votes are empty %v, %v", e.VoteA, e.VoteB)
  896. }
  897. if err := e.VoteA.ValidateBasic(); err != nil {
  898. return fmt.Errorf("invalid VoteA: %v", err)
  899. }
  900. if err := e.VoteB.ValidateBasic(); err != nil {
  901. return fmt.Errorf("invalid VoteB: %v", err)
  902. }
  903. // Enforce Votes are lexicographically sorted on blockID
  904. if strings.Compare(e.VoteA.BlockID.Key(), e.VoteB.BlockID.Key()) >= 0 {
  905. return errors.New("amnesia votes in invalid order")
  906. }
  907. // H/S must be the same
  908. if e.VoteA.Height != e.VoteB.Height ||
  909. e.VoteA.Type != e.VoteB.Type {
  910. return fmt.Errorf("h/s do not match: %d/%v vs %d/%v",
  911. e.VoteA.Height, e.VoteA.Type, e.VoteB.Height, e.VoteB.Type)
  912. }
  913. // R must be different
  914. if e.VoteA.Round == e.VoteB.Round {
  915. return fmt.Errorf("expected votes from different rounds, got %d", e.VoteA.Round)
  916. }
  917. // Address must be the same
  918. if !bytes.Equal(e.VoteA.ValidatorAddress, e.VoteB.ValidatorAddress) {
  919. return fmt.Errorf("validator addresses do not match: %X vs %X",
  920. e.VoteA.ValidatorAddress,
  921. e.VoteB.ValidatorAddress,
  922. )
  923. }
  924. // Index must be the same
  925. // https://github.com/tendermint/tendermint/issues/4619
  926. if e.VoteA.ValidatorIndex != e.VoteB.ValidatorIndex {
  927. return fmt.Errorf(
  928. "duplicateVoteEvidence Error: Validator indices do not match. Got %d and %d",
  929. e.VoteA.ValidatorIndex,
  930. e.VoteB.ValidatorIndex,
  931. )
  932. }
  933. // BlockIDs must be different
  934. if e.VoteA.BlockID.Equals(e.VoteB.BlockID) {
  935. return fmt.Errorf(
  936. "block IDs are the same (%v) - not a real duplicate vote",
  937. e.VoteA.BlockID,
  938. )
  939. }
  940. return nil
  941. }
  942. func (e PotentialAmnesiaEvidence) String() string {
  943. return fmt.Sprintf("PotentialAmnesiaEvidence{VoteA: %v, VoteB: %v}", e.VoteA, e.VoteB)
  944. }
  945. // ProofOfLockChange (POLC) proves that a node followed the consensus protocol and voted for a precommit in two
  946. // different rounds because the node received a majority of votes for a different block in the latter round. In cases of
  947. // amnesia evidence, a suspected node will need ProofOfLockChange to prove that the node did not break protocol.
  948. type ProofOfLockChange struct {
  949. Votes []Vote `json:"votes"`
  950. PubKey crypto.PubKey `json:"pubkey"`
  951. }
  952. // MakePOLCFromVoteSet can be used when a majority of prevotes or precommits for a block is seen
  953. // that the node has itself not yet voted for in order to process the vote set into a proof of lock change
  954. func MakePOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) (ProofOfLockChange, error) {
  955. polc := makePOLCFromVoteSet(voteSet, pubKey, blockID)
  956. return polc, polc.ValidateBasic()
  957. }
  958. func makePOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) ProofOfLockChange {
  959. var votes []Vote
  960. valSetSize := voteSet.Size()
  961. for valIdx := int32(0); int(valIdx) < valSetSize; valIdx++ {
  962. vote := voteSet.GetByIndex(valIdx)
  963. if vote != nil && vote.BlockID.Equals(blockID) {
  964. votes = append(votes, *vote)
  965. }
  966. }
  967. return ProofOfLockChange{
  968. Votes: votes,
  969. PubKey: pubKey,
  970. }
  971. }
  972. func (e ProofOfLockChange) Height() int64 {
  973. return e.Votes[0].Height
  974. }
  975. // returns the time of the last vote
  976. func (e ProofOfLockChange) Time() time.Time {
  977. latest := e.Votes[0].Timestamp
  978. for _, vote := range e.Votes {
  979. if vote.Timestamp.After(latest) {
  980. latest = vote.Timestamp
  981. }
  982. }
  983. return latest
  984. }
  985. func (e ProofOfLockChange) Round() int32 {
  986. return e.Votes[0].Round
  987. }
  988. func (e ProofOfLockChange) Address() []byte {
  989. return e.PubKey.Address()
  990. }
  991. func (e ProofOfLockChange) BlockID() BlockID {
  992. return e.Votes[0].BlockID
  993. }
  994. // In order for a ProofOfLockChange to be valid, a validator must have received +2/3 majority of votes
  995. // MajorityOfVotes checks that there were sufficient votes in order to change locks
  996. func (e ProofOfLockChange) MajorityOfVotes(valSet *ValidatorSet) bool {
  997. talliedVotingPower := int64(0)
  998. votingPowerNeeded := valSet.TotalVotingPower() * 2 / 3
  999. for _, validator := range valSet.Validators {
  1000. for _, vote := range e.Votes {
  1001. if bytes.Equal(validator.Address, vote.ValidatorAddress) {
  1002. talliedVotingPower += validator.VotingPower
  1003. if talliedVotingPower > votingPowerNeeded {
  1004. return true
  1005. }
  1006. }
  1007. }
  1008. }
  1009. return false
  1010. }
  1011. func (e ProofOfLockChange) Equal(e2 ProofOfLockChange) bool {
  1012. return bytes.Equal(e.Address(), e2.Address()) && e.Height() == e2.Height() &&
  1013. e.Round() == e2.Round()
  1014. }
  1015. func (e ProofOfLockChange) ValidateBasic() error {
  1016. if e.PubKey == nil {
  1017. return errors.New("missing public key")
  1018. }
  1019. // validate basic doesn't count the number of votes and their voting power, this is to be done by VerifyEvidence
  1020. if e.Votes == nil {
  1021. return errors.New("missing votes")
  1022. }
  1023. // height, round and vote type must be the same for all votes
  1024. height := e.Height()
  1025. round := e.Round()
  1026. if round == 0 {
  1027. return errors.New("can't have a polc for the first round")
  1028. }
  1029. voteType := e.Votes[0].Type
  1030. for idx, vote := range e.Votes {
  1031. if err := vote.ValidateBasic(); err != nil {
  1032. return fmt.Errorf("invalid vote#%d: %w", idx, err)
  1033. }
  1034. if vote.Height != height {
  1035. return fmt.Errorf("invalid height for vote#%d: %d instead of %d", idx, vote.Height, height)
  1036. }
  1037. if vote.Round != round {
  1038. return fmt.Errorf("invalid round for vote#%d: %d instead of %d", idx, vote.Round, round)
  1039. }
  1040. if vote.Type != voteType {
  1041. return fmt.Errorf("invalid vote type for vote#%d: %d instead of %d", idx, vote.Type, voteType)
  1042. }
  1043. if !vote.BlockID.Equals(e.BlockID()) {
  1044. return fmt.Errorf("vote must be for the same block id: %v instead of %v", e.BlockID(), vote.BlockID)
  1045. }
  1046. if bytes.Equal(vote.ValidatorAddress.Bytes(), e.PubKey.Address().Bytes()) {
  1047. return fmt.Errorf("vote validator address cannot be the same as the public key address: %X all votes %v",
  1048. vote.ValidatorAddress.Bytes(), e.Votes)
  1049. }
  1050. for i := idx + 1; i < len(e.Votes); i++ {
  1051. if bytes.Equal(vote.ValidatorAddress.Bytes(), e.Votes[i].ValidatorAddress.Bytes()) {
  1052. return fmt.Errorf("duplicate votes: %v", vote)
  1053. }
  1054. }
  1055. }
  1056. return nil
  1057. }
  1058. func (e ProofOfLockChange) String() string {
  1059. return fmt.Sprintf("ProofOfLockChange {Address: %X, Height: %d, Round: %d", e.Address(), e.Height(),
  1060. e.Votes[0].Round)
  1061. }
  1062. //-----------------------------------------------------------------
  1063. // UNSTABLE
  1064. type MockRandomEvidence struct {
  1065. MockEvidence
  1066. randBytes []byte
  1067. }
  1068. var _ Evidence = &MockRandomEvidence{}
  1069. // UNSTABLE
  1070. func NewMockRandomEvidence(height int64, eTime time.Time, address []byte, randBytes []byte) MockRandomEvidence {
  1071. return MockRandomEvidence{
  1072. MockEvidence{
  1073. EvidenceHeight: height,
  1074. EvidenceTime: eTime,
  1075. EvidenceAddress: address}, randBytes,
  1076. }
  1077. }
  1078. func (e MockRandomEvidence) Hash() []byte {
  1079. return []byte(fmt.Sprintf("%d-%x", e.EvidenceHeight, e.randBytes))
  1080. }
  1081. func (e MockRandomEvidence) Equal(ev Evidence) bool { return false }
  1082. // UNSTABLE
  1083. type MockEvidence struct {
  1084. EvidenceHeight int64
  1085. EvidenceTime time.Time
  1086. EvidenceAddress []byte
  1087. }
  1088. var _ Evidence = &MockEvidence{}
  1089. // UNSTABLE
  1090. func NewMockEvidence(height int64, eTime time.Time, address []byte) MockEvidence {
  1091. return MockEvidence{
  1092. EvidenceHeight: height,
  1093. EvidenceTime: eTime,
  1094. EvidenceAddress: address}
  1095. }
  1096. func (e MockEvidence) Height() int64 { return e.EvidenceHeight }
  1097. func (e MockEvidence) Time() time.Time { return e.EvidenceTime }
  1098. func (e MockEvidence) Address() []byte { return e.EvidenceAddress }
  1099. func (e MockEvidence) Hash() []byte {
  1100. return []byte(fmt.Sprintf("%d-%x-%s",
  1101. e.EvidenceHeight, e.EvidenceAddress, e.EvidenceTime))
  1102. }
  1103. func (e MockEvidence) Bytes() []byte {
  1104. return []byte(fmt.Sprintf("%d-%x-%s",
  1105. e.EvidenceHeight, e.EvidenceAddress, e.EvidenceTime))
  1106. }
  1107. func (e MockEvidence) Verify(chainID string, pubKey crypto.PubKey) error { return nil }
  1108. func (e MockEvidence) Equal(ev Evidence) bool {
  1109. return e.EvidenceHeight == ev.Height() &&
  1110. bytes.Equal(e.EvidenceAddress, ev.Address())
  1111. }
  1112. func (e MockEvidence) ValidateBasic() error { return nil }
  1113. func (e MockEvidence) String() string {
  1114. return fmt.Sprintf("Evidence: %d/%s/%s", e.EvidenceHeight, e.Time(), e.EvidenceAddress)
  1115. }
  1116. // mock polc - fails validate basic, not stable
  1117. func NewMockPOLC(height int64, time time.Time, pubKey crypto.PubKey) ProofOfLockChange {
  1118. voteVal := NewMockPV()
  1119. pKey, _ := voteVal.GetPubKey()
  1120. vote := Vote{Type: tmproto.PrecommitType, Height: height, Round: 1, BlockID: BlockID{},
  1121. Timestamp: time, ValidatorAddress: pKey.Address(), ValidatorIndex: 1, Signature: []byte{}}
  1122. _ = voteVal.SignVote("mock-chain-id", &vote)
  1123. return ProofOfLockChange{
  1124. Votes: []Vote{vote},
  1125. PubKey: pubKey,
  1126. }
  1127. }