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.

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