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.

246 lines
6.5 KiB

  1. package types
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "time"
  7. "github.com/tendermint/tendermint/crypto"
  8. "github.com/tendermint/tendermint/internal/libs/protoio"
  9. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  10. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  11. )
  12. const (
  13. nilVoteStr string = "nil-Vote"
  14. )
  15. var (
  16. ErrVoteUnexpectedStep = errors.New("unexpected step")
  17. ErrVoteInvalidValidatorIndex = errors.New("invalid validator index")
  18. ErrVoteInvalidValidatorAddress = errors.New("invalid validator address")
  19. ErrVoteInvalidSignature = errors.New("invalid signature")
  20. ErrVoteInvalidBlockHash = errors.New("invalid block hash")
  21. ErrVoteNonDeterministicSignature = errors.New("non-deterministic signature")
  22. ErrVoteNil = errors.New("nil vote")
  23. )
  24. type ErrVoteConflictingVotes struct {
  25. VoteA *Vote
  26. VoteB *Vote
  27. }
  28. func (err *ErrVoteConflictingVotes) Error() string {
  29. return fmt.Sprintf("conflicting votes from validator %X", err.VoteA.ValidatorAddress)
  30. }
  31. func NewConflictingVoteError(vote1, vote2 *Vote) *ErrVoteConflictingVotes {
  32. return &ErrVoteConflictingVotes{
  33. VoteA: vote1,
  34. VoteB: vote2,
  35. }
  36. }
  37. // Address is hex bytes.
  38. type Address = crypto.Address
  39. // Vote represents a prevote, precommit, or commit vote from validators for
  40. // consensus.
  41. type Vote struct {
  42. Type tmproto.SignedMsgType `json:"type"`
  43. Height int64 `json:"height,string"`
  44. Round int32 `json:"round"` // assume there will not be greater than 2_147_483_647 rounds
  45. BlockID BlockID `json:"block_id"` // zero if vote is nil.
  46. Timestamp time.Time `json:"timestamp"`
  47. ValidatorAddress Address `json:"validator_address"`
  48. ValidatorIndex int32 `json:"validator_index"`
  49. Signature []byte `json:"signature"`
  50. }
  51. // CommitSig converts the Vote to a CommitSig.
  52. func (vote *Vote) CommitSig() CommitSig {
  53. if vote == nil {
  54. return NewCommitSigAbsent()
  55. }
  56. var blockIDFlag BlockIDFlag
  57. switch {
  58. case vote.BlockID.IsComplete():
  59. blockIDFlag = BlockIDFlagCommit
  60. case vote.BlockID.IsNil():
  61. blockIDFlag = BlockIDFlagNil
  62. default:
  63. panic(fmt.Sprintf("Invalid vote %v - expected BlockID to be either empty or complete", vote))
  64. }
  65. return CommitSig{
  66. BlockIDFlag: blockIDFlag,
  67. ValidatorAddress: vote.ValidatorAddress,
  68. Timestamp: vote.Timestamp,
  69. Signature: vote.Signature,
  70. }
  71. }
  72. // VoteSignBytes returns the proto-encoding of the canonicalized Vote, for
  73. // signing. Panics is the marshaling fails.
  74. //
  75. // The encoded Protobuf message is varint length-prefixed (using MarshalDelimited)
  76. // for backwards-compatibility with the Amino encoding, due to e.g. hardware
  77. // devices that rely on this encoding.
  78. //
  79. // See CanonicalizeVote
  80. func VoteSignBytes(chainID string, vote *tmproto.Vote) []byte {
  81. pb := CanonicalizeVote(chainID, vote)
  82. bz, err := protoio.MarshalDelimited(&pb)
  83. if err != nil {
  84. panic(err)
  85. }
  86. return bz
  87. }
  88. func (vote *Vote) Copy() *Vote {
  89. voteCopy := *vote
  90. return &voteCopy
  91. }
  92. // String returns a string representation of Vote.
  93. //
  94. // 1. validator index
  95. // 2. first 6 bytes of validator address
  96. // 3. height
  97. // 4. round,
  98. // 5. type byte
  99. // 6. type string
  100. // 7. first 6 bytes of block hash
  101. // 8. first 6 bytes of signature
  102. // 9. timestamp
  103. func (vote *Vote) String() string {
  104. if vote == nil {
  105. return nilVoteStr
  106. }
  107. var typeString string
  108. switch vote.Type {
  109. case tmproto.PrevoteType:
  110. typeString = "Prevote"
  111. case tmproto.PrecommitType:
  112. typeString = "Precommit"
  113. default:
  114. panic("Unknown vote type")
  115. }
  116. return fmt.Sprintf("Vote{%v:%X %v/%02d/%v(%v) %X %X @ %s}",
  117. vote.ValidatorIndex,
  118. tmbytes.Fingerprint(vote.ValidatorAddress),
  119. vote.Height,
  120. vote.Round,
  121. vote.Type,
  122. typeString,
  123. tmbytes.Fingerprint(vote.BlockID.Hash),
  124. tmbytes.Fingerprint(vote.Signature),
  125. CanonicalTime(vote.Timestamp),
  126. )
  127. }
  128. func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
  129. if !bytes.Equal(pubKey.Address(), vote.ValidatorAddress) {
  130. return ErrVoteInvalidValidatorAddress
  131. }
  132. v := vote.ToProto()
  133. if !pubKey.VerifySignature(VoteSignBytes(chainID, v), vote.Signature) {
  134. return ErrVoteInvalidSignature
  135. }
  136. return nil
  137. }
  138. // ValidateBasic performs basic validation.
  139. func (vote *Vote) ValidateBasic() error {
  140. if !IsVoteTypeValid(vote.Type) {
  141. return errors.New("invalid Type")
  142. }
  143. if vote.Height < 0 {
  144. return errors.New("negative Height")
  145. }
  146. if vote.Round < 0 {
  147. return errors.New("negative Round")
  148. }
  149. // NOTE: Timestamp validation is subtle and handled elsewhere.
  150. if err := vote.BlockID.ValidateBasic(); err != nil {
  151. return fmt.Errorf("wrong BlockID: %w", err)
  152. }
  153. // BlockID.ValidateBasic would not err if we for instance have an empty hash but a
  154. // non-empty PartsSetHeader:
  155. if !vote.BlockID.IsNil() && !vote.BlockID.IsComplete() {
  156. return fmt.Errorf("blockID must be either empty or complete, got: %v", vote.BlockID)
  157. }
  158. if len(vote.ValidatorAddress) != crypto.AddressSize {
  159. return fmt.Errorf("expected ValidatorAddress size to be %d bytes, got %d bytes",
  160. crypto.AddressSize,
  161. len(vote.ValidatorAddress),
  162. )
  163. }
  164. if vote.ValidatorIndex < 0 {
  165. return errors.New("negative ValidatorIndex")
  166. }
  167. if len(vote.Signature) == 0 {
  168. return errors.New("signature is missing")
  169. }
  170. if len(vote.Signature) > MaxSignatureSize {
  171. return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize)
  172. }
  173. return nil
  174. }
  175. // ToProto converts the handwritten type to proto generated type
  176. // return type, nil if everything converts safely, otherwise nil, error
  177. func (vote *Vote) ToProto() *tmproto.Vote {
  178. if vote == nil {
  179. return nil
  180. }
  181. return &tmproto.Vote{
  182. Type: vote.Type,
  183. Height: vote.Height,
  184. Round: vote.Round,
  185. BlockID: vote.BlockID.ToProto(),
  186. Timestamp: vote.Timestamp,
  187. ValidatorAddress: vote.ValidatorAddress,
  188. ValidatorIndex: vote.ValidatorIndex,
  189. Signature: vote.Signature,
  190. }
  191. }
  192. // FromProto converts a proto generetad type to a handwritten type
  193. // return type, nil if everything converts safely, otherwise nil, error
  194. func VoteFromProto(pv *tmproto.Vote) (*Vote, error) {
  195. if pv == nil {
  196. return nil, errors.New("nil vote")
  197. }
  198. blockID, err := BlockIDFromProto(&pv.BlockID)
  199. if err != nil {
  200. return nil, err
  201. }
  202. vote := new(Vote)
  203. vote.Type = pv.Type
  204. vote.Height = pv.Height
  205. vote.Round = pv.Round
  206. vote.BlockID = *blockID
  207. vote.Timestamp = pv.Timestamp
  208. vote.ValidatorAddress = pv.ValidatorAddress
  209. vote.ValidatorIndex = pv.ValidatorIndex
  210. vote.Signature = pv.Signature
  211. return vote, vote.ValidateBasic()
  212. }