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.

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