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.

708 lines
23 KiB

  1. package types
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "sort"
  9. "strings"
  10. "time"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. "github.com/tendermint/tendermint/crypto/merkle"
  13. "github.com/tendermint/tendermint/crypto/tmhash"
  14. tmjson "github.com/tendermint/tendermint/libs/json"
  15. tmrand "github.com/tendermint/tendermint/libs/rand"
  16. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  17. )
  18. // Evidence represents any provable malicious activity by a validator.
  19. // Verification logic for each evidence is part of the evidence module.
  20. type Evidence interface {
  21. ABCI() []abci.Evidence // forms individual evidence to be sent to the application
  22. Bytes() []byte // bytes which comprise the evidence
  23. Hash() []byte // hash of the evidence
  24. Height() int64 // height of the infraction
  25. String() string // string format of the evidence
  26. Time() time.Time // time of the infraction
  27. ValidateBasic() error // basic consistency check
  28. }
  29. //--------------------------------------------------------------------------------------
  30. // DuplicateVoteEvidence contains evidence of a single validator signing two conflicting votes.
  31. type DuplicateVoteEvidence struct {
  32. VoteA *Vote `json:"vote_a"`
  33. VoteB *Vote `json:"vote_b"`
  34. // abci specific information
  35. TotalVotingPower int64
  36. ValidatorPower int64
  37. Timestamp time.Time
  38. }
  39. var _ Evidence = &DuplicateVoteEvidence{}
  40. // NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given
  41. // two conflicting votes. If one of the votes is nil, evidence returned is nil as well
  42. func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *ValidatorSet) *DuplicateVoteEvidence {
  43. var voteA, voteB *Vote
  44. if vote1 == nil || vote2 == nil || valSet == nil {
  45. return nil
  46. }
  47. idx, val := valSet.GetByAddress(vote1.ValidatorAddress)
  48. if idx == -1 {
  49. return nil
  50. }
  51. if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 {
  52. voteA = vote1
  53. voteB = vote2
  54. } else {
  55. voteA = vote2
  56. voteB = vote1
  57. }
  58. return &DuplicateVoteEvidence{
  59. VoteA: voteA,
  60. VoteB: voteB,
  61. TotalVotingPower: valSet.TotalVotingPower(),
  62. ValidatorPower: val.VotingPower,
  63. Timestamp: blockTime,
  64. }
  65. }
  66. // ABCI returns the application relevant representation of the evidence
  67. func (dve *DuplicateVoteEvidence) ABCI() []abci.Evidence {
  68. return []abci.Evidence{{
  69. Type: abci.EvidenceType_DUPLICATE_VOTE,
  70. Validator: abci.Validator{
  71. Address: dve.VoteA.ValidatorAddress,
  72. Power: dve.ValidatorPower,
  73. },
  74. Height: dve.VoteA.Height,
  75. Time: dve.Timestamp,
  76. TotalVotingPower: dve.TotalVotingPower,
  77. }}
  78. }
  79. // Bytes returns the proto-encoded evidence as a byte array.
  80. func (dve *DuplicateVoteEvidence) Bytes() []byte {
  81. pbe := dve.ToProto()
  82. bz, err := pbe.Marshal()
  83. if err != nil {
  84. panic(err)
  85. }
  86. return bz
  87. }
  88. // Hash returns the hash of the evidence.
  89. func (dve *DuplicateVoteEvidence) Hash() []byte {
  90. return tmhash.Sum(dve.Bytes())
  91. }
  92. // Height returns the height of the infraction
  93. func (dve *DuplicateVoteEvidence) Height() int64 {
  94. return dve.VoteA.Height
  95. }
  96. // String returns a string representation of the evidence.
  97. func (dve *DuplicateVoteEvidence) String() string {
  98. return fmt.Sprintf("DuplicateVoteEvidence{VoteA: %v, VoteB: %v}", dve.VoteA, dve.VoteB)
  99. }
  100. // Time returns the time of the infraction
  101. func (dve *DuplicateVoteEvidence) Time() time.Time {
  102. return dve.Timestamp
  103. }
  104. // ValidateBasic performs basic validation.
  105. func (dve *DuplicateVoteEvidence) ValidateBasic() error {
  106. if dve == nil {
  107. return errors.New("empty duplicate vote evidence")
  108. }
  109. if dve.VoteA == nil || dve.VoteB == nil {
  110. return fmt.Errorf("one or both of the votes are empty %v, %v", dve.VoteA, dve.VoteB)
  111. }
  112. if err := dve.VoteA.ValidateBasic(); err != nil {
  113. return fmt.Errorf("invalid VoteA: %w", err)
  114. }
  115. if err := dve.VoteB.ValidateBasic(); err != nil {
  116. return fmt.Errorf("invalid VoteB: %w", err)
  117. }
  118. // Enforce Votes are lexicographically sorted on blockID
  119. if strings.Compare(dve.VoteA.BlockID.Key(), dve.VoteB.BlockID.Key()) >= 0 {
  120. return errors.New("duplicate votes in invalid order")
  121. }
  122. return nil
  123. }
  124. // ValidateABCI validates the ABCI component of the evidence by checking the
  125. // timestamp, validator power and total voting power.
  126. func (dve *DuplicateVoteEvidence) ValidateABCI(
  127. val *Validator,
  128. valSet *ValidatorSet,
  129. evidenceTime time.Time,
  130. ) error {
  131. if dve.Timestamp != evidenceTime {
  132. return fmt.Errorf(
  133. "evidence has a different time to the block it is associated with (%v != %v)",
  134. dve.Timestamp, evidenceTime)
  135. }
  136. if val.VotingPower != dve.ValidatorPower {
  137. return fmt.Errorf("validator power from evidence and our validator set does not match (%d != %d)",
  138. dve.ValidatorPower, val.VotingPower)
  139. }
  140. if valSet.TotalVotingPower() != dve.TotalVotingPower {
  141. return fmt.Errorf("total voting power from the evidence and our validator set does not match (%d != %d)",
  142. dve.TotalVotingPower, valSet.TotalVotingPower())
  143. }
  144. return nil
  145. }
  146. // GenerateABCI populates the ABCI component of the evidence. This includes the
  147. // validator power, timestamp and total voting power.
  148. func (dve *DuplicateVoteEvidence) GenerateABCI(
  149. val *Validator,
  150. valSet *ValidatorSet,
  151. evidenceTime time.Time,
  152. ) {
  153. dve.ValidatorPower = val.VotingPower
  154. dve.TotalVotingPower = valSet.TotalVotingPower()
  155. dve.Timestamp = evidenceTime
  156. }
  157. // ToProto encodes DuplicateVoteEvidence to protobuf
  158. func (dve *DuplicateVoteEvidence) ToProto() *tmproto.DuplicateVoteEvidence {
  159. voteB := dve.VoteB.ToProto()
  160. voteA := dve.VoteA.ToProto()
  161. tp := tmproto.DuplicateVoteEvidence{
  162. VoteA: voteA,
  163. VoteB: voteB,
  164. TotalVotingPower: dve.TotalVotingPower,
  165. ValidatorPower: dve.ValidatorPower,
  166. Timestamp: dve.Timestamp,
  167. }
  168. return &tp
  169. }
  170. // DuplicateVoteEvidenceFromProto decodes protobuf into DuplicateVoteEvidence
  171. func DuplicateVoteEvidenceFromProto(pb *tmproto.DuplicateVoteEvidence) (*DuplicateVoteEvidence, error) {
  172. if pb == nil {
  173. return nil, errors.New("nil duplicate vote evidence")
  174. }
  175. vA, err := VoteFromProto(pb.VoteA)
  176. if err != nil {
  177. return nil, err
  178. }
  179. vB, err := VoteFromProto(pb.VoteB)
  180. if err != nil {
  181. return nil, err
  182. }
  183. dve := &DuplicateVoteEvidence{
  184. VoteA: vA,
  185. VoteB: vB,
  186. TotalVotingPower: pb.TotalVotingPower,
  187. ValidatorPower: pb.ValidatorPower,
  188. Timestamp: pb.Timestamp,
  189. }
  190. return dve, dve.ValidateBasic()
  191. }
  192. //------------------------------------ LIGHT EVIDENCE --------------------------------------
  193. // LightClientAttackEvidence is a generalized evidence that captures all forms of known attacks on
  194. // a light client such that a full node can verify, propose and commit the evidence on-chain for
  195. // punishment of the malicious validators. There are three forms of attacks: Lunatic, Equivocation
  196. // and Amnesia. These attacks are exhaustive. You can find a more detailed overview of this at
  197. // tendermint/docs/architecture/adr-047-handling-evidence-from-light-client.md
  198. type LightClientAttackEvidence struct {
  199. ConflictingBlock *LightBlock
  200. CommonHeight int64
  201. // abci specific information
  202. ByzantineValidators []*Validator // validators in the validator set that misbehaved in creating the conflicting block
  203. TotalVotingPower int64 // total voting power of the validator set at the common height
  204. Timestamp time.Time // timestamp of the block at the common height
  205. }
  206. var _ Evidence = &LightClientAttackEvidence{}
  207. // ABCI forms an array of abci evidence for each byzantine validator
  208. func (l *LightClientAttackEvidence) ABCI() []abci.Evidence {
  209. abciEv := make([]abci.Evidence, len(l.ByzantineValidators))
  210. for idx, val := range l.ByzantineValidators {
  211. abciEv[idx] = abci.Evidence{
  212. Type: abci.EvidenceType_LIGHT_CLIENT_ATTACK,
  213. Validator: TM2PB.Validator(val),
  214. Height: l.Height(),
  215. Time: l.Timestamp,
  216. TotalVotingPower: l.TotalVotingPower,
  217. }
  218. }
  219. return abciEv
  220. }
  221. // Bytes returns the proto-encoded evidence as a byte array
  222. func (l *LightClientAttackEvidence) Bytes() []byte {
  223. pbe, err := l.ToProto()
  224. if err != nil {
  225. panic(err)
  226. }
  227. bz, err := pbe.Marshal()
  228. if err != nil {
  229. panic(err)
  230. }
  231. return bz
  232. }
  233. // GetByzantineValidators finds out what style of attack LightClientAttackEvidence was and then works out who
  234. // the malicious validators were and returns them. This is used both for forming the ByzantineValidators
  235. // field and for validating that it is correct. Validators are ordered based on validator power
  236. func (l *LightClientAttackEvidence) GetByzantineValidators(commonVals *ValidatorSet,
  237. trusted *SignedHeader) []*Validator {
  238. var validators []*Validator
  239. // First check if the header is invalid. This means that it is a lunatic attack and therefore we take the
  240. // validators who are in the commonVals and voted for the lunatic header
  241. if l.ConflictingHeaderIsInvalid(trusted.Header) {
  242. for _, commitSig := range l.ConflictingBlock.Commit.Signatures {
  243. if !commitSig.ForBlock() {
  244. continue
  245. }
  246. _, val := commonVals.GetByAddress(commitSig.ValidatorAddress)
  247. if val == nil {
  248. // validator wasn't in the common validator set
  249. continue
  250. }
  251. validators = append(validators, val)
  252. }
  253. sort.Sort(ValidatorsByVotingPower(validators))
  254. return validators
  255. } else if trusted.Commit.Round == l.ConflictingBlock.Commit.Round {
  256. // This is an equivocation attack as both commits are in the same round. We then find the validators
  257. // from the conflicting light block validator set that voted in both headers.
  258. // Validator hashes are the same therefore the indexing order of validators are the same and thus we
  259. // only need a single loop to find the validators that voted twice.
  260. for i := 0; i < len(l.ConflictingBlock.Commit.Signatures); i++ {
  261. sigA := l.ConflictingBlock.Commit.Signatures[i]
  262. if !sigA.ForBlock() {
  263. continue
  264. }
  265. sigB := trusted.Commit.Signatures[i]
  266. if !sigB.ForBlock() {
  267. continue
  268. }
  269. _, val := l.ConflictingBlock.ValidatorSet.GetByAddress(sigA.ValidatorAddress)
  270. validators = append(validators, val)
  271. }
  272. sort.Sort(ValidatorsByVotingPower(validators))
  273. return validators
  274. }
  275. // if the rounds are different then this is an amnesia attack. Unfortunately, given the nature of the attack,
  276. // we aren't able yet to deduce which are malicious validators and which are not hence we return an
  277. // empty validator set.
  278. return validators
  279. }
  280. // ConflictingHeaderIsInvalid takes a trusted header and matches it againt a conflicting header
  281. // to determine whether the conflicting header was the product of a valid state transition
  282. // or not. If it is then all the deterministic fields of the header should be the same.
  283. // If not, it is an invalid header and constitutes a lunatic attack.
  284. func (l *LightClientAttackEvidence) ConflictingHeaderIsInvalid(trustedHeader *Header) bool {
  285. return !bytes.Equal(trustedHeader.ValidatorsHash, l.ConflictingBlock.ValidatorsHash) ||
  286. !bytes.Equal(trustedHeader.NextValidatorsHash, l.ConflictingBlock.NextValidatorsHash) ||
  287. !bytes.Equal(trustedHeader.ConsensusHash, l.ConflictingBlock.ConsensusHash) ||
  288. !bytes.Equal(trustedHeader.AppHash, l.ConflictingBlock.AppHash) ||
  289. !bytes.Equal(trustedHeader.LastResultsHash, l.ConflictingBlock.LastResultsHash)
  290. }
  291. // Hash returns the hash of the header and the commonHeight. This is designed to cause hash collisions
  292. // with evidence that have the same conflicting header and common height but different permutations
  293. // of validator commit signatures. The reason for this is that we don't want to allow several
  294. // permutations of the same evidence to be committed on chain. Ideally we commit the header with the
  295. // most commit signatures (captures the most byzantine validators) but anything greater than 1/3 is
  296. // sufficient.
  297. // TODO: We should change the hash to include the commit, header, total voting power, byzantine
  298. // validators and timestamp
  299. func (l *LightClientAttackEvidence) Hash() []byte {
  300. buf := make([]byte, binary.MaxVarintLen64)
  301. n := binary.PutVarint(buf, l.CommonHeight)
  302. bz := make([]byte, tmhash.Size+n)
  303. copy(bz[:tmhash.Size-1], l.ConflictingBlock.Hash().Bytes())
  304. copy(bz[tmhash.Size:], buf)
  305. return tmhash.Sum(bz)
  306. }
  307. // Height returns the last height at which the primary provider and witness provider had the same header.
  308. // We use this as the height of the infraction rather than the actual conflicting header because we know
  309. // that the malicious validators were bonded at this height which is important for evidence expiry
  310. func (l *LightClientAttackEvidence) Height() int64 {
  311. return l.CommonHeight
  312. }
  313. // String returns a string representation of LightClientAttackEvidence
  314. func (l *LightClientAttackEvidence) String() string {
  315. return fmt.Sprintf(`LightClientAttackEvidence{
  316. ConflictingBlock: %v,
  317. CommonHeight: %d,
  318. ByzatineValidators: %v,
  319. TotalVotingPower: %d,
  320. Timestamp: %v}#%X`,
  321. l.ConflictingBlock.String(), l.CommonHeight, l.ByzantineValidators,
  322. l.TotalVotingPower, l.Timestamp, l.Hash())
  323. }
  324. // Time returns the time of the common block where the infraction leveraged off.
  325. func (l *LightClientAttackEvidence) Time() time.Time {
  326. return l.Timestamp
  327. }
  328. // ValidateBasic performs basic validation such that the evidence is consistent and can now be used for verification.
  329. func (l *LightClientAttackEvidence) ValidateBasic() error {
  330. if l.ConflictingBlock == nil {
  331. return errors.New("conflicting block is nil")
  332. }
  333. // this check needs to be done before we can run validate basic
  334. if l.ConflictingBlock.Header == nil {
  335. return errors.New("conflicting block missing header")
  336. }
  337. if l.TotalVotingPower <= 0 {
  338. return errors.New("negative or zero total voting power")
  339. }
  340. if l.CommonHeight <= 0 {
  341. return errors.New("negative or zero common height")
  342. }
  343. // check that common height isn't ahead of the height of the conflicting block. It
  344. // is possible that they are the same height if the light node witnesses either an
  345. // amnesia or a equivocation attack.
  346. if l.CommonHeight > l.ConflictingBlock.Height {
  347. return fmt.Errorf("common height is ahead of the conflicting block height (%d > %d)",
  348. l.CommonHeight, l.ConflictingBlock.Height)
  349. }
  350. if err := l.ConflictingBlock.ValidateBasic(l.ConflictingBlock.ChainID); err != nil {
  351. return fmt.Errorf("invalid conflicting light block: %w", err)
  352. }
  353. return nil
  354. }
  355. // ValidateABCI validates the ABCI component of the evidence by checking the
  356. // timestamp, byzantine validators and total voting power all match. ABCI
  357. // components are validated separately because they can be re generated if
  358. // invalid.
  359. func (l *LightClientAttackEvidence) ValidateABCI(
  360. commonVals *ValidatorSet,
  361. trustedHeader *SignedHeader,
  362. evidenceTime time.Time,
  363. ) error {
  364. if evTotal, valsTotal := l.TotalVotingPower, commonVals.TotalVotingPower(); evTotal != valsTotal {
  365. return fmt.Errorf("total voting power from the evidence and our validator set does not match (%d != %d)",
  366. evTotal, valsTotal)
  367. }
  368. if l.Timestamp != evidenceTime {
  369. return fmt.Errorf(
  370. "evidence has a different time to the block it is associated with (%v != %v)",
  371. l.Timestamp, evidenceTime)
  372. }
  373. // Find out what type of attack this was and thus extract the malicious
  374. // validators. Note, in the case of an Amnesia attack we don't have any
  375. // malicious validators.
  376. validators := l.GetByzantineValidators(commonVals, trustedHeader)
  377. // Ensure this matches the validators that are listed in the evidence. They
  378. // should be ordered based on power.
  379. if validators == nil && l.ByzantineValidators != nil {
  380. return fmt.Errorf(
  381. "expected nil validators from an amnesia light client attack but got %d",
  382. len(l.ByzantineValidators),
  383. )
  384. }
  385. if exp, got := len(validators), len(l.ByzantineValidators); exp != got {
  386. return fmt.Errorf("expected %d byzantine validators from evidence but got %d", exp, got)
  387. }
  388. for idx, val := range validators {
  389. if !bytes.Equal(l.ByzantineValidators[idx].Address, val.Address) {
  390. return fmt.Errorf(
  391. "evidence contained an unexpected byzantine validator address; expected: %v, got: %v",
  392. val.Address, l.ByzantineValidators[idx].Address,
  393. )
  394. }
  395. if l.ByzantineValidators[idx].VotingPower != val.VotingPower {
  396. return fmt.Errorf(
  397. "evidence contained unexpected byzantine validator power; expected %d, got %d",
  398. val.VotingPower, l.ByzantineValidators[idx].VotingPower,
  399. )
  400. }
  401. }
  402. return nil
  403. }
  404. // GenerateABCI populates the ABCI component of the evidence: the timestamp,
  405. // total voting power and byantine validators
  406. func (l *LightClientAttackEvidence) GenerateABCI(
  407. commonVals *ValidatorSet,
  408. trustedHeader *SignedHeader,
  409. evidenceTime time.Time,
  410. ) {
  411. l.Timestamp = evidenceTime
  412. l.TotalVotingPower = commonVals.TotalVotingPower()
  413. l.ByzantineValidators = l.GetByzantineValidators(commonVals, trustedHeader)
  414. }
  415. // ToProto encodes LightClientAttackEvidence to protobuf
  416. func (l *LightClientAttackEvidence) ToProto() (*tmproto.LightClientAttackEvidence, error) {
  417. conflictingBlock, err := l.ConflictingBlock.ToProto()
  418. if err != nil {
  419. return nil, err
  420. }
  421. byzVals := make([]*tmproto.Validator, len(l.ByzantineValidators))
  422. for idx, val := range l.ByzantineValidators {
  423. valpb, err := val.ToProto()
  424. if err != nil {
  425. return nil, err
  426. }
  427. byzVals[idx] = valpb
  428. }
  429. return &tmproto.LightClientAttackEvidence{
  430. ConflictingBlock: conflictingBlock,
  431. CommonHeight: l.CommonHeight,
  432. ByzantineValidators: byzVals,
  433. TotalVotingPower: l.TotalVotingPower,
  434. Timestamp: l.Timestamp,
  435. }, nil
  436. }
  437. // LightClientAttackEvidenceFromProto decodes protobuf
  438. func LightClientAttackEvidenceFromProto(lpb *tmproto.LightClientAttackEvidence) (*LightClientAttackEvidence, error) {
  439. if lpb == nil {
  440. return nil, errors.New("empty light client attack evidence")
  441. }
  442. conflictingBlock, err := LightBlockFromProto(lpb.ConflictingBlock)
  443. if err != nil {
  444. return nil, err
  445. }
  446. byzVals := make([]*Validator, len(lpb.ByzantineValidators))
  447. for idx, valpb := range lpb.ByzantineValidators {
  448. val, err := ValidatorFromProto(valpb)
  449. if err != nil {
  450. return nil, err
  451. }
  452. byzVals[idx] = val
  453. }
  454. l := &LightClientAttackEvidence{
  455. ConflictingBlock: conflictingBlock,
  456. CommonHeight: lpb.CommonHeight,
  457. ByzantineValidators: byzVals,
  458. TotalVotingPower: lpb.TotalVotingPower,
  459. Timestamp: lpb.Timestamp,
  460. }
  461. return l, l.ValidateBasic()
  462. }
  463. //------------------------------------------------------------------------------------------
  464. // EvidenceList is a list of Evidence. Evidences is not a word.
  465. type EvidenceList []Evidence
  466. // Hash returns the simple merkle root hash of the EvidenceList.
  467. func (evl EvidenceList) Hash() []byte {
  468. // These allocations are required because Evidence is not of type Bytes, and
  469. // golang slices can't be typed cast. This shouldn't be a performance problem since
  470. // the Evidence size is capped.
  471. evidenceBzs := make([][]byte, len(evl))
  472. for i := 0; i < len(evl); i++ {
  473. // TODO: We should change this to the hash. Using bytes contains some unexported data that
  474. // may cause different hashes
  475. evidenceBzs[i] = evl[i].Bytes()
  476. }
  477. return merkle.HashFromByteSlices(evidenceBzs)
  478. }
  479. func (evl EvidenceList) String() string {
  480. s := ""
  481. for _, e := range evl {
  482. s += fmt.Sprintf("%s\t\t", e)
  483. }
  484. return s
  485. }
  486. // Has returns true if the evidence is in the EvidenceList.
  487. func (evl EvidenceList) Has(evidence Evidence) bool {
  488. for _, ev := range evl {
  489. if bytes.Equal(evidence.Hash(), ev.Hash()) {
  490. return true
  491. }
  492. }
  493. return false
  494. }
  495. //------------------------------------------ PROTO --------------------------------------
  496. // EvidenceToProto is a generalized function for encoding evidence that conforms to the
  497. // evidence interface to protobuf
  498. func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error) {
  499. if evidence == nil {
  500. return nil, errors.New("nil evidence")
  501. }
  502. switch evi := evidence.(type) {
  503. case *DuplicateVoteEvidence:
  504. pbev := evi.ToProto()
  505. return &tmproto.Evidence{
  506. Sum: &tmproto.Evidence_DuplicateVoteEvidence{
  507. DuplicateVoteEvidence: pbev,
  508. },
  509. }, nil
  510. case *LightClientAttackEvidence:
  511. pbev, err := evi.ToProto()
  512. if err != nil {
  513. return nil, err
  514. }
  515. return &tmproto.Evidence{
  516. Sum: &tmproto.Evidence_LightClientAttackEvidence{
  517. LightClientAttackEvidence: pbev,
  518. },
  519. }, nil
  520. default:
  521. return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi)
  522. }
  523. }
  524. // EvidenceFromProto is a generalized function for decoding protobuf into the
  525. // evidence interface
  526. func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error) {
  527. if evidence == nil {
  528. return nil, errors.New("nil evidence")
  529. }
  530. switch evi := evidence.Sum.(type) {
  531. case *tmproto.Evidence_DuplicateVoteEvidence:
  532. return DuplicateVoteEvidenceFromProto(evi.DuplicateVoteEvidence)
  533. case *tmproto.Evidence_LightClientAttackEvidence:
  534. return LightClientAttackEvidenceFromProto(evi.LightClientAttackEvidence)
  535. default:
  536. return nil, errors.New("evidence is not recognized")
  537. }
  538. }
  539. func init() {
  540. tmjson.RegisterType(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence")
  541. tmjson.RegisterType(&LightClientAttackEvidence{}, "tendermint/LightClientAttackEvidence")
  542. }
  543. //-------------------------------------------- ERRORS --------------------------------------
  544. // ErrInvalidEvidence wraps a piece of evidence and the error denoting how or why it is invalid.
  545. type ErrInvalidEvidence struct {
  546. Evidence Evidence
  547. Reason error
  548. }
  549. // NewErrInvalidEvidence returns a new EvidenceInvalid with the given err.
  550. func NewErrInvalidEvidence(ev Evidence, err error) *ErrInvalidEvidence {
  551. return &ErrInvalidEvidence{ev, err}
  552. }
  553. // Error returns a string representation of the error.
  554. func (err *ErrInvalidEvidence) Error() string {
  555. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.Reason, err.Evidence)
  556. }
  557. // ErrEvidenceOverflow is for when there the amount of evidence exceeds the max bytes.
  558. type ErrEvidenceOverflow struct {
  559. Max int64
  560. Got int64
  561. }
  562. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  563. func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow {
  564. return &ErrEvidenceOverflow{max, got}
  565. }
  566. // Error returns a string representation of the error.
  567. func (err *ErrEvidenceOverflow) Error() string {
  568. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.Max, err.Got)
  569. }
  570. //-------------------------------------------- MOCKING --------------------------------------
  571. // unstable - use only for testing
  572. // assumes the round to be 0 and the validator index to be 0
  573. func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence {
  574. val := NewMockPV()
  575. return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID)
  576. }
  577. // assumes voting power to be 10 and validator to be the only one in the set
  578. func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time,
  579. pv PrivValidator, chainID string) *DuplicateVoteEvidence {
  580. pubKey, _ := pv.GetPubKey(context.Background())
  581. val := NewValidator(pubKey, 10)
  582. voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  583. vA := voteA.ToProto()
  584. _ = pv.SignVote(context.Background(), chainID, vA)
  585. voteA.Signature = vA.Signature
  586. voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  587. vB := voteB.ToProto()
  588. _ = pv.SignVote(context.Background(), chainID, vB)
  589. voteB.Signature = vB.Signature
  590. return NewDuplicateVoteEvidence(voteA, voteB, time, NewValidatorSet([]*Validator{val}))
  591. }
  592. func makeMockVote(height int64, round, index int32, addr Address,
  593. blockID BlockID, time time.Time) *Vote {
  594. return &Vote{
  595. Type: tmproto.SignedMsgType(2),
  596. Height: height,
  597. Round: round,
  598. BlockID: blockID,
  599. Timestamp: time,
  600. ValidatorAddress: addr,
  601. ValidatorIndex: index,
  602. }
  603. }
  604. func randBlockID() BlockID {
  605. return BlockID{
  606. Hash: tmrand.Bytes(tmhash.Size),
  607. PartSetHeader: PartSetHeader{
  608. Total: 1,
  609. Hash: tmrand.Bytes(tmhash.Size),
  610. },
  611. }
  612. }