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.

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