structs.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 ChainIDOasis:
  86. return "oasis"
  87. case ChainIDAlgorand:
  88. return "algorand"
  89. case ChainIDEthereumRopsten:
  90. return "ethereum-ropsten"
  91. default:
  92. return fmt.Sprintf("unknown chain ID: %d", c)
  93. }
  94. }
  95. func ChainIDFromString(s string) (ChainID, error) {
  96. s = strings.ToLower(s)
  97. switch s {
  98. case "solana":
  99. return ChainIDSolana, nil
  100. case "ethereum":
  101. return ChainIDEthereum, nil
  102. case "terra":
  103. return ChainIDTerra, nil
  104. case "bsc":
  105. return ChainIDBSC, nil
  106. case "polygon":
  107. return ChainIDPolygon, nil
  108. case "avalanche":
  109. return ChainIDAvalanche, nil
  110. case "oasis":
  111. return ChainIDOasis, nil
  112. case "algorand":
  113. return ChainIDAlgorand, nil
  114. case "ethereum-ropsten":
  115. return ChainIDEthereumRopsten, nil
  116. default:
  117. return ChainIDUnset, fmt.Errorf("unknown chain ID: %s", s)
  118. }
  119. }
  120. const (
  121. ChainIDUnset ChainID = 0
  122. // ChainIDSolana is the ChainID of Solana
  123. ChainIDSolana ChainID = 1
  124. // ChainIDEthereum is the ChainID of Ethereum
  125. ChainIDEthereum ChainID = 2
  126. // ChainIDTerra is the ChainID of Terra
  127. ChainIDTerra ChainID = 3
  128. // ChainIDBSC is the ChainID of Binance Smart Chain
  129. ChainIDBSC ChainID = 4
  130. // ChainIDPolygon is the ChainID of Polygon
  131. ChainIDPolygon ChainID = 5
  132. // ChainIDAvalanche is the ChainID of Avalanche
  133. ChainIDAvalanche ChainID = 6
  134. // ChainIDOasis is the ChainID of Oasis
  135. ChainIDOasis ChainID = 7
  136. // ChainIDAlgorand is the ChainID of Algorand
  137. ChainIDAlgorand ChainID = 8
  138. // ChainIDEthereumRopsten is the ChainID of Ethereum Ropsten
  139. ChainIDEthereumRopsten ChainID = 10001
  140. minVAALength = 1 + 4 + 52 + 4 + 1 + 1
  141. SupportedVAAVersion = 0x01
  142. )
  143. // Unmarshal deserializes the binary representation of a VAA
  144. func Unmarshal(data []byte) (*VAA, error) {
  145. if len(data) < minVAALength {
  146. return nil, fmt.Errorf("VAA is too short")
  147. }
  148. v := &VAA{}
  149. v.Version = data[0]
  150. if v.Version != SupportedVAAVersion {
  151. return nil, fmt.Errorf("unsupported VAA version: %d", v.Version)
  152. }
  153. reader := bytes.NewReader(data[1:])
  154. if err := binary.Read(reader, binary.BigEndian, &v.GuardianSetIndex); err != nil {
  155. return nil, fmt.Errorf("failed to read guardian set index: %w", err)
  156. }
  157. lenSignatures, er := reader.ReadByte()
  158. if er != nil {
  159. return nil, fmt.Errorf("failed to read signature length")
  160. }
  161. v.Signatures = make([]*Signature, lenSignatures)
  162. for i := 0; i < int(lenSignatures); i++ {
  163. index, err := reader.ReadByte()
  164. if err != nil {
  165. return nil, fmt.Errorf("failed to read validator index [%d]", i)
  166. }
  167. signature := [65]byte{}
  168. if n, err := reader.Read(signature[:]); err != nil || n != 65 {
  169. return nil, fmt.Errorf("failed to read signature [%d]: %w", i, err)
  170. }
  171. v.Signatures[i] = &Signature{
  172. Index: index,
  173. Signature: signature,
  174. }
  175. }
  176. unixSeconds := uint32(0)
  177. if err := binary.Read(reader, binary.BigEndian, &unixSeconds); err != nil {
  178. return nil, fmt.Errorf("failed to read timestamp: %w", err)
  179. }
  180. v.Timestamp = time.Unix(int64(unixSeconds), 0)
  181. if err := binary.Read(reader, binary.BigEndian, &v.Nonce); err != nil {
  182. return nil, fmt.Errorf("failed to read nonce: %w", err)
  183. }
  184. if err := binary.Read(reader, binary.BigEndian, &v.EmitterChain); err != nil {
  185. return nil, fmt.Errorf("failed to read emitter chain: %w", err)
  186. }
  187. emitterAddress := Address{}
  188. if n, err := reader.Read(emitterAddress[:]); err != nil || n != 32 {
  189. return nil, fmt.Errorf("failed to read emitter address [%d]: %w", n, err)
  190. }
  191. v.EmitterAddress = emitterAddress
  192. if err := binary.Read(reader, binary.BigEndian, &v.Sequence); err != nil {
  193. return nil, fmt.Errorf("failed to read sequence: %w", err)
  194. }
  195. if err := binary.Read(reader, binary.BigEndian, &v.ConsistencyLevel); err != nil {
  196. return nil, fmt.Errorf("failed to read commitment: %w", err)
  197. }
  198. payload := make([]byte, 1000)
  199. n, err := reader.Read(payload)
  200. if err != nil || n == 0 {
  201. return nil, fmt.Errorf("failed to read payload [%d]: %w", n, err)
  202. }
  203. v.Payload = payload[:n]
  204. return v, nil
  205. }
  206. // signingBody returns the binary representation of the data that is relevant for signing and verifying the VAA
  207. func (v *VAA) signingBody() []byte {
  208. return v.serializeBody()
  209. }
  210. // SigningMsg returns the hash of the signing body. This is used for signature generation and verification
  211. func (v *VAA) SigningMsg() common.Hash {
  212. // In order to save space in the solana signature verification instruction, we hash twice so we only need to pass in
  213. // the first hash (32 bytes) vs the full body data.
  214. hash := crypto.Keccak256Hash(crypto.Keccak256Hash(v.signingBody()).Bytes())
  215. return hash
  216. }
  217. // VerifySignatures verifies the signature of the VAA given the signer addresses.
  218. // Returns true if the signatures were verified successfully.
  219. func (v *VAA) VerifySignatures(addresses []common.Address) bool {
  220. if len(addresses) < len(v.Signatures) {
  221. return false
  222. }
  223. h := v.SigningMsg()
  224. for _, sig := range v.Signatures {
  225. if int(sig.Index) >= len(addresses) {
  226. return false
  227. }
  228. pubKey, err := crypto.Ecrecover(h.Bytes(), sig.Signature[:])
  229. if err != nil {
  230. return false
  231. }
  232. addr := common.BytesToAddress(crypto.Keccak256(pubKey[1:])[12:])
  233. if addr != addresses[sig.Index] {
  234. return false
  235. }
  236. }
  237. return true
  238. }
  239. // Marshal returns the binary representation of the VAA
  240. func (v *VAA) Marshal() ([]byte, error) {
  241. buf := new(bytes.Buffer)
  242. MustWrite(buf, binary.BigEndian, v.Version)
  243. MustWrite(buf, binary.BigEndian, v.GuardianSetIndex)
  244. // Write signatures
  245. MustWrite(buf, binary.BigEndian, uint8(len(v.Signatures)))
  246. for _, sig := range v.Signatures {
  247. MustWrite(buf, binary.BigEndian, sig.Index)
  248. buf.Write(sig.Signature[:])
  249. }
  250. // Write Body
  251. buf.Write(v.serializeBody())
  252. return buf.Bytes(), nil
  253. }
  254. // MessageID returns a human-readable emitter_chain/emitter_address/sequence tuple.
  255. func (v *VAA) MessageID() string {
  256. return fmt.Sprintf("%d/%s/%d", v.EmitterChain, v.EmitterAddress, v.Sequence)
  257. }
  258. // HexDigest returns the hex-encoded digest.
  259. func (v *VAA) HexDigest() string {
  260. return hex.EncodeToString(v.SigningMsg().Bytes())
  261. }
  262. func (v *VAA) serializeBody() []byte {
  263. buf := new(bytes.Buffer)
  264. MustWrite(buf, binary.BigEndian, uint32(v.Timestamp.Unix()))
  265. MustWrite(buf, binary.BigEndian, v.Nonce)
  266. MustWrite(buf, binary.BigEndian, v.EmitterChain)
  267. buf.Write(v.EmitterAddress[:])
  268. MustWrite(buf, binary.BigEndian, v.Sequence)
  269. MustWrite(buf, binary.BigEndian, v.ConsistencyLevel)
  270. buf.Write(v.Payload)
  271. return buf.Bytes()
  272. }
  273. func (v *VAA) AddSignature(key *ecdsa.PrivateKey, index uint8) {
  274. sig, err := crypto.Sign(v.SigningMsg().Bytes(), key)
  275. if err != nil {
  276. panic(err)
  277. }
  278. sigData := [65]byte{}
  279. copy(sigData[:], sig)
  280. v.Signatures = append(v.Signatures, &Signature{
  281. Index: index,
  282. Signature: sigData,
  283. })
  284. }
  285. // MustWrite calls binary.Write and panics on errors
  286. func MustWrite(w io.Writer, order binary.ByteOrder, data interface{}) {
  287. if err := binary.Write(w, order, data); err != nil {
  288. panic(fmt.Errorf("failed to write binary data: %v", data).Error())
  289. }
  290. }