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.

584 lines
19 KiB

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