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.

585 lines
19 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 sufficient.
  263. func (l *LightClientAttackEvidence) Hash() []byte {
  264. buf := make([]byte, binary.MaxVarintLen64)
  265. n := binary.PutVarint(buf, l.CommonHeight)
  266. bz := make([]byte, tmhash.Size+n)
  267. copy(bz[:tmhash.Size-1], l.ConflictingBlock.Hash().Bytes())
  268. copy(bz[tmhash.Size:], buf)
  269. return tmhash.Sum(bz)
  270. }
  271. // Height returns the last height at which the primary provider and witness provider had the same header.
  272. // We use this as the height of the infraction rather than the actual conflicting header because we know
  273. // that the malicious validators were bonded at this height which is important for evidence expiry
  274. func (l *LightClientAttackEvidence) Height() int64 {
  275. return l.CommonHeight
  276. }
  277. // String returns a string representation of LightClientAttackEvidence
  278. func (l *LightClientAttackEvidence) String() string {
  279. return fmt.Sprintf("LightClientAttackEvidence{ConflictingBlock: %v, CommonHeight: %d}",
  280. l.ConflictingBlock.String(), l.CommonHeight)
  281. }
  282. // Time returns the time of the common block where the infraction leveraged off.
  283. func (l *LightClientAttackEvidence) Time() time.Time {
  284. return l.Timestamp
  285. }
  286. // ValidateBasic performs basic validation such that the evidence is consistent and can now be used for verification.
  287. func (l *LightClientAttackEvidence) ValidateBasic() error {
  288. if l.ConflictingBlock == nil {
  289. return errors.New("conflicting block is nil")
  290. }
  291. // this check needs to be done before we can run validate basic
  292. if l.ConflictingBlock.Header == nil {
  293. return errors.New("conflicting block missing header")
  294. }
  295. if err := l.ConflictingBlock.ValidateBasic(l.ConflictingBlock.ChainID); err != nil {
  296. return fmt.Errorf("invalid conflicting light block: %w", err)
  297. }
  298. if l.CommonHeight <= 0 {
  299. return errors.New("negative or zero common height")
  300. }
  301. // check that common height isn't ahead of the height of the conflicting block. It
  302. // is possible that they are the same height if the light node witnesses either an
  303. // amnesia or a equivocation attack.
  304. if l.CommonHeight > l.ConflictingBlock.Height {
  305. return fmt.Errorf("common height is ahead of the conflicting block height (%d > %d)",
  306. l.CommonHeight, l.ConflictingBlock.Height)
  307. }
  308. return nil
  309. }
  310. // ToProto encodes LightClientAttackEvidence to protobuf
  311. func (l *LightClientAttackEvidence) ToProto() (*tmproto.LightClientAttackEvidence, error) {
  312. conflictingBlock, err := l.ConflictingBlock.ToProto()
  313. if err != nil {
  314. return nil, err
  315. }
  316. byzVals := make([]*tmproto.Validator, len(l.ByzantineValidators))
  317. for idx, val := range l.ByzantineValidators {
  318. valpb, err := val.ToProto()
  319. if err != nil {
  320. return nil, err
  321. }
  322. byzVals[idx] = valpb
  323. }
  324. return &tmproto.LightClientAttackEvidence{
  325. ConflictingBlock: conflictingBlock,
  326. CommonHeight: l.CommonHeight,
  327. ByzantineValidators: byzVals,
  328. TotalVotingPower: l.TotalVotingPower,
  329. Timestamp: l.Timestamp,
  330. }, nil
  331. }
  332. // LightClientAttackEvidenceFromProto decodes protobuf
  333. func LightClientAttackEvidenceFromProto(lpb *tmproto.LightClientAttackEvidence) (*LightClientAttackEvidence, error) {
  334. if lpb == nil {
  335. return nil, errors.New("empty light client attack evidence")
  336. }
  337. conflictingBlock, err := LightBlockFromProto(lpb.ConflictingBlock)
  338. if err != nil {
  339. return nil, err
  340. }
  341. byzVals := make([]*Validator, len(lpb.ByzantineValidators))
  342. for idx, valpb := range lpb.ByzantineValidators {
  343. val, err := ValidatorFromProto(valpb)
  344. if err != nil {
  345. return nil, err
  346. }
  347. byzVals[idx] = val
  348. }
  349. l := &LightClientAttackEvidence{
  350. ConflictingBlock: conflictingBlock,
  351. CommonHeight: lpb.CommonHeight,
  352. ByzantineValidators: byzVals,
  353. TotalVotingPower: lpb.TotalVotingPower,
  354. Timestamp: lpb.Timestamp,
  355. }
  356. return l, l.ValidateBasic()
  357. }
  358. //------------------------------------------------------------------------------------------
  359. // EvidenceList is a list of Evidence. Evidences is not a word.
  360. type EvidenceList []Evidence
  361. // Hash returns the simple merkle root hash of the EvidenceList.
  362. func (evl EvidenceList) Hash() []byte {
  363. // These allocations are required because Evidence is not of type Bytes, and
  364. // golang slices can't be typed cast. This shouldn't be a performance problem since
  365. // the Evidence size is capped.
  366. evidenceBzs := make([][]byte, len(evl))
  367. for i := 0; i < len(evl); i++ {
  368. evidenceBzs[i] = evl[i].Bytes()
  369. }
  370. return merkle.HashFromByteSlices(evidenceBzs)
  371. }
  372. func (evl EvidenceList) String() string {
  373. s := ""
  374. for _, e := range evl {
  375. s += fmt.Sprintf("%s\t\t", e)
  376. }
  377. return s
  378. }
  379. // Has returns true if the evidence is in the EvidenceList.
  380. func (evl EvidenceList) Has(evidence Evidence) bool {
  381. for _, ev := range evl {
  382. if bytes.Equal(evidence.Hash(), ev.Hash()) {
  383. return true
  384. }
  385. }
  386. return false
  387. }
  388. //------------------------------------------ PROTO --------------------------------------
  389. // EvidenceToProto is a generalized function for encoding evidence that conforms to the
  390. // evidence interface to protobuf
  391. func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error) {
  392. if evidence == nil {
  393. return nil, errors.New("nil evidence")
  394. }
  395. switch evi := evidence.(type) {
  396. case *DuplicateVoteEvidence:
  397. pbev := evi.ToProto()
  398. return &tmproto.Evidence{
  399. Sum: &tmproto.Evidence_DuplicateVoteEvidence{
  400. DuplicateVoteEvidence: pbev,
  401. },
  402. }, nil
  403. case *LightClientAttackEvidence:
  404. pbev, err := evi.ToProto()
  405. if err != nil {
  406. return nil, err
  407. }
  408. return &tmproto.Evidence{
  409. Sum: &tmproto.Evidence_LightClientAttackEvidence{
  410. LightClientAttackEvidence: pbev,
  411. },
  412. }, nil
  413. default:
  414. return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi)
  415. }
  416. }
  417. // EvidenceFromProto is a generalized function for decoding protobuf into the
  418. // evidence interface
  419. func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error) {
  420. if evidence == nil {
  421. return nil, errors.New("nil evidence")
  422. }
  423. switch evi := evidence.Sum.(type) {
  424. case *tmproto.Evidence_DuplicateVoteEvidence:
  425. return DuplicateVoteEvidenceFromProto(evi.DuplicateVoteEvidence)
  426. case *tmproto.Evidence_LightClientAttackEvidence:
  427. return LightClientAttackEvidenceFromProto(evi.LightClientAttackEvidence)
  428. default:
  429. return nil, errors.New("evidence is not recognized")
  430. }
  431. }
  432. func init() {
  433. tmjson.RegisterType(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence")
  434. tmjson.RegisterType(&LightClientAttackEvidence{}, "tendermint/LightClientAttackEvidence")
  435. }
  436. //-------------------------------------------- ERRORS --------------------------------------
  437. // ErrInvalidEvidence wraps a piece of evidence and the error denoting how or why it is invalid.
  438. type ErrInvalidEvidence struct {
  439. Evidence Evidence
  440. Reason error
  441. }
  442. // NewErrInvalidEvidence returns a new EvidenceInvalid with the given err.
  443. func NewErrInvalidEvidence(ev Evidence, err error) *ErrInvalidEvidence {
  444. return &ErrInvalidEvidence{ev, err}
  445. }
  446. // Error returns a string representation of the error.
  447. func (err *ErrInvalidEvidence) Error() string {
  448. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.Reason, err.Evidence)
  449. }
  450. // ErrEvidenceOverflow is for when there the amount of evidence exceeds the max bytes.
  451. type ErrEvidenceOverflow struct {
  452. Max int64
  453. Got int64
  454. }
  455. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  456. func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow {
  457. return &ErrEvidenceOverflow{max, got}
  458. }
  459. // Error returns a string representation of the error.
  460. func (err *ErrEvidenceOverflow) Error() string {
  461. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.Max, err.Got)
  462. }
  463. //-------------------------------------------- MOCKING --------------------------------------
  464. // unstable - use only for testing
  465. // assumes the round to be 0 and the validator index to be 0
  466. func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence {
  467. val := NewMockPV()
  468. return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID)
  469. }
  470. // assumes voting power to be 10 and validator to be the only one in the set
  471. func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time,
  472. pv PrivValidator, chainID string) *DuplicateVoteEvidence {
  473. pubKey, _ := pv.GetPubKey(context.Background())
  474. val := NewValidator(pubKey, 10)
  475. voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  476. vA := voteA.ToProto()
  477. _ = pv.SignVote(context.Background(), chainID, vA)
  478. voteA.Signature = vA.Signature
  479. voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  480. vB := voteB.ToProto()
  481. _ = pv.SignVote(context.Background(), chainID, vB)
  482. voteB.Signature = vB.Signature
  483. return NewDuplicateVoteEvidence(voteA, voteB, time, NewValidatorSet([]*Validator{val}))
  484. }
  485. func makeMockVote(height int64, round, index int32, addr Address,
  486. blockID BlockID, time time.Time) *Vote {
  487. return &Vote{
  488. Type: tmproto.SignedMsgType(2),
  489. Height: height,
  490. Round: round,
  491. BlockID: blockID,
  492. Timestamp: time,
  493. ValidatorAddress: addr,
  494. ValidatorIndex: index,
  495. }
  496. }
  497. func randBlockID() BlockID {
  498. return BlockID{
  499. Hash: tmrand.Bytes(tmhash.Size),
  500. PartSetHeader: PartSetHeader{
  501. Total: 1,
  502. Hash: tmrand.Bytes(tmhash.Size),
  503. },
  504. }
  505. }