forked from 0xPolygon/polygon-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadtest.go
More file actions
2017 lines (1801 loc) · 63.9 KB
/
loadtest.go
File metadata and controls
2017 lines (1801 loc) · 63.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
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
package loadtest
import (
"bufio"
"context"
"crypto/ecdsa"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"math/rand"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto/kzg4844"
"github.com/ethereum/go-ethereum/signer/core/apitypes"
"github.com/holiman/uint256"
"github.com/0xPolygon/polygon-cli/bindings/tester"
"github.com/0xPolygon/polygon-cli/bindings/tokens"
uniswapv3loadtest "github.com/0xPolygon/polygon-cli/cmd/loadtest/uniswapv3"
"github.com/0xPolygon/polygon-cli/abi"
"github.com/0xPolygon/polygon-cli/rpctypes"
"github.com/0xPolygon/polygon-cli/util"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
ethcommon "github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
ethrpc "github.com/ethereum/go-ethereum/rpc"
"github.com/rs/zerolog/log"
"golang.org/x/time/rate"
)
//go:generate stringer -type=loadTestMode
type (
loadTestMode int
)
const (
// These constants are "stringered".
// If you add a new constant, it fill fail to compile until you regenerate the strings.
// There are two steps needed:
// 1. Install stringer: `go install golang.org/x/tools/cmd/stringer`.
// 2. Generate the string: `go generate github.com/0xPolygon/polygon-cli/cmd/loadtest`.
// You can also use `make gen-loadtest-modes`.
loadTestModeERC20 loadTestMode = iota
loadTestModeERC721
loadTestModeBlob
loadTestModeCall
loadTestModeContractCall
loadTestModeDeploy
loadTestModeFunction
loadTestModeInscription
loadTestModeIncrement
loadTestModeRandomPrecompiledContract
loadTestModeSpecificPrecompiledContract
loadTestModeRandom
loadTestModeRecall
loadTestModeRPC
loadTestModeStore
loadTestModeTransaction
loadTestModeUniswapV3
codeQualitySeed = "code code code code code code code code code code code quality"
codeQualityPrivateKey = "42b6e34dc21598a807dc19d7784c71b2a7a01f6480dc6f58258f78e539f1a1fa"
)
func characterToLoadTestMode(mode string) (loadTestMode, error) {
switch mode {
case "2", "erc20":
return loadTestModeERC20, nil
case "7", "erc721":
return loadTestModeERC721, nil
case "b", "blob":
return loadTestModeBlob, nil
case "c", "call":
return loadTestModeCall, nil
case "cc", "contract-call":
return loadTestModeContractCall, nil
case "d", "deploy":
return loadTestModeDeploy, nil
case "f", "function":
return loadTestModeFunction, nil
case "i", "inscription":
return loadTestModeInscription, nil
case "inc", "increment":
return loadTestModeIncrement, nil
case "pr", "random-precompile":
return loadTestModeRandomPrecompiledContract, nil
case "px", "specific-precompile":
return loadTestModeSpecificPrecompiledContract, nil
case "r", "random":
return loadTestModeRandom, nil
case "R", "recall":
return loadTestModeRecall, nil
case "rpc":
return loadTestModeRPC, nil
case "s", "store":
return loadTestModeStore, nil
case "t", "transaction":
return loadTestModeTransaction, nil
case "v3", "uniswapv3":
return loadTestModeUniswapV3, nil
default:
return 0, fmt.Errorf("unrecognized load test mode: %s", mode)
}
}
func getRandomMode() loadTestMode {
// Does not include the following modes:
// blob, call, contract call, inscription,
// recall, rpc, uniswap v3
modes := []loadTestMode{
loadTestModeERC20,
loadTestModeERC721,
// loadTestModeBlob,
// loadTestModeCall,
// loadTestModeContractCall,
loadTestModeDeploy,
loadTestModeFunction,
// loadTestModeInscription,
loadTestModeIncrement,
loadTestModeRandomPrecompiledContract,
loadTestModeSpecificPrecompiledContract,
// loadTestModeRandom,
// loadTestModeRecall,
// loadTestModeRPC,
loadTestModeStore,
loadTestModeTransaction,
// loadTestModeUniswapV3,
}
return modes[randSrc.Intn(len(modes))]
}
func modeRequiresLoadTestContract(m loadTestMode) bool {
if m == loadTestModeCall ||
m == loadTestModeFunction ||
m == loadTestModeIncrement ||
m == loadTestModeRandom ||
m == loadTestModeStore ||
m == loadTestModeRandomPrecompiledContract ||
m == loadTestModeSpecificPrecompiledContract {
return true
}
return false
}
func anyModeRequiresLoadTestContract(modes []loadTestMode) bool {
for _, m := range modes {
if modeRequiresLoadTestContract(m) {
return true
}
}
return false
}
func hasMode(mode loadTestMode, modes []loadTestMode) bool {
for _, m := range modes {
if m == mode {
return true
}
}
return false
}
func hasUniqueModes(modes []loadTestMode) bool {
seen := make(map[loadTestMode]bool, len(modes))
for _, m := range modes {
if !seen[m] {
seen[m] = true
} else {
return false
}
}
return true
}
func initializeLoadTestParams(ctx context.Context, c *ethclient.Client) error {
log.Info().Msg("Connecting with RPC endpoint to initialize load test parameters")
gas, err := c.SuggestGasPrice(ctx)
if err != nil {
log.Error().Err(err).Msg("Unable to retrieve gas price")
return err
}
log.Trace().Interface("gasprice", gas).Msg("Retrieved current gas price")
if !*inputLoadTestParams.LegacyTransactionMode {
gasTipCap, _err := c.SuggestGasTipCap(ctx)
if _err != nil {
log.Error().Err(_err).Msg("Unable to retrieve gas tip cap")
return _err
}
log.Trace().Interface("gastipcap", gasTipCap).Msg("Retrieved current gas tip cap")
inputLoadTestParams.CurrentGasTipCap = gasTipCap
}
trimmedHexPrivateKey := strings.TrimPrefix(*inputLoadTestParams.PrivateKey, "0x")
privateKey, err := ethcrypto.HexToECDSA(trimmedHexPrivateKey)
if err != nil {
log.Error().Err(err).Msg("Couldn't process the hex private key")
return err
}
blockNumber, err := c.BlockNumber(ctx)
bigBlockNumber := big.NewInt(int64(blockNumber))
if err != nil {
log.Error().Err(err).Msg("Couldn't get the current block number")
return err
}
log.Trace().Uint64("blocknumber", blockNumber).Msg("Current Block Number")
ethAddress := ethcrypto.PubkeyToAddress(privateKey.PublicKey)
nonce, err := c.NonceAt(ctx, ethAddress, bigBlockNumber)
if err != nil {
log.Error().Err(err).Msg("Unable to get account nonce")
return err
}
accountBal, err := c.BalanceAt(ctx, ethAddress, bigBlockNumber)
if err != nil {
log.Error().Err(err).Msg("Unable to get the balance for the account")
return err
}
log.Trace().
Str("addr", ethAddress.Hex()).
Interface("balance", accountBal).
Msg("funding account balance")
toAddr := ethcommon.HexToAddress(*inputLoadTestParams.ToAddress)
amt := new(big.Int).SetUint64(*inputLoadTestParams.EthAmountInWei)
header, err := c.HeaderByNumber(ctx, nil)
if err != nil {
log.Error().Err(err).Msg("Unable to get header")
return err
}
if header.BaseFee != nil {
inputLoadTestParams.ChainSupportBaseFee = true
log.Debug().Msg("Eip-1559 support detected")
}
chainID, err := c.ChainID(ctx)
if err != nil {
log.Error().Err(err).Msg("Unable to fetch chain ID")
return err
}
log.Trace().Uint64("chainID", chainID.Uint64()).Msg("Detected Chain ID")
inputLoadTestParams.BigGasPriceMultiplier = big.NewFloat(*inputLoadTestParams.GasPriceMultiplier)
if *inputLoadTestParams.LegacyTransactionMode && *inputLoadTestParams.ForcePriorityGasPrice > 0 {
log.Warn().Msg("Cannot set priority gas price in legacy mode")
}
if *inputLoadTestParams.ForceGasPrice < *inputLoadTestParams.ForcePriorityGasPrice {
return errors.New("max priority fee per gas higher than max fee per gas")
}
if *inputLoadTestParams.AdaptiveRateLimit && *inputLoadTestParams.CallOnly {
return errors.New("the adaptive rate limit is based on the pending transaction pool. It doesn't use this feature while also using call only")
}
contractAddr := ethcommon.HexToAddress(*inputLoadTestParams.ContractAddress)
inputLoadTestParams.ContractETHAddress = &contractAddr
inputLoadTestParams.ToETHAddress = &toAddr
inputLoadTestParams.SendAmount = amt
inputLoadTestParams.CurrentGasPrice = gas
inputLoadTestParams.CurrentNonce = &nonce
inputLoadTestParams.ECDSAPrivateKey = privateKey
inputLoadTestParams.FromETHAddress = ðAddress
if *inputLoadTestParams.ChainID == 0 {
*inputLoadTestParams.ChainID = chainID.Uint64()
}
modes := *inputLoadTestParams.Modes
if len(modes) == 0 {
return errors.New("expected at least one mode")
}
inputLoadTestParams.ParsedModes = make([]loadTestMode, 0)
for _, m := range modes {
var parsedMode loadTestMode
parsedMode, err = characterToLoadTestMode(m)
if err != nil {
return err
}
inputLoadTestParams.ParsedModes = append(inputLoadTestParams.ParsedModes, parsedMode)
}
// Logic checking input parameters for specific conditions such as multiple inputs.
if len(modes) > 1 {
inputLoadTestParams.MultiMode = true
if !hasUniqueModes(inputLoadTestParams.ParsedModes) {
return errors.New("duplicate modes detected, check input modes for duplicates")
}
} else {
inputLoadTestParams.MultiMode = false
inputLoadTestParams.Mode, _ = characterToLoadTestMode((*inputLoadTestParams.Modes)[0])
}
if hasMode(loadTestModeRandom, inputLoadTestParams.ParsedModes) && inputLoadTestParams.MultiMode {
return errors.New("random mode can't be used in combinations with any other modes")
}
if hasMode(loadTestModeRPC, inputLoadTestParams.ParsedModes) && inputLoadTestParams.MultiMode && !*inputLoadTestParams.CallOnly {
return errors.New("rpc mode must be called with call-only when multiple modes are used")
} else if hasMode(loadTestModeRPC, inputLoadTestParams.ParsedModes) {
log.Trace().Msg("Setting call only mode since we're doing RPC testing")
*inputLoadTestParams.CallOnly = true
}
if hasMode(loadTestModeContractCall, inputLoadTestParams.ParsedModes) && (*inputLoadTestParams.ContractAddress == "" || (*inputLoadTestParams.ContractCallData == "" && *inputLoadTestParams.ContractCallFunctionSignature == "")) {
return errors.New("`--contract-call` requires both a `--contract-address` and calldata, either with `--calldata` or `--function-signature --function-arg` flags")
}
if *inputLoadTestParams.CallOnly && *inputLoadTestParams.AdaptiveRateLimit {
return errors.New("using call only with adaptive rate limit doesn't make sense")
}
if hasMode(loadTestModeBlob, inputLoadTestParams.ParsedModes) && inputLoadTestParams.MultiMode {
return errors.New("blob mode should only be used by itself. Blob mode will take significantly longer than other transactions to finalize, and the address will be reserved, preventing other transactions form being made")
}
randSrc = rand.New(rand.NewSource(*inputLoadTestParams.Seed))
// setup account pool
fundingAmount := inputLoadTestParams.AddressFundingAmount
sendingAddressCount := *inputLoadTestParams.SendingAddressCount
sendingAddressesFile := *inputLoadTestParams.SendingAddressesFile
accountPool, err = NewAccountPool(ctx, c, privateKey, fundingAmount)
if err != nil {
log.Error().Err(err).Msg("Unable to create account pool")
return fmt.Errorf("unable to create account pool. %w", err)
}
if len(sendingAddressesFile) > 0 {
log.Trace().
Str("sendingAddressFile", sendingAddressesFile).
Msg("Adding accounts from file to the account pool")
privateKeys, iErr := readPrivateKeysFromFile(sendingAddressesFile)
if iErr != nil {
log.Error().
Err(iErr).
Msg("Unable to read private keys from file")
return fmt.Errorf("unable to read private keys from file. %w", iErr)
}
if len(privateKeys) == 0 && *inputLoadTestParams.StartNonce > 0 {
log.Fatal().
Str("sendingAddressFile", sendingAddressesFile).
Msg("nonce can't be set while using multiple sending accounts")
}
err = accountPool.AddN(ctx, privateKeys...)
} else if sendingAddressCount > 1 {
log.Trace().
Uint64("sendingAddressCount", sendingAddressCount).
Msg("Adding random accounts to the account pool")
if *inputLoadTestParams.StartNonce > 0 {
log.Fatal().
Uint64("sendingAddressCount", sendingAddressCount).
Msg("nonce can't be set while using multiple sending accounts")
}
err = accountPool.AddRandomN(ctx, sendingAddressCount)
} else {
log.Trace().
Uint64("sendingAddressCount", sendingAddressCount).
Msg("Using the same account for all transactions")
var nonce *uint64
if *inputLoadTestParams.StartNonce > 0 {
nonce = inputLoadTestParams.StartNonce
}
err = accountPool.Add(ctx, privateKey, nonce)
}
if err != nil {
log.Error().Err(err).Msg("unable to set account pool")
return fmt.Errorf("unable to set account pool. %w", err)
}
preFundSendingAddresses := *inputLoadTestParams.PreFundSendingAddresses
if preFundSendingAddresses && inputLoadTestParams.AddressFundingAmount.Cmp(new(big.Int)) > 0 {
err := accountPool.FundAccounts(ctx)
if err != nil {
log.Error().Err(err).Msg("Unable to fund sending addresses")
iErr := accountPool.ReturnFunds(ctx)
if iErr != nil {
log.Error().
Err(iErr).
Msg("There was an issue returning the funds from the sending addresses back to the funding address")
return fmt.Errorf("unable to return funds from sending addresses. %w", iErr)
}
return fmt.Errorf("unable to fund sending addresses. %w", err)
}
}
return nil
}
func readPrivateKeysFromFile(sendingAddressesFile string) ([]*ecdsa.PrivateKey, error) {
file, err := os.Open(sendingAddressesFile)
if err != nil {
return nil, fmt.Errorf("unable to open sending addresses file: %w", err)
}
defer file.Close()
var privateKeys []*ecdsa.PrivateKey
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) == 0 {
continue
}
privateKey, err := ethcrypto.HexToECDSA(strings.TrimPrefix(line, "0x"))
if err != nil {
log.Error().Err(err).Str("key", line).Msg("Unable to parse private key")
return nil, fmt.Errorf("unable to parse private key: %w", err)
}
privateKeys = append(privateKeys, privateKey)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading sending address file: %w", err)
}
return privateKeys, nil
}
func completeLoadTest(ctx context.Context, c *ethclient.Client, rpc *ethrpc.Client) error {
if *inputLoadTestParams.SendOnly {
log.Info().
Msg("SendOnly mode enabled - skipping wait period and summarization")
return nil
}
log.Debug().
Msg("Waiting for remaining transactions to be completed and mined")
startTime := loadTestResults[0].RequestTime
endTime := time.Now()
log.Debug().
Uint64("final block number", finalBlockNumber).
Msg("Got final block number")
if *inputLoadTestParams.CallOnly {
log.Info().Msg("CallOnly mode enabled - blocks aren't mined")
lightSummary(loadTestResults, startTime, endTime, rl)
return nil
}
var err error
finalBlockNumber, err = waitForFinalBlock(ctx, c, rpc, startBlockNumber)
if err != nil {
log.Error().
Err(err).
Msg("There was an issue waiting for all transactions to be mined")
}
if len(loadTestResults) == 0 {
return errors.New("no transactions observed")
}
err = accountPool.ReturnFunds(ctx)
if err != nil {
log.Error().
Err(err).
Msg("There was an issue returning the funds from the sending addresses back to the funding address")
}
if *inputLoadTestParams.ShouldProduceSummary {
err = summarizeTransactions(ctx, c, rpc, startBlockNumber, finalBlockNumber)
if err != nil {
log.Error().
Err(err).
Msg("There was an issue creating the load test summary")
}
}
lightSummary(loadTestResults, startTime, endTime, rl)
return nil
}
// runLoadTest initiates and runs the entire load test process, including initialization,
// the main load test loop, and the completion steps. It takes a context for cancellation signals.
// The function returns an error if there are issues during the load test process.
func runLoadTest(ctx context.Context) error {
log.Info().Msg("Starting Load Test")
// Configure the overall time limit for the load test.
timeLimit := *inputLoadTestParams.TimeLimit
var overallTimer *time.Timer
if timeLimit > 0 {
overallTimer = time.NewTimer(time.Duration(timeLimit) * time.Second)
} else {
overallTimer = new(time.Timer)
}
// connLimit is the value we'll use to configure the connection limit within the http transport
connLimit := 2 * int(*inputLoadTestParams.Concurrency)
// Most of these transport options are defaults. We might want to make this configurable from the CLI at some point.
// The goal here is to avoid opening a ton of connections that go idle then get closed and eventually exhausting
// client-side connections.
transport := &http.Transport{
MaxIdleConns: connLimit,
MaxIdleConnsPerHost: connLimit,
MaxConnsPerHost: connLimit,
}
if inputLoadTestParams.Proxy != nil && *inputLoadTestParams.Proxy != "" {
proxyURL, err := url.Parse(*inputLoadTestParams.Proxy)
if err != nil {
return fmt.Errorf("invalid proxy address %s %w", *inputLoadTestParams.Proxy, err)
}
proxyFunc := http.ProxyURL(proxyURL)
transport.Proxy = proxyFunc
log.Debug().Stringer("proxyURL", proxyURL).Msg("transport proxy configured")
}
goHttpClient := &http.Client{
Transport: transport,
}
rpcOption := ethrpc.WithHTTPClient(goHttpClient)
rpc, err := ethrpc.DialOptions(ctx, *inputLoadTestParams.RPCUrl, rpcOption)
if err != nil {
log.Error().Err(err).Msg("Unable to dial rpc")
return err
}
defer rpc.Close()
rpc.SetHeader("Accept-Encoding", "identity")
ec := ethclient.NewClient(rpc)
// Define the main loop function.
// Make sure to define any logic associated to the load test (initialization, main load test loop
// or completion steps) in this function in order to handle cancellation signals properly.
loopFunc := func() error {
if err = initializeLoadTestParams(ctx, ec); err != nil {
log.Error().Err(err).Msg("Error initializing load test parameters")
return err
}
if err = mainLoop(ctx, ec, rpc); err != nil {
log.Error().Err(err).Msg("Error during the main load test loop")
return err
}
log.Debug().
Msg("Finished main load test loop")
if err = completeLoadTest(ctx, ec, rpc); err != nil {
log.Error().Err(err).Msg("Encountered error while wrapping up loadtest")
}
return nil
}
// Set up signal handling for interrupts.
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
// Initialize channels for handling errors and running the main loop.
loadTestResults = make([]loadTestSample, 0)
errCh := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func(ctx context.Context) {
select {
case <-ctx.Done():
return
default:
errCh <- loopFunc()
}
}(ctx)
// Wait for the load test to complete, either due to time limit, interrupt signal, or completion.
select {
case <-overallTimer.C:
log.Info().Msg("Time's up")
case <-sigCh:
log.Info().Msg("Interrupted.. Stopping load test")
if *inputLoadTestParams.ShouldProduceSummary {
finalBlockNumber, err = ec.BlockNumber(ctx)
if err != nil {
log.Error().Err(err).Msg("Unable to retrieve final block number")
}
err = summarizeTransactions(ctx, ec, rpc, startBlockNumber, finalBlockNumber)
if err != nil {
log.Error().Err(err).Msg("There was an issue creating the load test summary")
}
} else {
if len(loadTestResults) > 0 {
lightSummary(loadTestResults, loadTestResults[0].RequestTime, time.Now(), rl)
}
}
cancel()
case err = <-errCh:
if err != nil {
log.Fatal().Err(err).Msg("Received critical error while running load test")
}
}
log.Info().Msg("Finished")
return nil
}
func updateRateLimit(ctx context.Context, rl *rate.Limiter, rpc *ethrpc.Client, accountPool *AccountPool, steadyStateQueueSize uint64, rateLimitIncrement uint64, cycleDuration time.Duration, backoff float64) {
tryTxPool := true
ticker := time.NewTicker(cycleDuration)
defer ticker.Stop()
for {
select {
case <-ticker.C:
var txPoolSize uint64
var err error
var pendingTxs uint64
var queuedTxs uint64
// TODO perhaps this should be a mode rather than a fallback
if tryTxPool {
pendingTxs, queuedTxs, err = util.GetTxPoolStatus(rpc)
}
if err != nil {
tryTxPool = false
log.Warn().
Err(err).
Msg("Error getting txpool size. Falling back to latest nonce and disabling txpool check")
pendingTxs, err = accountPool.NumberOfPendingTxs(ctx)
if err != nil {
log.Error().
Err(err).
Msg("Unable to get pending transactions to update rate limit")
break
}
txPoolSize = pendingTxs
} else {
txPoolSize = pendingTxs + queuedTxs
}
if txPoolSize < steadyStateQueueSize {
// additively increment requests per second if txpool less than queue steady state
newRateLimit := rate.Limit(float64(rl.Limit()) + float64(rateLimitIncrement))
rl.SetLimit(newRateLimit)
log.Info().Float64("New Rate Limit (RPS)", float64(rl.Limit())).Uint64("Current Tx Pool Size", txPoolSize).Uint64("Steady State Tx Pool Size", steadyStateQueueSize).Msg("Increased rate limit")
} else if txPoolSize > steadyStateQueueSize {
// halve rate limit requests per second if txpool greater than queue steady state
rl.SetLimit(rl.Limit() / rate.Limit(backoff))
log.Info().Float64("New Rate Limit (RPS)", float64(rl.Limit())).Uint64("Current Tx Pool Size", txPoolSize).Uint64("Steady State Tx Pool Size", steadyStateQueueSize).Msg("Backed off rate limit")
}
case <-ctx.Done():
return
}
}
}
func mainLoop(ctx context.Context, c *ethclient.Client, rpc *ethrpc.Client) error {
ltp := inputLoadTestParams
log.Trace().Interface("Input Params", ltp).Msg("Params")
maxRoutines := *ltp.Concurrency
maxRequests := *ltp.Requests
chainID := new(big.Int).SetUint64(*ltp.ChainID)
privateKey := ltp.ECDSAPrivateKey
mode := ltp.Mode
steadyStateTxPoolSize := *ltp.SteadyStateTxPoolSize
adaptiveRateLimitIncrement := *ltp.AdaptiveRateLimitIncrement
rl = rate.NewLimiter(rate.Limit(*ltp.RateLimit), 1)
if *ltp.RateLimit <= 0.0 {
rl = nil
}
rateLimitCtx, cancel := context.WithCancel(ctx)
defer cancel()
if *ltp.AdaptiveRateLimit && rl != nil {
go updateRateLimit(rateLimitCtx, rl, rpc, accountPool, steadyStateTxPoolSize, adaptiveRateLimitIncrement, time.Duration(*ltp.AdaptiveCycleDuration)*time.Second, *ltp.AdaptiveBackoffFactor)
}
tops, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
tops = configureTransactOpts(ctx, c, tops)
// configureTransactOpts will set some parameters meant for load testing that could interfere with the deployment of our contracts
tops.GasLimit = 0
tops.GasPrice = nil
tops.GasFeeCap = nil
tops.GasTipCap = nil
if err != nil {
log.Error().Err(err).Msg("Unable create transaction signer")
return err
}
cops := new(bind.CallOpts)
// deploy and instantiate the load tester contract
var ltAddr ethcommon.Address
var ltContract *tester.LoadTester
if anyModeRequiresLoadTestContract(ltp.ParsedModes) || *inputLoadTestParams.ForceContractDeploy {
ltAddr, ltContract, err = getLoadTestContract(ctx, c, tops, cops)
if err != nil {
return err
}
log.Debug().Str("ltAddr", ltAddr.String()).Msg("Obtained load test contract address")
}
var erc20Addr ethcommon.Address
var erc20Contract *tokens.ERC20
if hasMode(loadTestModeERC20, ltp.ParsedModes) || hasMode(loadTestModeRandom, ltp.ParsedModes) || hasMode(loadTestModeRPC, ltp.ParsedModes) {
erc20Addr, erc20Contract, err = getERC20Contract(ctx, c, tops, cops)
if err != nil {
return err
}
log.Debug().Str("erc20Addr", erc20Addr.String()).Msg("Obtained erc 20 contract address")
}
var erc721Addr ethcommon.Address
var erc721Contract *tokens.ERC721
if hasMode(loadTestModeERC721, ltp.ParsedModes) || hasMode(loadTestModeRandom, ltp.ParsedModes) || hasMode(loadTestModeRPC, ltp.ParsedModes) {
erc721Addr, erc721Contract, err = getERC721Contract(ctx, c, tops, cops)
if err != nil {
return err
}
log.Debug().Str("erc721Addr", erc721Addr.String()).Msg("Obtained erc 721 contract address")
}
var recallTransactions []rpctypes.PolyTransaction
if hasMode(loadTestModeRecall, ltp.ParsedModes) {
recallTransactions, err = getRecallTransactions(ctx, c, rpc)
if err != nil {
return err
}
if len(recallTransactions) == 0 {
return errors.New("we weren't able to fetch any recall transactions")
}
log.Debug().Int("txs", len(recallTransactions)).Msg("Retrieved transactions for total recall")
}
var indexedActivity *IndexedActivity
if hasMode(loadTestModeRPC, ltp.ParsedModes) {
indexedActivity, err = getIndexedRecentActivity(ctx, c, rpc)
if err != nil {
return err
}
if len(indexedActivity.ERC20Addresses) == 0 {
indexedActivity.ERC20Addresses = append(indexedActivity.ERC20Addresses, erc20Addr.String())
}
if len(indexedActivity.ERC721Addresses) == 0 {
indexedActivity.ERC721Addresses = append(indexedActivity.ERC721Addresses, erc721Addr.String())
}
log.Debug().
Int("transactions", len(indexedActivity.TransactionIDs)).
Int("blocks", len(indexedActivity.BlockNumbers)).
Int("addresses", len(indexedActivity.Addresses)).
Int("erc20s", len(indexedActivity.ERC20Addresses)).
Int("erc721", len(indexedActivity.ERC721Addresses)).
Int("contracts", len(indexedActivity.Contracts)).
Msg("Retrieved recent indexed activity")
}
var uniswapV3Config uniswapv3loadtest.UniswapV3Config
var poolConfig uniswapv3loadtest.PoolConfig
if hasMode(loadTestModeUniswapV3, ltp.ParsedModes) {
uniswapAddresses := uniswapv3loadtest.UniswapV3Addresses{
FactoryV3: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapFactoryV3),
Multicall: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapMulticall),
ProxyAdmin: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapProxyAdmin),
TickLens: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapTickLens),
NFTDescriptorLib: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapNFTLibDescriptor),
NonfungibleTokenPositionDescriptor: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapNonfungibleTokenPositionDescriptor),
TransparentUpgradeableProxy: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapUpgradeableProxy),
NonfungiblePositionManager: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapNonfungiblePositionManager),
Migrator: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapMigrator),
Staker: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapStaker),
QuoterV2: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapQuoterV2),
SwapRouter02: ethcommon.HexToAddress(*uniswapv3LoadTestParams.UniswapSwapRouter),
WETH9: ethcommon.HexToAddress(*uniswapv3LoadTestParams.WETH9),
}
uniswapV3Config, poolConfig, err = initUniswapV3Loadtest(ctx, c, tops, cops, uniswapAddresses, *ltp.FromETHAddress)
if err != nil {
return err
}
}
startBlockNumber, err = c.BlockNumber(ctx)
if err != nil {
log.Error().
Err(err).
Msg("Failed to get current block number")
return err
}
err = accountPool.RefreshNonce(ctx, tops.From)
if err != nil {
return err
}
log.Debug().Msg("Starting main load test loop")
var wg sync.WaitGroup
for routineID := int64(0); routineID < maxRoutines; routineID++ {
log.Trace().
Int64("routineID", routineID).
Msg("starting concurrent routine")
wg.Add(1)
go func(routineID int64) {
var startReq time.Time
var endReq time.Time
var tErr error
var ltTxHash common.Hash
for requestID := int64(0); requestID < maxRequests; requestID++ {
if rl != nil {
tErr = rl.Wait(ctx)
if tErr != nil {
log.Error().
Int64("routineID", routineID).
Int64("requestID", requestID).
Err(tErr).
Msg("Encountered a rate limiting error")
}
}
localMode := mode
// if there are multiple modes, iterate through them, 'r' mode is supported here
if ltp.MultiMode {
localMode = ltp.ParsedModes[int(routineID+requestID)%(len(ltp.ParsedModes))]
}
// if we're doing random, we'll just pick one based on the current index
if localMode == loadTestModeRandom {
localMode = getRandomMode()
}
account, err := accountPool.Next(ctx)
if err != nil {
log.Error().
Int64("routineID", routineID).
Int64("requestID", requestID).
Err(err).
Msg("Unable to get next account from account pool")
return
}
chainID := new(big.Int).SetUint64(*ltp.ChainID)
sendingTops, err := bind.NewKeyedTransactorWithChainID(account.privateKey, chainID)
if err != nil {
log.Error().
Int64("routineID", routineID).
Int64("requestID", requestID).
Err(err).
Msg("Unable create transaction signer")
return
}
sendingTops.Nonce = new(big.Int).SetUint64(account.nonce)
sendingTops = configureTransactOpts(ctx, c, sendingTops)
switch localMode {
case loadTestModeERC20:
startReq, endReq, ltTxHash, tErr = loadTestERC20(ctx, c, sendingTops, erc20Contract, ltAddr)
case loadTestModeERC721:
startReq, endReq, ltTxHash, tErr = loadTestERC721(ctx, c, sendingTops, erc721Contract, ltAddr)
case loadTestModeBlob:
startReq, endReq, ltTxHash, tErr = loadTestBlob(ctx, c, sendingTops)
case loadTestModeContractCall:
startReq, endReq, ltTxHash, tErr = loadTestContractCall(ctx, c, sendingTops)
case loadTestModeDeploy:
startReq, endReq, ltTxHash, tErr = loadTestDeploy(ctx, c, sendingTops)
case loadTestModeFunction, loadTestModeCall:
startReq, endReq, ltTxHash, tErr = loadTestFunction(ctx, c, sendingTops, ltContract)
case loadTestModeInscription:
startReq, endReq, ltTxHash, tErr = loadTestInscription(ctx, c, sendingTops)
case loadTestModeIncrement:
startReq, endReq, ltTxHash, tErr = loadTestIncrement(ctx, c, sendingTops, ltContract)
case loadTestModeRandomPrecompiledContract:
startReq, endReq, ltTxHash, tErr = loadTestCallPrecompiledContract(ctx, c, sendingTops, ltContract, false)
case loadTestModeSpecificPrecompiledContract:
startReq, endReq, ltTxHash, tErr = loadTestCallPrecompiledContract(ctx, c, sendingTops, ltContract, true)
case loadTestModeRecall:
startReq, endReq, ltTxHash, tErr = loadTestRecall(ctx, c, sendingTops, recallTransactions[int(sendingTops.Nonce.Uint64())%len(recallTransactions)])
case loadTestModeRPC:
startReq, endReq, tErr = loadTestRPC(ctx, c, indexedActivity)
case loadTestModeStore:
startReq, endReq, ltTxHash, tErr = loadTestStore(ctx, c, sendingTops, ltContract)
case loadTestModeTransaction:
startReq, endReq, ltTxHash, tErr = loadTestTransaction(ctx, c, sendingTops)
case loadTestModeUniswapV3:
swapAmountIn := big.NewInt(int64(*uniswapv3LoadTestParams.SwapAmountInput))
startReq, endReq, ltTxHash, tErr = runUniswapV3Loadtest(ctx, c, sendingTops, uniswapV3Config, poolConfig, swapAmountIn)
default:
log.Error().Str("mode", mode.String()).Msg("We've arrived at a load test mode that we don't recognize")
}
if !*inputLoadTestParams.SendOnly {
recordSample(routineID, requestID, tErr, startReq, endReq, sendingTops.Nonce.Uint64())
}
if tErr != nil {
log.Error().
Int64("routineID", routineID).
Int64("requestID", requestID).
Err(tErr).
Str("mode", localMode.String()).
Str("address", sendingTops.From.String()).
Uint64("nonce", sendingTops.Nonce.Uint64()).
Uint64("gas", sendingTops.GasLimit).
Any("gasPrice", sendingTops.GasPrice).
Any("gasFeeCap", sendingTops.GasFeeCap).
Any("gasTipCap", sendingTops.GasTipCap).
Int64("request time", endReq.Sub(startReq).Milliseconds()).
Msg("recorded an error while sending transactions")
// check nonce for reuse
// if we're not in call only mode, we want to retry
if !*ltp.CallOnly {
// we start setting nonce to be reused
reuseNonce := true
// if the transaction hash is not zero, this means a tx was
// created, in this case we want to check the error to understand
// if the nonce can be reused
if ltTxHash.String() != (ethcommon.Hash{}).String() {
// if it is an error that consumes the nonce, we can't retry it
if strings.Contains(tErr.Error(), "replacement transaction underpriced") ||
strings.Contains(tErr.Error(), "transaction underpriced") ||
strings.Contains(tErr.Error(), "nonce too low") ||
strings.Contains(tErr.Error(), "already known") ||
strings.Contains(tErr.Error(), "could not replace existing") {
reuseNonce = false
}
}
// if we can reuse the nonce, we add it back to the account pool
// for the specific account
if reuseNonce {
err := accountPool.AddReusableNonce(ctx, sendingTops.From, sendingTops.Nonce.Uint64())
if err != nil {
log.Error().
Str("address", sendingTops.From.String()).
Uint64("nonce", sendingTops.Nonce.Uint64()).
Err(err).
Msg("Unable to add reusable nonce to account pool")
}
}
}
}
log.Trace().
Int64("routineID", routineID).
Int64("requestID", requestID).
Stringer("txhash", ltTxHash).
Any("nonce", sendingTops.Nonce).
Str("mode", localMode.String()).
Msg("Request")
}
wg.Done()
}(routineID)
}
log.Trace().Msg("Finished starting go routines. Waiting..")
wg.Wait()
cancel()
if *ltp.CallOnly {
return nil
}
return nil
}
func getLoadTestContract(ctx context.Context, c *ethclient.Client, tops *bind.TransactOpts, cops *bind.CallOpts) (ltAddr ethcommon.Address, ltContract *tester.LoadTester, err error) {
ltAddr = ethcommon.HexToAddress(*inputLoadTestParams.LtAddress)
if *inputLoadTestParams.LtAddress == "" {
ltAddr, _, _, err = tester.DeployLoadTester(tops, c)
if err != nil {
log.Error().Err(err).Msg("Failed to create the load testing contract. Do you have the right chain id? Do you have enough funds?")
return
}
}
log.Trace().Interface("contractaddress", ltAddr).Msg("Load test contract address")
ltContract, err = tester.NewLoadTester(ltAddr, c)
if err != nil {
log.Error().Err(err).Msg("Unable to instantiate new contract")
return
}
err = util.BlockUntilSuccessful(ctx, c, func() error {
_, err = ltContract.GetCallCounter(cops)
return err
})
return
}
func getERC20Contract(ctx context.Context, c *ethclient.Client, tops *bind.TransactOpts, cops *bind.CallOpts) (erc20Addr ethcommon.Address, erc20Contract *tokens.ERC20, err error) {
erc20Addr = ethcommon.HexToAddress(*inputLoadTestParams.ERC20Address)
if *inputLoadTestParams.ERC20Address == "" {
log.Info().Msg("Deploying ERC20 contract")
erc20Addr, _, _, err = tokens.DeployERC20(tops, c)
if err != nil {
log.Error().Err(err).Msg("Unable to deploy ERC20 contract")
return
}
// Tokens already minted and sent to the address of the deployer.
}
log.Info().Interface("contractaddress", erc20Addr).Msg("ERC20 contract address")
erc20Contract, err = tokens.NewERC20(erc20Addr, c)
if err != nil {
log.Error().Err(err).Msg("Unable to instantiate new erc20 contract")