-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathloadtest.go
More file actions
1580 lines (1406 loc) · 50.6 KB
/
loadtest.go
File metadata and controls
1580 lines (1406 loc) · 50.6 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 (
"context"
_ "embed"
"encoding/hex"
"errors"
"fmt"
"io"
"math/big"
"math/rand"
"os"
"os/signal"
"strings"
"sync"
"time"
"github.com/maticnetwork/polygon-cli/bindings/tester"
"github.com/maticnetwork/polygon-cli/bindings/tokens"
uniswapv3loadtest "github.com/maticnetwork/polygon-cli/cmd/loadtest/uniswapv3"
"github.com/maticnetwork/polygon-cli/abi"
"github.com/maticnetwork/polygon-cli/rpctypes"
"github.com/maticnetwork/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 with something like `go install golang.org/x/tools/cmd/stringer`
// 2. now that its installed (make sure your GOBIN is on the PATH) you can run `go generate github.com/maticnetwork/polygon-cli/cmd/loadtest`
loadTestModeTransaction loadTestMode = iota
loadTestModeDeploy
loadTestModeCall
loadTestModeFunction
loadTestModeInc
loadTestModeStore
loadTestModeERC20
loadTestModeERC721
loadTestModePrecompiledContracts
loadTestModePrecompiledContract
// All the modes AFTER random mode will not be used when mode random is selected
loadTestModeRandom
loadTestModeRecall
loadTestModeRPC
loadTestModeContractCall
loadTestModeInscription
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 "t", "transaction":
return loadTestModeTransaction, nil
case "d", "deploy":
return loadTestModeDeploy, nil
case "c", "call":
return loadTestModeCall, nil
case "f", "function":
return loadTestModeFunction, nil
case "i", "inc", "increment":
return loadTestModeInc, nil
case "r", "random":
return loadTestModeRandom, nil
case "s", "store":
return loadTestModeStore, nil
case "2", "erc20":
return loadTestModeERC20, nil
case "7", "erc721":
return loadTestModeERC721, nil
case "p", "precompile":
return loadTestModePrecompiledContract, nil
case "P", "precompiles":
return loadTestModePrecompiledContracts, nil
case "R", "recall":
return loadTestModeRecall, nil
case "v3", "uniswapv3":
return loadTestModeUniswapV3, nil
case "rpc":
return loadTestModeRPC, nil
case "cc", "contract-call":
return loadTestModeContractCall, nil
case "inscription":
return loadTestModeInscription, nil
default:
return 0, fmt.Errorf("unrecognized load test mode: %s", mode)
}
}
func getRandomMode() loadTestMode {
maxMode := int(loadTestModeRandom)
return loadTestMode(randSrc.Intn(maxMode))
}
func modeRequiresLoadTestContract(m loadTestMode) bool {
if m == loadTestModeCall ||
m == loadTestModeFunction ||
m == loadTestModeInc ||
m == loadTestModeRandom ||
m == loadTestModeStore ||
m == loadTestModePrecompiledContract ||
m == loadTestModePrecompiledContracts {
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 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
}
*inputLoadTestParams.PrivateKey = strings.TrimPrefix(*inputLoadTestParams.PrivateKey, "0x")
privateKey, err := ethcrypto.HexToECDSA(*inputLoadTestParams.PrivateKey)
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().Interface("balance", accountBal).Msg("Current account balance")
toAddr := ethcommon.HexToAddress(*inputLoadTestParams.ToAddress)
amt := util.EthToWei(*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")
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()
}
inputLoadTestParams.CurrentBaseFee = header.BaseFee
modes := *inputLoadTestParams.Modes
if len(modes) == 0 {
return errors.New("expected at least one mode")
}
inputLoadTestParams.ParsedModes = make([]loadTestMode, 0)
for _, m := range modes {
parsedMode, err := characterToLoadTestMode(m)
if err != nil {
return err
}
inputLoadTestParams.ParsedModes = append(inputLoadTestParams.ParsedModes, parsedMode)
}
if len(modes) > 1 {
inputLoadTestParams.MultiMode = true
} 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.")
}
// TODO check for duplicate modes?
if *inputLoadTestParams.CallOnly && *inputLoadTestParams.AdaptiveRateLimit {
return errors.New("using call only with adaptive rate limit doesn't make sense")
}
randSrc = rand.New(rand.NewSource(*inputLoadTestParams.Seed))
return nil
}
func initNonce(ctx context.Context, c *ethclient.Client, rpc *ethrpc.Client) error {
var err error
startBlockNumber, err = c.BlockNumber(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to get current block number")
return err
}
currentNonce, err = c.NonceAt(ctx, *inputLoadTestParams.FromETHAddress, new(big.Int).SetUint64(startBlockNumber))
startNonce = currentNonce
if err != nil {
log.Error().Err(err).Msg("Unable to get account nonce")
return err
}
return nil
}
func completeLoadTest(ctx context.Context, c *ethclient.Client, rpc *ethrpc.Client) error {
log.Debug().Uint64("startNonce", startNonce).Uint64("lastNonce", currentNonce).Msg("Finished main load test loop")
if *inputLoadTestParams.SendOnly {
log.Info().Uint64("transactionsSent", currentNonce-startNonce).Msg("SendOnly mode enabled - skipping wait period and summarization")
return nil
}
log.Debug().Msg("Waiting for remaining transactions to be completed and mined")
var err error
finalBlockNumber, err = waitForFinalBlock(ctx, c, rpc, startBlockNumber, startNonce, currentNonce)
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")
}
if *inputLoadTestParams.CallOnly {
log.Info().Msg("CallOnly mode enabled - blocks aren't mined")
return nil
}
startTime := loadTestResults[0].RequestTime
endTime := time.Now()
log.Debug().Uint64("currentNonce", currentNonce).Uint64("final block number", finalBlockNumber).Msg("Got final block number")
if *inputLoadTestParams.ShouldProduceSummary {
err = summarizeTransactions(ctx, c, rpc, startBlockNumber, startNonce, finalBlockNumber, currentNonce)
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)
}
// Dial the Ethereum RPC server.
var rpc *ethrpc.Client
var err error
if inputLoadTestParams.ParsedHTTPHeaders == nil {
log.Trace().Msg("No HeadersAdding custom headers")
rpc, err = ethrpc.DialContext(ctx, *inputLoadTestParams.RPCUrl)
} else {
log.Trace().Msg("Adding custom headers")
rpc, err = ethrpc.DialOptions(ctx, *inputLoadTestParams.RPCUrl, ethrpc.WithHTTPAuth(util.GetHTTPAuth(inputLoadTestParams.ParsedHTTPHeaders)))
}
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
}
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)
go func() {
errCh <- loopFunc()
}()
// 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")
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, steadyStateQueueSize uint64, rateLimitIncrement uint64, cycleDuration time.Duration, backoff float64) {
ticker := time.NewTicker(cycleDuration)
defer ticker.Stop()
for {
select {
case <-ticker.C:
txPoolSize, err := util.GetTxPoolSize(rpc)
if err != nil {
log.Error().Err(err).Msg("Error getting txpool size")
return
}
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")
routines := *ltp.Concurrency
requests := *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, steadyStateTxPoolSize, adaptiveRateLimitIncrement, time.Duration(*ltp.AdaptiveCycleDuration)*time.Second, *ltp.AdaptiveBackoffFactor)
}
tops, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
tops = configureTransactOpts(tops)
// configureTransactOpts will set some paramters 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 mode == loadTestModeERC20 || mode == loadTestModeRandom {
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 mode == loadTestModeERC721 || mode == loadTestModeRandom {
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 mode == loadTestModeRecall {
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 mode == loadTestModeRPC {
indexedActivity, err = getIndexedRecentActivity(ctx, c, rpc)
if err != nil {
return err
}
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 mode == loadTestModeUniswapV3 {
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
}
}
var i int64
err = initNonce(ctx, c, rpc)
if err != nil {
return err
}
log.Debug().Uint64("currentNonce", currentNonce).Msg("Starting main load test loop")
var wg sync.WaitGroup
for i = 0; i < routines; i = i + 1 {
log.Trace().Int64("routine", i).Msg("Starting Thread")
wg.Add(1)
go func(i int64) {
var j int64
var startReq time.Time
var endReq time.Time
var retryForNonce bool = false
var myNonceValue uint64
var tErr error
for j = 0; j < requests; j = j + 1 {
if rl != nil {
tErr = rl.Wait(ctx)
if tErr != nil {
log.Error().Err(tErr).Msg("Encountered a rate limiting error")
}
}
if retryForNonce {
retryForNonce = false
} else {
currentNonceMutex.Lock()
myNonceValue = currentNonce
currentNonce = currentNonce + 1
currentNonceMutex.Unlock()
}
localMode := mode
// if there are multiple modes, iterate through them, 'r' mode is supported here
if ltp.MultiMode {
localMode = ltp.ParsedModes[int(i+j)%(len(ltp.ParsedModes))]
}
// if we're doing random, we'll just pick one based on the current index
if localMode == loadTestModeRandom {
localMode = getRandomMode()
}
switch localMode {
case loadTestModeTransaction:
startReq, endReq, tErr = loadTestTransaction(ctx, c, myNonceValue)
case loadTestModeDeploy:
startReq, endReq, tErr = loadTestDeploy(ctx, c, myNonceValue)
case loadTestModeFunction, loadTestModeCall:
startReq, endReq, tErr = loadTestFunction(ctx, c, myNonceValue, ltContract)
case loadTestModeInc:
startReq, endReq, tErr = loadTestInc(ctx, c, myNonceValue, ltContract)
case loadTestModeStore:
startReq, endReq, tErr = loadTestStore(ctx, c, myNonceValue, ltContract)
case loadTestModeERC20:
startReq, endReq, tErr = loadTestERC20(ctx, c, myNonceValue, erc20Contract, ltAddr)
case loadTestModeERC721:
startReq, endReq, tErr = loadTestERC721(ctx, c, myNonceValue, erc721Contract, ltAddr)
case loadTestModePrecompiledContract:
startReq, endReq, tErr = loadTestCallPrecompiledContracts(ctx, c, myNonceValue, ltContract, true)
case loadTestModePrecompiledContracts:
startReq, endReq, tErr = loadTestCallPrecompiledContracts(ctx, c, myNonceValue, ltContract, false)
case loadTestModeRecall:
startReq, endReq, tErr = loadTestRecall(ctx, c, myNonceValue, recallTransactions[int(currentNonce)%len(recallTransactions)])
case loadTestModeUniswapV3:
swapAmountIn := big.NewInt(int64(*uniswapv3LoadTestParams.SwapAmountInput))
startReq, endReq, tErr = runUniswapV3Loadtest(ctx, c, myNonceValue, uniswapV3Config, poolConfig, swapAmountIn)
case loadTestModeRPC:
startReq, endReq, tErr = loadTestRPC(ctx, c, myNonceValue, indexedActivity)
case loadTestModeContractCall:
startReq, endReq, tErr = loadTestContractCall(ctx, c, myNonceValue)
case loadTestModeInscription:
startReq, endReq, tErr = loadTestInscription(ctx, c, myNonceValue)
default:
log.Error().Str("mode", mode.String()).Msg("We've arrived at a load test mode that we don't recognize")
}
recordSample(i, j, tErr, startReq, endReq, myNonceValue)
if tErr != nil {
log.Error().Err(tErr).Uint64("nonce", myNonceValue).Int64("request time", endReq.Sub(startReq).Milliseconds()).Msg("Recorded an error while sending transactions")
// The nonce is used to index the recalled transactions in call-only mode. We don't want to retry a transaction if it legit failed on the chain
if !*ltp.CallOnly {
retryForNonce = true
}
if strings.Contains(tErr.Error(), "replacement transaction underpriced") && retryForNonce {
retryForNonce = false
}
if strings.Contains(tErr.Error(), "transaction underpriced") && retryForNonce {
retryForNonce = false
}
if strings.Contains(tErr.Error(), "nonce too low") && retryForNonce {
retryForNonce = false
}
}
log.Trace().Uint64("nonce", myNonceValue).Int64("routine", i).Str("mode", localMode.String()).Int64("request", j).Msg("Request")
}
wg.Done()
}(i)
}
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 == "" {
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.Trace().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")
return
}
err = util.BlockUntilSuccessful(ctx, c, func() error {
var balance *big.Int
balance, err = erc20Contract.BalanceOf(cops, *inputLoadTestParams.FromETHAddress)
if err != nil {
return err
}
if balance.Uint64() == 0 {
err = errors.New("ERC20 Balance is Zero")
return err
}
return nil
})
return
}
func getERC721Contract(ctx context.Context, c *ethclient.Client, tops *bind.TransactOpts, cops *bind.CallOpts) (erc721Addr ethcommon.Address, erc721Contract *tokens.ERC721, err error) {
erc721Addr = ethcommon.HexToAddress(*inputLoadTestParams.ERC721Address)
shouldMint := true
if *inputLoadTestParams.ERC721Address == "" {
erc721Addr, _, _, err = tokens.DeployERC721(tops, c)
if err != nil {
log.Error().Err(err).Msg("Unable to deploy ERC721 contract")
return
}
shouldMint = false
}
log.Trace().Interface("contractaddress", erc721Addr).Msg("ERC721 contract address")
erc721Contract, err = tokens.NewERC721(erc721Addr, c)
if err != nil {
log.Error().Err(err).Msg("Unable to instantiate new erc721 contract")
return
}
err = util.BlockUntilSuccessful(ctx, c, func() error {
_, err = erc721Contract.BalanceOf(cops, *inputLoadTestParams.FromETHAddress)
return err
})
if err != nil {
return
}
if !shouldMint {
return
}
err = util.BlockUntilSuccessful(ctx, c, func() error {
_, err = erc721Contract.MintBatch(tops, *inputLoadTestParams.FromETHAddress, new(big.Int).SetUint64(1))
return err
})
return
}
func loadTestTransaction(ctx context.Context, c *ethclient.Client, nonce uint64) (t1 time.Time, t2 time.Time, err error) {
ltp := inputLoadTestParams
to := ltp.ToETHAddress
if *ltp.ToRandom {
to = getRandomAddress()
}
amount := ltp.SendAmount
chainID := new(big.Int).SetUint64(*ltp.ChainID)
privateKey := ltp.ECDSAPrivateKey
tops, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
log.Error().Err(err).Msg("Unable create transaction signer")
return
}
tops.GasLimit = uint64(21000)
tops = configureTransactOpts(tops)
gasPrice, gasTipCap := getSuggestedGasPrices(ctx, c)
var tx *ethtypes.Transaction
if *ltp.LegacyTransactionMode {
tx = ethtypes.NewTx(ðtypes.LegacyTx{
Nonce: nonce,
To: to,
Value: amount,
Gas: tops.GasLimit,
GasPrice: gasPrice,
Data: nil,
})
} else {
dynamicFeeTx := ðtypes.DynamicFeeTx{
ChainID: chainID,
Nonce: nonce,
To: to,
Gas: tops.GasLimit,
GasFeeCap: gasPrice,
GasTipCap: gasTipCap,
Data: nil,
Value: amount,
}
tx = ethtypes.NewTx(dynamicFeeTx)
}
stx, err := tops.Signer(*ltp.FromETHAddress, tx)
if err != nil {
log.Error().Err(err).Msg("Unable to sign transaction")
return
}
t1 = time.Now()
defer func() { t2 = time.Now() }()
if *ltp.CallOnly {
_, err = c.CallContract(ctx, txToCallMsg(stx), nil)
} else {
err = c.SendTransaction(ctx, stx)
}
return
}
var (
cachedBlockNumber uint64
cachedGasPriceLock sync.Mutex
cachedGasPrice *big.Int
cachedGasTipCap *big.Int
)
func getSuggestedGasPrices(ctx context.Context, c *ethclient.Client) (*big.Int, *big.Int) {
// this should be one of the fastest RPC calls, so hopefully there isn't too much overhead calling this
bn, err := c.BlockNumber(ctx)
if err != nil {
log.Error().Err(err).Msg("Unable to get block number while checking gas prices")
return nil, nil
}
isDynamic := inputLoadTestParams.ChainSupportBaseFee
cachedGasPriceLock.Lock()
defer cachedGasPriceLock.Unlock()
if bn <= cachedBlockNumber {
return cachedGasPrice, cachedGasTipCap
}
gp, pErr := c.SuggestGasPrice(ctx)
gt, tErr := c.SuggestGasTipCap(ctx)
// In the case of an EVM compatible system not supporting EIP-1559
if *inputLoadTestParams.LegacyTransactionMode {
gt = big.NewInt(0)
}
if pErr == nil && (tErr == nil || !isDynamic) {
cachedBlockNumber = bn
cachedGasPrice = gp
cachedGasTipCap = gt
if inputLoadTestParams.ForceGasPrice != nil && *inputLoadTestParams.ForceGasPrice != 0 {
cachedGasPrice = new(big.Int).SetUint64(*inputLoadTestParams.ForceGasPrice)
}
if inputLoadTestParams.ForcePriorityGasPrice != nil && *inputLoadTestParams.ForcePriorityGasPrice != 0 {
cachedGasTipCap = new(big.Int).SetUint64(*inputLoadTestParams.ForcePriorityGasPrice)
}
if cachedGasTipCap.Cmp(cachedGasPrice) == 1 {
cachedGasTipCap = cachedGasPrice
}
l := log.Debug().Uint64("cachedBlockNumber", bn).Uint64("cachedgasPrice", cachedGasPrice.Uint64())
if cachedGasTipCap != nil {
l = l.Uint64("cachedGasTipCap", cachedGasTipCap.Uint64())
}
l.Msg("Updating gas prices")
return cachedGasPrice, cachedGasTipCap
}
// Something went wrong
if pErr != nil {
log.Error().Err(pErr).Msg("Unable to suggest gas price")
return cachedGasPrice, cachedGasTipCap
}
if tErr != nil && isDynamic {
log.Error().Err(tErr).Msg("Unable to suggest gas tip cap")
return cachedGasPrice, cachedGasTipCap
}
log.Error().Err(tErr).Msg("This error should not have happened. We got a gas tip price error in an environment that is not dynamic")
return cachedGasPrice, cachedGasTipCap
}
// TODO - in the future it might be more interesting if this mode takes input or random contracts to be deployed
func loadTestDeploy(ctx context.Context, c *ethclient.Client, nonce uint64) (t1 time.Time, t2 time.Time, err error) {
ltp := inputLoadTestParams
chainID := new(big.Int).SetUint64(*ltp.ChainID)
privateKey := ltp.ECDSAPrivateKey
tops, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
log.Error().Err(err).Msg("Unable create transaction signer")
return
}
tops.Nonce = new(big.Int).SetUint64(nonce)
tops = configureTransactOpts(tops)
t1 = time.Now()
defer func() { t2 = time.Now() }()
if *ltp.CallOnly {
msg := transactOptsToCallMsg(tops)
msg.Data = ethcommon.FromHex(tester.LoadTesterMetaData.Bin)
_, err = c.CallContract(ctx, msg, nil)
} else {
_, _, _, err = tester.DeployLoadTester(tops, c)
}
return
}
// getCurrentLoadTestFunction is meant to handle the business logic
// around deciding which function to execute. When we're in function
// mode where the user has provided a specific function to execute, we
// should use that function. Otherwise, we'll select random functions.
func getCurrentLoadTestFunction() uint64 {
if loadTestModeFunction == inputLoadTestParams.Mode {
return *inputLoadTestParams.Function
}
return tester.GetRandomOPCode()
}
func loadTestFunction(ctx context.Context, c *ethclient.Client, nonce uint64, ltContract *tester.LoadTester) (t1 time.Time, t2 time.Time, err error) {
ltp := inputLoadTestParams
chainID := new(big.Int).SetUint64(*ltp.ChainID)
privateKey := ltp.ECDSAPrivateKey
iterations := ltp.Iterations
f := getCurrentLoadTestFunction()
tops, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
log.Error().Err(err).Msg("Unable create transaction signer")
return
}
tops.Nonce = new(big.Int).SetUint64(nonce)
tops = configureTransactOpts(tops)
t1 = time.Now()
defer func() { t2 = time.Now() }()
if *ltp.CallOnly {
tops.NoSend = true
var tx *ethtypes.Transaction
tx, err = tester.CallLoadTestFunctionByOpCode(f, ltContract, tops, *iterations)
if err != nil {
return
}
msg := txToCallMsg(tx)
_, err = c.CallContract(ctx, msg, nil)
} else {
_, err = tester.CallLoadTestFunctionByOpCode(f, ltContract, tops, *iterations)
}
return
}
func loadTestCallPrecompiledContracts(ctx context.Context, c *ethclient.Client, nonce uint64, ltContract *tester.LoadTester, useSelectedAddress bool) (t1 time.Time, t2 time.Time, err error) {
var f int
ltp := inputLoadTestParams
chainID := new(big.Int).SetUint64(*ltp.ChainID)
privateKey := ltp.ECDSAPrivateKey
iterations := ltp.Iterations
if useSelectedAddress {
f = int(*ltp.Function)
} else {
f = tester.GetRandomPrecompiledContractAddress()
}
tops, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
log.Error().Err(err).Msg("Unable create transaction signer")
return
}
tops.Nonce = new(big.Int).SetUint64(nonce)
tops = configureTransactOpts(tops)
t1 = time.Now()
defer func() { t2 = time.Now() }()
if *ltp.CallOnly {
tops.NoSend = true
var tx *ethtypes.Transaction
tx, err = tester.CallPrecompiledContracts(f, ltContract, tops, *iterations, privateKey)
if err != nil {
return
}
msg := txToCallMsg(tx)
_, err = c.CallContract(ctx, msg, nil)
} else {
_, err = tester.CallPrecompiledContracts(f, ltContract, tops, *iterations, privateKey)
}
return
}
func loadTestInc(ctx context.Context, c *ethclient.Client, nonce uint64, ltContract *tester.LoadTester) (t1 time.Time, t2 time.Time, err error) {
ltp := inputLoadTestParams
chainID := new(big.Int).SetUint64(*ltp.ChainID)