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.

600 lines
20 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. // ToProto encodes DuplicateVoteEvidence to protobuf
  125. func (dve *DuplicateVoteEvidence) ToProto() *tmproto.DuplicateVoteEvidence {
  126. voteB := dve.VoteB.ToProto()
  127. voteA := dve.VoteA.ToProto()
  128. tp := tmproto.DuplicateVoteEvidence{
  129. VoteA: voteA,
  130. VoteB: voteB,
  131. TotalVotingPower: dve.TotalVotingPower,
  132. ValidatorPower: dve.ValidatorPower,
  133. Timestamp: dve.Timestamp,
  134. }
  135. return &tp
  136. }
  137. // DuplicateVoteEvidenceFromProto decodes protobuf into DuplicateVoteEvidence
  138. func DuplicateVoteEvidenceFromProto(pb *tmproto.DuplicateVoteEvidence) (*DuplicateVoteEvidence, error) {
  139. if pb == nil {
  140. return nil, errors.New("nil duplicate vote evidence")
  141. }
  142. vA, err := VoteFromProto(pb.VoteA)
  143. if err != nil {
  144. return nil, err
  145. }
  146. vB, err := VoteFromProto(pb.VoteB)
  147. if err != nil {
  148. return nil, err
  149. }
  150. dve := &DuplicateVoteEvidence{
  151. VoteA: vA,
  152. VoteB: vB,
  153. TotalVotingPower: pb.TotalVotingPower,
  154. ValidatorPower: pb.ValidatorPower,
  155. Timestamp: pb.Timestamp,
  156. }
  157. return dve, dve.ValidateBasic()
  158. }
  159. //------------------------------------ LIGHT EVIDENCE --------------------------------------
  160. // LightClientAttackEvidence is a generalized evidence that captures all forms of known attacks on
  161. // a light client such that a full node can verify, propose and commit the evidence on-chain for
  162. // punishment of the malicious validators. There are three forms of attacks: Lunatic, Equivocation
  163. // and Amnesia. These attacks are exhaustive. You can find a more detailed overview of this at
  164. // tendermint/docs/architecture/adr-047-handling-evidence-from-light-client.md
  165. type LightClientAttackEvidence struct {
  166. ConflictingBlock *LightBlock
  167. CommonHeight int64
  168. // abci specific information
  169. ByzantineValidators []*Validator // validators in the validator set that misbehaved in creating the conflicting block
  170. TotalVotingPower int64 // total voting power of the validator set at the common height
  171. Timestamp time.Time // timestamp of the block at the common height
  172. }
  173. var _ Evidence = &LightClientAttackEvidence{}
  174. // ABCI forms an array of abci evidence for each byzantine validator
  175. func (l *LightClientAttackEvidence) ABCI() []abci.Evidence {
  176. abciEv := make([]abci.Evidence, len(l.ByzantineValidators))
  177. for idx, val := range l.ByzantineValidators {
  178. abciEv[idx] = abci.Evidence{
  179. Type: abci.EvidenceType_LIGHT_CLIENT_ATTACK,
  180. Validator: TM2PB.Validator(val),
  181. Height: l.Height(),
  182. Time: l.Timestamp,
  183. TotalVotingPower: l.TotalVotingPower,
  184. }
  185. }
  186. return abciEv
  187. }
  188. // Bytes returns the proto-encoded evidence as a byte array
  189. func (l *LightClientAttackEvidence) Bytes() []byte {
  190. pbe, err := l.ToProto()
  191. if err != nil {
  192. panic(err)
  193. }
  194. bz, err := pbe.Marshal()
  195. if err != nil {
  196. panic(err)
  197. }
  198. return bz
  199. }
  200. // GetByzantineValidators finds out what style of attack LightClientAttackEvidence was and then works out who
  201. // the malicious validators were and returns them. This is used both for forming the ByzantineValidators
  202. // field and for validating that it is correct. Validators are ordered based on validator power
  203. func (l *LightClientAttackEvidence) GetByzantineValidators(commonVals *ValidatorSet,
  204. trusted *SignedHeader) []*Validator {
  205. var validators []*Validator
  206. // First check if the header is invalid. This means that it is a lunatic attack and therefore we take the
  207. // validators who are in the commonVals and voted for the lunatic header
  208. if l.ConflictingHeaderIsInvalid(trusted.Header) {
  209. for _, commitSig := range l.ConflictingBlock.Commit.Signatures {
  210. if !commitSig.ForBlock() {
  211. continue
  212. }
  213. _, val := commonVals.GetByAddress(commitSig.ValidatorAddress)
  214. if val == nil {
  215. // validator wasn't in the common validator set
  216. continue
  217. }
  218. validators = append(validators, val)
  219. }
  220. sort.Sort(ValidatorsByVotingPower(validators))
  221. return validators
  222. } else if trusted.Commit.Round == l.ConflictingBlock.Commit.Round {
  223. // This is an equivocation attack as both commits are in the same round. We then find the validators
  224. // from the conflicting light block validator set that voted in both headers.
  225. // Validator hashes are the same therefore the indexing order of validators are the same and thus we
  226. // only need a single loop to find the validators that voted twice.
  227. for i := 0; i < len(l.ConflictingBlock.Commit.Signatures); i++ {
  228. sigA := l.ConflictingBlock.Commit.Signatures[i]
  229. if sigA.Absent() {
  230. continue
  231. }
  232. sigB := trusted.Commit.Signatures[i]
  233. if sigB.Absent() {
  234. continue
  235. }
  236. _, val := l.ConflictingBlock.ValidatorSet.GetByAddress(sigA.ValidatorAddress)
  237. validators = append(validators, val)
  238. }
  239. sort.Sort(ValidatorsByVotingPower(validators))
  240. return validators
  241. }
  242. // if the rounds are different then this is an amnesia attack. Unfortunately, given the nature of the attack,
  243. // we aren't able yet to deduce which are malicious validators and which are not hence we return an
  244. // empty validator set.
  245. return validators
  246. }
  247. // ConflictingHeaderIsInvalid takes a trusted header and matches it againt a conflicting header
  248. // to determine whether the conflicting header was the product of a valid state transition
  249. // or not. If it is then all the deterministic fields of the header should be the same.
  250. // If not, it is an invalid header and constitutes a lunatic attack.
  251. func (l *LightClientAttackEvidence) ConflictingHeaderIsInvalid(trustedHeader *Header) bool {
  252. return !bytes.Equal(trustedHeader.ValidatorsHash, l.ConflictingBlock.ValidatorsHash) ||
  253. !bytes.Equal(trustedHeader.NextValidatorsHash, l.ConflictingBlock.NextValidatorsHash) ||
  254. !bytes.Equal(trustedHeader.ConsensusHash, l.ConflictingBlock.ConsensusHash) ||
  255. !bytes.Equal(trustedHeader.AppHash, l.ConflictingBlock.AppHash) ||
  256. !bytes.Equal(trustedHeader.LastResultsHash, l.ConflictingBlock.LastResultsHash)
  257. }
  258. // Hash returns the hash of the header and the commonHeight. This is designed to cause hash collisions
  259. // with evidence that have the same conflicting header and common height but different permutations
  260. // of validator commit signatures. The reason for this is that we don't want to allow several
  261. // permutations of the same evidence to be committed on chain. Ideally we commit the header with the
  262. // most commit signatures (captures the most byzantine validators) but anything greater than 1/3 is
  263. // sufficient.
  264. // TODO: We should change the hash to include the commit, header, total voting power, byzantine
  265. // validators and timestamp
  266. func (l *LightClientAttackEvidence) Hash() []byte {
  267. buf := make([]byte, binary.MaxVarintLen64)
  268. n := binary.PutVarint(buf, l.CommonHeight)
  269. bz := make([]byte, tmhash.Size+n)
  270. copy(bz[:tmhash.Size-1], l.ConflictingBlock.Hash().Bytes())
  271. copy(bz[tmhash.Size:], buf)
  272. return tmhash.Sum(bz)
  273. }
  274. // Height returns the last height at which the primary provider and witness provider had the same header.
  275. // We use this as the height of the infraction rather than the actual conflicting header because we know
  276. // that the malicious validators were bonded at this height which is important for evidence expiry
  277. func (l *LightClientAttackEvidence) Height() int64 {
  278. return l.CommonHeight
  279. }
  280. // String returns a string representation of LightClientAttackEvidence
  281. func (l *LightClientAttackEvidence) String() string {
  282. return fmt.Sprintf(`LightClientAttackEvidence{
  283. ConflictingBlock: %v,
  284. CommonHeight: %d,
  285. ByzatineValidators: %v,
  286. TotalVotingPower: %d,
  287. Timestamp: %v}#%X`,
  288. l.ConflictingBlock.String(), l.CommonHeight, l.ByzantineValidators,
  289. l.TotalVotingPower, l.Timestamp, l.Hash())
  290. }
  291. // Time returns the time of the common block where the infraction leveraged off.
  292. func (l *LightClientAttackEvidence) Time() time.Time {
  293. return l.Timestamp
  294. }
  295. // ValidateBasic performs basic validation such that the evidence is consistent and can now be used for verification.
  296. func (l *LightClientAttackEvidence) ValidateBasic() error {
  297. if l.ConflictingBlock == nil {
  298. return errors.New("conflicting block is nil")
  299. }
  300. // this check needs to be done before we can run validate basic
  301. if l.ConflictingBlock.Header == nil {
  302. return errors.New("conflicting block missing header")
  303. }
  304. if l.TotalVotingPower <= 0 {
  305. return errors.New("negative or zero total voting power")
  306. }
  307. if l.CommonHeight <= 0 {
  308. return errors.New("negative or zero common height")
  309. }
  310. // check that common height isn't ahead of the height of the conflicting block. It
  311. // is possible that they are the same height if the light node witnesses either an
  312. // amnesia or a equivocation attack.
  313. if l.CommonHeight > l.ConflictingBlock.Height {
  314. return fmt.Errorf("common height is ahead of the conflicting block height (%d > %d)",
  315. l.CommonHeight, l.ConflictingBlock.Height)
  316. }
  317. if err := l.ConflictingBlock.ValidateBasic(l.ConflictingBlock.ChainID); err != nil {
  318. return fmt.Errorf("invalid conflicting light block: %w", err)
  319. }
  320. return nil
  321. }
  322. // ToProto encodes LightClientAttackEvidence to protobuf
  323. func (l *LightClientAttackEvidence) ToProto() (*tmproto.LightClientAttackEvidence, error) {
  324. conflictingBlock, err := l.ConflictingBlock.ToProto()
  325. if err != nil {
  326. return nil, err
  327. }
  328. byzVals := make([]*tmproto.Validator, len(l.ByzantineValidators))
  329. for idx, val := range l.ByzantineValidators {
  330. valpb, err := val.ToProto()
  331. if err != nil {
  332. return nil, err
  333. }
  334. byzVals[idx] = valpb
  335. }
  336. return &tmproto.LightClientAttackEvidence{
  337. ConflictingBlock: conflictingBlock,
  338. CommonHeight: l.CommonHeight,
  339. ByzantineValidators: byzVals,
  340. TotalVotingPower: l.TotalVotingPower,
  341. Timestamp: l.Timestamp,
  342. }, nil
  343. }
  344. // LightClientAttackEvidenceFromProto decodes protobuf
  345. func LightClientAttackEvidenceFromProto(lpb *tmproto.LightClientAttackEvidence) (*LightClientAttackEvidence, error) {
  346. if lpb == nil {
  347. return nil, errors.New("empty light client attack evidence")
  348. }
  349. conflictingBlock, err := LightBlockFromProto(lpb.ConflictingBlock)
  350. if err != nil {
  351. return nil, err
  352. }
  353. byzVals := make([]*Validator, len(lpb.ByzantineValidators))
  354. for idx, valpb := range lpb.ByzantineValidators {
  355. val, err := ValidatorFromProto(valpb)
  356. if err != nil {
  357. return nil, err
  358. }
  359. byzVals[idx] = val
  360. }
  361. l := &LightClientAttackEvidence{
  362. ConflictingBlock: conflictingBlock,
  363. CommonHeight: lpb.CommonHeight,
  364. ByzantineValidators: byzVals,
  365. TotalVotingPower: lpb.TotalVotingPower,
  366. Timestamp: lpb.Timestamp,
  367. }
  368. return l, l.ValidateBasic()
  369. }
  370. //------------------------------------------------------------------------------------------
  371. // EvidenceList is a list of Evidence. Evidences is not a word.
  372. type EvidenceList []Evidence
  373. // Hash returns the simple merkle root hash of the EvidenceList.
  374. func (evl EvidenceList) Hash() []byte {
  375. // These allocations are required because Evidence is not of type Bytes, and
  376. // golang slices can't be typed cast. This shouldn't be a performance problem since
  377. // the Evidence size is capped.
  378. evidenceBzs := make([][]byte, len(evl))
  379. for i := 0; i < len(evl); i++ {
  380. // TODO: We should change this to the hash. Using bytes contains some unexported data that
  381. // may cause different hashes
  382. evidenceBzs[i] = evl[i].Bytes()
  383. }
  384. return merkle.HashFromByteSlices(evidenceBzs)
  385. }
  386. func (evl EvidenceList) String() string {
  387. s := ""
  388. for _, e := range evl {
  389. s += fmt.Sprintf("%s\t\t", e)
  390. }
  391. return s
  392. }
  393. // Has returns true if the evidence is in the EvidenceList.
  394. func (evl EvidenceList) Has(evidence Evidence) bool {
  395. for _, ev := range evl {
  396. if bytes.Equal(evidence.Hash(), ev.Hash()) {
  397. return true
  398. }
  399. }
  400. return false
  401. }
  402. //------------------------------------------ PROTO --------------------------------------
  403. // EvidenceToProto is a generalized function for encoding evidence that conforms to the
  404. // evidence interface to protobuf
  405. func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error) {
  406. if evidence == nil {
  407. return nil, errors.New("nil evidence")
  408. }
  409. switch evi := evidence.(type) {
  410. case *DuplicateVoteEvidence:
  411. pbev := evi.ToProto()
  412. return &tmproto.Evidence{
  413. Sum: &tmproto.Evidence_DuplicateVoteEvidence{
  414. DuplicateVoteEvidence: pbev,
  415. },
  416. }, nil
  417. case *LightClientAttackEvidence:
  418. pbev, err := evi.ToProto()
  419. if err != nil {
  420. return nil, err
  421. }
  422. return &tmproto.Evidence{
  423. Sum: &tmproto.Evidence_LightClientAttackEvidence{
  424. LightClientAttackEvidence: pbev,
  425. },
  426. }, nil
  427. default:
  428. return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi)
  429. }
  430. }
  431. // EvidenceFromProto is a generalized function for decoding protobuf into the
  432. // evidence interface
  433. func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error) {
  434. if evidence == nil {
  435. return nil, errors.New("nil evidence")
  436. }
  437. switch evi := evidence.Sum.(type) {
  438. case *tmproto.Evidence_DuplicateVoteEvidence:
  439. return DuplicateVoteEvidenceFromProto(evi.DuplicateVoteEvidence)
  440. case *tmproto.Evidence_LightClientAttackEvidence:
  441. return LightClientAttackEvidenceFromProto(evi.LightClientAttackEvidence)
  442. default:
  443. return nil, errors.New("evidence is not recognized")
  444. }
  445. }
  446. func init() {
  447. tmjson.RegisterType(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence")
  448. tmjson.RegisterType(&LightClientAttackEvidence{}, "tendermint/LightClientAttackEvidence")
  449. }
  450. //-------------------------------------------- ERRORS --------------------------------------
  451. // ErrInvalidEvidence wraps a piece of evidence and the error denoting how or why it is invalid.
  452. type ErrInvalidEvidence struct {
  453. Evidence Evidence
  454. Reason error
  455. }
  456. // NewErrInvalidEvidence returns a new EvidenceInvalid with the given err.
  457. func NewErrInvalidEvidence(ev Evidence, err error) *ErrInvalidEvidence {
  458. return &ErrInvalidEvidence{ev, err}
  459. }
  460. // Error returns a string representation of the error.
  461. func (err *ErrInvalidEvidence) Error() string {
  462. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.Reason, err.Evidence)
  463. }
  464. // ErrEvidenceOverflow is for when there the amount of evidence exceeds the max bytes.
  465. type ErrEvidenceOverflow struct {
  466. Max int64
  467. Got int64
  468. }
  469. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  470. func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow {
  471. return &ErrEvidenceOverflow{max, got}
  472. }
  473. // Error returns a string representation of the error.
  474. func (err *ErrEvidenceOverflow) Error() string {
  475. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.Max, err.Got)
  476. }
  477. //-------------------------------------------- MOCKING --------------------------------------
  478. // unstable - use only for testing
  479. // assumes the round to be 0 and the validator index to be 0
  480. func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence {
  481. val := NewMockPV()
  482. return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID)
  483. }
  484. // assumes voting power to be 10 and validator to be the only one in the set
  485. func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time,
  486. pv PrivValidator, chainID string) *DuplicateVoteEvidence {
  487. pubKey, _ := pv.GetPubKey(context.Background())
  488. val := NewValidator(pubKey, 10)
  489. voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  490. vA := voteA.ToProto()
  491. _ = pv.SignVote(context.Background(), chainID, vA)
  492. voteA.Signature = vA.Signature
  493. voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  494. vB := voteB.ToProto()
  495. _ = pv.SignVote(context.Background(), chainID, vB)
  496. voteB.Signature = vB.Signature
  497. return NewDuplicateVoteEvidence(voteA, voteB, time, NewValidatorSet([]*Validator{val}))
  498. }
  499. func makeMockVote(height int64, round, index int32, addr Address,
  500. blockID BlockID, time time.Time) *Vote {
  501. return &Vote{
  502. Type: tmproto.SignedMsgType(2),
  503. Height: height,
  504. Round: round,
  505. BlockID: blockID,
  506. Timestamp: time,
  507. ValidatorAddress: addr,
  508. ValidatorIndex: index,
  509. }
  510. }
  511. func randBlockID() BlockID {
  512. return BlockID{
  513. Hash: tmrand.Bytes(tmhash.Size),
  514. PartSetHeader: PartSetHeader{
  515. Total: 1,
  516. Hash: tmrand.Bytes(tmhash.Size),
  517. },
  518. }
  519. }