/
v1.go
1062 lines (872 loc) · 28.4 KB
/
v1.go
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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Sequence v1 core primitives
package v1
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"math"
"math/big"
"github.com/0xsequence/ethkit/ethcoder"
"github.com/0xsequence/ethkit/ethcontract"
"github.com/0xsequence/ethkit/ethrpc"
"github.com/0xsequence/ethkit/go-ethereum/accounts/abi/bind"
"github.com/0xsequence/ethkit/go-ethereum/common"
"github.com/0xsequence/ethkit/go-ethereum/common/hexutil"
"github.com/0xsequence/ethkit/go-ethereum/crypto"
"github.com/0xsequence/go-sequence/contracts"
"github.com/0xsequence/go-sequence/core"
)
var isValidSignatureMagicValue = [4]byte{0x16, 0x26, 0xba, 0x7e}
var Core core.Core[*WalletConfig, core.Signature[*WalletConfig]] = v1Core{}
func init() {
core.RegisterCore(Core)
}
type v1Core struct{}
func (v1Core) DecodeSignature(data []byte) (core.Signature[*WalletConfig], error) {
threshold, err := readUint16(&data)
if err != nil {
return nil, fmt.Errorf("missing signature threshold: %w", err)
}
var leaves []signatureLeaf
for len(data) != 0 {
var leaf signatureLeaf
switch data[0] {
case byte(signatureLeafTypeECDSASignature):
leaf, err = decodeSignatureTreeECDSASignatureLeaf(&data)
if err != nil {
return nil, fmt.Errorf("unable to decode ecdsa signature leaf %v: %w", len(leaves), err)
}
case byte(signatureLeafTypeAddress):
leaf, err = decodeSignatureTreeAddressLeaf(&data)
if err != nil {
return nil, fmt.Errorf("unable to decode address leaf %v: %w", len(leaves), err)
}
case byte(signatureLeafTypeDynamicSignature):
leaf, err = decodeSignatureTreeDynamicSignatureLeaf(&data)
if err != nil {
return nil, fmt.Errorf("unable to decode dynamic signature leaf %v: %w", len(leaves), err)
}
default:
return nil, fmt.Errorf("unknown signature leaf type %v for leaf %v", data[0], len(leaves))
}
leaves = append(leaves, leaf)
}
return &signature{threshold, leaves}, nil
}
func (v1Core) DecodeWalletConfig(object any) (*WalletConfig, error) {
object_, ok := object.(map[string]any)
if !ok {
return nil, fmt.Errorf("wallet config must be an object")
}
threshold, ok := object_["threshold"]
if !ok {
return nil, fmt.Errorf(`missing required "threshold" property`)
}
threshold_, err := toUint16(threshold)
if err != nil {
return nil, fmt.Errorf("unable to convert threshold: %w", err)
}
signers, ok := object_["signers"]
if !ok {
return nil, fmt.Errorf(`missing required "signers" property`)
}
signers_, ok := signers.([]any)
if !ok {
signers__, ok := signers.([]map[string]any)
if !ok {
return nil, fmt.Errorf("signers must be an array")
}
signers_ = make([]any, 0, len(signers__))
for _, signer := range signers__ {
signers_ = append(signers_, signer)
}
}
signers__ := make([]*WalletConfigSigner, 0, len(signers_))
for i, signer := range signers_ {
signer_, err := decodeWalletConfigSigner(signer)
if err != nil {
return nil, fmt.Errorf("signer %v is invalid: %w", i, err)
}
signers__ = append(signers__, signer_)
}
return &WalletConfig{
Threshold_: threshold_,
Signers_: signers__,
}, nil
}
type signerSignature struct {
signer common.Address
type_ core.SignerSignatureType
signature []byte
}
type signature struct {
threshold uint16
leaves []signatureLeaf
}
func (s *signature) Threshold() uint16 {
return s.threshold
}
func (s *signature) Checkpoint() uint32 {
return 0
}
func (s *signature) Recover(ctx context.Context, digest core.Digest, wallet common.Address, chainID *big.Int, provider *ethrpc.Provider, signerSignatures ...core.SignerSignatures) (*WalletConfig, *big.Int, error) {
if chainID == nil {
if provider == nil {
return nil, nil, fmt.Errorf("provider is required if chain ID is not specified")
}
var err error
chainID, err = provider.ChainID(ctx)
if err != nil {
return nil, nil, fmt.Errorf("unable to get chain ID: %w", err)
}
}
subdigest := digest.Subdigest(wallet, chainID)
return s.RecoverSubdigest(ctx, subdigest, provider, signerSignatures...)
}
func (s *signature) RecoverSubdigest(ctx context.Context, subDigest core.Subdigest, provider *ethrpc.Provider, signerSignatures ...core.SignerSignatures) (*WalletConfig, *big.Int, error) {
if len(signerSignatures) == 0 {
signerSignatures = []core.SignerSignatures{nil}
}
var signers []*WalletConfigSigner
var total big.Int
for i, leaf := range s.leaves {
signer, weight, err := leaf.recover(ctx, subDigest, provider, signerSignatures[0])
if err != nil {
return nil, nil, fmt.Errorf("unable to recover signer for leaf %v: %w", i, err)
}
signers = append(signers, signer)
total.Add(&total, weight)
}
return &WalletConfig{
Threshold_: s.threshold,
Signers_: signers,
}, &total, nil
}
const (
eoaCost = 3000 + 65*16
addressCost = 20 * 16
)
func (s *signature) Join(subdigest core.Subdigest, other core.Signature[*WalletConfig]) (core.Signature[*WalletConfig], error) {
var copyLeafs = make([]signatureLeaf, len(s.leaves))
copy(copyLeafs, s.leaves)
leafAddress := func(leaf2 signatureLeaf) (common.Address, core.SignerSignatureType, error) {
switch leaf2 := leaf2.(type) {
case *signatureTreeECDSASignatureLeaf:
address, err := ecrecover(subdigest.EthSignSubdigest(), leaf2.signature[:])
return address, core.SignerSignatureTypeEthSign, err
case *signatureTreeAddressLeaf:
return leaf2.address, 0, nil
case *signatureTreeDynamicSignatureLeaf:
return leaf2.address, core.SignerSignatureTypeEIP1271, nil
default:
panic(fmt.Errorf("unknown signature leaf type %T", leaf2))
}
}
for index, leaf := range copyLeafs {
lAddress, lType, _ := leafAddress(leaf)
if lType == 0 {
for _, leaf2 := range other.(*signature).leaves {
l2Address, l2Type, err := leafAddress(leaf2)
if err != nil {
continue
}
if lAddress == l2Address && (l2Type == core.SignerSignatureTypeEthSign ||
l2Type == core.SignerSignatureTypeEIP1271) {
copyLeafs[index] = leaf2
}
}
}
}
return &signature{
threshold: s.threshold,
leaves: copyLeafs,
}, nil
}
func (s *signature) Reduce(subdigest core.Subdigest) core.Signature[*WalletConfig] {
var leaves []signatureLeaf
var weights []int
var costs []int
var weight int
addresses := make([]common.Address, len(s.leaves))
for i, leaf := range s.leaves {
switch leaf := leaf.(type) {
case *signatureTreeECDSASignatureLeaf:
var err error
addresses[i], err = ecrecover(subdigest, leaf.signature[:])
if err == nil {
leaves = append(leaves, leaf)
weights = append(weights, int(leaf.weight))
costs = append(costs, eoaCost)
weight += int(leaf.weight)
} else {
// never prune an EOA signature that cannot be recovered
leaves = append(leaves, leaf)
weights = append(weights, math.MaxInt32)
costs = append(costs, eoaCost)
weight += int(leaf.weight)
}
case *signatureTreeAddressLeaf:
leaves = append(leaves, leaf)
weights = append(weights, math.MaxInt32)
costs = append(costs, addressCost)
case *signatureTreeDynamicSignatureLeaf:
value, cost := leaf.signature, eoaCost
if subsignature, err := Core.DecodeSignature(leaf.signature); err == nil {
subsignature = subsignature.Reduce(subdigest)
if cost, err = subsignature.(*signature).cost(); err == nil {
value, _ = subsignature.Data()
}
}
leaves = append(leaves, &signatureTreeDynamicSignatureLeaf{
weight: leaf.weight,
address: leaf.address,
type_: leaf.type_,
signature: value,
})
weights = append(weights, int(leaf.weight))
costs = append(costs, cost)
weight += int(leaf.weight)
}
}
if weight > int(s.threshold) {
// This signature possesses more weight than is necessary to meet the threshold.
// Solve the knapsack problem to find the optimal sub-signatures to prune.
_, redundant := knapsack(weight-int(s.threshold), weights, costs)
for _, i := range redundant {
switch leaf := leaves[i].(type) {
case *signatureTreeECDSASignatureLeaf:
leaves[i] = &signatureTreeAddressLeaf{
weight: leaf.weight,
address: addresses[i],
}
case *signatureTreeAddressLeaf:
panic("address leaf is redundant")
case *signatureTreeDynamicSignatureLeaf:
leaves[i] = &signatureTreeAddressLeaf{
weight: leaf.weight,
address: leaf.address,
}
}
}
}
return &signature{
threshold: s.threshold,
leaves: leaves,
}
}
// Estimates the gas needed to encode and validate this signature
func (s *signature) cost() (int, error) {
var cost int
for _, leaf := range s.leaves {
switch leaf := leaf.(type) {
case *signatureTreeECDSASignatureLeaf:
cost += eoaCost
case *signatureTreeAddressLeaf:
cost += addressCost
case *signatureTreeDynamicSignatureLeaf:
subsignature, err := Core.DecodeSignature(leaf.signature)
if err != nil {
return 0, err
}
dynamicCost, err := subsignature.(*signature).cost()
if err != nil {
return 0, err
}
cost += dynamicCost
}
}
cost++ // perturb the cost ever so slightly to bias against nesting
return cost, nil
}
// Solves the knapsack problem
func knapsack(capacity int, weights []int, values []int) (int, []int) {
// m[i][j] = maximum value achievable using only first i items up to capacity j
m := [][]int{make([]int, capacity+1)}
for range weights {
m = append(m, make([]int, capacity+1))
}
for i, w := range weights {
for j := 0; j <= capacity; j++ {
m[i+1][j] = m[i][j]
if j >= w && m[i+1][j] < m[i][j-w]+values[i] {
m[i+1][j] = m[i][j-w] + values[i]
}
}
}
var s []int
j := capacity
for i := len(weights) - 1; i >= 0; i-- {
if m[i+1][j] != m[i][j] {
s = append(s, i)
j -= weights[i]
}
}
return m[len(weights)][capacity], s
}
func (s *signature) Data() ([]byte, error) {
var buffer bytes.Buffer
err := s.Write(&buffer)
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func (s *signature) Write(writer io.Writer) error {
err := binary.Write(writer, binary.BigEndian, s.threshold)
if err != nil {
return fmt.Errorf("unable to write signature threshold: %w", err)
}
for i, leaf := range s.leaves {
err = leaf.write(writer)
if err != nil {
return fmt.Errorf("unable to write signature leaf %v: %w", i, err)
}
}
return nil
}
func (s *signature) String() string {
data, _ := s.Data()
return hexutil.Encode(data)
}
type signatureLeaf interface {
recover(ctx context.Context, subdigest core.Subdigest, provider *ethrpc.Provider, signerSignatures core.SignerSignatures) (*WalletConfigSigner, *big.Int, error)
write(writer io.Writer) error
}
type signatureLeafType byte
const (
signatureLeafTypeECDSASignature signatureLeafType = 0
signatureLeafTypeAddress signatureLeafType = 1
signatureLeafTypeDynamicSignature signatureLeafType = 2
)
type eCDSASignatureType byte
const (
eCDSASignatureTypeEIP712 eCDSASignatureType = 1
eCDSASignatureTypeEthSign eCDSASignatureType = 2
)
func (t eCDSASignatureType) signerSignatureType() core.SignerSignatureType {
switch t {
case eCDSASignatureTypeEIP712:
return core.SignerSignatureTypeEIP712
case eCDSASignatureTypeEthSign:
return core.SignerSignatureTypeEthSign
default:
panic(fmt.Sprintf("invalid ecdsa signature type %v", t))
}
}
type signatureTreeECDSASignatureLeaf struct {
weight uint8
type_ eCDSASignatureType
signature [crypto.SignatureLength]byte
}
func decodeSignatureTreeECDSASignatureLeaf(data *[]byte) (*signatureTreeECDSASignatureLeaf, error) {
next := *data
if len(next) < 1+1+crypto.SignatureLength+1 {
return nil, fmt.Errorf("insufficient data for ecdsa signature leaf")
}
var leafType byte
var weight byte
var signature []byte
var signatureType byte
leafType, weight, signature, signatureType, next = next[0], next[1], next[1+1:1+1+crypto.SignatureLength], next[1+1+crypto.SignatureLength], next[1+1+crypto.SignatureLength+1:]
if leafType != byte(signatureLeafTypeECDSASignature) {
return nil, fmt.Errorf("expected ecdsa signature leaf type %v, got %v", signatureLeafTypeECDSASignature, leafType)
}
switch signatureType {
case byte(eCDSASignatureTypeEIP712), byte(eCDSASignatureTypeEthSign):
default:
return nil, fmt.Errorf("unknown ecdsa signature type %v", signatureType)
}
*data = next
leaf := signatureTreeECDSASignatureLeaf{
weight: weight,
type_: eCDSASignatureType(signatureType),
}
copy(leaf.signature[:], signature)
return &leaf, nil
}
func (l *signatureTreeECDSASignatureLeaf) recover(ctx context.Context, subdigest core.Subdigest, provider *ethrpc.Provider, signerSignatures core.SignerSignatures) (*WalletConfigSigner, *big.Int, error) {
var address common.Address
var err error
switch l.type_ {
case eCDSASignatureTypeEthSign:
address, err = ecrecover(subdigest.EthSignSubdigest(), l.signature[:])
default:
address, err = ecrecover(subdigest, l.signature[:])
}
if err != nil {
return nil, nil, fmt.Errorf("unable to recover ecdsa signature leaf: %w", err)
}
signerSignatures.Insert(address, core.SignerSignature{
Subdigest: subdigest,
Type: l.type_.signerSignatureType(),
Signature: l.signature[:],
})
return &WalletConfigSigner{
Weight: l.weight,
Address: address,
}, new(big.Int).SetUint64(uint64(l.weight)), nil
}
func (l *signatureTreeECDSASignatureLeaf) write(writer io.Writer) error {
_, err := writer.Write([]byte{byte(signatureLeafTypeECDSASignature)})
if err != nil {
return fmt.Errorf("unable to write ecdsa signature leaf type: %w", err)
}
_, err = writer.Write([]byte{l.weight})
if err != nil {
return fmt.Errorf("unable to write ecdsa signature leaf weight: %w", err)
}
_, err = writer.Write(l.signature[:])
if err != nil {
return fmt.Errorf("unable to write ecdsa signature leaf signature: %w", err)
}
_, err = writer.Write([]byte{byte(l.type_)})
if err != nil {
return fmt.Errorf("unable to write ecdsa signature leaf signature type: %w", err)
}
return nil
}
type signatureTreeAddressLeaf struct {
weight uint8
address common.Address
}
func decodeSignatureTreeAddressLeaf(data *[]byte) (*signatureTreeAddressLeaf, error) {
next := *data
if len(next) < 1+1+common.AddressLength {
return nil, fmt.Errorf("insufficient data for address leaf")
}
var leafType byte
var weight byte
var address []byte
leafType, weight, address, next = next[0], next[1], next[1+1:1+1+common.AddressLength], next[1+1+common.AddressLength:]
if leafType != byte(signatureLeafTypeAddress) {
return nil, fmt.Errorf("expected address leaf type %v, got %v", signatureLeafTypeAddress, leafType)
}
*data = next
return &signatureTreeAddressLeaf{
weight: weight,
address: common.BytesToAddress(address),
}, nil
}
func (l *signatureTreeAddressLeaf) recover(ctx context.Context, subdigest core.Subdigest, provider *ethrpc.Provider, signerSignatures core.SignerSignatures) (*WalletConfigSigner, *big.Int, error) {
return &WalletConfigSigner{
Weight: l.weight,
Address: l.address,
}, new(big.Int), nil
}
func (l *signatureTreeAddressLeaf) write(writer io.Writer) error {
_, err := writer.Write([]byte{byte(signatureLeafTypeAddress)})
if err != nil {
return fmt.Errorf("unable to write address leaf type: %w", err)
}
_, err = writer.Write([]byte{l.weight})
if err != nil {
return fmt.Errorf("unable to write address leaf weight: %w", err)
}
_, err = writer.Write(l.address.Bytes())
if err != nil {
return fmt.Errorf("unable to write address leaf address: %w", err)
}
return nil
}
type dynamicSignatureType byte
const (
dynamicSignatureTypeEIP712 dynamicSignatureType = 1
dynamicSignatureTypeEthSign dynamicSignatureType = 2
dynamicSignatureTypeEIP1271 dynamicSignatureType = 3
)
func (t dynamicSignatureType) signerSignatureType() core.SignerSignatureType {
switch t {
case dynamicSignatureTypeEIP712:
return core.SignerSignatureTypeEIP712
case dynamicSignatureTypeEthSign:
return core.SignerSignatureTypeEthSign
case dynamicSignatureTypeEIP1271:
return core.SignerSignatureTypeEIP1271
default:
panic(fmt.Sprintf("invalid dynamic signature type %v", t))
}
}
type signatureTreeDynamicSignatureLeaf struct {
weight uint8
address common.Address
type_ dynamicSignatureType
signature []byte
}
func decodeSignatureTreeDynamicSignatureLeaf(data *[]byte) (*signatureTreeDynamicSignatureLeaf, error) {
next := *data
if len(next) < 1+1+common.AddressLength+2 {
return nil, fmt.Errorf("insufficient data for dynamic signature leaf")
}
var leafType byte
var weight byte
var address []byte
var signatureLength []byte
leafType, weight, address, signatureLength, next = next[0], next[1], next[1+1:1+1+common.AddressLength], next[1+1+common.AddressLength:1+1+common.AddressLength+2], next[1+1+common.AddressLength+2:]
if leafType != byte(signatureLeafTypeDynamicSignature) {
return nil, fmt.Errorf("expected dynamic signature leaf type %v, got %v", signatureLeafTypeDynamicSignature, leafType)
}
length, err := readUint16(&signatureLength)
if err != nil {
return nil, fmt.Errorf("unable to read signature length: %w", err)
}
if len(next) < int(length) {
return nil, fmt.Errorf("insufficient data for dynamic signature leaf")
}
if length == 0 {
return nil, fmt.Errorf("missing dynamic signature type")
}
var signature []byte
var signatureType byte
signature, signatureType, next = next[:length-1], next[length-1], next[length:]
switch signatureType {
case byte(dynamicSignatureTypeEIP712), byte(dynamicSignatureTypeEthSign), byte(dynamicSignatureTypeEIP1271):
default:
return nil, fmt.Errorf("unknown dynamic signature type %v", signatureType)
}
*data = next
return &signatureTreeDynamicSignatureLeaf{
weight: weight,
address: common.BytesToAddress(address),
type_: dynamicSignatureType(signatureType),
signature: signature,
}, nil
}
func (l *signatureTreeDynamicSignatureLeaf) recover(ctx context.Context, subdigest core.Subdigest, provider *ethrpc.Provider, signerSignatures core.SignerSignatures) (*WalletConfigSigner, *big.Int, error) {
switch l.type_ {
case dynamicSignatureTypeEIP712, dynamicSignatureTypeEthSign:
var address common.Address
var err error
switch l.type_ {
case dynamicSignatureTypeEthSign:
address, err = ecrecover(subdigest.EthSignSubdigest(), l.signature)
default:
address, err = ecrecover(subdigest, l.signature)
}
if err != nil {
return nil, nil, fmt.Errorf("unable to recover dynamic signature leaf: %w", err)
}
if address != l.address {
return nil, nil, fmt.Errorf("expected dynamic signature by %v, got dynamic signature by %v", l.address, address)
}
signerSignatures.Insert(l.address, core.SignerSignature{
Subdigest: subdigest,
Type: l.type_.signerSignatureType(),
Signature: l.signature,
})
return &WalletConfigSigner{
Weight: l.weight,
Address: l.address,
}, new(big.Int).SetUint64(uint64(l.weight)), nil
case dynamicSignatureTypeEIP1271:
effectiveWeight := l.weight
if provider != nil {
contract := ethcontract.NewContractCaller(l.address, contracts.IERC1271.ABI, provider)
var results []any
err := contract.Call(&bind.CallOpts{Context: ctx}, &results, "isValidSignature", subdigest.Hash, l.signature)
if err != nil {
return nil, nil, fmt.Errorf("unable to call isValidSignature on %v: %w", l.address, err)
}
if len(results) != 1 {
return nil, nil, fmt.Errorf("expected single return value from isValidSignature, got %v", len(results))
}
magicValue, ok := results[0].([4]byte)
if !ok {
return nil, nil, fmt.Errorf("expected [4]byte return value from isValidSignature, got %T", results[0])
}
if magicValue != isValidSignatureMagicValue {
return nil, nil, fmt.Errorf("isValidSignature returned %v, expected %v", hexutil.Encode(magicValue[:]), hexutil.Encode(isValidSignatureMagicValue[:]))
}
} else {
// Set the effective weight to 0
// we can still get the signer address (and its corresponding weight)
// but we should not count it towards the total weight
effectiveWeight = 0
}
signerSignatures.Insert(l.address, core.SignerSignature{
Subdigest: subdigest,
Type: l.type_.signerSignatureType(),
Signature: l.signature,
})
return &WalletConfigSigner{
Weight: l.weight,
Address: l.address,
}, new(big.Int).SetUint64(uint64(effectiveWeight)), nil
default:
return nil, nil, fmt.Errorf("unknown dynamic signature type %v", l.type_)
}
}
func (l *signatureTreeDynamicSignatureLeaf) write(writer io.Writer) error {
_, err := writer.Write([]byte{byte(signatureLeafTypeDynamicSignature)})
if err != nil {
return fmt.Errorf("unable to write dynamic signature leaf type: %w", err)
}
_, err = writer.Write([]byte{l.weight})
if err != nil {
return fmt.Errorf("unable to write dynamic signature leaf weight: %w", err)
}
_, err = writer.Write(l.address.Bytes())
if err != nil {
return fmt.Errorf("unable to write dynamic signature leaf address: %w", err)
}
err = binary.Write(writer, binary.BigEndian, uint16(len(l.signature)+1))
if err != nil {
return fmt.Errorf("unable to write dynamic signature leaf signature length: %w", err)
}
_, err = writer.Write(l.signature)
if err != nil {
return fmt.Errorf("unable to write dynamic signature leaf signature: %w", err)
}
_, err = writer.Write([]byte{byte(l.type_)})
if err != nil {
return fmt.Errorf("unable to write dynamic signature leaf signature type: %w", err)
}
return nil
}
type WalletConfigSigners []*WalletConfigSigner
func (s WalletConfigSigners) Len() int { return len(s) }
func (s WalletConfigSigners) Less(i, j int) bool {
return s[i].Address.Hash().Big().Cmp(s[j].Address.Hash().Big()) < 0
}
func (s WalletConfigSigners) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type WalletConfig struct {
Threshold_ uint16 `json:"threshold" toml:"threshold"`
Signers_ WalletConfigSigners `json:"signers" toml:"signers"`
}
func (c *WalletConfig) Threshold() uint16 {
return c.Threshold_
}
func (c *WalletConfig) Checkpoint() uint32 {
return 0
}
func (c *WalletConfig) Signers() map[common.Address]uint16 {
signers := map[common.Address]uint16{}
for _, signer := range c.Signers_ {
signers[signer.Address] = uint16(signer.Weight)
}
return signers
}
func (c *WalletConfig) SignersWeight(signers []common.Address) uint16 {
var totalWeight uint16
for _, sa := range signers {
for address, weight := range c.Signers() {
if address == sa {
totalWeight += weight
}
}
}
return totalWeight
}
func (c *WalletConfig) IsUsable() error {
if c.Threshold_ == 0 {
return fmt.Errorf("threshold is 0")
}
var weight uint64
for _, signer := range c.Signers_ {
weight += uint64(signer.Weight)
if weight >= uint64(c.Threshold_) {
return nil
}
}
return fmt.Errorf("threshold %v exceeds maximum weight %v", c.Threshold_, weight)
}
func (c *WalletConfig) ImageHash() core.ImageHash {
imageHash := common.BigToHash(new(big.Int).SetUint64(uint64(c.Threshold_)))
for _, signer := range c.Signers_ {
preimage, err := ethcoder.AbiCoder(
[]string{"bytes32", "uint8", "address"},
[]any{imageHash, signer.Weight, signer.Address},
)
if err != nil {
return core.ImageHash{}
}
imageHash = crypto.Keccak256Hash(preimage)
}
return core.ImageHash{Hash: imageHash, Preimage: c}
}
func (c *WalletConfig) BuildSignature(ctx context.Context, sign core.SigningFunction, validateSigningPower ...bool) (core.Signature[*WalletConfig], error) {
isValid := false
if len(validateSigningPower) > 0 {
isValid = !validateSigningPower[0]
}
signerWeights := map[common.Address]*big.Int{}
for _, signer := range c.Signers_ {
weight := signerWeights[signer.Address]
if weight == nil {
weight = new(big.Int)
signerWeights[signer.Address] = weight
}
weight.Add(weight, new(big.Int).SetUint64(uint64(signer.Weight)))
}
signCtx, signCancel := context.WithCancel(ctx)
defer signCancel()
signerSignatureCh := core.SigningOrchestrator(signCtx, c.Signers(), sign)
signerSignatures := map[common.Address]signerSignature{}
weight := new(big.Int)
for range signerWeights {
signerSig := <-signerSignatureCh
if signerSig.Error != nil {
signCancel()
return nil, fmt.Errorf("signer %s signing error: %w", signerSig.Signer.Hex(), signerSig.Error)
}
if signerSig.Signature != nil {
signerSignatures[signerSig.Signer] = signerSignature{
signerSig.Signer, signerSig.Type, signerSig.Signature,
}
weight.Add(weight, signerWeights[signerSig.Signer])
if weight.Cmp(new(big.Int).SetUint64(uint64(c.Threshold_))) >= 0 {
signCancel()
isValid = true
}
}
}
if isValid {
var leaves []signatureLeaf
for _, signer := range c.Signers_ {
leaves = append(leaves, signer.buildSignatureLeaf(signerSignatures))
}
return &signature{
threshold: c.Threshold_,
leaves: leaves,
}, nil
} else {
return nil, fmt.Errorf("not enough signers to build signature")
}
}
func (c *WalletConfig) Clone() *WalletConfig {
signers := make(WalletConfigSigners, len(c.Signers_))
copy(signers, c.Signers_)
return &WalletConfig{
Threshold_: c.Threshold_,
Signers_: signers,
}
}
type WalletConfigSigner struct {
Weight uint8 `json:"weight" toml:"weight"`
Address common.Address `json:"address" toml:"address"`
}
func decodeWalletConfigSigner(object any) (*WalletConfigSigner, error) {
object_, ok := object.(map[string]any)
if !ok {
return nil, fmt.Errorf("wallet config signer must be an object")
}
weight, ok := object_["weight"]
if !ok {
return nil, fmt.Errorf(`missing required "weight" property`)
}
weight_, err := toUint8(weight)
if err != nil {
return nil, fmt.Errorf("unable to convert weight: %w", err)
}
address, ok := object_["address"]
if !ok {
return nil, fmt.Errorf(`missing required "address" property`)
}
address_, ok := address.(string)
if !ok {
return nil, fmt.Errorf("address must be a string")
}
if !common.IsHexAddress(address_) {
return nil, fmt.Errorf(`"%v" is not a valid address`, address_)
}
return &WalletConfigSigner{
Weight: weight_,
Address: common.HexToAddress(address_),
}, nil
}
func (s *WalletConfigSigner) buildSignatureLeaf(signerSignatures map[common.Address]signerSignature) signatureLeaf {
signature, ok := signerSignatures[s.Address]
if ok {
switch signature.type_ {
case core.SignerSignatureTypeEIP712:
leaf := signatureTreeECDSASignatureLeaf{
weight: s.Weight,
type_: eCDSASignatureTypeEIP712,
}
copy(leaf.signature[:], signature.signature)
return &leaf
case core.SignerSignatureTypeEthSign:
leaf := signatureTreeECDSASignatureLeaf{
weight: s.Weight,
type_: eCDSASignatureTypeEthSign,
}
copy(leaf.signature[:], signature.signature)
return &leaf
case core.SignerSignatureTypeEIP1271:
return &signatureTreeDynamicSignatureLeaf{
weight: s.Weight,
address: s.Address,
type_: dynamicSignatureTypeEIP1271,
signature: signature.signature,
}
default:
panic(fmt.Sprintf("unknown signer signature type %v", signature.type_))
}
} else {
return &signatureTreeAddressLeaf{
weight: s.Weight,
address: s.Address,
}
}
}
func (s *WalletConfigSigner) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"weight": s.Weight,
"address": s.Address.String(),
})