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.

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