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.

345 lines
10 KiB

  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. "github.com/pkg/errors"
  7. "github.com/tendermint/tendermint/crypto/tmhash"
  8. amino "github.com/tendermint/go-amino"
  9. "github.com/tendermint/tendermint/crypto"
  10. "github.com/tendermint/tendermint/crypto/merkle"
  11. )
  12. const (
  13. // MaxEvidenceBytes is a maximum size of any evidence (including amino overhead).
  14. MaxEvidenceBytes int64 = 484
  15. )
  16. // ErrEvidenceInvalid wraps a piece of evidence and the error denoting how or why it is invalid.
  17. type ErrEvidenceInvalid struct {
  18. Evidence Evidence
  19. ErrorValue error
  20. }
  21. // NewErrEvidenceInvalid returns a new EvidenceInvalid with the given err.
  22. func NewErrEvidenceInvalid(ev Evidence, err error) *ErrEvidenceInvalid {
  23. return &ErrEvidenceInvalid{ev, err}
  24. }
  25. // Error returns a string representation of the error.
  26. func (err *ErrEvidenceInvalid) Error() string {
  27. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.ErrorValue, err.Evidence)
  28. }
  29. // ErrEvidenceOverflow is for when there is too much evidence in a block.
  30. type ErrEvidenceOverflow struct {
  31. MaxNum int64
  32. GotNum int64
  33. }
  34. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  35. func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow {
  36. return &ErrEvidenceOverflow{max, got}
  37. }
  38. // Error returns a string representation of the error.
  39. func (err *ErrEvidenceOverflow) Error() string {
  40. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.MaxNum, err.GotNum)
  41. }
  42. //-------------------------------------------
  43. // Evidence represents any provable malicious activity by a validator
  44. type Evidence interface {
  45. Height() int64 // height of the equivocation
  46. Address() []byte // address of the equivocating validator
  47. Bytes() []byte // bytes which compromise the evidence
  48. Hash() []byte // hash of the evidence
  49. Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence
  50. Equal(Evidence) bool // check equality of evidence
  51. ValidateBasic() error
  52. String() string
  53. }
  54. func RegisterEvidences(cdc *amino.Codec) {
  55. cdc.RegisterInterface((*Evidence)(nil), nil)
  56. cdc.RegisterConcrete(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence", nil)
  57. }
  58. func RegisterMockEvidences(cdc *amino.Codec) {
  59. cdc.RegisterConcrete(MockGoodEvidence{}, "tendermint/MockGoodEvidence", nil)
  60. cdc.RegisterConcrete(MockRandomGoodEvidence{}, "tendermint/MockRandomGoodEvidence", nil)
  61. cdc.RegisterConcrete(MockBadEvidence{}, "tendermint/MockBadEvidence", nil)
  62. }
  63. const (
  64. MaxEvidenceBytesDenominator = 10
  65. )
  66. // MaxEvidencePerBlock returns the maximum number of evidences
  67. // allowed in the block and their maximum total size (limitted to 1/10th
  68. // of the maximum block size).
  69. // TODO: change to a constant, or to a fraction of the validator set size.
  70. // See https://github.com/tendermint/tendermint/issues/2590
  71. func MaxEvidencePerBlock(blockMaxBytes int64) (int64, int64) {
  72. maxBytes := blockMaxBytes / MaxEvidenceBytesDenominator
  73. maxNum := maxBytes / MaxEvidenceBytes
  74. return maxNum, maxBytes
  75. }
  76. //-------------------------------------------
  77. // DuplicateVoteEvidence contains evidence a validator signed two conflicting
  78. // votes.
  79. type DuplicateVoteEvidence struct {
  80. PubKey crypto.PubKey
  81. VoteA *Vote
  82. VoteB *Vote
  83. }
  84. var _ Evidence = &DuplicateVoteEvidence{}
  85. // NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given
  86. // two conflicting votes. If one of the votes is nil, evidence returned is nil as well
  87. func NewDuplicateVoteEvidence(pubkey crypto.PubKey, vote1 *Vote, vote2 *Vote) *DuplicateVoteEvidence {
  88. var voteA, voteB *Vote
  89. if vote1 == nil || vote2 == nil {
  90. return nil
  91. }
  92. if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 {
  93. voteA = vote1
  94. voteB = vote2
  95. } else {
  96. voteA = vote2
  97. voteB = vote1
  98. }
  99. return &DuplicateVoteEvidence{
  100. PubKey: pubkey,
  101. VoteA: voteA,
  102. VoteB: voteB,
  103. }
  104. }
  105. // String returns a string representation of the evidence.
  106. func (dve *DuplicateVoteEvidence) String() string {
  107. return fmt.Sprintf("VoteA: %v; VoteB: %v", dve.VoteA, dve.VoteB)
  108. }
  109. // Height returns the height this evidence refers to.
  110. func (dve *DuplicateVoteEvidence) Height() int64 {
  111. return dve.VoteA.Height
  112. }
  113. // Address returns the address of the validator.
  114. func (dve *DuplicateVoteEvidence) Address() []byte {
  115. return dve.PubKey.Address()
  116. }
  117. // Hash returns the hash of the evidence.
  118. func (dve *DuplicateVoteEvidence) Bytes() []byte {
  119. return cdcEncode(dve)
  120. }
  121. // Hash returns the hash of the evidence.
  122. func (dve *DuplicateVoteEvidence) Hash() []byte {
  123. return tmhash.Sum(cdcEncode(dve))
  124. }
  125. // Verify returns an error if the two votes aren't conflicting.
  126. // To be conflicting, they must be from the same validator, for the same H/R/S, but for different blocks.
  127. func (dve *DuplicateVoteEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  128. // H/R/S must be the same
  129. if dve.VoteA.Height != dve.VoteB.Height ||
  130. dve.VoteA.Round != dve.VoteB.Round ||
  131. dve.VoteA.Type != dve.VoteB.Type {
  132. return fmt.Errorf("duplicateVoteEvidence Error: H/R/S does not match. Got %v and %v", dve.VoteA, dve.VoteB)
  133. }
  134. // Address must be the same
  135. if !bytes.Equal(dve.VoteA.ValidatorAddress, dve.VoteB.ValidatorAddress) {
  136. return fmt.Errorf(
  137. "duplicateVoteEvidence Error: Validator addresses do not match. Got %X and %X",
  138. dve.VoteA.ValidatorAddress,
  139. dve.VoteB.ValidatorAddress,
  140. )
  141. }
  142. // Index must be the same
  143. if dve.VoteA.ValidatorIndex != dve.VoteB.ValidatorIndex {
  144. return fmt.Errorf(
  145. "duplicateVoteEvidence Error: Validator indices do not match. Got %d and %d",
  146. dve.VoteA.ValidatorIndex,
  147. dve.VoteB.ValidatorIndex,
  148. )
  149. }
  150. // BlockIDs must be different
  151. if dve.VoteA.BlockID.Equals(dve.VoteB.BlockID) {
  152. return fmt.Errorf(
  153. "duplicateVoteEvidence Error: BlockIDs are the same (%v) - not a real duplicate vote",
  154. dve.VoteA.BlockID,
  155. )
  156. }
  157. // pubkey must match address (this should already be true, sanity check)
  158. addr := dve.VoteA.ValidatorAddress
  159. if !bytes.Equal(pubKey.Address(), addr) {
  160. return fmt.Errorf("duplicateVoteEvidence FAILED SANITY CHECK - address (%X) doesn't match pubkey (%v - %X)",
  161. addr, pubKey, pubKey.Address())
  162. }
  163. // Signatures must be valid
  164. if !pubKey.VerifyBytes(dve.VoteA.SignBytes(chainID), dve.VoteA.Signature) {
  165. return fmt.Errorf("duplicateVoteEvidence Error verifying VoteA: %v", ErrVoteInvalidSignature)
  166. }
  167. if !pubKey.VerifyBytes(dve.VoteB.SignBytes(chainID), dve.VoteB.Signature) {
  168. return fmt.Errorf("duplicateVoteEvidence Error verifying VoteB: %v", ErrVoteInvalidSignature)
  169. }
  170. return nil
  171. }
  172. // Equal checks if two pieces of evidence are equal.
  173. func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool {
  174. if _, ok := ev.(*DuplicateVoteEvidence); !ok {
  175. return false
  176. }
  177. // just check their hashes
  178. dveHash := tmhash.Sum(cdcEncode(dve))
  179. evHash := tmhash.Sum(cdcEncode(ev))
  180. return bytes.Equal(dveHash, evHash)
  181. }
  182. // ValidateBasic performs basic validation.
  183. func (dve *DuplicateVoteEvidence) ValidateBasic() error {
  184. if len(dve.PubKey.Bytes()) == 0 {
  185. return errors.New("empty PubKey")
  186. }
  187. if dve.VoteA == nil || dve.VoteB == nil {
  188. return fmt.Errorf("one or both of the votes are empty %v, %v", dve.VoteA, dve.VoteB)
  189. }
  190. if err := dve.VoteA.ValidateBasic(); err != nil {
  191. return fmt.Errorf("invalid VoteA: %v", err)
  192. }
  193. if err := dve.VoteB.ValidateBasic(); err != nil {
  194. return fmt.Errorf("invalid VoteB: %v", err)
  195. }
  196. // Enforce Votes are lexicographically sorted on blockID
  197. if strings.Compare(dve.VoteA.BlockID.Key(), dve.VoteB.BlockID.Key()) >= 0 {
  198. return errors.New("duplicate votes in invalid order")
  199. }
  200. return nil
  201. }
  202. //-----------------------------------------------------------------
  203. // UNSTABLE
  204. type MockRandomGoodEvidence struct {
  205. MockGoodEvidence
  206. randBytes []byte
  207. }
  208. var _ Evidence = &MockRandomGoodEvidence{}
  209. // UNSTABLE
  210. func NewMockRandomGoodEvidence(height int64, address []byte, randBytes []byte) MockRandomGoodEvidence {
  211. return MockRandomGoodEvidence{
  212. MockGoodEvidence{height, address}, randBytes,
  213. }
  214. }
  215. func (e MockRandomGoodEvidence) Hash() []byte {
  216. return []byte(fmt.Sprintf("%d-%x", e.Height_, e.randBytes))
  217. }
  218. // UNSTABLE
  219. type MockGoodEvidence struct {
  220. Height_ int64
  221. Address_ []byte
  222. }
  223. var _ Evidence = &MockGoodEvidence{}
  224. // UNSTABLE
  225. func NewMockGoodEvidence(height int64, idx int, address []byte) MockGoodEvidence {
  226. return MockGoodEvidence{height, address}
  227. }
  228. func (e MockGoodEvidence) Height() int64 { return e.Height_ }
  229. func (e MockGoodEvidence) Address() []byte { return e.Address_ }
  230. func (e MockGoodEvidence) Hash() []byte {
  231. return []byte(fmt.Sprintf("%d-%x", e.Height_, e.Address_))
  232. }
  233. func (e MockGoodEvidence) Bytes() []byte {
  234. return []byte(fmt.Sprintf("%d-%x", e.Height_, e.Address_))
  235. }
  236. func (e MockGoodEvidence) Verify(chainID string, pubKey crypto.PubKey) error { return nil }
  237. func (e MockGoodEvidence) Equal(ev Evidence) bool {
  238. e2 := ev.(MockGoodEvidence)
  239. return e.Height_ == e2.Height_ &&
  240. bytes.Equal(e.Address_, e2.Address_)
  241. }
  242. func (e MockGoodEvidence) ValidateBasic() error { return nil }
  243. func (e MockGoodEvidence) String() string {
  244. return fmt.Sprintf("GoodEvidence: %d/%s", e.Height_, e.Address_)
  245. }
  246. // UNSTABLE
  247. type MockBadEvidence struct {
  248. MockGoodEvidence
  249. }
  250. func (e MockBadEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  251. return fmt.Errorf("mockBadEvidence")
  252. }
  253. func (e MockBadEvidence) Equal(ev Evidence) bool {
  254. e2 := ev.(MockBadEvidence)
  255. return e.Height_ == e2.Height_ &&
  256. bytes.Equal(e.Address_, e2.Address_)
  257. }
  258. func (e MockBadEvidence) ValidateBasic() error { return nil }
  259. func (e MockBadEvidence) String() string {
  260. return fmt.Sprintf("BadEvidence: %d/%s", e.Height_, e.Address_)
  261. }
  262. //-------------------------------------------
  263. // EvidenceList is a list of Evidence. Evidences is not a word.
  264. type EvidenceList []Evidence
  265. // Hash returns the simple merkle root hash of the EvidenceList.
  266. func (evl EvidenceList) Hash() []byte {
  267. // These allocations are required because Evidence is not of type Bytes, and
  268. // golang slices can't be typed cast. This shouldn't be a performance problem since
  269. // the Evidence size is capped.
  270. evidenceBzs := make([][]byte, len(evl))
  271. for i := 0; i < len(evl); i++ {
  272. evidenceBzs[i] = evl[i].Bytes()
  273. }
  274. return merkle.SimpleHashFromByteSlices(evidenceBzs)
  275. }
  276. func (evl EvidenceList) String() string {
  277. s := ""
  278. for _, e := range evl {
  279. s += fmt.Sprintf("%s\t\t", e)
  280. }
  281. return s
  282. }
  283. // Has returns true if the evidence is in the EvidenceList.
  284. func (evl EvidenceList) Has(evidence Evidence) bool {
  285. for _, ev := range evl {
  286. if ev.Equal(evidence) {
  287. return true
  288. }
  289. }
  290. return false
  291. }