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.

760 lines
25 KiB

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