forked from decred/dcrdex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodeclient_harness_test.go
2379 lines (2116 loc) · 70.3 KB
/
nodeclient_harness_test.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
//go:build harness
// This test requires that the simnet harness be running. Some tests will
// alternatively work on testnet.
//
// NOTE: These test reuse a light node that lives in the dextest folders.
// However, when recreating the test database for every test, the nonce used
// for imported accounts is sometimes, randomly, off, which causes transactions
// to not be mined and effectively makes the node unusable (at least before
// restarting). It also seems to have caused getting balance of an account to
// fail, and sometimes the redeem and refund functions to also fail. This could
// be a problem in the future if a user restores from seed. Punting on this
// particular problem for now.
package eth
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"math"
"math/big"
"math/rand"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/encode"
dexeth "decred.org/dcrdex/dex/networks/eth"
swapv0 "decred.org/dcrdex/dex/networks/eth/contracts/v0"
"github.com/davecgh/go-spew/spew"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/secp256k1"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/rpc"
// "encoding/binary"
// "github.com/decred/dcrd/dcrutil/v4"
// "github.com/decred/dcrd/crypto/blake256"
)
const (
alphaNode = "enode://897c84f6e4f18195413c1d02927e6a4093f5e7574b52bdec6f20844c4f1f6dd3f16036a9e600bd8681ab50fd8dd144df4a6ba9dd8722bb578a86aaa8222c964f@127.0.0.1:30304"
alphaAddr = "18d65fb8d60c1199bb1ad381be47aa692b482605"
pw = "bee75192465cef9f8ab1198093dfed594e93ae810ccbbf2b3b12e1771cc6cb19"
maxFeeRate uint64 = 200 // gwei per gas
// addPeer is optional and will be added if set. It should looks
// something like enode://[email protected]:30303
// Be sure the full node is run with --light.serve ##
addPeer = ""
)
var (
homeDir = os.Getenv("HOME")
harnessCtlDir = filepath.Join(homeDir, "dextest", "eth", "harness-ctl")
simnetWalletDir = filepath.Join(homeDir, "dextest", "eth", "client_rpc_tests", "simnet")
participantWalletDir = filepath.Join(homeDir, "dextest", "eth", "client_rpc_tests", "participant")
testnetWalletDir string
testnetParticipantWalletDir string
alphaNodeDir = filepath.Join(homeDir, "dextest", "eth", "alpha", "node")
alphaIPCFile = filepath.Join(alphaNodeDir, "geth.ipc")
betaNodeDir = filepath.Join(homeDir, "dextest", "eth", "beta", "node")
betaIPCFile = filepath.Join(betaNodeDir, "geth.ipc")
ctx context.Context
tLogger = dex.StdOutLogger("ETHTEST", dex.LevelWarn)
simnetWalletSeed = "0812f5244004217452059e2fd11603a511b5d0870ead753df76c966ce3c71531"
simnetAddr common.Address
simnetAcct *accounts.Account
ethClient ethFetcher
participantWalletSeed = "a897afbdcba037c8c735cc63080558a30d72851eb5a3d05684400ec4123a2d00"
participantAddr common.Address
participantAcct *accounts.Account
participantEthClient ethFetcher
simnetContractor contractor
participantContractor contractor
simnetTokenContractor tokenContractor
participantTokenContractor tokenContractor
ethGases *dexeth.Gases
tokenGases *dexeth.Gases
testnetSecPerBlock = 15 * time.Second
// secPerBlock is one for simnet, because it takes one second to mine a
// block currently. Is set in code to testnetSecPerBlock if running on
// testnet.
secPerBlock = time.Second
// If you are testing on testnet, you must specify the rpcNode. You can also
// specify it in the testnet-credentials.json file.
rpcProviders []string
// useRPC can be set to true to test the RPC clients.
useRPC bool
// isTestnet can be set to true to perform tests on the goerli testnet.
// May need some setup including sending testnet coins to the addresses
// and a lengthy sync. Wallet addresses are the same as simnet. Tests may
// need to be run with a high --timeout=2h for the initial sync.
//
// Only for non-token tests, so run with --run=TestGroupName.
//
// TODO: Make this also work for token tests.
isTestnet bool
// testnetWalletSeed and testnetParticipantWalletSeed are required for
// use on testnet and can be any 256 bit hex. If the wallets created by
// these seeds do not have enough funds to test, addresses that need
// funds will be printed.
testnetWalletSeed string
testnetParticipantWalletSeed string
usdcID, _ = dex.BipSymbolID("usdc.eth")
testTokenID uint32
masterToken *dexeth.Token
contractAddr common.Address
v1 bool
ver uint32
)
func newContract(stamp uint64, secretHash [32]byte, val uint64) *asset.Contract {
return &asset.Contract{
LockTime: stamp,
SecretHash: secretHash[:],
Address: participantAddr.String(),
Value: val,
}
}
func acLocator(c *asset.Contract) []byte {
return makeLocator(bytesToArray(c.SecretHash), c.Value, c.LockTime)
}
func makeLocator(secretHash [32]byte, valg, lockTime uint64) []byte {
if ver == 1 {
return (&dexeth.SwapVector{
From: ethClient.address(),
To: participantEthClient.address(),
Value: valg,
SecretHash: secretHash,
LockTime: lockTime,
}).Locator()
}
return secretHash[:]
}
func newRedeem(secret, secretHash [32]byte, valg, lockTime uint64) *asset.Redemption {
return &asset.Redemption{
Spends: &asset.AuditInfo{
SecretHash: secretHash[:],
Recipient: participantEthClient.address().String(),
Expiration: time.Unix(int64(lockTime), 0),
Coin: &coin{
// id: txHash,
value: valg,
},
Contract: dexeth.EncodeContractData(ver, makeLocator(secretHash, valg, lockTime)),
},
Secret: secret[:],
}
}
// waitForReceipt waits for a tx. This is useful on testnet when a tx may be "missing"
// due to reorg. Wait for a few blocks to find the main chain and hopefully our tx.
func waitForReceipt(nc ethFetcher, tx *types.Transaction) (*types.Receipt, error) {
hash := tx.Hash()
// Waiting as much as five blocks.
timesUp := time.After(5 * secPerBlock)
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(time.Second):
receipt, _, err := nc.transactionReceipt(ctx, hash)
if err != nil {
if errors.Is(err, asset.CoinNotFoundError) {
continue
}
return nil, err
}
// spew.Dump(receipt)
return receipt, nil
case <-timesUp:
spew.Dump(tx)
return nil, errors.New("wait for receipt timed out, txn might be missing due to reorg, " +
"check the preceding tx for a bad nonce or low gas cap")
}
}
}
func waitForMinedRPC() error {
hdr, err := ethClient.bestHeader(ctx)
if err != nil {
return err
}
const targetConfs = 1
currentHeight := hdr.Number
barrierHeight := new(big.Int).Add(currentHeight, big.NewInt(targetConfs))
fmt.Println("Waiting for RPC blocks")
for {
select {
case <-time.After(time.Second):
hdr, err = ethClient.bestHeader(ctx)
if err != nil {
return err
}
if hdr.Number.Cmp(barrierHeight) > 0 {
return nil
}
if hdr.Number.Cmp(currentHeight) > 0 {
currentHeight = hdr.Number
fmt.Println("Block mined!!!", new(big.Int).Sub(barrierHeight, currentHeight).Uint64()+1, "to go")
}
case <-ctx.Done():
return ctx.Err()
}
}
}
// waitForMined will multiply the time limit by secPerBlock for
// testnet and mine blocks when on simnet.
func waitForMined(nBlock int, waitTimeLimit bool) error {
timesUp := time.After(time.Duration(nBlock) * secPerBlock)
if useRPC {
return waitForMinedRPC()
}
if !isTestnet {
err := exec.Command("geth", "--datadir="+alphaNodeDir, "attach", "--exec", "miner.start()").Run()
if err != nil {
return err
}
defer func() {
_ = exec.Command("geth", "--datadir="+alphaNodeDir, "attach", "--exec", "miner.stop()").Run()
}()
}
out:
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-timesUp:
return errors.New("timed out")
case <-time.After(time.Second):
// NOTE: Not effectual for providers. waitForMinedRPC
// above handles waiting for mined blocks that we assume
// have our transactions.
txsa, err := ethClient.(txPoolFetcher).pendingTransactions()
if err != nil {
return fmt.Errorf("initiator pendingTransactions error: %v", err)
}
txsb, err := participantEthClient.(txPoolFetcher).pendingTransactions()
if err != nil {
return fmt.Errorf("participant pendingTransactions error: %v", err)
}
if len(txsa)+len(txsb) == 0 {
break out
}
}
}
if waitTimeLimit {
select {
case <-ctx.Done():
return ctx.Err()
case <-timesUp:
}
}
return nil
}
func prepareRPCClient(name, dataDir string, providers []string, net dex.Network) (*multiRPCClient, *accounts.Account, error) {
cfg, err := ChainConfig(net)
if err != nil {
return nil, nil, err
}
c, err := newMultiRPCClient(dataDir, providers, tLogger.SubLogger(name), cfg, net)
if err != nil {
return nil, nil, fmt.Errorf("(%s) newNodeClient error: %v", name, err)
}
if err := c.connect(ctx); err != nil {
return nil, nil, fmt.Errorf("(%s) connect error: %v", name, err)
}
return c, c.creds.acct, nil
}
func rpcEndpoints(net dex.Network) ([]string, []string) {
if net == dex.Testnet {
return rpcProviders, rpcProviders
}
return []string{alphaIPCFile}, []string{betaIPCFile}
}
func prepareTestRPCClients(initiatorDir, participantDir string, net dex.Network) (err error) {
initiatorEndpoints, participantEndpoints := rpcEndpoints(net)
ethClient, simnetAcct, err = prepareRPCClient("initiator", initiatorDir, initiatorEndpoints, net)
if err != nil {
return err
}
fmt.Println("initiator address is", ethClient.address())
participantEthClient, participantAcct, err = prepareRPCClient("participant", participantDir, participantEndpoints, net)
if err != nil {
ethClient.shutdown()
return err
}
fmt.Println("participant address is", participantEthClient.address())
return nil
}
func prepareNodeClient(name, dataDir string, net dex.Network) (*nodeClient, *accounts.Account, error) {
c, err := newNodeClient(getWalletDir(dataDir, net), dexeth.ChainIDs[net], net, tLogger.SubLogger(name))
if err != nil {
return nil, nil, fmt.Errorf("(%s) newNodeClient error: %v", name, err)
}
if err := c.connect(ctx); err != nil {
return nil, nil, fmt.Errorf("(%s) connect error: %v", name, err)
}
accts, err := exportAccountsFromNode(c.node)
if err != nil {
c.shutdown()
return nil, nil, fmt.Errorf("(%s) account export error: %v", name, err)
}
if len(accts) != 1 {
c.shutdown()
return nil, nil, fmt.Errorf("(%s) expected 1 account to be exported but got %v", name, len(accts))
}
if addPeer != "" {
if err = c.addPeer(addPeer); err != nil {
c.shutdown()
return nil, nil, fmt.Errorf("initiator unable to add peer: %w", err)
}
}
return c, &accts[0], nil
}
func prepareTestNodeClients(initiatorDir, participantDir string, net dex.Network) (err error) {
ethClient, simnetAcct, err = prepareNodeClient("initiator", initiatorDir, net)
if err != nil {
return err
}
participantEthClient, participantAcct, err = prepareNodeClient("participant", participantDir, net)
if err != nil {
ethClient.shutdown()
return err
}
fmt.Println("initiator address is", ethClient.address())
fmt.Println("participant address is", participantEthClient.address())
return
}
func runSimnet(m *testing.M) (int, error) {
testTokenID = simnetTokenID
// Create dir if none yet exists. This persists for the life of the
// testing harness.
err := os.MkdirAll(simnetWalletDir, 0755)
if err != nil {
return 1, fmt.Errorf("error creating simnet wallet dir dir: %v", err)
}
err = os.MkdirAll(participantWalletDir, 0755)
if err != nil {
return 1, fmt.Errorf("error creating participant wallet dir: %v", err)
}
tokenGases = &dexeth.Tokens[testTokenID].NetTokens[dex.Simnet].SwapContracts[ver].Gas
// ETH swap contract.
token := dexeth.Tokens[testTokenID].NetTokens[dex.Simnet]
fmt.Printf("ETH swap contract address is %v\n", dexeth.ContractAddresses[ver][dex.Simnet])
fmt.Printf("Token swap contract addr is %v\n", token.SwapContracts[ver].Address)
fmt.Printf("Test token contract addr is %v\n", token.Address)
contractAddr = dexeth.ContractAddresses[ver][dex.Simnet]
initiatorProviders, participantProviders := rpcEndpoints(dex.Simnet)
err = setupWallet(simnetWalletDir, simnetWalletSeed, "localhost:30355", initiatorProviders, dex.Simnet)
if err != nil {
return 1, err
}
err = setupWallet(participantWalletDir, participantWalletSeed, "localhost:30356", participantProviders, dex.Simnet)
if err != nil {
return 1, err
}
if useRPC {
err = prepareTestRPCClients(simnetWalletDir, participantWalletDir, dex.Simnet)
} else {
err = prepareTestNodeClients(simnetWalletDir, participantWalletDir, dex.Simnet)
}
if err != nil {
return 1, err
}
defer ethClient.shutdown()
defer participantEthClient.shutdown()
if err := syncClient(ethClient); err != nil {
return 1, fmt.Errorf("error initializing initiator client: %v", err)
}
if err := syncClient(participantEthClient); err != nil {
return 1, fmt.Errorf("error initializing participant client: %v", err)
}
simnetAddr = simnetAcct.Address
participantAddr = participantAcct.Address
contractAddr, exists := dexeth.ContractAddresses[ver][dex.Simnet]
if !exists || contractAddr == (common.Address{}) {
return 1, fmt.Errorf("no contract address for version %d", ver)
}
if v1 {
prepareV1SimnetContractors()
} else {
prepareV0SimnetContractors()
}
if err := ethClient.unlock(pw); err != nil {
return 1, fmt.Errorf("error unlocking initiator client: %w", err)
}
if err := participantEthClient.unlock(pw); err != nil {
return 1, fmt.Errorf("error unlocking initiator client: %w", err)
}
// Fund the wallets.
send := func(exe, addr, amt string) error {
cmd := exec.CommandContext(ctx, exe, addr, amt)
cmd.Dir = harnessCtlDir
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error running %q: %v", cmd, err)
}
fmt.Printf("result from %q: %s\n", cmd, out)
return nil
}
for _, s := range []*struct {
exe, addr, amt string
}{
{"./sendtoaddress", simnetAddr.String(), "10"},
{"./sendtoaddress", participantAddr.String(), "10"},
{"./sendTokens", simnetAddr.String(), "10"},
{"./sendTokens", participantAddr.String(), "10"},
} {
if err := send(s.exe, s.addr, s.amt); err != nil {
return 1, err
}
}
cmd := exec.CommandContext(ctx, "./mine-alpha", "1")
cmd.Dir = harnessCtlDir
if err := cmd.Run(); err != nil {
return 1, fmt.Errorf("error mining block after funding wallets")
}
code := m.Run()
if code != 0 {
return code, nil
}
if err := ethClient.lock(); err != nil {
return 1, fmt.Errorf("error locking initiator client: %w", err)
}
if err := participantEthClient.lock(); err != nil {
return 1, fmt.Errorf("error locking initiator client: %w", err)
}
return code, nil
}
func runTestnet(m *testing.M) (int, error) {
testTokenID = usdcID
masterToken = dexeth.Tokens[testTokenID]
tokenGases = &masterToken.NetTokens[dex.Testnet].SwapContracts[ver].Gas
if testnetWalletSeed == "" || testnetParticipantWalletSeed == "" {
return 1, errors.New("testnet seeds not set")
}
// Create dir if none yet exists. This persists for the life of the
// testing harness.
err := os.MkdirAll(testnetWalletDir, 0755)
if err != nil {
return 1, fmt.Errorf("error creating testnet wallet dir dir: %v", err)
}
err = os.MkdirAll(testnetParticipantWalletDir, 0755)
if err != nil {
return 1, fmt.Errorf("error creating testnet participant wallet dir: %v", err)
}
secPerBlock = testnetSecPerBlock
contractAddr = dexeth.ContractAddresses[ver][dex.Testnet]
fmt.Printf("ETH swap contract address is %v\n", contractAddr)
initiatorRPC, participantRPC := rpcEndpoints(dex.Testnet)
err = setupWallet(testnetWalletDir, testnetWalletSeed, "localhost:30355", initiatorRPC, dex.Testnet)
if err != nil {
return 1, err
}
err = setupWallet(testnetParticipantWalletDir, testnetParticipantWalletSeed, "localhost:30356", participantRPC, dex.Testnet)
if err != nil {
return 1, err
}
if useRPC {
err = prepareTestRPCClients(testnetWalletDir, testnetParticipantWalletDir, dex.Testnet)
} else {
err = prepareTestNodeClients(testnetWalletDir, testnetParticipantWalletDir, dex.Testnet)
}
if err != nil {
return 1, err
}
defer ethClient.shutdown()
defer participantEthClient.shutdown()
fmt.Println("Testnet nodes starting sync, this may take a while...")
wg := sync.WaitGroup{}
wg.Add(2)
var initerErr, participantErr error
go func() {
initerErr = syncClient(ethClient)
wg.Done()
}()
go func() {
participantErr = syncClient(participantEthClient)
wg.Done()
}()
wg.Wait()
if initerErr != nil {
return 1, fmt.Errorf("error initializing initiator client: %v", initerErr)
}
if participantErr != nil {
return 1, fmt.Errorf("error initializing participant client: %v", participantErr)
}
fmt.Println("Testnet nodes synced!!")
simnetAddr = simnetAcct.Address
participantAddr = participantAcct.Address
contractAddr, exists := dexeth.ContractAddresses[ver][dex.Testnet]
if !exists || contractAddr == (common.Address{}) {
return 1, fmt.Errorf("no contract address for version %d", ver)
}
ctor, tokenCtor := newV0Contractor, newV0TokenContractor
if ver == 1 {
ctor, tokenCtor = newV1Contractor, newV1TokenContractor
}
if simnetContractor, err = ctor(dex.Testnet, contractAddr, simnetAddr, ethClient.contractBackend()); err != nil {
return 1, fmt.Errorf("newV0Contractor error: %w", err)
}
if participantContractor, err = ctor(dex.Testnet, contractAddr, participantAddr, participantEthClient.contractBackend()); err != nil {
return 1, fmt.Errorf("participant newV0Contractor error: %w", err)
}
if err := ethClient.unlock(pw); err != nil {
return 1, fmt.Errorf("error unlocking initiator client: %w", err)
}
if err := participantEthClient.unlock(pw); err != nil {
return 1, fmt.Errorf("error unlocking initiator client: %w", err)
}
if simnetTokenContractor, err = tokenCtor(dex.Testnet, dexeth.Tokens[usdcID], simnetAddr, ethClient.contractBackend()); err != nil {
return 1, fmt.Errorf("newV0TokenContractor error: %w", err)
}
// I don't know why this is needed for the participant client but not
// the initiator. Without this, we'll get a bind.ErrNoCode from
// (*BoundContract).Call while calling (*ERC20Swap).TokenAddress.
time.Sleep(time.Second)
if participantTokenContractor, err = tokenCtor(dex.Testnet, dexeth.Tokens[usdcID], participantAddr, participantEthClient.contractBackend()); err != nil {
return 1, fmt.Errorf("participant newV0TokenContractor error: %w", err)
}
code := m.Run()
if code != 0 {
return code, nil
}
if err := ethClient.lock(); err != nil {
return 1, fmt.Errorf("error locking initiator client: %w", err)
}
if err := participantEthClient.lock(); err != nil {
return 1, fmt.Errorf("error locking initiator client: %w", err)
}
return code, nil
}
func prepareV0SimnetContractors() (err error) {
return prepareSimnetContractors(newV0Contractor, newV0TokenContractor)
}
func prepareV1SimnetContractors() (err error) {
return prepareSimnetContractors(newV1Contractor, newV1TokenContractor)
}
func prepareSimnetContractors(c contractorConstructor, tc tokenContractorConstructor) (err error) {
if simnetContractor, err = c(dex.Simnet, contractAddr, simnetAddr, ethClient.contractBackend()); err != nil {
return fmt.Errorf("new contractor error: %w", err)
}
if participantContractor, err = c(dex.Simnet, contractAddr, participantAddr, participantEthClient.contractBackend()); err != nil {
return fmt.Errorf("participant new contractor error: %w", err)
}
if simnetTokenContractor, err = tc(dex.Simnet, masterToken, simnetAddr, ethClient.contractBackend()); err != nil {
return fmt.Errorf("new token contractor error: %w", err)
}
// I don't know why this is needed for the participant client but not
// the initiator. Without this, we'll get a bind.ErrNoCode from
// (*BoundContract).Call while calling (*ERC20Swap).TokenAddress.
time.Sleep(time.Second)
if participantTokenContractor, err = tc(dex.Simnet, masterToken, participantAddr, participantEthClient.contractBackend()); err != nil {
return fmt.Errorf("participant new token contractor error: %w", err)
}
return
}
func useTestnet() error {
isTestnet = true
b, err := os.ReadFile(filepath.Join(homeDir, "dextest", "credentials.json"))
if err != nil {
return fmt.Errorf("error reading credentials file: %v", err)
}
var creds providersFile
if err = json.Unmarshal(b, &creds); err != nil {
return fmt.Errorf("error decoding credential: %w", err)
}
if len(creds.Seed) == 0 {
return errors.New("no seed found in credentials file")
}
seed2 := sha256.Sum256(creds.Seed)
testnetWalletSeed = hex.EncodeToString(creds.Seed)
testnetParticipantWalletSeed = hex.EncodeToString(seed2[:])
rpcProviders = creds.Providers["eth"][dex.Testnet.String()]
return nil
}
func TestMain(m *testing.M) {
rand.Seed(time.Now().UnixNano())
dexeth.MaybeReadSimnetAddrs()
flag.BoolVar(&isTestnet, "testnet", false, "use testnet")
flag.BoolVar(&useRPC, "rpc", true, "use RPC")
flag.BoolVar(&v1, "v1", true, "Use Version 1 contract")
flag.Parse()
if v1 {
ver = 1
}
ethGases = dexeth.VersionedGases[ver]
contractAddr = dexeth.ContractAddresses[BipID][dex.Simnet]
if isTestnet {
contractAddr = dexeth.ContractAddresses[BipID][dex.Testnet]
tmpDir, err := os.MkdirTemp("", "")
if err != nil {
fmt.Fprintf(os.Stderr, "error creating temporary directory: %v", err)
os.Exit(1)
}
testnetWalletDir = filepath.Join(tmpDir, "initiator")
defer os.RemoveAll(testnetWalletDir)
testnetParticipantWalletDir = filepath.Join(tmpDir, "participant")
defer os.RemoveAll(testnetParticipantWalletDir)
if err := useTestnet(); err != nil {
fmt.Fprintf(os.Stderr, "error loading testnet: %v", err)
os.Exit(1)
}
}
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(context.Background())
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
select {
case <-c:
cancel()
case <-ctx.Done():
}
}()
// Run in function so that defers happen before os.Exit is called.
run := runSimnet
if isTestnet {
run = runTestnet
}
exitCode, err := run(m)
if err != nil {
fmt.Println(err)
}
signal.Stop(c)
cancel()
os.Exit(exitCode)
}
func setupWallet(walletDir, seed, listenAddress string, providers []string, net dex.Network) error {
walletType := walletTypeGeth
settings := map[string]string{
"nodelistenaddr": listenAddress,
}
if useRPC {
walletType = walletTypeRPC
settings = map[string]string{
providersKey: strings.Join(providers, " "),
}
}
seedB, _ := hex.DecodeString(seed)
createWalletParams := asset.CreateWalletParams{
Type: walletType,
Seed: seedB,
Pass: []byte(pw),
Settings: settings,
DataDir: walletDir,
Net: net,
Logger: tLogger,
}
compat, err := NetworkCompatibilityData(net)
if err != nil {
return err
}
return CreateEVMWallet(dexeth.ChainIDs[net], &createWalletParams, &compat, true)
}
func prepareTokenClients(t *testing.T) {
err := ethClient.unlock(pw)
if err != nil {
t.Fatalf("initiator unlock error; %v", err)
}
txOpts, err := ethClient.txOpts(ctx, 0, tokenGases.Approve, nil, nil)
if err != nil {
t.Fatalf("txOpts error: %v", err)
}
var tx1, tx2 *types.Transaction
if tx1, err = simnetTokenContractor.approve(txOpts, unlimitedAllowance); err != nil {
t.Fatalf("initiator approveToken error: %v", err)
}
err = participantEthClient.unlock(pw)
if err != nil {
t.Fatalf("participant unlock error; %v", err)
}
txOpts, err = participantEthClient.txOpts(ctx, 0, tokenGases.Approve, nil, nil)
if err != nil {
t.Fatalf("txOpts error: %v", err)
}
if tx2, err = participantTokenContractor.approve(txOpts, unlimitedAllowance); err != nil {
t.Fatalf("participant approveToken error: %v", err)
}
if err := waitForMined(8, true); err != nil {
t.Fatalf("unexpected error while waiting to mine approval block: %v", err)
}
_, err = waitForReceipt(ethClient, tx1)
if err != nil {
t.Fatal(err)
}
// spew.Dump(receipt1)
_, err = waitForReceipt(participantEthClient, tx2)
if err != nil {
t.Fatal(err)
}
// spew.Dump(receipt2)
}
func syncClient(cl ethFetcher) error {
giveUpAt := 60
if isTestnet {
giveUpAt = 10000
}
for i := 0; ; i++ {
if err := ctx.Err(); err != nil {
return err
}
prog, tipTime, err := cl.syncProgress(ctx)
if err != nil {
return err
}
if isTestnet {
timeDiff := time.Now().Unix() - int64(tipTime)
if timeDiff < dexeth.MaxBlockInterval {
return nil
}
} else {
// If client has ever synced, assume synced with
// harness. This avoids checking the header time which
// is probably old.
if prog.CurrentBlock > 20 {
return nil
}
}
if i == giveUpAt {
return fmt.Errorf("block count has not synced in %d seconds", giveUpAt)
}
time.Sleep(time.Second)
}
}
func TestBasicRetrieval(t *testing.T) {
if !t.Run("testAddressesHaveFunds", testAddressesHaveFundsFn(100_000 /* gwei */)) {
t.Fatal("not enough funds")
}
t.Run("testBestHeader", testBestHeader)
t.Run("testPendingTransactions", testPendingTransactions)
t.Run("testHeaderByHash", testHeaderByHash)
t.Run("testTransactionReceipt", testTransactionReceipt)
}
func TestPeering(t *testing.T) {
t.Run("testAddPeer", testAddPeer)
t.Run("testSyncProgress", testSyncProgress)
t.Run("testGetCodeAt", testGetCodeAt)
}
func TestAccount(t *testing.T) {
if !t.Run("testAddressesHaveFunds", testAddressesHaveFundsFn(10_000_000 /* gwei */)) {
t.Fatal("not enough funds")
}
t.Run("testAddressBalance", testAddressBalance)
t.Run("testSendTransaction", testSendTransaction)
t.Run("testSendSignedTransaction", testSendSignedTransaction)
t.Run("testSignMessage", testSignMessage)
}
// TestContract tests methods that interact with the contract.
func TestContract(t *testing.T) {
if !t.Run("testAddressesHaveFunds", testAddressesHaveFundsFn(100_000_000 /* gwei */)) {
t.Fatal("not enough funds")
}
// t.Run("testSwap", func(t *testing.T) { testSwap(t, BipID) }) // TODO: Replace with testStatusAndVector?
t.Run("testInitiate", func(t *testing.T) { testInitiate(t, BipID) })
t.Run("testRedeem", func(t *testing.T) { testRedeem(t, BipID) })
t.Run("testRefund", func(t *testing.T) { testRefund(t, BipID) })
}
func TestGas(t *testing.T) {
// t.Run("testInitiateGas", func(t *testing.T) { testInitiateGas(t, BipID) })
t.Run("testRedeemGas", func(t *testing.T) { testRedeemGas(t, BipID) })
t.Run("testRefundGas", func(t *testing.T) { testRefundGas(t, BipID) })
}
func TestTokenContract(t *testing.T) {
// t.Run("testTokenSwap", func(t *testing.T) { testSwap(t, testTokenID) }) // TODO: Replace with testTokenStatusAndVector?
t.Run("testInitiateToken", func(t *testing.T) { testInitiate(t, testTokenID) })
t.Run("testRedeemToken", func(t *testing.T) { testRedeem(t, testTokenID) })
t.Run("testRefundToken", func(t *testing.T) { testRefund(t, testTokenID) })
}
func TestTokenGas(t *testing.T) {
t.Run("testTransferGas", testTransferGas)
t.Run("testApproveGas", testApproveGas)
// t.Run("testInitiateTokenGas", func(t *testing.T) { testInitiateGas(t, testTokenID) })
t.Run("testRedeemTokenGas", func(t *testing.T) { testRedeemGas(t, testTokenID) })
t.Run("testRefundTokenGas", func(t *testing.T) { testRefundGas(t, testTokenID) })
}
func TestTokenAccess(t *testing.T) {
t.Run("testTokenBalance", testTokenBalance)
t.Run("testApproveAllowance", testApproveAllowance)
}
func testAddPeer(t *testing.T) {
c, is := ethClient.(*nodeClient)
if !is {
t.Skip("add peer not supported for RPC clients")
}
if err := c.addPeer(alphaNode); err != nil {
t.Fatal(err)
}
}
func testBestHeader(t *testing.T) {
bh, err := ethClient.bestHeader(ctx)
if err != nil {
t.Fatal(err)
}
spew.Dump(bh)
}
func testAddressBalance(t *testing.T) {
bal, err := ethClient.addressBalance(ctx, simnetAddr)
if err != nil {
t.Fatalf("error getting initiator balance: %v", err)
}
if bal == nil {
t.Fatalf("empty balance")
}
fmt.Printf("Initiator balance: %.9f ETH \n", float64(dexeth.WeiToGwei(bal))/dexeth.GweiFactor)
bal, err = participantEthClient.addressBalance(ctx, participantAddr)
if err != nil {
t.Fatalf("error getting participant balance: %v", err)
}
fmt.Printf("Participant balance: %.9f ETH \n", float64(dexeth.WeiToGwei(bal))/dexeth.GweiFactor)
}
func testTokenBalance(t *testing.T) {
bal, err := simnetTokenContractor.balance(ctx)
if err != nil {
t.Fatal(err)
}
if bal == nil {
t.Fatalf("empty balance")
}
fmt.Println("### Balance:", simnetAddr, stringifyTokenBalance(t, bal))
}
func stringifyTokenBalance(t *testing.T, evmBal *big.Int) string {
t.Helper()
atomicBal := masterToken.EVMToAtomic(evmBal)
ui, err := asset.UnitInfo(testTokenID)
if err != nil {
t.Fatalf("cannot get unit info: %v", err)
}
prec := math.Round(math.Log10(float64(ui.Conventional.ConversionFactor)))
return strconv.FormatFloat(float64(atomicBal)/float64(ui.Conventional.ConversionFactor), 'f', int(prec), 64)
}
// testAddressesHaveFundsFn returns a function that tests that addresses used
// in tests have enough funds to complete those tests.
func testAddressesHaveFundsFn(amt uint64) func(t *testing.T) {
return func(t *testing.T) {
checkAddr := func(addr common.Address) error {
bal, err := ethClient.addressBalance(ctx, addr)
if err != nil {
return err
}
if bal == nil {
return errors.New("empty balance")
}
gweiBal := dexeth.WeiToGwei(bal)
if gweiBal < amt {
fmt.Printf("Balance is too low to test. Send more than %v test eth to %v.\n", float64(amt-gweiBal)/1e9, addr)
return fmt.Errorf("balance too low")
}
return nil
}
var errs error
if err := checkAddr(simnetAddr); err != nil {
errs = fmt.Errorf("client one: %v", err)
}
if err := checkAddr(participantAddr); err != nil {
err = fmt.Errorf("client two: %v", err)
if errs != nil {
errs = fmt.Errorf("%v: %v", errs, err)
} else {
errs = err
}
}
if errs != nil {
t.Fatal(errs)
}
}
}
func testSendTransaction(t *testing.T) {
// Checking confirmations for a random hash should result in not found error.
var txHash common.Hash
copy(txHash[:], encode.RandomBytes(32))
_, err := ethClient.transactionConfirmations(ctx, txHash)
if !errors.Is(err, asset.CoinNotFoundError) {
t.Fatalf("no CoinNotFoundError")
}
txOpts, err := ethClient.txOpts(ctx, 1, defaultSendGasLimit, nil, nil)
if err != nil {
t.Fatalf("txOpts error: %v", err)
}
tx, err := ethClient.sendTransaction(ctx, txOpts, participantAddr, nil)