Repository navigation
Expand file tree
/
Copy pathstructs.go
More file actions
958 lines (835 loc) · 31.7 KB
/
Copy pathstructs.go
File metadata and controls
958 lines (835 loc) · 31.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
package vaa
import (
"bytes"
"crypto/ecdsa"
"encoding"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/big"
"strconv"
"strings"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)
type (
// VAA is a verifiable action approval of the Wormhole protocol
VAA struct {
// Version of the VAA schema
Version uint8
// GuardianSetIndex is the index of the guardian set that signed this VAA
GuardianSetIndex uint32
// SignatureData is the signature of the guardian set
Signatures []*Signature
// Timestamp when the VAA was created
Timestamp time.Time
// Nonce of the VAA
Nonce uint32
// Sequence of the VAA
Sequence uint64
/// ConsistencyLevel of the VAA
ConsistencyLevel uint8
// EmitterChain the VAA was emitted on
EmitterChain ChainID
// EmitterAddress of the contract that emitted the Message
EmitterAddress Address
// Payload of the message
Payload []byte
}
// ChainID of a Wormhole chain
ChainID uint16
// Action of a VAA
Action uint8
// Address is a Wormhole protocol address otherwise referred to as a "wormhole normalized address." It typically
// contains the native chain's address for chains where the addresses are <= 32 bytes.
//
// If the address data type of a chain is < 32 bytes, the value is zero-padded on the left.
//
// For chains with addresses that support lengths greater than 32 bytes, this type MAY be used
// to represent an on-chain address by hashing it using an algorithm like sha256.
//
// For chains with variable length addresses, users MUST use this type consistently such that addresses
// can be uniquely identified. For example, if a chain supports addresses between length 2 and 64, this type
// should always encode addresses for that chain as sha256 digests. This helps to avoid a situation where
// addresses with length < 32 have zero-padded EVM-like addresses, but larger addresses on the same chain
// are represented as digests.
//
// Other uses of this type are NOT RECOMMENDED given that they can overload the semantic meaning of this field
// which already does a lot of conceptual work across disparate blockchain implementations.
Address [32]byte
// Signature of a single guardian
Signature struct {
// Index of the validator
Index uint8
// Signature data
Signature SignatureData
}
SignatureData [65]byte
Observation struct {
// Index of the observation in a Batch array
Index uint8
// Signed Observation data
Observation *VAA
}
TransferPayloadHdr struct {
Type uint8
Amount *big.Int
OriginAddress Address
OriginChain ChainID
TargetAddress Address
TargetChain ChainID
}
// DelegatedGuardianConfig contains the threshold and keys for delegated guardians on a specific chain
DelegatedGuardianConfig struct {
Threshold uint8
Keys []common.Address
}
// Attestation interface contains the methods common to all VAA types
Attestation interface {
encoding.BinaryMarshaler
encoding.BinaryUnmarshaler
serializeBody()
signingBody() []byte
SigningMsg() common.Hash
VerifySignatures(addrs []common.Address) bool
UniqueID() string
HexDigest() string
AddSignature(key *ecdsa.PrivateKey, index uint8)
GetEmitterChain() ChainID
}
// number is a constraint for generic functions that can safely convert integer types to a ChainID (uint16).
number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}
)
const (
ConsistencyLevelPublishImmediately = uint8(200)
ConsistencyLevelSafe = uint8(201)
ConsistencyLevelFinalized = uint8(202)
ConsistencyLevelCustom = uint8(203)
)
//nolint:unparam // error is always nil here but the return type is required to satisfy the interface.
func (a Address) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, a)), nil
}
// Standard marshal stores the Address like this: "[0,0,0,0,0,0,0,0,0,0,0,0,2,144,251,22,114,8,175,69,91,177,55,120,1,99,183,183,169,161,12,22]"
// The above MarshalJSON stores it like this (66 bytes): ""0000000000000000000000000290fb167208af455bb137780163b7b7a9a10c16""
func (a *Address) UnmarshalJSON(data []byte) error {
addr, err := StringToAddress(strings.Trim(string(data), `"`))
if err != nil {
return err
}
*a = addr
return nil
}
func (a Address) String() string {
return hex.EncodeToString(a[:])
}
func (a Address) Bytes() []byte {
return a[:]
}
//nolint:unparam // error is always nil here but the return type is required to satisfy the interface.
func (a SignatureData) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, a)), nil
}
func (a SignatureData) String() string {
return hex.EncodeToString(a[:])
}
// ChainIDFromNumber converts an unsigned integer into a ChainID. This function only determines whether the input is valid
// with respect to its type; it does not check whether the ChainID is actually registered or used anywhere.
// This function can be used to validate ChainID values that are deserialized from protobuf messages. (As protobuf
// does not support the uint16 type, ChainIDs are usually encoded as uint32.)
// https://protobuf.dev/reference/protobuf/proto3-spec/#fields
// Returns an error if the argument would overflow uint16.
func ChainIDFromNumber[N number](n N) (ChainID, error) {
if n < 0 {
return ChainIDUnset, fmt.Errorf("chainID cannot be negative but got %d", n)
}
switch any(n).(type) {
case int8, uint8, int16, uint16:
// Because these values have been checked to be non-negative, we can return early with a simple conversion.
return ChainID(n), nil
}
// Use intermediate uint64 to safely handle conversion and allow comparison with MaxUint16.
// This is safe to do because the negative case is already handled.
val := uint64(n)
if val > uint64(math.MaxUint16) {
return ChainIDUnset, fmt.Errorf("chainID must be less than or equal to %d but got %d", math.MaxUint16, n)
}
return ChainID(n), nil
}
// KnownChainIDFromNumber converts an unsigned integer into a known ChainID. It is a wrapper function for ChainIDFromNumber
// that also checks whether the ChainID corresponds to a real, configured chain.
func KnownChainIDFromNumber[N number](n N) (ChainID, error) {
id, err := ChainIDFromNumber(n)
if err != nil {
return ChainIDUnset, err
}
// NOTE: slice.Contains is not used here because some SDK integrators (e.g. wormchain, maybe others) use old versions of Go.
for _, known := range GetAllNetworkIDs() {
if id == known {
return id, nil
}
}
return ChainIDUnset, fmt.Errorf("no known ChainID for input %d", n)
}
// TimeFromUnix converts an integer of any signed or unsigned type into a [time.Time], assuming the value
// represents Unix seconds.
// This function can be used to convert on-chain values that represent timestamps into Go's Time type.
// For example, message publication events parsed from a Wormhole core contract might encode the timestamp in a uint64.
// This function can parse that value into the wire-format value used by a VAA, returning an error if the on-chain value
// does not represent a valid uint32 timestamp value.
//
// Returns an error if the value is negative or exceeds [math.MaxUint32], which
// is the Wormhole protocol's on-wire timestamp precision. See also [VAA.serializeBody]
func TimeFromUnix[N number](n N) (time.Time, error) {
if n < 0 {
return time.Time{}, fmt.Errorf("timestamp cannot be negative but got %d", n)
}
// Use intermediate uint64 to safely handle conversion and allow comparison with MaxUint32.
val := uint64(n)
if val > uint64(math.MaxUint32) {
return time.Time{}, fmt.Errorf("timestamp must be less than or equal to %d but got %d", math.MaxUint32, n)
}
return time.Unix(int64(n), 0), nil
}
// TimeFromUnixUint32 converts a uint32 of Unix seconds into a [time.Time].
// Unlike [TimeFromUnix], it returns no error: every uint32 is already a valid
// on-wire Wormhole timestamp (0..math.MaxUint32), so the range checks cannot fail.
//
// ANTI-PATTERN: only call this with a value whose type is already uint32. Never
// convert another type to uint32 to reach this function, e.g.
// TimeFromUnixUint32(uint32(x)). For a signed value the conversion turns a
// negative number into a large positive one, and for a wider unsigned value it
// drops the high bits; either way it silently produces a wrong timestamp and
// bypasses the validation [TimeFromUnix] performs. For any non-uint32 value,
// call [TimeFromUnix] and check the error.
func TimeFromUnixUint32(n uint32) time.Time {
return time.Unix(int64(n), 0)
}
// StringToKnownChainID converts from a string representation of a chain into a ChainID that is registered in the SDK.
// The argument can be either a numeric string representation of a number or a known chain name such as "solana".
// Inputs of unknown ChainIDs, including 0, will result in an error.
func StringToKnownChainID(s string) (ChainID, error) {
// Try to convert from chain name first, and return early if it's found.
id, err := ChainIDFromString(s)
if err == nil {
return id, nil
}
// Ensure that the string can be parsed into a uint16 in order to avoid overflow issues when converting
// to ChainID (which is a uint16).
u16, err := strconv.ParseUint(s, 10, 16)
if err != nil {
return ChainIDUnset, err
}
return KnownChainIDFromNumber(u16)
}
// NOTE: Please keep these in numerical order.
const (
ChainIDUnset ChainID = 0
// ChainIDSolana is the ChainID of Solana
ChainIDSolana ChainID = 1
// ChainIDEthereum is the ChainID of Ethereum
ChainIDEthereum ChainID = 2
// OBSOLETE: ChainIDTerra ChainID = 3
// ChainIDBSC is the ChainID of Binance Smart Chain
ChainIDBSC ChainID = 4
// ChainIDPolygon is the ChainID of Polygon
ChainIDPolygon ChainID = 5
// ChainIDAvalanche is the ChainID of Avalanche
ChainIDAvalanche ChainID = 6
// OBSOLETE: ChainIDOasis ChainID = 7
// ChainIDAlgorand is the ChainID of Algorand
ChainIDAlgorand ChainID = 8
// OBSOLETE: ChainIDAurora ChainID = 9
// OBSOLETE: ChainIDFantom ChainID = 10
// OBSOLETE: ChainIDKarura ChainID = 11
// OBSOLETE: ChainIDAcala ChainID = 12
// ChainIDKlaytn is the ChainID of Klaytn
ChainIDKlaytn ChainID = 13
// ChainIDCelo is the ChainID of Celo
ChainIDCelo ChainID = 14
// ChainIDNear is the ChainID of Near
ChainIDNear ChainID = 15
// ChainIDMoonbeam is the ChainID of Moonbeam
ChainIDMoonbeam ChainID = 16
// OBSOLETE: ChainIDNeon ChainID = 17
// WARNING: ChainIDTerra2 is only supported in devnet / Tilt.
ChainIDTerra2 ChainID = 18
// ChainIDInjective is the ChainID of Injective
ChainIDInjective ChainID = 19
// ChainIDOsmosis is the ChainID of Osmosis
ChainIDOsmosis ChainID = 20
// ChainIDSui is the ChainID of Sui
ChainIDSui ChainID = 21
// ChainIDAptos is the ChainID of Aptos
ChainIDAptos ChainID = 22
// ChainIDArbitrum is the ChainID of Arbitrum
ChainIDArbitrum ChainID = 23
// ChainIDOptimism is the ChainID of Optimism
ChainIDOptimism ChainID = 24
// ChainIDGnosis is the ChainID of Gnosis
ChainIDGnosis ChainID = 25
// ChainIDPythNet is the ChainID of PythNet
ChainIDPythNet ChainID = 26
// NOTE: 27 belongs to a chain that was never deployed.
// OBSOLETE: ChainIDXpla ChainID = 28
// ChainIDBtc is the ChainID of Bitcoin
ChainIDBtc ChainID = 29
// ChainIDBase is the ChainID of Base
ChainIDBase ChainID = 30
// ChainIDFileCoin is the ChainID of FileCoin
ChainIDFileCoin ChainID = 31
// ChainIDSei is the ChainID of Sei
ChainIDSei ChainID = 32
// ChainIDRootstock is the ChainID of Rootstock
ChainIDRootstock ChainID = 33
// OBSOLETE: ChainIDScroll ChainID = 34
// OBSOLETE: ChainIDMantle ChainID = 35
// OBSOLETE: ChainIDBlast ChainID = 36
// OBSOLETE: ChainIDXLayer ChainID = 37
// ChainIDLinea is the ChainID of Linea
ChainIDLinea ChainID = 38
// ChainIDBerachain is the ChainID of Berachain
ChainIDBerachain ChainID = 39
// ChainIDSeiEVM is the ChainID of SeiEVM
ChainIDSeiEVM ChainID = 40
// ChainIDEclipse is the ChainID of Eclipse
ChainIDEclipse ChainID = 41
// ChainIDBOB is the ChainID of BOB
ChainIDBOB ChainID = 42
// OBSOLETE: ChainIDSnaxchain ChainID = 43
// ChainIDUnichain is the ChainID of Unichain
ChainIDUnichain ChainID = 44
// ChainIDWorldchain is the ChainID of Worldchain
ChainIDWorldchain ChainID = 45
// ChainIDInk is the ChainID of Ink
ChainIDInk ChainID = 46
// ChainIDHyperEVM is the ChainID of HyperEVM
ChainIDHyperEVM ChainID = 47
// ChainIDMonad is the ChainID of Monad
ChainIDMonad ChainID = 48
// ChainIDMovement is the ChainID of Movement
ChainIDMovement ChainID = 49
// ChainIDMezo is the ChainID of Mezo
ChainIDMezo ChainID = 50
// ChainIDFogo is the ChainID of Fogo
ChainIDFogo ChainID = 51
// ChainIDSonic is the ChainID of Sonic
ChainIDSonic ChainID = 52
// ChainIDConverge is the ChainID of Converge
ChainIDConverge ChainID = 53
// ChainIDCodex is the ChainID of Codex
ChainIDCodex ChainID = 54
// ChainIdPlume is the ChainID of Plume
ChainIDPlume ChainID = 55
// ChainIdAztec is the ChainID of Aztec
ChainIDAztec ChainID = 56
// ChainIdXRPLEVM is the ChainID of XRPL-EVM
ChainIDXRPLEVM ChainID = 57
// ChainIDPlasma is the ChainID of Plasma
ChainIDPlasma ChainID = 58
// ChainIDCreditCoin is the ChainID of CreditCoin
ChainIDCreditCoin ChainID = 59
// ChainIDStacks is the ChainID of Stacks
ChainIDStacks ChainID = 60
// ChainIDStellar is the ChainID of Stellar
ChainIDStellar ChainID = 61
// ChainIDTON is the ChainID of TON
ChainIDTON ChainID = 62
// ChainIDMoca is the ChainID of Moca
ChainIDMoca ChainID = 63
// ChainIDMegaETH is the ChainID of MegaETH
ChainIDMegaETH ChainID = 64
// ChainIDDogecoin is the ChainID of Dogecoin
ChainIDDogecoin ChainID = 65
// ChainIDXRPL is the ChainID of XRP Ledger
ChainIDXRPL ChainID = 66
// ChainIDZeroGravity is the ChainID of ZeroGravity,
ChainIDZeroGravity ChainID = 67
// ChainIDTempo is the ChainID of Tempo
ChainIDTempo ChainID = 68
// ChainIDNexus is the ChainID of Nexus
ChainIDNexus ChainID = 69
// ChainIDTron is the ChainID of Tron
ChainIDTron ChainID = 70
// ChainIDArc is the ChainID of Arc
ChainIDArc ChainID = 71
// ChainIDRobinhoodChain is the ChainID of Robinhood Chain
ChainIDRobinhoodChain ChainID = 72
// ChainIDHydration is the ChainID of Hydration
ChainIDHydration ChainID = 73
// ChainIDElysium is the ChainID of Elysium
ChainIDElysium ChainID = 74
// ChainIDWormchain is the ChainID of Wormchain and is in its own range.
ChainIDWormchain ChainID = 3104
// The IBC chains start at 4000.
// ChainIDCosmoshub is the ChainID of Cosmoshub
ChainIDCosmoshub ChainID = 4000
// ChainIDEvmos is the ChainID of Evmos
ChainIDEvmos ChainID = 4001
// ChainIDKujira is the ChainID of Kujira
ChainIDKujira ChainID = 4002
// ChainIDNeutron is the ChainID of Neutron
ChainIDNeutron ChainID = 4003
// ChainIDCelestia is the ChainID of Celestia
ChainIDCelestia ChainID = 4004
// ChainIDStargaze is the ChainID of Stargaze
ChainIDStargaze ChainID = 4005
// ChainIDSeda is the ChainID of Seda
ChainIDSeda ChainID = 4006
// ChainIDDymension is the ChainID of Dymension
ChainIDDymension ChainID = 4007
// ChainIDProvenance is the ChainID of Provenance
ChainIDProvenance ChainID = 4008
// ChainIDNoble is the ChainID of Noble
ChainIDNoble ChainID = 4009
// The Testnet only chains start at 10000.
// ChainIDSepolia is the ChainID of Sepolia
ChainIDSepolia ChainID = 10002
// ChainIDArbitrumSepolia is the ChainID of Arbitrum on Sepolia
ChainIDArbitrumSepolia ChainID = 10003
// ChainIDBaseSepolia is the ChainID of Base on Sepolia
ChainIDBaseSepolia ChainID = 10004
// ChainIDOptimismSepolia is the ChainID of Optimism on Sepolia
ChainIDOptimismSepolia ChainID = 10005
// ChainIDHolesky is the ChainID of Holesky
ChainIDHolesky ChainID = 10006
// ChainIDPolygonSepolia is the ChainID of Polygon on Sepolia
ChainIDPolygonSepolia ChainID = 10007
// OBSOLETE: ChainIDMonadDevnet ChainID = 10008
ChainIDMonadTestnet ChainID = 10009
// Special or bespoke chains start at 60000.
// ChainIDHyperCore is the ChainID of HyperCore (ID taken from Mayan)
ChainIDHyperCore ChainID = 65000
// Minimum VAA size is derrived from the following assumptions:
// HEADER
// - Supported VAA Version (1 byte)
// - Guardian Set Index (4 bytes)
// - Length of Signatures (1 byte) <== assume no signatures
// - Actual Signatures (0 bytes)
// BODY
// - timestamp (4 bytes)
// - nonce (4 bytes)
// - emitter chain (2 bytes)
// - emitter address (32 bytes)
// - sequence (8 bytes)
// - consistency level (1 byte)
// - payload (0 bytes)
// BATCH
// - Length of Observation Hashes (1 byte) <== minimum one
// - Observation Hash (32 bytes)
// - Length of Observations (1 byte) <== minimum one
// - Observation Index (1 byte)
// - Observation Length (1 byte)
// - Observation, aka BODY, aka Headless (51 bytes)
// From Above:
// HEADER: 1 + 4 + 1 + 0 = 6
// BODY: 4 + 4 + 2 + 32 + 8 + 1 + 0 = 51
// BATCH: 1 + 32 + 1 + 1 + 1 + 51 = 88
//
// More details here: https://docs.wormholenetwork.com/wormhole/vaas
minHeadlessVAALength = 51 // HEADER
minVAALength = 57 // HEADER + BODY
SupportedVAAVersion = 0x01
)
// UnmarshalBody deserializes the binary representation of a VAA's "BODY" properties
// The BODY fields are common among multiple types of VAA - v1, v2, etc
// parameter. This function should probably be reworked as a method of the VAA type.
//
//nolint:unparam // TODO: The argument data is not used here. Instead data is read from the VAA
func UnmarshalBody(data []byte, reader *bytes.Reader, v *VAA) (*VAA, error) {
unixSeconds := uint32(0)
if err := binary.Read(reader, binary.BigEndian, &unixSeconds); err != nil {
return nil, fmt.Errorf("failed to read timestamp: %w", err)
}
v.Timestamp = time.Unix(int64(unixSeconds), 0)
if err := binary.Read(reader, binary.BigEndian, &v.Nonce); err != nil {
return nil, fmt.Errorf("failed to read nonce: %w", err)
}
if err := binary.Read(reader, binary.BigEndian, &v.EmitterChain); err != nil {
return nil, fmt.Errorf("failed to read emitter chain: %w", err)
}
emitterAddress := Address{}
if n, err := reader.Read(emitterAddress[:]); err != nil || n != 32 {
return nil, fmt.Errorf("failed to read emitter address [%d]: %w", n, err)
}
v.EmitterAddress = emitterAddress
if err := binary.Read(reader, binary.BigEndian, &v.Sequence); err != nil {
return nil, fmt.Errorf("failed to read sequence: %w", err)
}
if err := binary.Read(reader, binary.BigEndian, &v.ConsistencyLevel); err != nil {
return nil, fmt.Errorf("failed to read commitment: %w", err)
}
// Make sure to only read the payload if the VAA has one; VAAs may have a 0 length payload
if reader.Len() != 0 {
payload := make([]byte, reader.Len())
n, err := reader.Read(payload)
if err != nil {
return nil, fmt.Errorf("failed to read payload [%d]: %w", n, err)
}
v.Payload = payload[:n]
} else {
v.Payload = []byte{}
}
return v, nil
}
// Unmarshal deserializes the binary representation of a VAA
func Unmarshal(data []byte) (*VAA, error) {
if len(data) < minVAALength {
return nil, fmt.Errorf("VAA is too short")
}
v := &VAA{}
v.Version = data[0]
if v.Version != SupportedVAAVersion {
return nil, fmt.Errorf("unsupported VAA version: %d", v.Version)
}
reader := bytes.NewReader(data[1:])
if err := binary.Read(reader, binary.BigEndian, &v.GuardianSetIndex); err != nil {
return nil, fmt.Errorf("failed to read guardian set index: %w", err)
}
lenSignatures, er := reader.ReadByte()
if er != nil {
return nil, fmt.Errorf("failed to read signature length")
}
v.Signatures = make([]*Signature, lenSignatures)
for i := 0; i < int(lenSignatures); i++ {
index, err := reader.ReadByte()
if err != nil {
return nil, fmt.Errorf("failed to read validator index [%d]", i)
}
signature := [65]byte{}
if n, err := reader.Read(signature[:]); err != nil || n != 65 {
return nil, fmt.Errorf("failed to read signature [%d]: %w", i, err)
}
v.Signatures[i] = &Signature{
Index: index,
Signature: signature,
}
}
return UnmarshalBody(data, reader, v)
}
// signingBody returns the binary representation of the data that is relevant for signing and verifying the VAA
func (v *VAA) signingBody() []byte {
return v.serializeBody()
}
func doubleKeccak(bz []byte) common.Hash {
// In order to save space in the solana signature verification instruction, we hash twice so we only need to pass in
// the first hash (32 bytes) vs the full body data.
return crypto.Keccak256Hash(crypto.Keccak256Hash(bz).Bytes())
}
// This is a temporary method to produce a vaa signing digest on raw bytes.
// It is error prone and we should use `v.SigningDigest()` instead.
// whenever possible.
// This will be removed in a subsequent release.
func DeprecatedSigningDigest(bz []byte) common.Hash {
return doubleKeccak(bz)
}
// MessageSigningDigest returns the hash of the data prepended with it's signing prefix.
// This is intending to be used for signing messages of different types from VAA's.
// The message prefix helps protect from message collisions.
func MessageSigningDigest(prefix []byte, data []byte) (common.Hash, error) {
if len(prefix) < 32 {
// Prefixes must be at least 32 bytes
// https://github.com/wormhole-foundation/wormhole/blob/main/whitepapers/0009_guardian_signer.md
return common.Hash([32]byte{}), errors.New("prefix must be at least 32 bytes")
}
return crypto.Keccak256Hash(prefix[:], data), nil
}
// SigningDigest returns the hash of the vaa hash to be signed directly.
// This is used for signature generation and verification
func (v *VAA) SigningDigest() common.Hash {
return doubleKeccak(v.signingBody())
}
// Verify Signature checks that the provided address matches the address that created the signature for the provided digest
// Digest should be the output of SigningMsg(data).Bytes()
// Should not be public as other message types should be verified using a message prefix.
func verifySignature(vaa_digest []byte, signature *Signature, address common.Address) bool {
// retrieve the address that signed the data
pubKey, err := crypto.Ecrecover(vaa_digest, signature.Signature[:])
if err != nil {
return false
}
addr := common.BytesToAddress(crypto.Keccak256(pubKey[1:])[12:])
// check that the recovered address equals the provided address
return addr == address
}
// Digest should be the output of SigningMsg(data).Bytes()
// Should not be public as other message types should be verified using a message prefix.
// Returns false when the signatures or addresses are empty.
func verifySignatures(vaa_digest []byte, signatures []*Signature, addresses []common.Address) bool {
// An empty set is neither valid nor invalid, it's just specified incorrectly.
// To help with backward-compatibility, return false instead of changing the function
// signature to return an error.
if len(signatures) == 0 || len(addresses) == 0 {
return false
}
if len(addresses) < len(signatures) {
return false
}
last_index := -1
signing_addresses := []common.Address{}
for _, sig := range signatures {
if int(sig.Index) >= len(addresses) {
return false
}
// Ensure increasing indexes
if int(sig.Index) <= last_index {
return false
}
last_index = int(sig.Index)
// verify this signature
addr := addresses[sig.Index]
ok := verifySignature(vaa_digest, sig, addr)
if !ok {
return false
}
// Ensure we never see the same signer twice
for _, signing_address := range signing_addresses {
if signing_address == addr {
return false
}
}
signing_addresses = append(signing_addresses, addr)
}
return true
}
// Operating on bytes directly is error prone. We should use `vaa.VerifyingSignatures()` whenever possible.
// This function will be removed in a subsequent release.
func DeprecatedVerifySignatures(vaaBody []byte, signatures []*Signature, addresses []common.Address) bool {
vaaDigest := doubleKeccak(vaaBody)
return verifySignatures(vaaDigest[:], signatures, addresses)
}
func VerifyMessageSignature(prefix []byte, messageBody []byte, signatures *Signature, addresses common.Address) bool {
if len(prefix) < 32 {
return false
}
msgDigest, err := MessageSigningDigest(prefix, messageBody)
if err != nil {
return false
}
return verifySignature(msgDigest[:], signatures, addresses)
}
// VerifySignatures verifies the signature of the VAA given the signer addresses.
// Returns true if the signatures were verified successfully.
// Returns false when the signatures or addresses are empty.
//
// WARNING: This function is not sufficient for validating a VAA as it does not consider
// signature quorum. [VAA.Verify] should be used instead.
func (v *VAA) VerifySignatures(addresses []common.Address) bool {
return verifySignatures(v.SigningDigest().Bytes(), v.Signatures, addresses)
}
// Verify is a function on the VAA that takes a complete set of guardian keys as input and attempts certain checks with respect to this guardian.
// Verify will return nil if the VAA passes checks. Otherwise, Verify will return an error containing the text of the first check to fail.
// NOTE: Verify will not work correctly if a subset of the guardian set keys is passed in. The complete guardian set must be passed in.
// Verify does the following checks:
// - If the guardian does not have or know its own guardian set keys, then the VAA cannot be verified.
// - Quorum is calculated on the guardian set passed in and checks if the VAA has enough signatures.
// - The signatures in the VAA is verified against the guardian set keys.
func (v *VAA) Verify(addresses []common.Address) error {
if addresses == nil {
return errors.New("no addresses were provided")
}
// Check if VAA doesn't have any signatures
if len(v.Signatures) == 0 {
return errors.New("VAA was not signed")
}
// Verify VAA has enough signatures for quorum
quorum := CalculateQuorum(len(addresses))
if len(v.Signatures) < quorum {
return errors.New("VAA did not have a quorum")
}
// Verify VAA signatures to prevent a DoS attack on our local store.
if !v.VerifySignatures(addresses) {
return errors.New("VAA had bad signatures")
}
return nil
}
// Marshal returns the binary representation of the VAA
func (v *VAA) Marshal() ([]byte, error) {
buf := new(bytes.Buffer)
MustWrite(buf, binary.BigEndian, v.Version)
MustWrite(buf, binary.BigEndian, v.GuardianSetIndex)
// Write signatures
MustWrite(buf, binary.BigEndian, uint8(len(v.Signatures))) // #nosec G115 -- There will never be 256 guardians
for _, sig := range v.Signatures {
MustWrite(buf, binary.BigEndian, sig.Index)
buf.Write(sig.Signature[:])
}
// Write Body
buf.Write(v.serializeBody())
return buf.Bytes(), nil
}
// implement encoding.BinaryMarshaler interface for the VAA struct
func (v VAA) MarshalBinary() ([]byte, error) {
return v.Marshal()
}
// implement encoding.BinaryUnmarshaler interface for the VAA struct
func (v *VAA) UnmarshalBinary(data []byte) error {
vaa, err := Unmarshal(data)
if err != nil {
return err
}
// derefernce the stuct created by Unmarshal, and assign it to the method's context
*v = *vaa
return nil
}
// MessageID returns a human-readable emitter_chain/emitter_address/sequence tuple.
func (v *VAA) MessageID() string {
return fmt.Sprintf("%d/%s/%d", v.EmitterChain, v.EmitterAddress, v.Sequence)
}
// UniqueID normalizes the ID of the VAA (any type) for the Attestation interface
// UniqueID returns the MessageID that uniquely identifies the Attestation
func (v *VAA) UniqueID() string {
return v.MessageID()
}
// HexDigest returns the hex-encoded digest.
func (v *VAA) HexDigest() string {
return hex.EncodeToString(v.SigningDigest().Bytes())
}
/*
SECURITY: Do not change this code! Changing it could result in two different hashes for
the same observation. But xDapps rely on the hash of an observation for replay protection.
*/
func (v *VAA) serializeBody() []byte {
buf := new(bytes.Buffer)
MustWrite(buf, binary.BigEndian, uint32(v.Timestamp.Unix())) // #nosec G115 -- This conversion is safe until year 2106
MustWrite(buf, binary.BigEndian, v.Nonce)
MustWrite(buf, binary.BigEndian, v.EmitterChain)
buf.Write(v.EmitterAddress[:])
MustWrite(buf, binary.BigEndian, v.Sequence)
MustWrite(buf, binary.BigEndian, v.ConsistencyLevel)
buf.Write(v.Payload)
return buf.Bytes()
}
func (v *VAA) AddSignature(key *ecdsa.PrivateKey, index uint8) {
sig, err := crypto.Sign(v.SigningDigest().Bytes(), key)
if err != nil {
panic(err)
}
sigData := [65]byte{}
copy(sigData[:], sig)
v.Signatures = append(v.Signatures, &Signature{
Index: index,
Signature: sigData,
})
}
// isTransfer returns true if the VAA appears to be a Wrapped Token Transfer by checking the payload type.
// It does not apply to Native Token Transfers.
// NOTE: This check is necessary but not sufficient for verifying the VAA as it does not consider
// whether the VAA is sent emitted by a token bridge. Use IsWTT() from the SDK instead.
func IsTransfer(payload []byte) bool {
return (len(payload) > 0) && ((payload[0] == 1) || (payload[0] == 3))
}
func DecodeTransferPayloadHdr(payload []byte) (*TransferPayloadHdr, error) {
if !IsTransfer(payload) {
return nil, fmt.Errorf("unsupported payload type")
}
if len(payload) < 101 {
return nil, fmt.Errorf("buffer too short")
}
p := &TransferPayloadHdr{}
// Payload type: payload[0]
p.Type = uint8(payload[0])
// Amount: payload[1] for 32
p.Amount = new(big.Int)
p.Amount.SetBytes(payload[1:33])
reader := bytes.NewReader(payload[33:])
// Origin address: payload[33] for 32
err := binary.Read(reader, binary.BigEndian, &p.OriginAddress)
if err != nil {
return nil, err
}
// Origin chain ID: payload[65] for 2
err = binary.Read(reader, binary.BigEndian, &p.OriginChain)
if err != nil {
return nil, err
}
// Target address: payload[67] for 32
err = binary.Read(reader, binary.BigEndian, &p.TargetAddress)
if err != nil {
return nil, err
}
// Target chain ID: payload[99] for 2
err = binary.Read(reader, binary.BigEndian, &p.TargetChain)
if err != nil {
return nil, err
}
return p, nil
}
// GetEmitterChain implements the processor.Observation interface for *VAA.
func (v *VAA) GetEmitterChain() ChainID {
return v.EmitterChain
}
// MustWrite calls binary.Write and panics on errors
func MustWrite(w io.Writer, order binary.ByteOrder, data interface{}) {
if err := binary.Write(w, order, data); err != nil {
panic(fmt.Errorf("failed to write binary data: %v", data).Error())
}
}
// StringToAddress converts a hex-encoded address into a vaa.Address
func StringToAddress(value string) (Address, error) {
var address Address
// Make sure we have enough to decode
if len(value) < 2 {
return address, fmt.Errorf("value must be at least 1 byte")
}
// Trim any preceding "0x" to the address
value = strings.TrimPrefix(value, "0x")
// Decode the string from hex to binary
res, err := hex.DecodeString(value)
if err != nil {
return address, err
}
// Make sure we don't have too many bytes
if len(res) > 32 {
return address, fmt.Errorf("value must be no more than 32 bytes")
}
copy(address[32-len(res):], res)
return address, nil
}
func BytesToAddress(b []byte) (Address, error) {
var address Address
if len(b) > 32 {
return address, fmt.Errorf("value must be no more than 32 bytes")
}
copy(address[32-len(b):], b)
return address, nil
}
// StringToHash converts a hex-encoded string into a common.Hash
func StringToHash(value string) (common.Hash, error) {
var tx common.Hash
// Make sure we have enough to decode
if len(value) < 2 {
return tx, fmt.Errorf("value must be at least 1 byte")
}
// Trim any preceding "0x" to the address
value = strings.TrimPrefix(value, "0x")
res, err := hex.DecodeString(value)
if err != nil {
return tx, err
}
tx = common.BytesToHash(res)
return tx, nil
}
func BytesToHash(b []byte) (common.Hash, error) {
var hash common.Hash
if len(b) > 32 {
return hash, fmt.Errorf("value must be no more than 32 bytes")
}
hash = common.BytesToHash(b)
return hash, nil
}
// DebugString returns a pretty-formatted JSON string representation of the VAA.
func (v *VAA) DebugString() (string, error) {
jsonBytes, err := json.MarshalIndent(v, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal VAA to JSON for debugging: %w", err)
}
return string(jsonBytes), nil
}