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.

429 lines
13 KiB

  1. package types
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/tendermint/tendermint/crypto/merkle"
  10. "github.com/tendermint/tendermint/crypto/tmhash"
  11. tmjson "github.com/tendermint/tendermint/libs/json"
  12. tmrand "github.com/tendermint/tendermint/libs/rand"
  13. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  14. )
  15. // Evidence represents any provable malicious activity by a validator.
  16. // Verification logic for each evidence is part of the evidence module.
  17. type Evidence interface {
  18. Height() int64 // height of the infraction
  19. Bytes() []byte // bytes which comprise the evidence
  20. Hash() []byte // hash of the evidence
  21. ValidateBasic() error // basic consistency check
  22. String() string // string format of the evidence
  23. }
  24. const (
  25. // MaxEvidenceBytes is a maximum size of any evidence (including amino overhead).
  26. MaxEvidenceBytes int64 = 444
  27. )
  28. //--------------------------------------------------------------------------------------
  29. // DuplicateVoteEvidence contains evidence a validator signed two conflicting
  30. // votes.
  31. type DuplicateVoteEvidence struct {
  32. VoteA *Vote `json:"vote_a"`
  33. VoteB *Vote `json:"vote_b"`
  34. }
  35. var _ Evidence = &DuplicateVoteEvidence{}
  36. // NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given
  37. // two conflicting votes. If one of the votes is nil, evidence returned is nil as well
  38. func NewDuplicateVoteEvidence(vote1, vote2 *Vote) *DuplicateVoteEvidence {
  39. var voteA, voteB *Vote
  40. if vote1 == nil || vote2 == nil {
  41. return nil
  42. }
  43. if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 {
  44. voteA = vote1
  45. voteB = vote2
  46. } else {
  47. voteA = vote2
  48. voteB = vote1
  49. }
  50. return &DuplicateVoteEvidence{
  51. VoteA: voteA,
  52. VoteB: voteB,
  53. }
  54. }
  55. // String returns a string representation of the evidence.
  56. func (dve *DuplicateVoteEvidence) String() string {
  57. return fmt.Sprintf("DuplicateVoteEvidence{VoteA: %v, VoteB: %v}", dve.VoteA, dve.VoteB)
  58. }
  59. // Height returns the height this evidence refers to.
  60. func (dve *DuplicateVoteEvidence) Height() int64 {
  61. return dve.VoteA.Height
  62. }
  63. // Bytes returns the proto-encoded evidence as a byte array.
  64. func (dve *DuplicateVoteEvidence) Bytes() []byte {
  65. pbe := dve.ToProto()
  66. bz, err := pbe.Marshal()
  67. if err != nil {
  68. panic(err)
  69. }
  70. return bz
  71. }
  72. // Hash returns the hash of the evidence.
  73. func (dve *DuplicateVoteEvidence) Hash() []byte {
  74. return tmhash.Sum(dve.Bytes())
  75. }
  76. // ValidateBasic performs basic validation.
  77. func (dve *DuplicateVoteEvidence) ValidateBasic() error {
  78. if dve == nil {
  79. return errors.New("empty duplicate vote evidence")
  80. }
  81. if dve.VoteA == nil || dve.VoteB == nil {
  82. return fmt.Errorf("one or both of the votes are empty %v, %v", dve.VoteA, dve.VoteB)
  83. }
  84. if err := dve.VoteA.ValidateBasic(); err != nil {
  85. return fmt.Errorf("invalid VoteA: %w", err)
  86. }
  87. if err := dve.VoteB.ValidateBasic(); err != nil {
  88. return fmt.Errorf("invalid VoteB: %w", err)
  89. }
  90. // Enforce Votes are lexicographically sorted on blockID
  91. if strings.Compare(dve.VoteA.BlockID.Key(), dve.VoteB.BlockID.Key()) >= 0 {
  92. return errors.New("duplicate votes in invalid order")
  93. }
  94. return nil
  95. }
  96. // ToProto encodes DuplicateVoteEvidence to protobuf
  97. func (dve *DuplicateVoteEvidence) ToProto() *tmproto.DuplicateVoteEvidence {
  98. voteB := dve.VoteB.ToProto()
  99. voteA := dve.VoteA.ToProto()
  100. tp := tmproto.DuplicateVoteEvidence{
  101. VoteA: voteA,
  102. VoteB: voteB,
  103. }
  104. return &tp
  105. }
  106. // DuplicateVoteEvidenceFromProto decodes protobuf into DuplicateVoteEvidence
  107. func DuplicateVoteEvidenceFromProto(pb *tmproto.DuplicateVoteEvidence) (*DuplicateVoteEvidence, error) {
  108. if pb == nil {
  109. return nil, errors.New("nil duplicate vote evidence")
  110. }
  111. vA, err := VoteFromProto(pb.VoteA)
  112. if err != nil {
  113. return nil, err
  114. }
  115. vB, err := VoteFromProto(pb.VoteB)
  116. if err != nil {
  117. return nil, err
  118. }
  119. dve := NewDuplicateVoteEvidence(vA, vB)
  120. return dve, dve.ValidateBasic()
  121. }
  122. //------------------------------------ LIGHT EVIDENCE --------------------------------------
  123. // LightClientAttackEvidence is a generalized evidence that captures all forms of known attacks on
  124. // a light client such that a full node can verify, propose and commit the evidence on-chain for
  125. // punishment of the malicious validators. There are three forms of attacks: Lunatic, Equivocation
  126. // and Amnesia. These attacks are exhaustive. You can find a more detailed overview of this at
  127. // tendermint/docs/architecture/adr-047-handling-evidence-from-light-client.md
  128. type LightClientAttackEvidence struct {
  129. ConflictingBlock *LightBlock
  130. CommonHeight int64
  131. }
  132. var _ Evidence = &LightClientAttackEvidence{}
  133. // Height returns the last height at which the primary provider and witness provider had the same header.
  134. // We use this as the height of the infraction rather than the actual conflicting header because we know
  135. // that the malicious validators were bonded at this height which is important for evidence expiry
  136. func (l *LightClientAttackEvidence) Height() int64 {
  137. return l.CommonHeight
  138. }
  139. // Bytes returns the proto-encoded evidence as a byte array
  140. func (l *LightClientAttackEvidence) Bytes() []byte {
  141. pbe, err := l.ToProto()
  142. if err != nil {
  143. panic(err)
  144. }
  145. bz, err := pbe.Marshal()
  146. if err != nil {
  147. panic(err)
  148. }
  149. return bz
  150. }
  151. // Hash returns the hash of the header and the commonHeight. This is designed to cause hash collisions with evidence
  152. // that have the same conflicting header and common height but different permutations of validator commit signatures.
  153. // The reason for this is that we don't want to allow several permutations of the same evidence to be committed on
  154. // chain. Ideally we commit the header with the most commit signatures but anything greater than 1/3 is sufficient.
  155. func (l *LightClientAttackEvidence) Hash() []byte {
  156. buf := make([]byte, binary.MaxVarintLen64)
  157. n := binary.PutVarint(buf, l.CommonHeight)
  158. bz := make([]byte, tmhash.Size+n)
  159. copy(bz[:tmhash.Size-1], l.ConflictingBlock.Hash().Bytes())
  160. copy(bz[tmhash.Size:], buf)
  161. return tmhash.Sum(bz)
  162. }
  163. // ValidateBasic performs basic validation such that the evidence is consistent and can now be used for verification.
  164. func (l *LightClientAttackEvidence) ValidateBasic() error {
  165. if l.ConflictingBlock == nil {
  166. return errors.New("conflicting block is nil")
  167. }
  168. // this check needs to be done before we can run validate basic
  169. if l.ConflictingBlock.Header == nil {
  170. return errors.New("conflicting block missing header")
  171. }
  172. if err := l.ConflictingBlock.ValidateBasic(l.ConflictingBlock.ChainID); err != nil {
  173. return fmt.Errorf("invalid conflicting light block: %w", err)
  174. }
  175. if l.CommonHeight <= 0 {
  176. return errors.New("negative or zero common height")
  177. }
  178. // check that common height isn't ahead of the height of the conflicting block. It
  179. // is possible that they are the same height if the light node witnesses either an
  180. // amnesia or a equivocation attack.
  181. if l.CommonHeight > l.ConflictingBlock.Height {
  182. return fmt.Errorf("common height is ahead of the conflicting block height (%d > %d)",
  183. l.CommonHeight, l.ConflictingBlock.Height)
  184. }
  185. return nil
  186. }
  187. // String returns a string representation of LightClientAttackEvidence
  188. func (l *LightClientAttackEvidence) String() string {
  189. return fmt.Sprintf("LightClientAttackEvidence{ConflictingBlock: %v, CommonHeight: %d}",
  190. l.ConflictingBlock.String(), l.CommonHeight)
  191. }
  192. // ToProto encodes LightClientAttackEvidence to protobuf
  193. func (l *LightClientAttackEvidence) ToProto() (*tmproto.LightClientAttackEvidence, error) {
  194. conflictingBlock, err := l.ConflictingBlock.ToProto()
  195. if err != nil {
  196. return nil, err
  197. }
  198. return &tmproto.LightClientAttackEvidence{
  199. ConflictingBlock: conflictingBlock,
  200. CommonHeight: l.CommonHeight,
  201. }, nil
  202. }
  203. // LightClientAttackEvidenceFromProto decodes protobuf
  204. func LightClientAttackEvidenceFromProto(l *tmproto.LightClientAttackEvidence) (*LightClientAttackEvidence, error) {
  205. if l == nil {
  206. return nil, errors.New("empty light client attack evidence")
  207. }
  208. conflictingBlock, err := LightBlockFromProto(l.ConflictingBlock)
  209. if err != nil {
  210. return nil, err
  211. }
  212. le := &LightClientAttackEvidence{
  213. ConflictingBlock: conflictingBlock,
  214. CommonHeight: l.CommonHeight,
  215. }
  216. return le, le.ValidateBasic()
  217. }
  218. //------------------------------------------------------------------------------------------
  219. // EvidenceList is a list of Evidence. Evidences is not a word.
  220. type EvidenceList []Evidence
  221. // Hash returns the simple merkle root hash of the EvidenceList.
  222. func (evl EvidenceList) Hash() []byte {
  223. // These allocations are required because Evidence is not of type Bytes, and
  224. // golang slices can't be typed cast. This shouldn't be a performance problem since
  225. // the Evidence size is capped.
  226. evidenceBzs := make([][]byte, len(evl))
  227. for i := 0; i < len(evl); i++ {
  228. evidenceBzs[i] = evl[i].Bytes()
  229. }
  230. return merkle.HashFromByteSlices(evidenceBzs)
  231. }
  232. func (evl EvidenceList) String() string {
  233. s := ""
  234. for _, e := range evl {
  235. s += fmt.Sprintf("%s\t\t", e)
  236. }
  237. return s
  238. }
  239. // Has returns true if the evidence is in the EvidenceList.
  240. func (evl EvidenceList) Has(evidence Evidence) bool {
  241. for _, ev := range evl {
  242. if bytes.Equal(evidence.Hash(), ev.Hash()) {
  243. return true
  244. }
  245. }
  246. return false
  247. }
  248. //------------------------------------------ PROTO --------------------------------------
  249. // EvidenceToProto is a generalized function for encoding evidence that conforms to the
  250. // evidence interface to protobuf
  251. func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error) {
  252. if evidence == nil {
  253. return nil, errors.New("nil evidence")
  254. }
  255. switch evi := evidence.(type) {
  256. case *DuplicateVoteEvidence:
  257. pbev := evi.ToProto()
  258. return &tmproto.Evidence{
  259. Sum: &tmproto.Evidence_DuplicateVoteEvidence{
  260. DuplicateVoteEvidence: pbev,
  261. },
  262. }, nil
  263. case *LightClientAttackEvidence:
  264. pbev, err := evi.ToProto()
  265. if err != nil {
  266. return nil, err
  267. }
  268. return &tmproto.Evidence{
  269. Sum: &tmproto.Evidence_LightClientAttackEvidence{
  270. LightClientAttackEvidence: pbev,
  271. },
  272. }, nil
  273. default:
  274. return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi)
  275. }
  276. }
  277. // EvidenceFromProto is a generalized function for decoding protobuf into the
  278. // evidence interface
  279. func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error) {
  280. if evidence == nil {
  281. return nil, errors.New("nil evidence")
  282. }
  283. switch evi := evidence.Sum.(type) {
  284. case *tmproto.Evidence_DuplicateVoteEvidence:
  285. return DuplicateVoteEvidenceFromProto(evi.DuplicateVoteEvidence)
  286. case *tmproto.Evidence_LightClientAttackEvidence:
  287. return LightClientAttackEvidenceFromProto(evi.LightClientAttackEvidence)
  288. default:
  289. return nil, errors.New("evidence is not recognized")
  290. }
  291. }
  292. func init() {
  293. tmjson.RegisterType(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence")
  294. tmjson.RegisterType(&LightClientAttackEvidence{}, "tendermint/LightClientAttackEvidence")
  295. }
  296. //-------------------------------------------- ERRORS --------------------------------------
  297. // ErrInvalidEvidence wraps a piece of evidence and the error denoting how or why it is invalid.
  298. type ErrInvalidEvidence struct {
  299. Evidence Evidence
  300. Reason error
  301. }
  302. // NewErrInvalidEvidence returns a new EvidenceInvalid with the given err.
  303. func NewErrInvalidEvidence(ev Evidence, err error) *ErrInvalidEvidence {
  304. return &ErrInvalidEvidence{ev, err}
  305. }
  306. // Error returns a string representation of the error.
  307. func (err *ErrInvalidEvidence) Error() string {
  308. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.Reason, err.Evidence)
  309. }
  310. // ErrEvidenceOverflow is for when there is too much evidence in a block.
  311. type ErrEvidenceOverflow struct {
  312. MaxNum int
  313. GotNum int
  314. }
  315. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  316. func NewErrEvidenceOverflow(max, got int) *ErrEvidenceOverflow {
  317. return &ErrEvidenceOverflow{max, got}
  318. }
  319. // Error returns a string representation of the error.
  320. func (err *ErrEvidenceOverflow) Error() string {
  321. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.MaxNum, err.GotNum)
  322. }
  323. //-------------------------------------------- MOCKING --------------------------------------
  324. // unstable - use only for testing
  325. // assumes the round to be 0 and the validator index to be 0
  326. func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence {
  327. val := NewMockPV()
  328. return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID)
  329. }
  330. func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time,
  331. pv PrivValidator, chainID string) *DuplicateVoteEvidence {
  332. pubKey, _ := pv.GetPubKey()
  333. voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  334. vA := voteA.ToProto()
  335. _ = pv.SignVote(chainID, vA)
  336. voteA.Signature = vA.Signature
  337. voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  338. vB := voteB.ToProto()
  339. _ = pv.SignVote(chainID, vB)
  340. voteB.Signature = vB.Signature
  341. return NewDuplicateVoteEvidence(voteA, voteB)
  342. }
  343. func makeMockVote(height int64, round, index int32, addr Address,
  344. blockID BlockID, time time.Time) *Vote {
  345. return &Vote{
  346. Type: tmproto.SignedMsgType(2),
  347. Height: height,
  348. Round: round,
  349. BlockID: blockID,
  350. Timestamp: time,
  351. ValidatorAddress: addr,
  352. ValidatorIndex: index,
  353. }
  354. }
  355. func randBlockID() BlockID {
  356. return BlockID{
  357. Hash: tmrand.Bytes(tmhash.Size),
  358. PartSetHeader: PartSetHeader{
  359. Total: 1,
  360. Hash: tmrand.Bytes(tmhash.Size),
  361. },
  362. }
  363. }