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.

393 lines
11 KiB

  1. package types
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/tendermint/tendermint/crypto"
  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. type Evidence interface {
  17. Height() int64 // height of the equivocation
  18. Time() time.Time // time of the equivocation
  19. Address() []byte // address of the equivocating validator
  20. Bytes() []byte // bytes which comprise the evidence
  21. Hash() []byte // hash of the evidence
  22. Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence
  23. Equal(Evidence) bool // check equality of evidence
  24. ValidateBasic() error
  25. String() string
  26. }
  27. const (
  28. // MaxEvidenceBytes is a maximum size of any evidence (including amino overhead).
  29. MaxEvidenceBytes int64 = 444
  30. )
  31. // ErrEvidenceInvalid wraps a piece of evidence and the error denoting how or why it is invalid.
  32. type ErrEvidenceInvalid struct {
  33. Evidence Evidence
  34. ErrorValue error
  35. }
  36. // NewErrEvidenceInvalid returns a new EvidenceInvalid with the given err.
  37. func NewErrEvidenceInvalid(ev Evidence, err error) *ErrEvidenceInvalid {
  38. return &ErrEvidenceInvalid{ev, err}
  39. }
  40. // Error returns a string representation of the error.
  41. func (err *ErrEvidenceInvalid) Error() string {
  42. return fmt.Sprintf("Invalid evidence: %v. Evidence: %v", err.ErrorValue, err.Evidence)
  43. }
  44. // ErrEvidenceOverflow is for when there is too much evidence in a block.
  45. type ErrEvidenceOverflow struct {
  46. MaxNum int
  47. GotNum int
  48. }
  49. // NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.
  50. func NewErrEvidenceOverflow(max, got int) *ErrEvidenceOverflow {
  51. return &ErrEvidenceOverflow{max, got}
  52. }
  53. // Error returns a string representation of the error.
  54. func (err *ErrEvidenceOverflow) Error() string {
  55. return fmt.Sprintf("Too much evidence: Max %d, got %d", err.MaxNum, err.GotNum)
  56. }
  57. //-------------------------------------------
  58. func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error) {
  59. if evidence == nil {
  60. return nil, errors.New("nil evidence")
  61. }
  62. switch evi := evidence.(type) {
  63. case *DuplicateVoteEvidence:
  64. pbevi := evi.ToProto()
  65. tp := &tmproto.Evidence{
  66. Sum: &tmproto.Evidence_DuplicateVoteEvidence{
  67. DuplicateVoteEvidence: pbevi,
  68. },
  69. }
  70. return tp, nil
  71. default:
  72. return nil, fmt.Errorf("toproto: evidence is not recognized: %T", evi)
  73. }
  74. }
  75. func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error) {
  76. if evidence == nil {
  77. return nil, errors.New("nil evidence")
  78. }
  79. switch evi := evidence.Sum.(type) {
  80. case *tmproto.Evidence_DuplicateVoteEvidence:
  81. return DuplicateVoteEvidenceFromProto(evi.DuplicateVoteEvidence)
  82. default:
  83. return nil, errors.New("evidence is not recognized")
  84. }
  85. }
  86. func init() {
  87. tmjson.RegisterType(&DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence")
  88. }
  89. //-------------------------------------------
  90. // DuplicateVoteEvidence contains evidence a validator signed two conflicting
  91. // votes.
  92. type DuplicateVoteEvidence struct {
  93. VoteA *Vote `json:"vote_a"`
  94. VoteB *Vote `json:"vote_b"`
  95. Timestamp time.Time `json:"timestamp"`
  96. }
  97. var _ Evidence = &DuplicateVoteEvidence{}
  98. // NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given
  99. // two conflicting votes. If one of the votes is nil, evidence returned is nil as well
  100. func NewDuplicateVoteEvidence(vote1, vote2 *Vote, time time.Time) *DuplicateVoteEvidence {
  101. var voteA, voteB *Vote
  102. if vote1 == nil || vote2 == nil {
  103. return nil
  104. }
  105. if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 {
  106. voteA = vote1
  107. voteB = vote2
  108. } else {
  109. voteA = vote2
  110. voteB = vote1
  111. }
  112. return &DuplicateVoteEvidence{
  113. VoteA: voteA,
  114. VoteB: voteB,
  115. Timestamp: time,
  116. }
  117. }
  118. // String returns a string representation of the evidence.
  119. func (dve *DuplicateVoteEvidence) String() string {
  120. return fmt.Sprintf("DuplicateVoteEvidence{VoteA: %v, VoteB: %v, Time: %v}", dve.VoteA, dve.VoteB, dve.Timestamp)
  121. }
  122. // Height returns the height this evidence refers to.
  123. func (dve *DuplicateVoteEvidence) Height() int64 {
  124. return dve.VoteA.Height
  125. }
  126. // Time returns time of the latest vote.
  127. func (dve *DuplicateVoteEvidence) Time() time.Time {
  128. return dve.Timestamp
  129. }
  130. // Address returns the address of the validator.
  131. func (dve *DuplicateVoteEvidence) Address() []byte {
  132. return dve.VoteA.ValidatorAddress
  133. }
  134. // Hash returns the hash of the evidence.
  135. func (dve *DuplicateVoteEvidence) Bytes() []byte {
  136. pbe := dve.ToProto()
  137. bz, err := pbe.Marshal()
  138. if err != nil {
  139. panic(err)
  140. }
  141. return bz
  142. }
  143. // Hash returns the hash of the evidence.
  144. func (dve *DuplicateVoteEvidence) Hash() []byte {
  145. pbe := dve.ToProto()
  146. bz, err := pbe.Marshal()
  147. if err != nil {
  148. panic(err)
  149. }
  150. return tmhash.Sum(bz)
  151. }
  152. // Verify returns an error if the two votes aren't conflicting.
  153. //
  154. // To be conflicting, they must be from the same validator, for the same H/R/S,
  155. // but for different blocks.
  156. func (dve *DuplicateVoteEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
  157. // H/R/S must be the same
  158. if dve.VoteA.Height != dve.VoteB.Height ||
  159. dve.VoteA.Round != dve.VoteB.Round ||
  160. dve.VoteA.Type != dve.VoteB.Type {
  161. return fmt.Errorf("h/r/s does not match: %d/%d/%v vs %d/%d/%v",
  162. dve.VoteA.Height, dve.VoteA.Round, dve.VoteA.Type,
  163. dve.VoteB.Height, dve.VoteB.Round, dve.VoteB.Type)
  164. }
  165. // Address must be the same
  166. if !bytes.Equal(dve.VoteA.ValidatorAddress, dve.VoteB.ValidatorAddress) {
  167. return fmt.Errorf("validator addresses do not match: %X vs %X",
  168. dve.VoteA.ValidatorAddress,
  169. dve.VoteB.ValidatorAddress,
  170. )
  171. }
  172. // BlockIDs must be different
  173. if dve.VoteA.BlockID.Equals(dve.VoteB.BlockID) {
  174. return fmt.Errorf(
  175. "block IDs are the same (%v) - not a real duplicate vote",
  176. dve.VoteA.BlockID,
  177. )
  178. }
  179. // pubkey must match address (this should already be true, sanity check)
  180. addr := dve.VoteA.ValidatorAddress
  181. if !bytes.Equal(pubKey.Address(), addr) {
  182. return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)",
  183. addr, pubKey, pubKey.Address())
  184. }
  185. va := dve.VoteA.ToProto()
  186. vb := dve.VoteB.ToProto()
  187. // Signatures must be valid
  188. if !pubKey.VerifySignature(VoteSignBytes(chainID, va), dve.VoteA.Signature) {
  189. return fmt.Errorf("verifying VoteA: %w", ErrVoteInvalidSignature)
  190. }
  191. if !pubKey.VerifySignature(VoteSignBytes(chainID, vb), dve.VoteB.Signature) {
  192. return fmt.Errorf("verifying VoteB: %w", ErrVoteInvalidSignature)
  193. }
  194. return nil
  195. }
  196. // Equal checks if two pieces of evidence are equal.
  197. func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool {
  198. if _, ok := ev.(*DuplicateVoteEvidence); !ok {
  199. return false
  200. }
  201. pbdev := dve.ToProto()
  202. bz, err := pbdev.Marshal()
  203. if err != nil {
  204. panic(err)
  205. }
  206. var evbz []byte
  207. if ev, ok := ev.(*DuplicateVoteEvidence); ok {
  208. evpb := ev.ToProto()
  209. evbz, err = evpb.Marshal()
  210. if err != nil {
  211. panic(err)
  212. }
  213. }
  214. // just check their hashes
  215. dveHash := tmhash.Sum(bz)
  216. evHash := tmhash.Sum(evbz)
  217. return bytes.Equal(dveHash, evHash)
  218. }
  219. // ValidateBasic performs basic validation.
  220. func (dve *DuplicateVoteEvidence) ValidateBasic() error {
  221. if dve == nil {
  222. return errors.New("empty duplicate vote evidence")
  223. }
  224. if dve.VoteA == nil || dve.VoteB == nil {
  225. return fmt.Errorf("one or both of the votes are empty %v, %v", dve.VoteA, dve.VoteB)
  226. }
  227. if err := dve.VoteA.ValidateBasic(); err != nil {
  228. return fmt.Errorf("invalid VoteA: %w", err)
  229. }
  230. if err := dve.VoteB.ValidateBasic(); err != nil {
  231. return fmt.Errorf("invalid VoteB: %w", err)
  232. }
  233. // Enforce Votes are lexicographically sorted on blockID
  234. if strings.Compare(dve.VoteA.BlockID.Key(), dve.VoteB.BlockID.Key()) >= 0 {
  235. return errors.New("duplicate votes in invalid order")
  236. }
  237. return nil
  238. }
  239. func (dve *DuplicateVoteEvidence) ToProto() *tmproto.DuplicateVoteEvidence {
  240. voteB := dve.VoteB.ToProto()
  241. voteA := dve.VoteA.ToProto()
  242. tp := tmproto.DuplicateVoteEvidence{
  243. VoteA: voteA,
  244. VoteB: voteB,
  245. Timestamp: dve.Timestamp,
  246. }
  247. return &tp
  248. }
  249. func DuplicateVoteEvidenceFromProto(pb *tmproto.DuplicateVoteEvidence) (*DuplicateVoteEvidence, error) {
  250. if pb == nil {
  251. return nil, errors.New("nil duplicate vote evidence")
  252. }
  253. vA, err := VoteFromProto(pb.VoteA)
  254. if err != nil {
  255. return nil, err
  256. }
  257. vB, err := VoteFromProto(pb.VoteB)
  258. if err != nil {
  259. return nil, err
  260. }
  261. dve := NewDuplicateVoteEvidence(vA, vB, pb.Timestamp)
  262. return dve, dve.ValidateBasic()
  263. }
  264. //--------------------------------------------------
  265. // EvidenceList is a list of Evidence. Evidences is not a word.
  266. type EvidenceList []Evidence
  267. // Hash returns the simple merkle root hash of the EvidenceList.
  268. func (evl EvidenceList) Hash() []byte {
  269. // These allocations are required because Evidence is not of type Bytes, and
  270. // golang slices can't be typed cast. This shouldn't be a performance problem since
  271. // the Evidence size is capped.
  272. evidenceBzs := make([][]byte, len(evl))
  273. for i := 0; i < len(evl); i++ {
  274. evidenceBzs[i] = evl[i].Bytes()
  275. }
  276. return merkle.HashFromByteSlices(evidenceBzs)
  277. }
  278. func (evl EvidenceList) String() string {
  279. s := ""
  280. for _, e := range evl {
  281. s += fmt.Sprintf("%s\t\t", e)
  282. }
  283. return s
  284. }
  285. // Has returns true if the evidence is in the EvidenceList.
  286. func (evl EvidenceList) Has(evidence Evidence) bool {
  287. for _, ev := range evl {
  288. if ev.Equal(evidence) {
  289. return true
  290. }
  291. }
  292. return false
  293. }
  294. //-------------------------------------------- MOCKING --------------------------------------
  295. // unstable - use only for testing
  296. // assumes the round to be 0 and the validator index to be 0
  297. func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence {
  298. val := NewMockPV()
  299. return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID)
  300. }
  301. func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time,
  302. pv PrivValidator, chainID string) *DuplicateVoteEvidence {
  303. pubKey, _ := pv.GetPubKey()
  304. voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  305. vA := voteA.ToProto()
  306. _ = pv.SignVote(chainID, vA)
  307. voteA.Signature = vA.Signature
  308. voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
  309. vB := voteB.ToProto()
  310. _ = pv.SignVote(chainID, vB)
  311. voteB.Signature = vB.Signature
  312. return NewDuplicateVoteEvidence(voteA, voteB, time)
  313. }
  314. func makeMockVote(height int64, round, index int32, addr Address,
  315. blockID BlockID, time time.Time) *Vote {
  316. return &Vote{
  317. Type: tmproto.SignedMsgType(2),
  318. Height: height,
  319. Round: round,
  320. BlockID: blockID,
  321. Timestamp: time,
  322. ValidatorAddress: addr,
  323. ValidatorIndex: index,
  324. }
  325. }
  326. func randBlockID() BlockID {
  327. return BlockID{
  328. Hash: tmrand.Bytes(tmhash.Size),
  329. PartSetHeader: PartSetHeader{
  330. Total: 1,
  331. Hash: tmrand.Bytes(tmhash.Size),
  332. },
  333. }
  334. }