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.

711 lines
24 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. //
  199. // CommonHeight is used to indicate the type of attack. If the height is different to the conflicting block
  200. // height, then nodes will treat this as of the Lunatic form, else it is of the Equivocation form.
  201. type LightClientAttackEvidence struct {
  202. ConflictingBlock *LightBlock
  203. CommonHeight int64
  204. // abci specific information
  205. ByzantineValidators []*Validator // validators in the validator set that misbehaved in creating the conflicting block
  206. TotalVotingPower int64 // total voting power of the validator set at the common height
  207. Timestamp time.Time // timestamp of the block at the common height
  208. }
  209. var _ Evidence = &LightClientAttackEvidence{}
  210. // ABCI forms an array of abci evidence for each byzantine validator
  211. func (l *LightClientAttackEvidence) ABCI() []abci.Evidence {
  212. abciEv := make([]abci.Evidence, len(l.ByzantineValidators))
  213. for idx, val := range l.ByzantineValidators {
  214. abciEv[idx] = abci.Evidence{
  215. Type: abci.EvidenceType_LIGHT_CLIENT_ATTACK,
  216. Validator: TM2PB.Validator(val),
  217. Height: l.Height(),
  218. Time: l.Timestamp,
  219. TotalVotingPower: l.TotalVotingPower,
  220. }
  221. }
  222. return abciEv
  223. }
  224. // Bytes returns the proto-encoded evidence as a byte array
  225. func (l *LightClientAttackEvidence) Bytes() []byte {
  226. pbe, err := l.ToProto()
  227. if err != nil {
  228. panic(err)
  229. }
  230. bz, err := pbe.Marshal()
  231. if err != nil {
  232. panic(err)
  233. }
  234. return bz
  235. }
  236. // GetByzantineValidators finds out what style of attack LightClientAttackEvidence was and then works out who
  237. // the malicious validators were and returns them. This is used both for forming the ByzantineValidators
  238. // field and for validating that it is correct. Validators are ordered based on validator power
  239. func (l *LightClientAttackEvidence) GetByzantineValidators(commonVals *ValidatorSet,
  240. trusted *SignedHeader) []*Validator {
  241. var validators []*Validator
  242. // First check if the header is invalid. This means that it is a lunatic attack and therefore we take the
  243. // validators who are in the commonVals and voted for the lunatic header
  244. if l.ConflictingHeaderIsInvalid(trusted.Header) {
  245. for _, commitSig := range l.ConflictingBlock.Commit.Signatures {
  246. if !commitSig.ForBlock() {
  247. continue
  248. }
  249. _, val := commonVals.GetByAddress(commitSig.ValidatorAddress)
  250. if val == nil {
  251. // validator wasn't in the common validator set
  252. continue
  253. }
  254. validators = append(validators, val)
  255. }
  256. sort.Sort(ValidatorsByVotingPower(validators))
  257. return validators
  258. } else if trusted.Commit.Round == l.ConflictingBlock.Commit.Round {
  259. // This is an equivocation attack as both commits are in the same round. We then find the validators
  260. // from the conflicting light block validator set that voted in both headers.
  261. // Validator hashes are the same therefore the indexing order of validators are the same and thus we
  262. // only need a single loop to find the validators that voted twice.
  263. for i := 0; i < len(l.ConflictingBlock.Commit.Signatures); i++ {
  264. sigA := l.ConflictingBlock.Commit.Signatures[i]
  265. if !sigA.ForBlock() {
  266. continue
  267. }
  268. sigB := trusted.Commit.Signatures[i]
  269. if !sigB.ForBlock() {
  270. continue
  271. }
  272. _, val := l.ConflictingBlock.ValidatorSet.GetByAddress(sigA.ValidatorAddress)
  273. validators = append(validators, val)
  274. }
  275. sort.Sort(ValidatorsByVotingPower(validators))
  276. return validators
  277. }
  278. // if the rounds are different then this is an amnesia attack. Unfortunately, given the nature of the attack,
  279. // we aren't able yet to deduce which are malicious validators and which are not hence we return an
  280. // empty validator set.
  281. return validators
  282. }
  283. // ConflictingHeaderIsInvalid takes a trusted header and matches it againt a conflicting header
  284. // to determine whether the conflicting header was the product of a valid state transition
  285. // or not. If it is then all the deterministic fields of the header should be the same.
  286. // If not, it is an invalid header and constitutes a lunatic attack.
  287. func (l *LightClientAttackEvidence) ConflictingHeaderIsInvalid(trustedHeader *Header) bool {
  288. return !bytes.Equal(trustedHeader.ValidatorsHash, l.ConflictingBlock.ValidatorsHash) ||
  289. !bytes.Equal(trustedHeader.NextValidatorsHash, l.ConflictingBlock.NextValidatorsHash) ||
  290. !bytes.Equal(trustedHeader.ConsensusHash, l.ConflictingBlock.ConsensusHash) ||
  291. !bytes.Equal(trustedHeader.AppHash, l.ConflictingBlock.AppHash) ||
  292. !bytes.Equal(trustedHeader.LastResultsHash, l.ConflictingBlock.LastResultsHash)
  293. }
  294. // Hash returns the hash of the header and the commonHeight. This is designed to cause hash collisions
  295. // with evidence that have the same conflicting header and common height but different permutations
  296. // of validator commit signatures. The reason for this is that we don't want to allow several
  297. // permutations of the same evidence to be committed on chain. Ideally we commit the header with the
  298. // most commit signatures (captures the most byzantine validators) but anything greater than 1/3 is
  299. // sufficient.
  300. // TODO: We should change the hash to include the commit, header, total voting power, byzantine
  301. // validators and timestamp
  302. func (l *LightClientAttackEvidence) Hash() []byte {
  303. buf := make([]byte, binary.MaxVarintLen64)
  304. n := binary.PutVarint(buf, l.CommonHeight)
  305. bz := make([]byte, tmhash.Size+n)
  306. copy(bz[:tmhash.Size-1], l.ConflictingBlock.Hash().Bytes())
  307. copy(bz[tmhash.Size:], buf)
  308. return tmhash.Sum(bz)
  309. }
  310. // Height returns the last height at which the primary provider and witness provider had the same header.
  311. // We use this as the height of the infraction rather than the actual conflicting header because we know
  312. // that the malicious validators were bonded at this height which is important for evidence expiry
  313. func (l *LightClientAttackEvidence) Height() int64 {
  314. return l.CommonHeight
  315. }
  316. // String returns a string representation of LightClientAttackEvidence
  317. func (l *LightClientAttackEvidence) String() string {
  318. return fmt.Sprintf(`LightClientAttackEvidence{
  319. ConflictingBlock: %v,
  320. CommonHeight: %d,
  321. ByzatineValidators: %v,
  322. TotalVotingPower: %d,
  323. Timestamp: %v}#%X`,
  324. l.ConflictingBlock.String(), l.CommonHeight, l.ByzantineValidators,
  325. l.TotalVotingPower, l.Timestamp, l.Hash())
  326. }
  327. // Time returns the time of the common block where the infraction leveraged off.
  328. func (l *LightClientAttackEvidence) Time() time.Time {
  329. return l.Timestamp
  330. }
  331. // ValidateBasic performs basic validation such that the evidence is consistent and can now be used for verification.
  332. func (l *LightClientAttackEvidence) ValidateBasic() error {
  333. if l.ConflictingBlock == nil {
  334. return errors.New("conflicting block is nil")
  335. }
  336. // this check needs to be done before we can run validate basic
  337. if l.ConflictingBlock.Header == nil {
  338. return errors.New("conflicting block missing header")
  339. }
  340. if l.TotalVotingPower <= 0 {
  341. return errors.New("negative or zero total voting power")
  342. }
  343. if l.CommonHeight <= 0 {
  344. return errors.New("negative or zero common height")
  345. }
  346. // check that common height isn't ahead of the height of the conflicting block. It
  347. // is possible that they are the same height if the light node witnesses either an
  348. // amnesia or a equivocation attack.
  349. if l.CommonHeight > l.ConflictingBlock.Height {
  350. return fmt.Errorf("common height is ahead of the conflicting block height (%d > %d)",
  351. l.CommonHeight, l.ConflictingBlock.Height)
  352. }
  353. if err := l.ConflictingBlock.ValidateBasic(l.ConflictingBlock.ChainID); err != nil {
  354. return fmt.Errorf("invalid conflicting light block: %w", err)
  355. }
  356. return nil
  357. }
  358. // ValidateABCI validates the ABCI component of the evidence by checking the
  359. // timestamp, byzantine validators and total voting power all match. ABCI
  360. // components are validated separately because they can be re generated if
  361. // invalid.
  362. func (l *LightClientAttackEvidence) ValidateABCI(
  363. commonVals *ValidatorSet,
  364. trustedHeader *SignedHeader,
  365. evidenceTime time.Time,
  366. ) error {
  367. if evTotal, valsTotal := l.TotalVotingPower, commonVals.TotalVotingPower(); evTotal != valsTotal {
  368. return fmt.Errorf("total voting power from the evidence and our validator set does not match (%d != %d)",
  369. evTotal, valsTotal)
  370. }
  371. if l.Timestamp != evidenceTime {
  372. return fmt.Errorf(
  373. "evidence has a different time to the block it is associated with (%v != %v)",
  374. l.Timestamp, evidenceTime)
  375. }
  376. // Find out what type of attack this was and thus extract the malicious
  377. // validators. Note, in the case of an Amnesia attack we don't have any
  378. // malicious validators.
  379. validators := l.GetByzantineValidators(commonVals, trustedHeader)
  380. // Ensure this matches the validators that are listed in the evidence. They
  381. // should be ordered based on power.
  382. if validators == nil && l.ByzantineValidators != nil {
  383. return fmt.Errorf(
  384. "expected nil validators from an amnesia light client attack but got %d",
  385. len(l.ByzantineValidators),
  386. )
  387. }
  388. if exp, got := len(validators), len(l.ByzantineValidators); exp != got {
  389. return fmt.Errorf("expected %d byzantine validators from evidence but got %d", exp, got)
  390. }
  391. for idx, val := range validators {
  392. if !bytes.Equal(l.ByzantineValidators[idx].Address, val.Address) {
  393. return fmt.Errorf(
  394. "evidence contained an unexpected byzantine validator address; expected: %v, got: %v",
  395. val.Address, l.ByzantineValidators[idx].Address,
  396. )
  397. }
  398. if l.ByzantineValidators[idx].VotingPower != val.VotingPower {
  399. return fmt.Errorf(
  400. "evidence contained unexpected byzantine validator power; expected %d, got %d",
  401. val.VotingPower, l.ByzantineValidators[idx].VotingPower,
  402. )
  403. }
  404. }
  405. return nil
  406. }
  407. // GenerateABCI populates the ABCI component of the evidence: the timestamp,
  408. // total voting power and byantine validators
  409. func (l *LightClientAttackEvidence) GenerateABCI(
  410. commonVals *ValidatorSet,
  411. trustedHeader *SignedHeader,
  412. evidenceTime time.Time,
  413. ) {
  414. l.Timestamp = evidenceTime
  415. l.TotalVotingPower = commonVals.TotalVotingPower()
  416. l.ByzantineValidators = l.GetByzantineValidators(commonVals, trustedHeader)
  417. }
  418. // ToProto encodes LightClientAttackEvidence to protobuf
  419. func (l *LightClientAttackEvidence) ToProto() (*tmproto.LightClientAttackEvidence, error) {
  420. conflictingBlock, err := l.ConflictingBlock.ToProto()
  421. if err != nil {
  422. return nil, err
  423. }
  424. byzVals := make([]*tmproto.Validator, len(l.ByzantineValidators))
  425. for idx, val := range l.ByzantineValidators {
  426. valpb, err := val.ToProto()
  427. if err != nil {
  428. return nil, err
  429. }
  430. byzVals[idx] = valpb
  431. }
  432. return &tmproto.LightClientAttackEvidence{
  433. ConflictingBlock: conflictingBlock,
  434. CommonHeight: l.CommonHeight,
  435. ByzantineValidators: byzVals,
  436. TotalVotingPower: l.TotalVotingPower,
  437. Timestamp: l.Timestamp,
  438. }, nil
  439. }
  440. // LightClientAttackEvidenceFromProto decodes protobuf
  441. func LightClientAttackEvidenceFromProto(lpb *tmproto.LightClientAttackEvidence) (*LightClientAttackEvidence, error) {
  442. if lpb == nil {
  443. return nil, errors.New("empty light client attack evidence")
  444. }
  445. conflictingBlock, err := LightBlockFromProto(lpb.ConflictingBlock)
  446. if err != nil {
  447. return nil, err
  448. }
  449. byzVals := make([]*Validator, len(lpb.ByzantineValidators))
  450. for idx, valpb := range lpb.ByzantineValidators {
  451. val, err := ValidatorFromProto(valpb)
  452. if err != nil {
  453. return nil, err
  454. }
  455. byzVals[idx] = val
  456. }
  457. l := &LightClientAttackEvidence{
  458. ConflictingBlock: conflictingBlock,
  459. CommonHeight: lpb.CommonHeight,
  460. ByzantineValidators: byzVals,
  461. TotalVotingPower: lpb.TotalVotingPower,
  462. Timestamp: lpb.Timestamp,
  463. }
  464. return l, l.ValidateBasic()
  465. }
  466. //------------------------------------------------------------------------------------------
  467. // EvidenceList is a list of Evidence. Evidences is not a word.
  468. type EvidenceList []Evidence
  469. // Hash returns the simple merkle root hash of the EvidenceList.
  470. func (evl EvidenceList) Hash() []byte {
  471. // These allocations are required because Evidence is not of type Bytes, and
  472. // golang slices can't be typed cast. This shouldn't be a performance problem since
  473. // the Evidence size is capped.
  474. evidenceBzs := make([][]byte, len(evl))
  475. for i := 0; i < len(evl); i++ {
  476. // TODO: We should change this to the hash. Using bytes contains some unexported data that
  477. // may cause different hashes
  478. evidenceBzs[i] = evl[i].Bytes()
  479. }
  480. return merkle.HashFromByteSlices(evidenceBzs)
  481. }
  482. func (evl EvidenceList) String() string {
  483. s := ""
  484. for _, e := range evl {
  485. s += fmt.Sprintf("%s\t\t", e)
  486. }
  487. return s
  488. }
  489. // Has returns true if the evidence is in the EvidenceList.
  490. func (evl EvidenceList) Has(evidence Evidence) bool {
  491. for _, ev := range evl {
  492. if bytes.Equal(evidence.Hash(), ev.Hash()) {
  493. return true
  494. }
  495. }
  496. return false
  497. }
  498. //------------------------------------------ PROTO --------------------------------------
  499. // EvidenceToProto is a generalized function for encoding evidence that conforms to the
  500. // evidence interface to protobuf
  501. func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error) {
  502. if evidence == nil {
  503. return nil, errors.New("nil evidence")
  504. }
  505. switch evi := evidence.(type) {
  506. case *DuplicateVoteEvidence:
  507. pbev := evi.ToProto()
  508. return &tmproto.Evidence{
  509. Sum: &tmproto.Evidence_DuplicateVoteEvidence{
  510. DuplicateVoteEvidence: pbev,
  511. },
  512. }, nil
  513. case *LightClientAttackEvidence:
  514. pbev, err := evi.ToProto()
  515. if err != nil {
  516. return nil, err
  517. }
  518. return &tmproto.Evidence{
  519. Sum: &tmproto.Evidence_LightClientAttackEvidence{
  520. LightClientAttackEvidence: pbev,
  521. },
  522. }, nil
  523. default:
  524. return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi)
  525. }
  526. }
  527. // EvidenceFromProto is a generalized function for decoding protobuf into the
  528. // evidence interface
  529. func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error) {
  530. if evidence == nil {
  531. return nil, errors.New("nil evidence")
  532. }
  533. switch evi := evidence.Sum.(type) {
  534. case *tmproto.Evidence_DuplicateVoteEvidence:
  535. return DuplicateVoteEvidenceFromProto(evi.DuplicateVoteEvidence)
  536. case *tmproto.Evidence_LightClientAttackEvidence:
  537. return LightClientAttackEvidenceFromProto(evi.LightClientAttackEvidence)
  538. default:
  539. return nil, errors.New("evidence is not recognized")
  540. }
  541. }
  542. func init() {
  543. tmjson.RegisterType(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence")
  544. tmjson.RegisterType(&LightClientAttackEvidence{}, "tendermint/LightClientAttackEvidence")
  545. }
  546. //-------------------------------------------- ERRORS --------------------------------------
  547. // ErrInvalidEvidence wraps a piece of evidence and the error denoting how or why it is invalid.
  548. type ErrInvalidEvidence struct {
  549. Evidence Evidence
  550. Reason error
  551. }
  552. // NewErrInvalidEvidence returns a new EvidenceInvalid with the given err.
  553. func NewErrInvalidEvidence(ev Evidence, err error) *ErrInvalidEvidence {
  554. return &ErrInvalidEvidence{ev, err}
  555. }
  556. // Error returns a string representation of the error.
  557. func (err *ErrInvalidEvidence) Error() string {
  558. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.Reason, err.Evidence)
  559. }
  560. // ErrEvidenceOverflow is for when there the amount of evidence exceeds the max bytes.
  561. type ErrEvidenceOverflow struct {
  562. Max int64
  563. Got int64
  564. }
  565. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  566. func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow {
  567. return &ErrEvidenceOverflow{max, got}
  568. }
  569. // Error returns a string representation of the error.
  570. func (err *ErrEvidenceOverflow) Error() string {
  571. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.Max, err.Got)
  572. }
  573. //-------------------------------------------- MOCKING --------------------------------------
  574. // unstable - use only for testing
  575. // assumes the round to be 0 and the validator index to be 0
  576. func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence {
  577. val := NewMockPV()
  578. return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID)
  579. }
  580. // assumes voting power to be 10 and validator to be the only one in the set
  581. func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time,
  582. pv PrivValidator, chainID string) *DuplicateVoteEvidence {
  583. pubKey, _ := pv.GetPubKey(context.Background())
  584. val := NewValidator(pubKey, 10)
  585. voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  586. vA := voteA.ToProto()
  587. _ = pv.SignVote(context.Background(), chainID, vA)
  588. voteA.Signature = vA.Signature
  589. voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  590. vB := voteB.ToProto()
  591. _ = pv.SignVote(context.Background(), chainID, vB)
  592. voteB.Signature = vB.Signature
  593. return NewDuplicateVoteEvidence(voteA, voteB, time, NewValidatorSet([]*Validator{val}))
  594. }
  595. func makeMockVote(height int64, round, index int32, addr Address,
  596. blockID BlockID, time time.Time) *Vote {
  597. return &Vote{
  598. Type: tmproto.SignedMsgType(2),
  599. Height: height,
  600. Round: round,
  601. BlockID: blockID,
  602. Timestamp: time,
  603. ValidatorAddress: addr,
  604. ValidatorIndex: index,
  605. }
  606. }
  607. func randBlockID() BlockID {
  608. return BlockID{
  609. Hash: tmrand.Bytes(tmhash.Size),
  610. PartSetHeader: PartSetHeader{
  611. Total: 1,
  612. Hash: tmrand.Bytes(tmhash.Size),
  613. },
  614. }
  615. }