structs.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package vaa
  2. import (
  3. "bytes"
  4. "crypto/ecdsa"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "fmt"
  8. "io"
  9. "strings"
  10. "time"
  11. "github.com/ethereum/go-ethereum/common"
  12. "github.com/ethereum/go-ethereum/crypto"
  13. )
  14. type (
  15. // VAA is a verifiable action approval of the Wormhole protocol
  16. VAA struct {
  17. // Version of the VAA schema
  18. Version uint8
  19. // GuardianSetIndex is the index of the guardian set that signed this VAA
  20. GuardianSetIndex uint32
  21. // SignatureData is the signature of the guardian set
  22. Signatures []*Signature
  23. // Timestamp when the VAA was created
  24. Timestamp time.Time
  25. // Nonce of the VAA
  26. Nonce uint32
  27. // Sequence of the VAA
  28. Sequence uint64
  29. /// ConsistencyLevel of the VAA
  30. ConsistencyLevel uint8
  31. // EmitterChain the VAA was emitted on
  32. EmitterChain ChainID
  33. // EmitterAddress of the contract that emitted the Message
  34. EmitterAddress Address
  35. // Payload of the message
  36. Payload []byte
  37. }
  38. // ChainID of a Wormhole chain
  39. ChainID uint16
  40. // Action of a VAA
  41. Action uint8
  42. // Address is a Wormhole protocol address, it contains the native chain's address. If the address data type of a
  43. // chain is < 32bytes the value is zero-padded on the left.
  44. Address [32]byte
  45. // Signature of a single guardian
  46. Signature struct {
  47. // Index of the validator
  48. Index uint8
  49. // Signature data
  50. Signature SignatureData
  51. }
  52. SignatureData [65]byte
  53. )
  54. func (a Address) MarshalJSON() ([]byte, error) {
  55. return []byte(fmt.Sprintf(`"%s"`, a)), nil
  56. }
  57. func (a Address) String() string {
  58. return hex.EncodeToString(a[:])
  59. }
  60. func (a Address) Bytes() []byte {
  61. return a[:]
  62. }
  63. func (a SignatureData) MarshalJSON() ([]byte, error) {
  64. return []byte(fmt.Sprintf(`"%s"`, a)), nil
  65. }
  66. func (a SignatureData) String() string {
  67. return hex.EncodeToString(a[:])
  68. }
  69. func (c ChainID) String() string {
  70. switch c {
  71. case ChainIDUnset:
  72. return "unset"
  73. case ChainIDSolana:
  74. return "solana"
  75. case ChainIDEthereum:
  76. return "ethereum"
  77. case ChainIDTerra:
  78. return "terra"
  79. case ChainIDBSC:
  80. return "bsc"
  81. case ChainIDPolygon:
  82. return "polygon"
  83. case ChainIDAvalanche:
  84. return "avalanche"
  85. case ChainIDEthereumRopsten:
  86. return "ethereum-ropsten"
  87. default:
  88. return fmt.Sprintf("unknown chain ID: %d", c)
  89. }
  90. }
  91. func ChainIDFromString(s string) (ChainID, error) {
  92. s = strings.ToLower(s)
  93. switch s {
  94. case "solana":
  95. return ChainIDSolana, nil
  96. case "ethereum":
  97. return ChainIDEthereum, nil
  98. case "terra":
  99. return ChainIDTerra, nil
  100. case "bsc":
  101. return ChainIDBSC, nil
  102. case "polygon":
  103. return ChainIDPolygon, nil
  104. case "avalanche":
  105. return ChainIDAvalanche, nil
  106. case "ethereum-ropsten":
  107. return ChainIDEthereumRopsten, nil
  108. default:
  109. return ChainIDUnset, fmt.Errorf("unknown chain ID: %s", s)
  110. }
  111. }
  112. const (
  113. ChainIDUnset ChainID = 0
  114. // ChainIDSolana is the ChainID of Solana
  115. ChainIDSolana ChainID = 1
  116. // ChainIDEthereum is the ChainID of Ethereum
  117. ChainIDEthereum ChainID = 2
  118. // ChainIDTerra is the ChainID of Terra
  119. ChainIDTerra ChainID = 3
  120. // ChainIDBSC is the ChainID of Binance Smart Chain
  121. ChainIDBSC ChainID = 4
  122. // ChainIDPolygon is the ChainID of Polygon
  123. ChainIDPolygon ChainID = 5
  124. // ChainIDAvalanche is the ChainID of Avalanche
  125. ChainIDAvalanche ChainID = 6
  126. // ChainIDEthereumRopsten is the ChainID of Ethereum Ropsten
  127. ChainIDEthereumRopsten ChainID = 10001
  128. minVAALength = 1 + 4 + 52 + 4 + 1 + 1
  129. SupportedVAAVersion = 0x01
  130. )
  131. // Unmarshal deserializes the binary representation of a VAA
  132. func Unmarshal(data []byte) (*VAA, error) {
  133. if len(data) < minVAALength {
  134. return nil, fmt.Errorf("VAA is too short")
  135. }
  136. v := &VAA{}
  137. v.Version = data[0]
  138. if v.Version != SupportedVAAVersion {
  139. return nil, fmt.Errorf("unsupported VAA version: %d", v.Version)
  140. }
  141. reader := bytes.NewReader(data[1:])
  142. if err := binary.Read(reader, binary.BigEndian, &v.GuardianSetIndex); err != nil {
  143. return nil, fmt.Errorf("failed to read guardian set index: %w", err)
  144. }
  145. lenSignatures, er := reader.ReadByte()
  146. if er != nil {
  147. return nil, fmt.Errorf("failed to read signature length")
  148. }
  149. v.Signatures = make([]*Signature, lenSignatures)
  150. for i := 0; i < int(lenSignatures); i++ {
  151. index, err := reader.ReadByte()
  152. if err != nil {
  153. return nil, fmt.Errorf("failed to read validator index [%d]", i)
  154. }
  155. signature := [65]byte{}
  156. if n, err := reader.Read(signature[:]); err != nil || n != 65 {
  157. return nil, fmt.Errorf("failed to read signature [%d]: %w", i, err)
  158. }
  159. v.Signatures[i] = &Signature{
  160. Index: index,
  161. Signature: signature,
  162. }
  163. }
  164. unixSeconds := uint32(0)
  165. if err := binary.Read(reader, binary.BigEndian, &unixSeconds); err != nil {
  166. return nil, fmt.Errorf("failed to read timestamp: %w", err)
  167. }
  168. v.Timestamp = time.Unix(int64(unixSeconds), 0)
  169. if err := binary.Read(reader, binary.BigEndian, &v.Nonce); err != nil {
  170. return nil, fmt.Errorf("failed to read nonce: %w", err)
  171. }
  172. if err := binary.Read(reader, binary.BigEndian, &v.EmitterChain); err != nil {
  173. return nil, fmt.Errorf("failed to read emitter chain: %w", err)
  174. }
  175. emitterAddress := Address{}
  176. if n, err := reader.Read(emitterAddress[:]); err != nil || n != 32 {
  177. return nil, fmt.Errorf("failed to read emitter address [%d]: %w", n, err)
  178. }
  179. v.EmitterAddress = emitterAddress
  180. if err := binary.Read(reader, binary.BigEndian, &v.Sequence); err != nil {
  181. return nil, fmt.Errorf("failed to read sequence: %w", err)
  182. }
  183. if err := binary.Read(reader, binary.BigEndian, &v.ConsistencyLevel); err != nil {
  184. return nil, fmt.Errorf("failed to read commitment: %w", err)
  185. }
  186. payload := make([]byte, 1000)
  187. n, err := reader.Read(payload)
  188. if err != nil || n == 0 {
  189. return nil, fmt.Errorf("failed to read payload [%d]: %w", n, err)
  190. }
  191. v.Payload = payload[:n]
  192. return v, nil
  193. }
  194. // signingBody returns the binary representation of the data that is relevant for signing and verifying the VAA
  195. func (v *VAA) signingBody() []byte {
  196. return v.serializeBody()
  197. }
  198. // SigningMsg returns the hash of the signing body. This is used for signature generation and verification
  199. func (v *VAA) SigningMsg() common.Hash {
  200. // In order to save space in the solana signature verification instruction, we hash twice so we only need to pass in
  201. // the first hash (32 bytes) vs the full body data.
  202. hash := crypto.Keccak256Hash(crypto.Keccak256Hash(v.signingBody()).Bytes())
  203. return hash
  204. }
  205. // VerifySignatures verifies the signature of the VAA given the signer addresses.
  206. // Returns true if the signatures were verified successfully.
  207. func (v *VAA) VerifySignatures(addresses []common.Address) bool {
  208. if len(addresses) < len(v.Signatures) {
  209. return false
  210. }
  211. h := v.SigningMsg()
  212. for _, sig := range v.Signatures {
  213. if int(sig.Index) >= len(addresses) {
  214. return false
  215. }
  216. pubKey, err := crypto.Ecrecover(h.Bytes(), sig.Signature[:])
  217. if err != nil {
  218. return false
  219. }
  220. addr := common.BytesToAddress(crypto.Keccak256(pubKey[1:])[12:])
  221. if addr != addresses[sig.Index] {
  222. return false
  223. }
  224. }
  225. return true
  226. }
  227. // Marshal returns the binary representation of the VAA
  228. func (v *VAA) Marshal() ([]byte, error) {
  229. buf := new(bytes.Buffer)
  230. MustWrite(buf, binary.BigEndian, v.Version)
  231. MustWrite(buf, binary.BigEndian, v.GuardianSetIndex)
  232. // Write signatures
  233. MustWrite(buf, binary.BigEndian, uint8(len(v.Signatures)))
  234. for _, sig := range v.Signatures {
  235. MustWrite(buf, binary.BigEndian, sig.Index)
  236. buf.Write(sig.Signature[:])
  237. }
  238. // Write Body
  239. buf.Write(v.serializeBody())
  240. return buf.Bytes(), nil
  241. }
  242. // MessageID returns a human-readable emitter_chain/emitter_address/sequence tuple.
  243. func (v *VAA) MessageID() string {
  244. return fmt.Sprintf("%d/%s/%d", v.EmitterChain, v.EmitterAddress, v.Sequence)
  245. }
  246. // HexDigest returns the hex-encoded digest.
  247. func (v *VAA) HexDigest() string {
  248. return hex.EncodeToString(v.SigningMsg().Bytes())
  249. }
  250. func (v *VAA) serializeBody() []byte {
  251. buf := new(bytes.Buffer)
  252. MustWrite(buf, binary.BigEndian, uint32(v.Timestamp.Unix()))
  253. MustWrite(buf, binary.BigEndian, v.Nonce)
  254. MustWrite(buf, binary.BigEndian, v.EmitterChain)
  255. buf.Write(v.EmitterAddress[:])
  256. MustWrite(buf, binary.BigEndian, v.Sequence)
  257. MustWrite(buf, binary.BigEndian, v.ConsistencyLevel)
  258. buf.Write(v.Payload)
  259. return buf.Bytes()
  260. }
  261. func (v *VAA) AddSignature(key *ecdsa.PrivateKey, index uint8) {
  262. sig, err := crypto.Sign(v.SigningMsg().Bytes(), key)
  263. if err != nil {
  264. panic(err)
  265. }
  266. sigData := [65]byte{}
  267. copy(sigData[:], sig)
  268. v.Signatures = append(v.Signatures, &Signature{
  269. Index: index,
  270. Signature: sigData,
  271. })
  272. }
  273. // MustWrite calls binary.Write and panics on errors
  274. func MustWrite(w io.Writer, order binary.ByteOrder, data interface{}) {
  275. if err := binary.Write(w, order, data); err != nil {
  276. panic(fmt.Errorf("failed to write binary data: %v", data).Error())
  277. }
  278. }