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.

1325 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
  293. VoteB *Vote
  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. var _ Evidence = ConflictingHeadersEvidence{}
  458. var _ CompositeEvidence = ConflictingHeadersEvidence{}
  459. // Split breaks up eviddence into smaller chunks (one per validator except for
  460. // PotentialAmnesiaEvidence): PhantomValidatorEvidence,
  461. // LunaticValidatorEvidence, DuplicateVoteEvidence and
  462. // PotentialAmnesiaEvidence.
  463. //
  464. // committedHeader - header at height H1.Height == H2.Height
  465. // valSet - validator set at height H1.Height == H2.Height
  466. // valToLastHeight - map between active validators and respective last heights
  467. func (ev ConflictingHeadersEvidence) Split(committedHeader *Header, valSet *ValidatorSet,
  468. valToLastHeight map[string]int64) []Evidence {
  469. evList := make([]Evidence, 0)
  470. var alternativeHeader *SignedHeader
  471. if bytes.Equal(committedHeader.Hash(), ev.H1.Hash()) {
  472. alternativeHeader = ev.H2
  473. } else {
  474. alternativeHeader = ev.H1
  475. }
  476. // If there are signers(alternativeHeader) that are not part of
  477. // validators(committedHeader), they misbehaved as they are signing protocol
  478. // messages in heights they are not validators => immediately slashable
  479. // (#F4).
  480. for i, sig := range alternativeHeader.Commit.Signatures {
  481. if sig.Absent() {
  482. continue
  483. }
  484. lastHeightValidatorWasInSet, ok := valToLastHeight[string(sig.ValidatorAddress)]
  485. if !ok {
  486. continue
  487. }
  488. if !valSet.HasAddress(sig.ValidatorAddress) {
  489. evList = append(evList, &PhantomValidatorEvidence{
  490. Vote: alternativeHeader.Commit.GetVote(i),
  491. LastHeightValidatorWasInSet: lastHeightValidatorWasInSet,
  492. })
  493. }
  494. }
  495. // If ValidatorsHash, NextValidatorsHash, ConsensusHash, AppHash, and
  496. // LastResultsHash in alternativeHeader are different (incorrect application
  497. // state transition), then it is a lunatic misbehavior => immediately
  498. // slashable (#F5).
  499. var invalidField string
  500. switch {
  501. case !bytes.Equal(committedHeader.ValidatorsHash, alternativeHeader.ValidatorsHash):
  502. invalidField = "ValidatorsHash"
  503. case !bytes.Equal(committedHeader.NextValidatorsHash, alternativeHeader.NextValidatorsHash):
  504. invalidField = "NextValidatorsHash"
  505. case !bytes.Equal(committedHeader.ConsensusHash, alternativeHeader.ConsensusHash):
  506. invalidField = "ConsensusHash"
  507. case !bytes.Equal(committedHeader.AppHash, alternativeHeader.AppHash):
  508. invalidField = "AppHash"
  509. case !bytes.Equal(committedHeader.LastResultsHash, alternativeHeader.LastResultsHash):
  510. invalidField = "LastResultsHash"
  511. }
  512. if invalidField != "" {
  513. for i, sig := range alternativeHeader.Commit.Signatures {
  514. if sig.Absent() {
  515. continue
  516. }
  517. evList = append(evList, &LunaticValidatorEvidence{
  518. Header: alternativeHeader.Header,
  519. Vote: alternativeHeader.Commit.GetVote(i),
  520. InvalidHeaderField: invalidField,
  521. })
  522. }
  523. return evList
  524. }
  525. // Use the fact that signatures are sorted by ValidatorAddress.
  526. var (
  527. i = 0
  528. j = 0
  529. )
  530. OUTER_LOOP:
  531. for i < len(ev.H1.Commit.Signatures) {
  532. sigA := ev.H1.Commit.Signatures[i]
  533. if sigA.Absent() {
  534. i++
  535. continue
  536. }
  537. // FIXME: Replace with HasAddress once DuplicateVoteEvidence#PubKey is
  538. // removed.
  539. _, val := valSet.GetByAddress(sigA.ValidatorAddress)
  540. if val == nil {
  541. i++
  542. continue
  543. }
  544. for j < len(ev.H2.Commit.Signatures) {
  545. sigB := ev.H2.Commit.Signatures[j]
  546. if sigB.Absent() {
  547. j++
  548. continue
  549. }
  550. switch bytes.Compare(sigA.ValidatorAddress, sigB.ValidatorAddress) {
  551. case 0:
  552. // if H1.Round == H2.Round, and some signers signed different precommit
  553. // messages in both commits, then it is an equivocation misbehavior =>
  554. // immediately slashable (#F1).
  555. if ev.H1.Commit.Round == ev.H2.Commit.Round {
  556. evList = append(evList, &DuplicateVoteEvidence{
  557. VoteA: ev.H1.Commit.GetVote(i),
  558. VoteB: ev.H2.Commit.GetVote(j),
  559. })
  560. } else {
  561. // if H1.Round != H2.Round we need to run full detection procedure => not
  562. // immediately slashable.
  563. evList = append(evList, &PotentialAmnesiaEvidence{
  564. VoteA: ev.H1.Commit.GetVote(i),
  565. VoteB: ev.H2.Commit.GetVote(j),
  566. })
  567. }
  568. i++
  569. j++
  570. continue OUTER_LOOP
  571. case 1:
  572. i++
  573. continue OUTER_LOOP
  574. case -1:
  575. j++
  576. }
  577. }
  578. }
  579. return evList
  580. }
  581. func (ev ConflictingHeadersEvidence) Height() int64 { return ev.H1.Height }
  582. // XXX: this is not the time of equivocation
  583. func (ev ConflictingHeadersEvidence) Time() time.Time { return ev.H1.Time }
  584. func (ev ConflictingHeadersEvidence) Address() []byte {
  585. panic("use ConflictingHeadersEvidence#Split to split evidence into individual pieces")
  586. }
  587. func (ev ConflictingHeadersEvidence) Bytes() []byte {
  588. return cdcEncode(ev)
  589. }
  590. func (ev ConflictingHeadersEvidence) Hash() []byte {
  591. bz := make([]byte, tmhash.Size*2)
  592. copy(bz[:tmhash.Size-1], ev.H1.Hash().Bytes())
  593. copy(bz[tmhash.Size:], ev.H2.Hash().Bytes())
  594. return tmhash.Sum(bz)
  595. }
  596. func (ev ConflictingHeadersEvidence) Verify(chainID string, _ crypto.PubKey) error {
  597. panic("use ConflictingHeadersEvidence#VerifyComposite to verify composite evidence")
  598. }
  599. // VerifyComposite verifies that both headers belong to the same chain, same
  600. // height and signed by 1/3+ of validators at height H1.Height == H2.Height.
  601. func (ev ConflictingHeadersEvidence) VerifyComposite(committedHeader *Header, valSet *ValidatorSet) error {
  602. var alternativeHeader *SignedHeader
  603. switch {
  604. case bytes.Equal(committedHeader.Hash(), ev.H1.Hash()):
  605. alternativeHeader = ev.H2
  606. case bytes.Equal(committedHeader.Hash(), ev.H2.Hash()):
  607. alternativeHeader = ev.H1
  608. default:
  609. return errors.New("none of the headers are committed from this node's perspective")
  610. }
  611. // ChainID must be the same
  612. if committedHeader.ChainID != alternativeHeader.ChainID {
  613. return errors.New("alt header is from a different chain")
  614. }
  615. // Height must be the same
  616. if committedHeader.Height != alternativeHeader.Height {
  617. return errors.New("alt header is from a different height")
  618. }
  619. // Limit the number of signatures to avoid DoS attacks where a header
  620. // contains too many signatures.
  621. //
  622. // Validator set size = 100 [node]
  623. // Max validator set size = 100 * 2 = 200 [fork?]
  624. maxNumValidators := valSet.Size() * 2
  625. if len(alternativeHeader.Commit.Signatures) > maxNumValidators {
  626. return fmt.Errorf("alt commit contains too many signatures: %d, expected no more than %d",
  627. len(alternativeHeader.Commit.Signatures),
  628. maxNumValidators)
  629. }
  630. // Header must be signed by at least 1/3+ of voting power of currently
  631. // trusted validator set.
  632. if err := valSet.VerifyCommitTrusting(
  633. alternativeHeader.ChainID,
  634. alternativeHeader.Commit,
  635. tmmath.Fraction{Numerator: 1, Denominator: 3}); err != nil {
  636. return fmt.Errorf("alt header does not have 1/3+ of voting power of our validator set: %w", err)
  637. }
  638. return nil
  639. }
  640. func (ev ConflictingHeadersEvidence) Equal(ev2 Evidence) bool {
  641. switch e2 := ev2.(type) {
  642. case ConflictingHeadersEvidence:
  643. return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash())
  644. case *ConflictingHeadersEvidence:
  645. return bytes.Equal(ev.H1.Hash(), e2.H1.Hash()) && bytes.Equal(ev.H2.Hash(), e2.H2.Hash())
  646. default:
  647. return false
  648. }
  649. }
  650. func (ev ConflictingHeadersEvidence) ValidateBasic() error {
  651. if ev.H1 == nil {
  652. return errors.New("first header is missing")
  653. }
  654. if ev.H2 == nil {
  655. return errors.New("second header is missing")
  656. }
  657. if err := ev.H1.ValidateBasic(ev.H1.ChainID); err != nil {
  658. return fmt.Errorf("h1: %w", err)
  659. }
  660. if err := ev.H2.ValidateBasic(ev.H2.ChainID); err != nil {
  661. return fmt.Errorf("h2: %w", err)
  662. }
  663. return nil
  664. }
  665. func (ev ConflictingHeadersEvidence) String() string {
  666. return fmt.Sprintf("ConflictingHeadersEvidence{H1: %d#%X, H2: %d#%X}",
  667. ev.H1.Height, ev.H1.Hash(),
  668. ev.H2.Height, ev.H2.Hash())
  669. }
  670. //-------------------------------------------
  671. type PhantomValidatorEvidence struct {
  672. Vote *Vote `json:"vote"`
  673. LastHeightValidatorWasInSet int64 `json:"last_height_validator_was_in_set"`
  674. }
  675. var _ Evidence = &PhantomValidatorEvidence{}
  676. var _ Evidence = PhantomValidatorEvidence{}
  677. func (e PhantomValidatorEvidence) Height() int64 {
  678. return e.Vote.Height
  679. }
  680. func (e PhantomValidatorEvidence) Time() time.Time {
  681. return e.Vote.Timestamp
  682. }
  683. func (e PhantomValidatorEvidence) Address() []byte {
  684. return e.Vote.ValidatorAddress
  685. }
  686. func (e PhantomValidatorEvidence) Hash() []byte {
  687. return tmhash.Sum(cdcEncode(e))
  688. }
  689. func (e PhantomValidatorEvidence) Bytes() []byte {
  690. return cdcEncode(e)
  691. }
  692. func (e PhantomValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  693. // signature must be verified to the chain ID
  694. if !pubKey.VerifyBytes(e.Vote.SignBytes(chainID), e.Vote.Signature) {
  695. return errors.New("invalid signature")
  696. }
  697. return nil
  698. }
  699. func (e PhantomValidatorEvidence) Equal(ev Evidence) bool {
  700. switch e2 := ev.(type) {
  701. case PhantomValidatorEvidence:
  702. return e.Vote.Height == e2.Vote.Height &&
  703. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  704. case *PhantomValidatorEvidence:
  705. return e.Vote.Height == e2.Vote.Height &&
  706. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  707. default:
  708. return false
  709. }
  710. }
  711. func (e PhantomValidatorEvidence) ValidateBasic() error {
  712. if e.Vote == nil {
  713. return errors.New("empty vote")
  714. }
  715. if err := e.Vote.ValidateBasic(); err != nil {
  716. return fmt.Errorf("invalid signature: %v", err)
  717. }
  718. if !e.Vote.BlockID.IsComplete() {
  719. return errors.New("expected vote for block")
  720. }
  721. if e.LastHeightValidatorWasInSet <= 0 {
  722. return errors.New("negative or zero LastHeightValidatorWasInSet")
  723. }
  724. return nil
  725. }
  726. func (e PhantomValidatorEvidence) String() string {
  727. return fmt.Sprintf("PhantomValidatorEvidence{%X voted at height %d}",
  728. e.Vote.ValidatorAddress, e.Vote.Height)
  729. }
  730. //-------------------------------------------
  731. type LunaticValidatorEvidence struct {
  732. Header *Header `json:"header"`
  733. Vote *Vote `json:"vote"`
  734. InvalidHeaderField string `json:"invalid_header_field"`
  735. }
  736. var _ Evidence = &LunaticValidatorEvidence{}
  737. var _ Evidence = LunaticValidatorEvidence{}
  738. func (e LunaticValidatorEvidence) Height() int64 {
  739. return e.Header.Height
  740. }
  741. func (e LunaticValidatorEvidence) Time() time.Time {
  742. return e.Header.Time
  743. }
  744. func (e LunaticValidatorEvidence) Address() []byte {
  745. return e.Vote.ValidatorAddress
  746. }
  747. func (e LunaticValidatorEvidence) Hash() []byte {
  748. bz := make([]byte, tmhash.Size+crypto.AddressSize)
  749. copy(bz[:tmhash.Size-1], e.Header.Hash().Bytes())
  750. copy(bz[tmhash.Size:], e.Vote.ValidatorAddress.Bytes())
  751. return tmhash.Sum(bz)
  752. }
  753. func (e LunaticValidatorEvidence) Bytes() []byte {
  754. return cdcEncode(e)
  755. }
  756. func (e LunaticValidatorEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  757. // chainID must be the same
  758. if chainID != e.Header.ChainID {
  759. return fmt.Errorf("chainID do not match: %s vs %s",
  760. chainID,
  761. e.Header.ChainID,
  762. )
  763. }
  764. if !pubKey.VerifyBytes(e.Vote.SignBytes(chainID), e.Vote.Signature) {
  765. return errors.New("invalid signature")
  766. }
  767. return nil
  768. }
  769. func (e LunaticValidatorEvidence) Equal(ev Evidence) bool {
  770. switch e2 := ev.(type) {
  771. case LunaticValidatorEvidence:
  772. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  773. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  774. case *LunaticValidatorEvidence:
  775. return bytes.Equal(e.Header.Hash(), e2.Header.Hash()) &&
  776. bytes.Equal(e.Vote.ValidatorAddress, e2.Vote.ValidatorAddress)
  777. default:
  778. return false
  779. }
  780. }
  781. func (e LunaticValidatorEvidence) ValidateBasic() error {
  782. if e.Header == nil {
  783. return errors.New("empty header")
  784. }
  785. if e.Vote == nil {
  786. return errors.New("empty vote")
  787. }
  788. if err := e.Header.ValidateBasic(); err != nil {
  789. return fmt.Errorf("invalid header: %v", err)
  790. }
  791. if err := e.Vote.ValidateBasic(); err != nil {
  792. return fmt.Errorf("invalid signature: %v", err)
  793. }
  794. if !e.Vote.BlockID.IsComplete() {
  795. return errors.New("expected vote for block")
  796. }
  797. if e.Header.Height != e.Vote.Height {
  798. return fmt.Errorf("header and vote have different heights: %d vs %d",
  799. e.Header.Height,
  800. e.Vote.Height,
  801. )
  802. }
  803. switch e.InvalidHeaderField {
  804. case "ValidatorsHash", "NextValidatorsHash", "ConsensusHash", "AppHash", "LastResultsHash":
  805. return nil
  806. default:
  807. return errors.New("unknown invalid header field")
  808. }
  809. }
  810. func (e LunaticValidatorEvidence) String() string {
  811. return fmt.Sprintf("LunaticValidatorEvidence{%X voted for %d/%X, which contains invalid %s}",
  812. e.Vote.ValidatorAddress, e.Header.Height, e.Header.Hash(), e.InvalidHeaderField)
  813. }
  814. func (e LunaticValidatorEvidence) VerifyHeader(committedHeader *Header) error {
  815. matchErr := func(field string) error {
  816. return fmt.Errorf("%s matches committed hash", field)
  817. }
  818. switch e.InvalidHeaderField {
  819. case ValidatorsHashField:
  820. if bytes.Equal(committedHeader.ValidatorsHash, e.Header.ValidatorsHash) {
  821. return matchErr(ValidatorsHashField)
  822. }
  823. case NextValidatorsHashField:
  824. if bytes.Equal(committedHeader.NextValidatorsHash, e.Header.NextValidatorsHash) {
  825. return matchErr(NextValidatorsHashField)
  826. }
  827. case ConsensusHashField:
  828. if bytes.Equal(committedHeader.ConsensusHash, e.Header.ConsensusHash) {
  829. return matchErr(ConsensusHashField)
  830. }
  831. case AppHashField:
  832. if bytes.Equal(committedHeader.AppHash, e.Header.AppHash) {
  833. return matchErr(AppHashField)
  834. }
  835. case LastResultsHashField:
  836. if bytes.Equal(committedHeader.LastResultsHash, e.Header.LastResultsHash) {
  837. return matchErr(LastResultsHashField)
  838. }
  839. default:
  840. return errors.New("unknown InvalidHeaderField")
  841. }
  842. return nil
  843. }
  844. //-------------------------------------------
  845. type PotentialAmnesiaEvidence struct {
  846. VoteA *Vote `json:"vote_a"`
  847. VoteB *Vote `json:"vote_b"`
  848. }
  849. var _ Evidence = &PotentialAmnesiaEvidence{}
  850. var _ Evidence = PotentialAmnesiaEvidence{}
  851. func (e PotentialAmnesiaEvidence) Height() int64 {
  852. return e.VoteA.Height
  853. }
  854. func (e PotentialAmnesiaEvidence) Time() time.Time {
  855. if e.VoteA.Timestamp.Before(e.VoteB.Timestamp) {
  856. return e.VoteA.Timestamp
  857. }
  858. return e.VoteB.Timestamp
  859. }
  860. func (e PotentialAmnesiaEvidence) Address() []byte {
  861. return e.VoteA.ValidatorAddress
  862. }
  863. func (e PotentialAmnesiaEvidence) Hash() []byte {
  864. return tmhash.Sum(cdcEncode(e))
  865. }
  866. func (e PotentialAmnesiaEvidence) Bytes() []byte {
  867. return cdcEncode(e)
  868. }
  869. func (e PotentialAmnesiaEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  870. // pubkey must match address (this should already be true, sanity check)
  871. addr := e.VoteA.ValidatorAddress
  872. if !bytes.Equal(pubKey.Address(), addr) {
  873. return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)",
  874. addr, pubKey, pubKey.Address())
  875. }
  876. // Signatures must be valid
  877. if !pubKey.VerifyBytes(e.VoteA.SignBytes(chainID), e.VoteA.Signature) {
  878. return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature)
  879. }
  880. if !pubKey.VerifyBytes(e.VoteB.SignBytes(chainID), e.VoteB.Signature) {
  881. return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature)
  882. }
  883. return nil
  884. }
  885. func (e PotentialAmnesiaEvidence) Equal(ev Evidence) bool {
  886. switch e2 := ev.(type) {
  887. case PotentialAmnesiaEvidence:
  888. return bytes.Equal(e.Hash(), e2.Hash())
  889. case *PotentialAmnesiaEvidence:
  890. return bytes.Equal(e.Hash(), e2.Hash())
  891. default:
  892. return false
  893. }
  894. }
  895. func (e PotentialAmnesiaEvidence) ValidateBasic() error {
  896. if e.VoteA == nil || e.VoteB == nil {
  897. return fmt.Errorf("one or both of the votes are empty %v, %v", e.VoteA, e.VoteB)
  898. }
  899. if err := e.VoteA.ValidateBasic(); err != nil {
  900. return fmt.Errorf("invalid VoteA: %v", err)
  901. }
  902. if err := e.VoteB.ValidateBasic(); err != nil {
  903. return fmt.Errorf("invalid VoteB: %v", err)
  904. }
  905. // Enforce Votes are lexicographically sorted on blockID
  906. if strings.Compare(e.VoteA.BlockID.Key(), e.VoteB.BlockID.Key()) >= 0 {
  907. return errors.New("amnesia votes in invalid order")
  908. }
  909. // H/S must be the same
  910. if e.VoteA.Height != e.VoteB.Height ||
  911. e.VoteA.Type != e.VoteB.Type {
  912. return fmt.Errorf("h/s do not match: %d/%v vs %d/%v",
  913. e.VoteA.Height, e.VoteA.Type, e.VoteB.Height, e.VoteB.Type)
  914. }
  915. // R must be different
  916. if e.VoteA.Round == e.VoteB.Round {
  917. return fmt.Errorf("expected votes from different rounds, got %d", e.VoteA.Round)
  918. }
  919. // Address must be the same
  920. if !bytes.Equal(e.VoteA.ValidatorAddress, e.VoteB.ValidatorAddress) {
  921. return fmt.Errorf("validator addresses do not match: %X vs %X",
  922. e.VoteA.ValidatorAddress,
  923. e.VoteB.ValidatorAddress,
  924. )
  925. }
  926. // Index must be the same
  927. // https://github.com/tendermint/tendermint/issues/4619
  928. if e.VoteA.ValidatorIndex != e.VoteB.ValidatorIndex {
  929. return fmt.Errorf(
  930. "duplicateVoteEvidence Error: Validator indices do not match. Got %d and %d",
  931. e.VoteA.ValidatorIndex,
  932. e.VoteB.ValidatorIndex,
  933. )
  934. }
  935. // BlockIDs must be different
  936. if e.VoteA.BlockID.Equals(e.VoteB.BlockID) {
  937. return fmt.Errorf(
  938. "block IDs are the same (%v) - not a real duplicate vote",
  939. e.VoteA.BlockID,
  940. )
  941. }
  942. return nil
  943. }
  944. func (e PotentialAmnesiaEvidence) String() string {
  945. return fmt.Sprintf("PotentialAmnesiaEvidence{VoteA: %v, VoteB: %v}", e.VoteA, e.VoteB)
  946. }
  947. // ProofOfLockChange (POLC) proves that a node followed the consensus protocol and voted for a precommit in two
  948. // different rounds because the node received a majority of votes for a different block in the latter round. In cases of
  949. // amnesia evidence, a suspected node will need ProofOfLockChange to prove that the node did not break protocol.
  950. type ProofOfLockChange struct {
  951. Votes []Vote `json:"votes"`
  952. PubKey crypto.PubKey `json:"pubkey"`
  953. }
  954. // MakePOLCFromVoteSet can be used when a majority of prevotes or precommits for a block is seen
  955. // that the node has itself not yet voted for in order to process the vote set into a proof of lock change
  956. func MakePOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) (ProofOfLockChange, error) {
  957. polc := makePOLCFromVoteSet(voteSet, pubKey, blockID)
  958. return polc, polc.ValidateBasic()
  959. }
  960. func makePOLCFromVoteSet(voteSet *VoteSet, pubKey crypto.PubKey, blockID BlockID) ProofOfLockChange {
  961. var votes []Vote
  962. valSetSize := voteSet.Size()
  963. for valIdx := 0; valIdx < valSetSize; valIdx++ {
  964. vote := voteSet.GetByIndex(valIdx)
  965. if vote != nil && vote.BlockID.Equals(blockID) {
  966. votes = append(votes, *vote)
  967. }
  968. }
  969. return ProofOfLockChange{
  970. Votes: votes,
  971. PubKey: pubKey,
  972. }
  973. }
  974. func (e ProofOfLockChange) Height() int64 {
  975. return e.Votes[0].Height
  976. }
  977. // returns the time of the last vote
  978. func (e ProofOfLockChange) Time() time.Time {
  979. latest := e.Votes[0].Timestamp
  980. for _, vote := range e.Votes {
  981. if vote.Timestamp.After(latest) {
  982. latest = vote.Timestamp
  983. }
  984. }
  985. return latest
  986. }
  987. func (e ProofOfLockChange) Round() int {
  988. return e.Votes[0].Round
  989. }
  990. func (e ProofOfLockChange) Address() []byte {
  991. return e.PubKey.Address()
  992. }
  993. func (e ProofOfLockChange) BlockID() BlockID {
  994. return e.Votes[0].BlockID
  995. }
  996. // In order for a ProofOfLockChange to be valid, a validator must have received +2/3 majority of votes
  997. // MajorityOfVotes checks that there were sufficient votes in order to change locks
  998. func (e ProofOfLockChange) MajorityOfVotes(valSet *ValidatorSet) bool {
  999. talliedVotingPower := int64(0)
  1000. votingPowerNeeded := valSet.TotalVotingPower() * 2 / 3
  1001. for _, validator := range valSet.Validators {
  1002. for _, vote := range e.Votes {
  1003. if bytes.Equal(validator.Address, vote.ValidatorAddress) {
  1004. talliedVotingPower += validator.VotingPower
  1005. if talliedVotingPower > votingPowerNeeded {
  1006. return true
  1007. }
  1008. }
  1009. }
  1010. }
  1011. return false
  1012. }
  1013. func (e ProofOfLockChange) Equal(e2 ProofOfLockChange) bool {
  1014. return bytes.Equal(e.Address(), e2.Address()) && e.Height() == e2.Height() &&
  1015. e.Round() == e2.Round()
  1016. }
  1017. func (e ProofOfLockChange) ValidateBasic() error {
  1018. if e.PubKey == nil {
  1019. return errors.New("missing public key")
  1020. }
  1021. // validate basic doesn't count the number of votes and their voting power, this is to be done by VerifyEvidence
  1022. if e.Votes == nil {
  1023. return errors.New("missing votes")
  1024. }
  1025. // height, round and vote type must be the same for all votes
  1026. height := e.Height()
  1027. round := e.Round()
  1028. if round == 0 {
  1029. return errors.New("can't have a polc for the first round")
  1030. }
  1031. voteType := e.Votes[0].Type
  1032. for idx, vote := range e.Votes {
  1033. if err := vote.ValidateBasic(); err != nil {
  1034. return fmt.Errorf("invalid vote#%d: %w", idx, err)
  1035. }
  1036. if vote.Height != height {
  1037. return fmt.Errorf("invalid height for vote#%d: %d instead of %d", idx, vote.Height, height)
  1038. }
  1039. if vote.Round != round {
  1040. return fmt.Errorf("invalid round for vote#%d: %d instead of %d", idx, vote.Round, round)
  1041. }
  1042. if vote.Type != voteType {
  1043. return fmt.Errorf("invalid vote type for vote#%d: %d instead of %d", idx, vote.Type, voteType)
  1044. }
  1045. if !vote.BlockID.Equals(e.BlockID()) {
  1046. return fmt.Errorf("vote must be for the same block id: %v instead of %v", e.BlockID(), vote.BlockID)
  1047. }
  1048. if bytes.Equal(vote.ValidatorAddress.Bytes(), e.PubKey.Address().Bytes()) {
  1049. return fmt.Errorf("vote validator address cannot be the same as the public key address: %X all votes %v",
  1050. vote.ValidatorAddress.Bytes(), e.Votes)
  1051. }
  1052. for i := idx + 1; i < len(e.Votes); i++ {
  1053. if bytes.Equal(vote.ValidatorAddress.Bytes(), e.Votes[i].ValidatorAddress.Bytes()) {
  1054. return fmt.Errorf("duplicate votes: %v", vote)
  1055. }
  1056. }
  1057. }
  1058. return nil
  1059. }
  1060. func (e ProofOfLockChange) String() string {
  1061. return fmt.Sprintf("ProofOfLockChange {Address: %X, Height: %d, Round: %d", e.Address(), e.Height(),
  1062. e.Votes[0].Round)
  1063. }
  1064. //-----------------------------------------------------------------
  1065. // UNSTABLE
  1066. type MockRandomEvidence struct {
  1067. MockEvidence
  1068. randBytes []byte
  1069. }
  1070. var _ Evidence = &MockRandomEvidence{}
  1071. // UNSTABLE
  1072. func NewMockRandomEvidence(height int64, eTime time.Time, address []byte, randBytes []byte) MockRandomEvidence {
  1073. return MockRandomEvidence{
  1074. MockEvidence{
  1075. EvidenceHeight: height,
  1076. EvidenceTime: eTime,
  1077. EvidenceAddress: address}, randBytes,
  1078. }
  1079. }
  1080. func (e MockRandomEvidence) Hash() []byte {
  1081. return []byte(fmt.Sprintf("%d-%x", e.EvidenceHeight, e.randBytes))
  1082. }
  1083. func (e MockRandomEvidence) Equal(ev Evidence) bool { return false }
  1084. // UNSTABLE
  1085. type MockEvidence struct {
  1086. EvidenceHeight int64
  1087. EvidenceTime time.Time
  1088. EvidenceAddress []byte
  1089. }
  1090. var _ Evidence = &MockEvidence{}
  1091. // UNSTABLE
  1092. func NewMockEvidence(height int64, eTime time.Time, address []byte) MockEvidence {
  1093. return MockEvidence{
  1094. EvidenceHeight: height,
  1095. EvidenceTime: eTime,
  1096. EvidenceAddress: address}
  1097. }
  1098. func (e MockEvidence) Height() int64 { return e.EvidenceHeight }
  1099. func (e MockEvidence) Time() time.Time { return e.EvidenceTime }
  1100. func (e MockEvidence) Address() []byte { return e.EvidenceAddress }
  1101. func (e MockEvidence) Hash() []byte {
  1102. return []byte(fmt.Sprintf("%d-%x-%s",
  1103. e.EvidenceHeight, e.EvidenceAddress, e.EvidenceTime))
  1104. }
  1105. func (e MockEvidence) Bytes() []byte {
  1106. return []byte(fmt.Sprintf("%d-%x-%s",
  1107. e.EvidenceHeight, e.EvidenceAddress, e.EvidenceTime))
  1108. }
  1109. func (e MockEvidence) Verify(chainID string, pubKey crypto.PubKey) error { return nil }
  1110. func (e MockEvidence) Equal(ev Evidence) bool {
  1111. return e.EvidenceHeight == ev.Height() &&
  1112. bytes.Equal(e.EvidenceAddress, ev.Address())
  1113. }
  1114. func (e MockEvidence) ValidateBasic() error { return nil }
  1115. func (e MockEvidence) String() string {
  1116. return fmt.Sprintf("Evidence: %d/%s/%s", e.EvidenceHeight, e.Time(), e.EvidenceAddress)
  1117. }
  1118. // mock polc - fails validate basic, not stable
  1119. func NewMockPOLC(height int64, time time.Time, pubKey crypto.PubKey) ProofOfLockChange {
  1120. voteVal := NewMockPV()
  1121. pKey, _ := voteVal.GetPubKey()
  1122. vote := Vote{Type: PrecommitType, Height: height, Round: 1, BlockID: BlockID{},
  1123. Timestamp: time, ValidatorAddress: pKey.Address(), ValidatorIndex: 1, Signature: []byte{}}
  1124. _ = voteVal.SignVote("mock-chain-id", &vote)
  1125. return ProofOfLockChange{
  1126. Votes: []Vote{vote},
  1127. PubKey: pubKey,
  1128. }
  1129. }