-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy patheth.go
6143 lines (5419 loc) · 199 KB
/
eth.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
// This code is available on the terms of the project LICENSE.md file,
// also available online at https://blueoakcouncil.org/license/1.0.0.
package eth
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"os"
"os/exec"
"os/user"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/config"
"decred.org/dcrdex/dex/encode"
"decred.org/dcrdex/dex/keygen"
"decred.org/dcrdex/dex/networks/erc20"
dexeth "decred.org/dcrdex/dex/networks/eth"
multibal "decred.org/dcrdex/dex/networks/eth/contracts/multibalance"
"github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
"github.com/decred/dcrd/hdkeychain/v3"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
ethmath "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/ethconfig"
"github.com/ethereum/go-ethereum/params"
"github.com/tyler-smith/go-bip39"
)
func init() {
dexeth.MaybeReadSimnetAddrs()
}
func registerToken(tokenID uint32, desc string) {
token, found := dexeth.Tokens[tokenID]
if !found {
panic("token " + strconv.Itoa(int(tokenID)) + " not known")
}
netAddrs := make(map[dex.Network]string)
for net, netToken := range token.NetTokens {
netAddrs[net] = netToken.Address.String()
}
asset.RegisterToken(tokenID, token.Token, &asset.WalletDefinition{
Type: walletTypeToken,
Tab: "Ethereum token",
Description: desc,
}, netAddrs)
}
func init() {
asset.Register(BipID, &Driver{})
registerToken(usdcTokenID, "The USDC Ethereum ERC20 token.")
registerToken(usdtTokenID, "The USDT Ethereum ERC20 token.")
registerToken(maticTokenID, "The MATIC Ethereum ERC20 token.")
}
const (
// BipID is the BIP-0044 asset ID for Ethereum.
BipID = 60
defaultGasFee = 82 // gwei
defaultGasFeeLimit = 200 // gwei
defaultSendGasLimit = 21_000
walletTypeGeth = "geth"
walletTypeRPC = "rpc"
walletTypeToken = "token"
providersKey = "providers"
// confCheckTimeout is the amount of time allowed to check for
// confirmations. Testing on testnet has shown spikes up to 2.5
// seconds. This value may need to be adjusted in the future.
confCheckTimeout = 4 * time.Second
// coinIDTakerFoundMakerRedemption is a prefix to identify one of CoinID formats,
// see DecodeCoinID func for details.
coinIDTakerFoundMakerRedemption = "TakerFoundMakerRedemption:"
// maxTxFeeGwei is the default max amount of eth that can be used in one
// transaction. This is set by the host in the case of providers. The
// internal node currently has no max but also cannot be used since the
// merge.
//
// TODO: Find a way to ask the host about their config set max fee and
// gas values.
maxTxFeeGwei = 1_000_000_000
LiveEstimateFailedError = dex.ErrorKind("live gas estimate failed")
// txAgeOut is the amount of time after which we forego any tx
// synchronization efforts for unconfirmed pending txs.
txAgeOut = 2 * time.Hour
// stateUpdateTick is the minimum amount of time between checks for
// new block and updating of pending txs, counter-party redemptions and
// approval txs.
// HTTP RPC clients meter tip header calls to minimum 10 seconds.
// WebSockets will stay up-to-date, so can expect new blocks often.
// A shorter blockTicker would be too much for e.g. Polygon where the block
// time is 2 or 3 seconds. We'd be doing a ton of calls for pending tx
// updates.
stateUpdateTick = time.Second * 5
// maxUnindexedTxs is the number of pending txs we will allow to be
// unverified on-chain before we halt broadcasting of new txs.
maxUnindexedTxs = 10
peerCountTicker = 5 * time.Second // no rpc calls here
contractVersionNewest = ^uint32(0)
)
var (
usdcTokenID, _ = dex.BipSymbolID("usdc.eth")
usdtTokenID, _ = dex.BipSymbolID("usdt.eth")
maticTokenID, _ = dex.BipSymbolID("matic.eth")
walletOpts = []*asset.ConfigOption{
{
Key: "gasfeelimit",
DisplayName: "Gas Fee Limit",
Description: "This is the highest network fee rate you are willing to " +
"pay on swap transactions. If gasfeelimit is lower than a market's " +
"maxfeerate, you will not be able to trade on that market with this " +
"wallet. Units: gwei / gas",
DefaultValue: defaultGasFeeLimit,
},
}
RPCOpts = []*asset.ConfigOption{
{
Key: providersKey,
DisplayName: "RPC Provider",
Description: "Specify one or more RPC providers. For infrastructure " +
"providers, prefer using wss address. Only url-based authentication " +
"is supported. For a local node, use the filepath to an IPC file.",
Repeatable: providerDelimiter,
RepeatN: 2,
DefaultValue: "",
},
}
// WalletInfo defines some general information about a Ethereum wallet.
WalletInfo = asset.WalletInfo{
Name: "Ethereum",
// SupportedVersions: For Ethereum, the server backend maintains a
// single protocol version, so tokens and ETH have the same set of
// supported versions. Even though the SupportedVersions are made
// accessible for tokens via (*TokenWallet).Info, the versions are not
// exposed though any Driver methods or assets/driver functions. Use the
// parent wallet's WalletInfo via (*Driver).Info if you need a token's
// supported versions before a wallet is available.
SupportedVersions: []uint32{0},
UnitInfo: dexeth.UnitInfo,
AvailableWallets: []*asset.WalletDefinition{
// {
// Type: walletTypeGeth,
// Tab: "Native",
// Description: "Use the built-in DEX wallet (geth light node)",
// ConfigOpts: WalletOpts,
// Seeded: true,
// },
{
Type: walletTypeRPC,
Tab: "RPC",
Description: "Infrastructure providers (e.g. Infura) or local nodes",
ConfigOpts: append(RPCOpts, walletOpts...),
Seeded: true,
GuideLink: "https://github.com/decred/dcrdex/blob/master/docs/wiki/Ethereum.md",
},
// MaxSwapsInTx and MaxRedeemsInTx are set in (Wallet).Info, since
// the value cannot be known until we connect and get network info.
},
IsAccountBased: true,
}
// unlimitedAllowance is the maximum supported allowance for an erc20
// contract, and is effectively unlimited.
unlimitedAllowance = ethmath.MaxBig256
// unlimitedAllowanceReplenishThreshold is the threshold below which we will
// require a new approval. In practice, this will never be hit, but any
// allowance below this will signal that WE didn't set it, and we'll require
// an upgrade to unlimited (since we don't support limited allowance yet).
unlimitedAllowanceReplenishThreshold = new(big.Int).Div(unlimitedAllowance, big.NewInt(2))
seedDerivationPath = []uint32{
hdkeychain.HardenedKeyStart + 44, // purpose 44' for HD wallets
hdkeychain.HardenedKeyStart + 60, // eth coin type 60'
hdkeychain.HardenedKeyStart, // account 0'
0, // branch 0
0, // index 0
}
)
// perTxGasLimit is the most gas we can use on a transaction. It is the lower of
// either the per tx or per block gas limit.
func perTxGasLimit(gasFeeLimit uint64) uint64 {
// maxProportionOfBlockGasLimitToUse sets the maximum proportion of a
// block's gas limit that a swap and redeem transaction will use. Since it
// is set to 4, the max that will be used is 25% (1/4) of the block's gas
// limit.
const maxProportionOfBlockGasLimitToUse = 4
// blockGasLimit is the amount of gas we can use in one transaction
// according to the block gas limit.
// Ethereum GasCeil: 30_000_000, Polygon: 8_000_000
blockGasLimit := ethconfig.Defaults.Miner.GasCeil / maxProportionOfBlockGasLimitToUse
// txGasLimit is the amount of gas we can use in one transaction
// according to the default transaction gas fee limit.
txGasLimit := maxTxFeeGwei / gasFeeLimit
if blockGasLimit > txGasLimit {
return txGasLimit
}
return blockGasLimit
}
// safeConfs returns the confirmations for a given tip and block number,
// returning 0 if the block number is zero or if the tip is lower than the
// block number.
func safeConfs(tip, blockNum uint64) uint64 {
if blockNum == 0 {
return 0
}
if tip < blockNum {
return 0
}
return tip - blockNum + 1
}
// safeConfsBig is safeConfs but with a *big.Int blockNum. A nil blockNum will
// result in a zero.
func safeConfsBig(tip uint64, blockNum *big.Int) uint64 {
if blockNum == nil {
return 0
}
return safeConfs(tip, blockNum.Uint64())
}
// WalletConfig are wallet-level configuration settings.
type WalletConfig struct {
GasFeeLimit uint64 `ini:"gasfeelimit"`
}
// parseWalletConfig parses the settings map into a *WalletConfig.
func parseWalletConfig(settings map[string]string) (cfg *WalletConfig, err error) {
cfg = new(WalletConfig)
err = config.Unmapify(settings, &cfg)
if err != nil {
return nil, fmt.Errorf("error parsing wallet config: %w", err)
}
return cfg, nil
}
// Driver implements asset.Driver.
type Driver struct{}
// Check that Driver implements Driver and Creator.
var _ asset.Driver = (*Driver)(nil)
var _ asset.Creator = (*Driver)(nil)
// Open opens the ETH exchange wallet. Start the wallet with its Run method.
func (d *Driver) Open(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) (asset.Wallet, error) {
return newWallet(cfg, logger, network)
}
// DecodeCoinID creates a human-readable representation of a coin ID for Ethereum.
// These are supported coin ID formats:
// 1. A transaction hash. 32 bytes
// 2. An encoded ETH funding coin id which includes the account address and
// amount. 20 + 8 = 28 bytes
// 3. An encoded token funding coin id which includes the account address,
// a token value, and fees. 20 + 8 + 8 = 36 bytes
// 4. A byte encoded string of the account address. 40 or 42 (with 0x) bytes
// 5. A byte encoded string which represents specific case where Taker found
// Maker redemption on his own (while Maker failed to notify him about it
// first). 26 (`TakerFoundMakerRedemption:` prefix) + 42 (Maker address
// with 0x) bytes
func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {
switch len(coinID) {
case common.HashLength:
var txHash common.Hash
copy(txHash[:], coinID)
return txHash.String(), nil
case fundingCoinIDSize:
c, err := decodeFundingCoin(coinID)
if err != nil {
return "", err
}
return c.String(), nil
case tokenFundingCoinIDSize:
c, err := decodeTokenFundingCoin(coinID)
if err != nil {
return "", err
}
return c.String(), nil
case common.AddressLength * 2, common.AddressLength*2 + 2:
hexAddr := string(coinID)
if !common.IsHexAddress(hexAddr) {
return "", fmt.Errorf("invalid hex address %q", coinID)
}
return common.HexToAddress(hexAddr).String(), nil
case len(coinIDTakerFoundMakerRedemption) + common.AddressLength*2 + 2:
coinIDStr := string(coinID)
if !strings.HasPrefix(coinIDStr, coinIDTakerFoundMakerRedemption) {
return "", fmt.Errorf("coinID %q has no %s prefix", coinID, coinIDTakerFoundMakerRedemption)
}
return coinIDStr, nil
}
return "", fmt.Errorf("unknown coin ID format: %x", coinID)
}
// Info returns basic information about the wallet and asset.
func (d *Driver) Info() *asset.WalletInfo {
wi := WalletInfo
return &wi
}
// Exists checks the existence of the wallet.
func (d *Driver) Exists(walletType, dataDir string, settings map[string]string, net dex.Network) (bool, error) {
switch walletType {
case walletTypeGeth, walletTypeRPC:
default:
return false, fmt.Errorf("wallet type %q unrecognized", walletType)
}
keyStoreDir := filepath.Join(getWalletDir(dataDir, net), "keystore")
ks := keystore.NewKeyStore(keyStoreDir, keystore.LightScryptN, keystore.LightScryptP)
// NOTE: If the keystore did not exist, a warning from an internal KeyStore
// goroutine may be printed to this effect. Not an issue.
return len(ks.Wallets()) > 0, nil
}
func (d *Driver) Create(cfg *asset.CreateWalletParams) error {
comp, err := NetworkCompatibilityData(cfg.Net)
if err != nil {
return fmt.Errorf("error finding compatibility data: %v", err)
}
return CreateEVMWallet(dexeth.ChainIDs[cfg.Net], cfg, &comp, false)
}
// Balance is the current balance, including information about the pending
// balance.
type Balance struct {
Current, PendingIn, PendingOut *big.Int
}
// ethFetcher represents a blockchain information fetcher. In practice, it is
// satisfied by *nodeClient. For testing, it can be satisfied by a stub.
type ethFetcher interface {
address() common.Address
addressBalance(ctx context.Context, addr common.Address) (*big.Int, error)
bestHeader(ctx context.Context) (*types.Header, error)
chainConfig() *params.ChainConfig
connect(ctx context.Context) error
peerCount() uint32
contractBackend() bind.ContractBackend
headerByHash(ctx context.Context, txHash common.Hash) (*types.Header, error)
lock() error
locked() bool
shutdown()
sendSignedTransaction(ctx context.Context, tx *types.Transaction, filts ...acceptabilityFilter) error
sendTransaction(ctx context.Context, txOpts *bind.TransactOpts, to common.Address, data []byte, filts ...acceptabilityFilter) (*types.Transaction, error)
signData(data []byte) (sig, pubKey []byte, err error)
syncProgress(context.Context) (progress *ethereum.SyncProgress, tipTime uint64, err error)
transactionConfirmations(context.Context, common.Hash) (uint32, error)
getTransaction(context.Context, common.Hash) (*types.Transaction, int64, error)
txOpts(ctx context.Context, val, maxGas uint64, maxFeeRate, tipCap, nonce *big.Int) (*bind.TransactOpts, error)
currentFees(ctx context.Context) (baseFees, tipCap *big.Int, err error)
unlock(pw string) error
getConfirmedNonce(context.Context) (uint64, error)
transactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
transactionAndReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, *types.Transaction, error)
nonce(ctx context.Context) (confirmed, next *big.Int, err error)
}
// txPoolFetcher can be implemented by node types that support fetching of
// txpool transactions.
type txPoolFetcher interface {
pendingTransactions() ([]*types.Transaction, error)
}
type pendingApproval struct {
txHash common.Hash
onConfirm func()
}
type cachedBalance struct {
stamp time.Time
height uint64
bal *big.Int
}
// Check that assetWallet satisfies the asset.Wallet interface.
var _ asset.Wallet = (*ETHWallet)(nil)
var _ asset.Wallet = (*TokenWallet)(nil)
var _ asset.AccountLocker = (*ETHWallet)(nil)
var _ asset.AccountLocker = (*TokenWallet)(nil)
var _ asset.TokenMaster = (*ETHWallet)(nil)
var _ asset.WalletRestorer = (*ETHWallet)(nil)
var _ asset.LiveReconfigurer = (*ETHWallet)(nil)
var _ asset.LiveReconfigurer = (*TokenWallet)(nil)
var _ asset.TxFeeEstimator = (*ETHWallet)(nil)
var _ asset.TxFeeEstimator = (*TokenWallet)(nil)
var _ asset.DynamicSwapper = (*ETHWallet)(nil)
var _ asset.DynamicSwapper = (*TokenWallet)(nil)
var _ asset.Authenticator = (*ETHWallet)(nil)
var _ asset.TokenApprover = (*TokenWallet)(nil)
var _ asset.WalletHistorian = (*ETHWallet)(nil)
var _ asset.WalletHistorian = (*TokenWallet)(nil)
type baseWallet struct {
// The asset subsystem starts with Connect(ctx). This ctx will be initialized
// in parent ETHWallet once and re-used in child TokenWallet instances.
ctx context.Context
net dex.Network
node ethFetcher
addr common.Address
log dex.Logger
dir string
walletType string
finalizeConfs uint64
multiBalanceAddress common.Address
multiBalanceContract *multibal.MultiBalanceV0
baseChainID uint32
chainCfg *params.ChainConfig
chainID int64
compat *CompatibilityData
tokens map[uint32]*dexeth.Token
startingBlocks atomic.Uint64
tipMtx sync.RWMutex
currentTip *types.Header
settingsMtx sync.RWMutex
settings map[string]string
gasFeeLimitV uint64 // atomic
walletsMtx sync.RWMutex
wallets map[uint32]*assetWallet
nonceMtx sync.RWMutex
pendingTxs []*extendedWalletTx
confirmedNonceAt *big.Int
pendingNonceAt *big.Int
recoveryRequestSent bool
balances struct {
sync.Mutex
m map[uint32]*cachedBalance
}
currentFees struct {
sync.Mutex
blockNum uint64
baseRate *big.Int
tipRate *big.Int
}
txDB txDB
}
// assetWallet is a wallet backend for Ethereum and Eth tokens. The backend is
// how Bison Wallet communicates with the Ethereum blockchain and wallet.
// assetWallet satisfies the dex.Wallet interface.
type assetWallet struct {
*baseWallet
assetID uint32
emit *asset.WalletEmitter
log dex.Logger
ui dex.UnitInfo
connected atomic.Bool
wi asset.WalletInfo
versionedContracts map[uint32]common.Address
versionedGases map[uint32]*dexeth.Gases
maxSwapGas uint64
maxRedeemGas uint64
lockedFunds struct {
mtx sync.RWMutex
initiateReserves uint64
redemptionReserves uint64
refundReserves uint64
}
findRedemptionMtx sync.RWMutex
findRedemptionReqs map[[32]byte]*findRedemptionRequest
approvalsMtx sync.RWMutex
pendingApprovals map[uint32]*pendingApproval
approvalCache map[uint32]bool
lastPeerCount uint32
peersChange func(uint32, error)
contractors map[uint32]contractor // version -> contractor
evmify func(uint64) *big.Int
atomize func(*big.Int) uint64
// pendingTxCheckBal is protected by the nonceMtx. We use this field
// as a secondary check to see if we need to request confirmations for
// pending txs, since tips are cached for up to 10 seconds. We check the
// status of pending txs if the tip has changed OR if the balance has
// changed.
pendingTxCheckBal *big.Int
}
// ETHWallet implements some Ethereum-specific methods.
type ETHWallet struct {
// 64-bit atomic variables first. See
// https://golang.org/pkg/sync/atomic/#pkg-note-BUG
tipAtConnect int64
defaultProviders []string
*assetWallet
}
// TokenWallet implements some token-specific methods.
type TokenWallet struct {
*assetWallet
cfg *tokenWalletConfig
parent *assetWallet
token *dexeth.Token
netToken *dexeth.NetToken
}
func (w *assetWallet) maxSwapsAndRedeems() (maxSwaps, maxRedeems uint64) {
txGasLimit := perTxGasLimit(atomic.LoadUint64(&w.gasFeeLimitV))
return txGasLimit / w.maxSwapGas, txGasLimit / w.maxRedeemGas
}
// Info returns basic information about the wallet and asset.
func (w *assetWallet) Info() *asset.WalletInfo {
wi := w.wi
maxSwaps, maxRedeems := w.maxSwapsAndRedeems()
wi.MaxSwapsInTx = maxSwaps
wi.MaxRedeemsInTx = maxRedeems
return &wi
}
// genWalletSeed uses the wallet seed passed from core as the entropy for
// generating a BIP-39 mnemonic. Then it returns the wallet seed generated
// from the mnemonic which can be used to derive a private key.
func genWalletSeed(entropy []byte) ([]byte, error) {
if len(entropy) < 32 || len(entropy) > 64 {
return nil, fmt.Errorf("wallet entropy must be 32 to 64 bytes long")
}
mnemonic, err := bip39.NewMnemonic(entropy)
if err != nil {
return nil, fmt.Errorf("error deriving mnemonic: %w", err)
}
return bip39.NewSeed(mnemonic, ""), nil
}
func privKeyFromSeed(seed []byte) (pk []byte, zero func(), err error) {
walletSeed, err := genWalletSeed(seed)
if err != nil {
return nil, nil, err
}
defer encode.ClearBytes(walletSeed)
extKey, err := keygen.GenDeepChild(walletSeed, seedDerivationPath)
if err != nil {
return nil, nil, err
}
// defer extKey.Zero()
pk, err = extKey.SerializedPrivKey()
if err != nil {
extKey.Zero()
return nil, nil, err
}
return pk, extKey.Zero, nil
}
func CreateEVMWallet(chainID int64, createWalletParams *asset.CreateWalletParams, compat *CompatibilityData, skipConnect bool) error {
switch createWalletParams.Type {
case walletTypeGeth:
return asset.ErrWalletTypeDisabled
case walletTypeRPC:
default:
return fmt.Errorf("wallet type %q unrecognized", createWalletParams.Type)
}
walletDir := getWalletDir(createWalletParams.DataDir, createWalletParams.Net)
privateKey, zero, err := privKeyFromSeed(createWalletParams.Seed)
if err != nil {
return err
}
defer zero()
switch createWalletParams.Type {
// case walletTypeGeth:
// node, err := prepareNode(&nodeConfig{
// net: createWalletParams.Net,
// appDir: walletDir,
// })
// if err != nil {
// return err
// }
// defer node.Close()
// return importKeyToNode(node, privateKey, createWalletParams.Pass)
case walletTypeRPC:
// Make the wallet dir if it does not exist, otherwise we may fail to
// write the compliant-providers.json file. Create the keystore
// subdirectory as well to avoid a "failed to watch keystore folder"
// error from the keystore's internal account cache supervisor.
keystoreDir := filepath.Join(walletDir, "keystore")
if err := os.MkdirAll(keystoreDir, 0700); err != nil {
return err
}
// TODO: This procedure may actually work for walletTypeGeth too.
ks := keystore.NewKeyStore(keystoreDir, keystore.LightScryptN, keystore.LightScryptP)
priv, err := crypto.ToECDSA(privateKey)
if err != nil {
return err
}
// If the user supplied endpoints, check them now.
providerDef := createWalletParams.Settings[providersKey]
if !skipConnect && len(providerDef) > 0 {
endpoints := strings.Split(providerDef, providerDelimiter)
if err := createAndCheckProviders(context.Background(), walletDir, endpoints,
big.NewInt(chainID), compat, createWalletParams.Net, createWalletParams.Logger, false); err != nil {
return fmt.Errorf("create and check providers: %v", err)
}
}
return importKeyToKeyStore(ks, priv, createWalletParams.Pass)
}
return fmt.Errorf("unknown wallet type %q", createWalletParams.Type)
}
// newWallet is the constructor for an Ethereum asset.Wallet.
func newWallet(assetCFG *asset.WalletConfig, logger dex.Logger, net dex.Network) (w *ETHWallet, err error) {
chainCfg, err := ChainConfig(net)
if err != nil {
return nil, fmt.Errorf("failed to locate Ethereum genesis configuration for network %s", net)
}
comp, err := NetworkCompatibilityData(net)
if err != nil {
return nil, fmt.Errorf("failed to locate Ethereum compatibility data: %s", net)
}
contracts := make(map[uint32]common.Address, 1)
for ver, netAddrs := range dexeth.ContractAddresses {
for netw, addr := range netAddrs {
if netw == net {
contracts[ver] = addr
break
}
}
}
var defaultProviders []string
switch net {
case dex.Simnet:
u, _ := user.Current()
defaultProviders = []string{filepath.Join(u.HomeDir, "dextest", "eth", "alpha", "node", "geth.ipc")}
case dex.Testnet:
defaultProviders = []string{
"https://rpc.ankr.com/eth_sepolia",
"https://ethereum-sepolia.blockpi.network/v1/rpc/public",
"https://eth-sepolia.public.blastapi.io",
"https://endpoints.omniatech.io/v1/eth/sepolia/public",
"https://rpc-sepolia.rockx.com",
"https://rpc.sepolia.org",
"https://eth-sepolia-public.unifra.io",
}
case dex.Mainnet:
defaultProviders = []string{
"https://rpc.ankr.com/eth",
"https://ethereum.blockpi.network/v1/rpc/public",
"https://eth-mainnet.nodereal.io/v1/1659dfb40aa24bbb8153a677b98064d7",
"https://rpc.builder0x69.io",
"https://rpc.flashbots.net",
"wss://eth.llamarpc.com",
}
}
return NewEVMWallet(&EVMWalletConfig{
BaseChainID: BipID,
ChainCfg: chainCfg,
AssetCfg: assetCFG,
CompatData: &comp,
VersionedGases: dexeth.VersionedGases,
Tokens: dexeth.Tokens,
FinalizeConfs: 3,
Logger: logger,
BaseChainContracts: contracts,
MultiBalAddress: dexeth.MultiBalanceAddresses[net],
WalletInfo: WalletInfo,
Net: net,
DefaultProviders: defaultProviders,
})
}
// EVMWalletConfig is the configuration for an evm-compatible wallet.
type EVMWalletConfig struct {
BaseChainID uint32
ChainCfg *params.ChainConfig
AssetCfg *asset.WalletConfig
CompatData *CompatibilityData
VersionedGases map[uint32]*dexeth.Gases
Tokens map[uint32]*dexeth.Token
FinalizeConfs uint64
Logger dex.Logger
BaseChainContracts map[uint32]common.Address
DefaultProviders []string
MultiBalAddress common.Address // If empty, separate calls for N tokens + 1
WalletInfo asset.WalletInfo
Net dex.Network
}
func NewEVMWallet(cfg *EVMWalletConfig) (w *ETHWallet, err error) {
assetID := cfg.BaseChainID
chainID := cfg.ChainCfg.ChainID.Int64()
// var cl ethFetcher
switch cfg.AssetCfg.Type {
case walletTypeGeth:
return nil, asset.ErrWalletTypeDisabled
case walletTypeRPC:
if providerDef := cfg.AssetCfg.Settings[providersKey]; len(providerDef) == 0 && len(cfg.DefaultProviders) == 0 {
return nil, errors.New("no providers specified")
}
default:
return nil, fmt.Errorf("unknown wallet type %q", cfg.AssetCfg.Type)
}
wCfg, err := parseWalletConfig(cfg.AssetCfg.Settings)
if err != nil {
return nil, err
}
gasFeeLimit := wCfg.GasFeeLimit
if gasFeeLimit == 0 {
gasFeeLimit = defaultGasFeeLimit
}
eth := &baseWallet{
net: cfg.Net,
baseChainID: cfg.BaseChainID,
chainCfg: cfg.ChainCfg,
chainID: chainID,
compat: cfg.CompatData,
tokens: cfg.Tokens,
log: cfg.Logger,
dir: cfg.AssetCfg.DataDir,
walletType: cfg.AssetCfg.Type,
finalizeConfs: cfg.FinalizeConfs,
settings: cfg.AssetCfg.Settings,
gasFeeLimitV: gasFeeLimit,
wallets: make(map[uint32]*assetWallet),
multiBalanceAddress: cfg.MultiBalAddress,
}
var maxSwapGas, maxRedeemGas uint64
for _, gases := range cfg.VersionedGases {
if gases.Swap > maxSwapGas {
maxSwapGas = gases.Swap
}
if gases.Redeem > maxRedeemGas {
maxRedeemGas = gases.Redeem
}
}
txGasLimit := perTxGasLimit(gasFeeLimit)
if maxSwapGas == 0 || txGasLimit < maxSwapGas {
return nil, errors.New("max swaps cannot be zero or undefined")
}
if maxRedeemGas == 0 || txGasLimit < maxRedeemGas {
return nil, errors.New("max redeems cannot be zero or undefined")
}
aw := &assetWallet{
baseWallet: eth,
log: cfg.Logger,
assetID: assetID,
versionedContracts: cfg.BaseChainContracts,
versionedGases: cfg.VersionedGases,
maxSwapGas: maxSwapGas,
maxRedeemGas: maxRedeemGas,
emit: cfg.AssetCfg.Emit,
findRedemptionReqs: make(map[[32]byte]*findRedemptionRequest),
pendingApprovals: make(map[uint32]*pendingApproval),
approvalCache: make(map[uint32]bool),
peersChange: cfg.AssetCfg.PeersChange,
contractors: make(map[uint32]contractor),
evmify: dexeth.GweiToWei,
atomize: dexeth.WeiToGwei,
ui: dexeth.UnitInfo,
pendingTxCheckBal: new(big.Int),
wi: cfg.WalletInfo,
}
maxSwaps, maxRedeems := aw.maxSwapsAndRedeems()
cfg.Logger.Debugf("ETH wallet will support a maximum of %d swaps and %d redeems per transaction.",
maxSwaps, maxRedeems)
aw.wallets = map[uint32]*assetWallet{
assetID: aw,
}
return ÐWallet{
assetWallet: aw,
defaultProviders: cfg.DefaultProviders,
}, nil
}
func getWalletDir(dataDir string, network dex.Network) string {
return filepath.Join(dataDir, network.String())
}
// Connect connects to the node RPC server. Satisfies dex.Connector.
func (w *ETHWallet) Connect(ctx context.Context) (_ *sync.WaitGroup, err error) {
var cl ethFetcher
switch w.walletType {
case walletTypeGeth:
// cl, err = newNodeClient(getWalletDir(w.dir, w.net), w.net, w.log.SubLogger("NODE"))
// if err != nil {
// return nil, err
// }
return nil, asset.ErrWalletTypeDisabled
case walletTypeRPC:
w.settingsMtx.RLock()
defer w.settingsMtx.RUnlock()
endpoints := w.defaultProviders
if providerDef, found := w.settings[providersKey]; found && len(providerDef) > 0 {
endpoints = strings.Split(providerDef, " ")
}
rpcCl, err := newMultiRPCClient(w.dir, endpoints, w.log.SubLogger("RPC"), w.chainCfg, w.finalizeConfs, w.net)
if err != nil {
return nil, err
}
rpcCl.finalizeConfs = w.finalizeConfs
cl = rpcCl
default:
return nil, fmt.Errorf("unknown wallet type %q", w.walletType)
}
w.node = cl
w.addr = cl.address()
w.ctx = ctx // TokenWallet will re-use this ctx.
err = w.node.connect(ctx)
if err != nil {
return nil, err
}
for ver, constructor := range contractorConstructors {
contractAddr, exists := w.versionedContracts[ver]
if !exists || contractAddr == (common.Address{}) {
return nil, fmt.Errorf("no contract address for version %d, net %s", ver, w.net)
}
c, err := constructor(contractAddr, w.addr, w.node.contractBackend())
if err != nil {
return nil, fmt.Errorf("error constructor version %d contractor: %v", ver, err)
}
w.contractors[ver] = c
}
if w.multiBalanceAddress != (common.Address{}) {
w.multiBalanceContract, err = multibal.NewMultiBalanceV0(w.multiBalanceAddress, cl.contractBackend())
if err != nil {
w.log.Errorf("Error loading MultiBalance contract: %v", err)
}
}
w.txDB, err = newBadgerTxDB(filepath.Join(w.dir, "txhistorydb"), w.log.SubLogger("TXDB"))
if err != nil {
return nil, err
}
txCM := dex.NewConnectionMaster(w.txDB)
if err := txCM.ConnectOnce(ctx); err != nil {
return nil, err
}
pendingTxs, err := w.txDB.getPendingTxs()
if err != nil {
return nil, err
}
sort.Slice(pendingTxs, func(i, j int) bool {
return pendingTxs[i].Nonce.Cmp(pendingTxs[j].Nonce) < 0
})
// Initialize the best block.
bestHdr, err := w.node.bestHeader(ctx)
if err != nil {
return nil, fmt.Errorf("error getting best block hash: %w", err)
}
confirmedNonce, nextNonce, err := w.node.nonce(ctx)
if err != nil {
return nil, fmt.Errorf("error establishing nonce: %w", err)
}
w.tipMtx.Lock()
w.currentTip = bestHdr
w.tipMtx.Unlock()
w.startingBlocks.Store(bestHdr.Number.Uint64())
w.nonceMtx.Lock()
w.pendingTxs = pendingTxs
w.confirmedNonceAt = confirmedNonce
w.pendingNonceAt = nextNonce
w.nonceMtx.Unlock()
if w.log.Level() <= dex.LevelDebug {
var highestPendingNonce, lowestPendingNonce uint64
for _, pendingTx := range pendingTxs {
n := pendingTx.Nonce.Uint64()
if n > highestPendingNonce {
highestPendingNonce = n
}
if lowestPendingNonce == 0 || n < lowestPendingNonce {
lowestPendingNonce = n
}
}
w.log.Debugf("Synced with header %s and confirmed nonce %s, pending nonce %s, %d pending txs from nonce %d to nonce %d",
bestHdr.Number, confirmedNonce, nextNonce, len(pendingTxs), highestPendingNonce, lowestPendingNonce)
}
height := w.currentTip.Number
// NOTE: We should be using the tipAtConnect to set Progress in SyncStatus.
atomic.StoreInt64(&w.tipAtConnect, height.Int64())
w.log.Infof("Connected to eth (%s), at height %d", w.walletType, height)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
w.monitorBlocks(ctx)
w.node.shutdown()
}()
wg.Add(1)
go func() {
defer wg.Done()
w.monitorPeers(ctx)
}()
w.connected.Store(true)
go func() {
<-ctx.Done()
txCM.Wait()
w.connected.Store(false)
}()
return &wg, nil
}
// Connect waits for context cancellation and closes the WaitGroup. Satisfies
// dex.Connector.
func (w *TokenWallet) Connect(ctx context.Context) (*sync.WaitGroup, error) {
if w.parent.ctx == nil || w.parent.ctx.Err() != nil {
return nil, fmt.Errorf("parent wallet not connected")
}
err := w.loadContractors()
if err != nil {
return nil, err
}
w.connected.Store(true)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-ctx.Done():
case <-w.parent.ctx.Done():
w.connected.Store(false)