-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathtxmgr_test.go
1599 lines (1368 loc) · 47.6 KB
/
txmgr_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
package txmgr
import (
"context"
"crypto/rand"
"errors"
"fmt"
"math/big"
"sync"
"testing"
"time"
"github.com/holiman/uint256"
"github.com/stretchr/testify/require"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/misc/eip4844"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/txpool"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto/kzg4844"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum-optimism/optimism/op-service/testlog"
"github.com/ethereum-optimism/optimism/op-service/txmgr/metrics"
)
const (
startingNonce = 1 // we pick something other than 0 so we can confirm nonces are getting set properly
)
var (
blobData1 = eth.Data("this is a blob!")
blobData2 = eth.Data("amazing, the txmgr can handle more than one blob in a tx!!")
)
type sendTransactionFunc func(ctx context.Context, tx *types.Transaction) error
func testSendState() *SendState {
return NewSendState(100, time.Hour)
}
// testHarness houses the necessary resources to test the SimpleTxManager.
type testHarness struct {
cfg *Config
mgr *SimpleTxManager
backend *mockBackend
gasPricer *gasPricer
}
// newTestHarnessWithConfig initializes a testHarness with a specific
// configuration.
func newTestHarnessWithConfig(t *testing.T, cfg *Config) *testHarness {
g := newGasPricer(3)
backend := newMockBackend(g)
cfg.Backend = backend
mgr := &SimpleTxManager{
chainID: cfg.ChainID,
name: "TEST",
cfg: cfg,
backend: cfg.Backend,
l: testlog.Logger(t, log.LevelCrit),
metr: &metrics.NoopTxMetrics{},
}
return &testHarness{
cfg: cfg,
mgr: mgr,
backend: backend,
gasPricer: g,
}
}
// newTestHarness initializes a testHarness with a default configuration that is
// suitable for most tests.
func newTestHarness(t *testing.T) *testHarness {
return newTestHarnessWithConfig(t, configWithNumConfs(1))
}
// createTxCandidate creates a mock [TxCandidate].
func (h testHarness) createTxCandidate() TxCandidate {
inbox := common.HexToAddress("0x42000000000000000000000000000000000000ff")
return TxCandidate{
To: &inbox,
TxData: []byte{0x00, 0x01, 0x02},
GasLimit: uint64(1337),
}
}
// createBlobTxCandidate creates a mock [TxCandidate] that results in a blob tx
func (h testHarness) createBlobTxCandidate() TxCandidate {
inbox := common.HexToAddress("0x42000000000000000000000000000000000000ff")
var b1, b2 eth.Blob
_ = b1.FromData(blobData1)
_ = b2.FromData(blobData2)
return TxCandidate{
To: &inbox,
TxData: []byte{0x00, 0x01, 0x02, 0x03},
GasLimit: uint64(1337),
Blobs: []*eth.Blob{&b1, &b2},
}
}
func configWithNumConfs(numConfirmations uint64) *Config {
cfg := Config{
ReceiptQueryInterval: 50 * time.Millisecond,
NumConfirmations: numConfirmations,
SafeAbortNonceTooLowCount: 3,
TxNotInMempoolTimeout: 1 * time.Hour,
Signer: func(ctx context.Context, from common.Address, tx *types.Transaction) (*types.Transaction, error) {
return tx, nil
},
From: common.Address{},
}
cfg.ResubmissionTimeout.Store(int64(time.Second))
cfg.FeeLimitMultiplier.Store(5)
cfg.MinBlobTxFee.Store(defaultMinBlobTxFee)
return &cfg
}
type gasPricer struct {
epoch int64
mineAtEpoch int64
baseGasTipFee *big.Int
baseBaseFee *big.Int
excessBlobGas uint64
err error
mu sync.Mutex
}
func newGasPricer(mineAtEpoch int64) *gasPricer {
return &gasPricer{
mineAtEpoch: mineAtEpoch,
baseGasTipFee: big.NewInt(5),
baseBaseFee: big.NewInt(7),
// Simulate 100 excess blobs, which results in a blobBaseFee of 50 wei. This default means
// blob txs will be subject to the geth minimum blobgas fee of 1 gwei.
excessBlobGas: 100 * (params.BlobTxBlobGasPerBlob),
}
}
func (g *gasPricer) expGasFeeCap() *big.Int {
_, gasFeeCap, _ := g.feesForEpoch(g.mineAtEpoch)
return gasFeeCap
}
func (g *gasPricer) expBlobFeeCap() *big.Int {
_, _, excessBlobGas := g.feesForEpoch(g.mineAtEpoch)
return eip4844.CalcBlobFee(excessBlobGas)
}
func (g *gasPricer) shouldMine(gasFeeCap *big.Int) bool {
return g.expGasFeeCap().Cmp(gasFeeCap) <= 0
}
func (g *gasPricer) shouldMineBlobTx(gasFeeCap, blobFeeCap *big.Int) bool {
return g.shouldMine(gasFeeCap) && g.expBlobFeeCap().Cmp(blobFeeCap) <= 0
}
func (g *gasPricer) feesForEpoch(epoch int64) (*big.Int, *big.Int, uint64) {
e := big.NewInt(epoch)
epochBaseFee := new(big.Int).Mul(g.baseBaseFee, e)
epochGasTipCap := new(big.Int).Mul(g.baseGasTipFee, e)
epochGasFeeCap := calcGasFeeCap(epochBaseFee, epochGasTipCap)
epochExcessBlobGas := g.excessBlobGas * uint64(epoch)
return epochGasTipCap, epochGasFeeCap, epochExcessBlobGas
}
func (g *gasPricer) baseFee() *big.Int {
g.mu.Lock()
defer g.mu.Unlock()
return new(big.Int).Mul(g.baseBaseFee, big.NewInt(g.epoch))
}
func (g *gasPricer) excessblobgas() uint64 {
g.mu.Lock()
defer g.mu.Unlock()
return g.excessBlobGas * uint64(g.epoch)
}
func (g *gasPricer) sample() (*big.Int, *big.Int, uint64) {
g.mu.Lock()
defer g.mu.Unlock()
g.epoch++
epochGasTipCap, epochGasFeeCap, epochExcessBlobGas := g.feesForEpoch(g.epoch)
return epochGasTipCap, epochGasFeeCap, epochExcessBlobGas
}
type minedTxInfo struct {
gasFeeCap *big.Int
blobFeeCap *big.Int
blockNumber uint64
}
// mockBackend implements ReceiptSource that tracks mined transactions
// along with the gas price used.
type mockBackend struct {
mu sync.RWMutex
g *gasPricer
send sendTransactionFunc
// blockHeight tracks the current height of the chain.
blockHeight uint64
// minedTxs maps the hash of a mined transaction to its details.
minedTxs map[common.Hash]minedTxInfo
}
// newMockBackend initializes a new mockBackend.
func newMockBackend(g *gasPricer) *mockBackend {
return &mockBackend{
g: g,
minedTxs: make(map[common.Hash]minedTxInfo),
}
}
// setTxSender sets the implementation for the sendTransactionFunction
func (b *mockBackend) setTxSender(s sendTransactionFunc) {
b.send = s
}
// mine records a (txHash, gasFeeCap) as confirmed. Subsequent calls to
// TransactionReceipt with a matching txHash will result in a non-nil receipt.
// If a nil txHash is supplied this has the effect of mining an empty block.
func (b *mockBackend) mine(txHash *common.Hash, gasFeeCap, blobFeeCap *big.Int) {
b.mu.Lock()
defer b.mu.Unlock()
b.blockHeight++
if txHash != nil {
b.minedTxs[*txHash] = minedTxInfo{
gasFeeCap: gasFeeCap,
blobFeeCap: blobFeeCap,
blockNumber: b.blockHeight,
}
}
}
// BlockNumber returns the most recent block number.
func (b *mockBackend) BlockNumber(ctx context.Context) (uint64, error) {
b.mu.RLock()
defer b.mu.RUnlock()
return b.blockHeight, nil
}
// Call mocks a call to the EVM.
func (b *mockBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
return nil, nil
}
func (b *mockBackend) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
b.mu.RLock()
defer b.mu.RUnlock()
num := big.NewInt(int64(b.blockHeight))
if number != nil {
num.Set(number)
}
bg := b.g.excessblobgas()
return &types.Header{
Number: num,
BaseFee: b.g.baseFee(),
ExcessBlobGas: &bg,
}, nil
}
func (b *mockBackend) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) {
if b.g.err != nil {
return 0, b.g.err
}
if msg.GasFeeCap.Cmp(msg.GasTipCap) < 0 {
return 0, core.ErrTipAboveFeeCap
}
return b.g.baseFee().Uint64(), nil
}
func (b *mockBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
tip, _, _ := b.g.sample()
return tip, nil
}
func (b *mockBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
if b.send == nil {
panic("set sender function was not set")
}
return b.send(ctx, tx)
}
func (b *mockBackend) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) {
return startingNonce, nil
}
func (b *mockBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
return startingNonce, nil
}
func (*mockBackend) ChainID(ctx context.Context) (*big.Int, error) {
return big.NewInt(1), nil
}
// TransactionReceipt queries the mockBackend for a mined txHash. If none is found, nil is returned
// for both return values. Otherwise, it returns a receipt containing the txHash, the gasFeeCap
// used in GasUsed, and the blobFeeCap in CumulativeGasUsed to make the values accessible from our
// test framework.
func (b *mockBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
b.mu.RLock()
defer b.mu.RUnlock()
txInfo, ok := b.minedTxs[txHash]
if !ok {
return nil, nil
}
// Return the gas fee cap for the transaction in the GasUsed field so that
// we can assert the proper tx confirmed in our tests.
var blobFeeCap uint64
if txInfo.blobFeeCap != nil {
blobFeeCap = txInfo.blobFeeCap.Uint64()
}
return &types.Receipt{
TxHash: txHash,
GasUsed: txInfo.gasFeeCap.Uint64(),
CumulativeGasUsed: blobFeeCap,
BlockNumber: big.NewInt(int64(txInfo.blockNumber)),
}, nil
}
func (b *mockBackend) Close() {
}
type testSendVariantsFn func(ctx context.Context, h *testHarness, tx TxCandidate) (*types.Receipt, error)
func testSendVariants(t *testing.T, testFn func(t *testing.T, send testSendVariantsFn)) {
t.Parallel()
t.Run("Send", func(t *testing.T) {
testFn(t, func(ctx context.Context, h *testHarness, tx TxCandidate) (*types.Receipt, error) {
return h.mgr.Send(ctx, tx)
})
})
t.Run("SendAsync", func(t *testing.T) {
testFn(t, func(ctx context.Context, h *testHarness, tx TxCandidate) (*types.Receipt, error) {
ch := make(chan SendResponse, 1)
h.mgr.SendAsync(ctx, tx, ch)
res := <-ch
return res.Receipt, res.Err
})
})
}
// TestTxMgrConfirmAtMinGasPrice asserts that Send returns the min gas price tx
// if the tx is mined instantly.
func TestTxMgrConfirmAtMinGasPrice(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
gasPricer := newGasPricer(1)
gasTipCap, gasFeeCap, _ := gasPricer.sample()
tx := types.NewTx(&types.DynamicFeeTx{
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
})
sendTx := func(ctx context.Context, tx *types.Transaction) error {
if gasPricer.shouldMine(tx.GasFeeCap()) {
txHash := tx.Hash()
h.backend.mine(&txHash, tx.GasFeeCap(), nil)
}
return nil
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, tx)
require.Nil(t, err)
require.NotNil(t, receipt)
require.Equal(t, gasPricer.expGasFeeCap().Uint64(), receipt.GasUsed)
}
// TestTxMgrNeverConfirmCancel asserts that a Send can be canceled even if no
// transaction is mined. This is done to ensure the the tx mgr can properly
// abort on shutdown, even if a txn is in the process of being published.
func TestTxMgrNeverConfirmCancel(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
gasTipCap, gasFeeCap, _ := h.gasPricer.sample()
tx := types.NewTx(&types.DynamicFeeTx{
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
})
sendTx := func(ctx context.Context, tx *types.Transaction) error {
// Don't publish tx to backend, simulating never being mined.
return nil
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, tx)
require.Equal(t, err, context.DeadlineExceeded)
require.Nil(t, receipt)
}
// TestTxMgrTxSendTimeout tests that the TxSendTimeout is respected when trying to send a
// transaction, even if NetworkTimeout expires first.
func TestTxMgrTxSendTimeout(t *testing.T) {
testSendVariants(t, func(t *testing.T, send testSendVariantsFn) {
conf := configWithNumConfs(1)
conf.TxSendTimeout = 3 * time.Second
conf.NetworkTimeout = 1 * time.Second
h := newTestHarnessWithConfig(t, conf)
txCandidate := h.createTxCandidate()
sendCount := 0
sendTx := func(ctx context.Context, tx *types.Transaction) error {
sendCount++
<-ctx.Done()
return context.DeadlineExceeded
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), time.Hour)
defer cancel()
receipt, err := send(ctx, h, txCandidate)
require.ErrorIs(t, err, context.DeadlineExceeded)
// Because network timeout is much shorter than send timeout, we should see multiple send attempts
// before the overall send fails.
require.Greater(t, sendCount, 1)
require.Nil(t, receipt)
})
}
// TestAlreadyReserved tests that AlreadyReserved error results in immediate abort of transaction
// sending.
func TestAlreadyReserved(t *testing.T) {
conf := configWithNumConfs(1)
h := newTestHarnessWithConfig(t, conf)
sendTx := func(ctx context.Context, tx *types.Transaction) error {
return txpool.ErrAlreadyReserved
}
h.backend.setTxSender(sendTx)
_, err := h.mgr.Send(context.Background(), TxCandidate{
To: &common.Address{},
})
require.ErrorIs(t, err, txpool.ErrAlreadyReserved)
}
// TestTxMgrConfirmsAtHigherGasPrice asserts that Send properly returns the max gas
// price receipt if none of the lower gas price txs were mined.
func TestTxMgrConfirmsAtHigherGasPrice(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
gasTipCap, gasFeeCap, _ := h.gasPricer.sample()
tx := types.NewTx(&types.DynamicFeeTx{
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
})
sendTx := func(ctx context.Context, tx *types.Transaction) error {
if h.gasPricer.shouldMine(tx.GasFeeCap()) {
txHash := tx.Hash()
h.backend.mine(&txHash, tx.GasFeeCap(), nil)
}
return nil
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, tx)
require.Nil(t, err)
require.NotNil(t, receipt)
require.Equal(t, h.gasPricer.expGasFeeCap().Uint64(), receipt.GasUsed)
}
// TestTxMgrConfirmsBlobTxAtHigherGasPrice asserts that Send properly returns the max gas price
// receipt if none of the lower gas price txs were mined when attempting to send a blob tx.
func TestTxMgrConfirmsBlobTxAtHigherGasPrice(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
gasTipCap, gasFeeCap, excessBlobGas := h.gasPricer.sample()
blobFeeCap := eip4844.CalcBlobFee(excessBlobGas)
t.Log("Blob fee cap:", blobFeeCap, "gasFeeCap:", gasFeeCap)
tx := types.NewTx(&types.BlobTx{
GasTipCap: uint256.MustFromBig(gasTipCap),
GasFeeCap: uint256.MustFromBig(gasFeeCap),
BlobFeeCap: uint256.MustFromBig(blobFeeCap),
})
sendTx := func(ctx context.Context, tx *types.Transaction) error {
if h.gasPricer.shouldMineBlobTx(tx.GasFeeCap(), tx.BlobGasFeeCap()) {
txHash := tx.Hash()
h.backend.mine(&txHash, tx.GasFeeCap(), tx.BlobGasFeeCap())
}
return nil
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, tx)
require.Nil(t, err)
require.NotNil(t, receipt)
// the fee cap for the blob tx at epoch == 3 should end up higher than the min required gas
// (expFeeCap()) since blob tx fee caps are bumped 100% with each epoch.
require.Less(t, h.gasPricer.expGasFeeCap().Uint64(), receipt.GasUsed)
require.Equal(t, h.gasPricer.expBlobFeeCap().Uint64(), receipt.CumulativeGasUsed)
}
// errRpcFailure is a sentinel error used in testing to fail publications.
var errRpcFailure = errors.New("rpc failure")
// TestTxMgrBlocksOnFailingRpcCalls asserts that if all of the publication
// attempts fail due to rpc failures, that the tx manager will return
// ErrPublishTimeout.
func TestTxMgrBlocksOnFailingRpcCalls(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
gasTipCap, gasFeeCap, _ := h.gasPricer.sample()
tx := types.NewTx(&types.DynamicFeeTx{
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
})
sendTx := func(ctx context.Context, tx *types.Transaction) error {
return errRpcFailure
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, tx)
require.Equal(t, err, context.DeadlineExceeded)
require.Nil(t, receipt)
}
// TestTxMgr_CraftTx ensures that the tx manager will create transactions as expected.
func TestTxMgr_CraftTx(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
candidate := h.createTxCandidate()
// Craft the transaction.
gasTipCap, gasFeeCap, _ := h.gasPricer.feesForEpoch(h.gasPricer.epoch + 1)
tx, err := h.mgr.craftTx(context.Background(), candidate)
require.Nil(t, err)
require.NotNil(t, tx)
require.Equal(t, byte(types.DynamicFeeTxType), tx.Type())
// Validate the gas tip cap and fee cap.
require.Equal(t, gasTipCap, tx.GasTipCap())
require.Equal(t, gasFeeCap, tx.GasFeeCap())
// Validate the nonce was set correctly using the backend.
require.Equal(t, uint64(startingNonce), tx.Nonce())
// Check that the gas was set using the gas limit.
require.Equal(t, candidate.GasLimit, tx.Gas())
}
// TestTxMgr_CraftBlobTx ensures that the tx manager will create blob transactions as expected.
func TestTxMgr_CraftBlobTx(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
candidate := h.createBlobTxCandidate()
// Craft the transaction.
gasTipCap, gasFeeCap, _ := h.gasPricer.feesForEpoch(h.gasPricer.epoch + 1)
tx, err := h.mgr.craftTx(context.Background(), candidate)
require.Nil(t, err)
require.NotNil(t, tx)
require.Equal(t, byte(types.BlobTxType), tx.Type())
// Validate the gas tip cap and fee cap.
require.Equal(t, gasTipCap, tx.GasTipCap())
require.Equal(t, gasFeeCap, tx.GasFeeCap())
require.Equal(t, defaultMinBlobTxFee, tx.BlobGasFeeCap())
// Validate the nonce was set correctly using the backend.
require.Equal(t, uint64(startingNonce), tx.Nonce())
// Check that the gas was set using the gas limit.
require.Equal(t, candidate.GasLimit, tx.Gas())
// Check the blob fields
require.Equal(t, 2, len(tx.BlobHashes()))
sidecar := tx.BlobTxSidecar()
require.Equal(t, 2, len(sidecar.Blobs))
require.Equal(t, 2, len(sidecar.Commitments))
require.Equal(t, 2, len(sidecar.Proofs))
// verify the blobs
for i := range sidecar.Blobs {
require.NoError(t, kzg4844.VerifyBlobProof(&sidecar.Blobs[i], sidecar.Commitments[i], sidecar.Proofs[i]))
}
b1 := eth.Blob(sidecar.Blobs[0])
d1, err := b1.ToData()
require.NoError(t, err)
require.Equal(t, blobData1, d1)
b2 := eth.Blob(sidecar.Blobs[1])
d2, err := b2.ToData()
require.NoError(t, err)
require.Equal(t, blobData2, d2)
}
// TestTxMgr_EstimateGas ensures that the tx manager will estimate
// the gas when candidate gas limit is zero in [CraftTx].
func TestTxMgr_EstimateGas(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
candidate := h.createTxCandidate()
// Set the gas limit to zero to trigger gas estimation.
candidate.GasLimit = 0
// Gas estimate
gasEstimate := h.gasPricer.baseBaseFee.Uint64()
// Craft the transaction.
tx, err := h.mgr.craftTx(context.Background(), candidate)
require.Nil(t, err)
require.NotNil(t, tx)
// Check that the gas was estimated correctly.
require.Equal(t, gasEstimate, tx.Gas())
}
func TestTxMgr_EstimateGasFails(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
candidate := h.createTxCandidate()
// Set the gas limit to zero to trigger gas estimation.
candidate.GasLimit = 0
// Craft a successful transaction.
tx, err := h.mgr.craftTx(context.Background(), candidate)
require.Nil(t, err)
lastNonce := tx.Nonce()
// Mock gas estimation failure.
h.gasPricer.err = errors.New("execution error")
_, err = h.mgr.craftTx(context.Background(), candidate)
require.ErrorContains(t, err, "failed to estimate gas")
// Ensure successful craft uses the correct nonce
h.gasPricer.err = nil
tx, err = h.mgr.craftTx(context.Background(), candidate)
require.Nil(t, err)
require.Equal(t, lastNonce+1, tx.Nonce())
}
func TestTxMgr_SigningFails(t *testing.T) {
t.Parallel()
errorSigning := false
cfg := configWithNumConfs(1)
cfg.Signer = func(ctx context.Context, from common.Address, tx *types.Transaction) (*types.Transaction, error) {
if errorSigning {
return nil, errors.New("signer error")
} else {
return tx, nil
}
}
h := newTestHarnessWithConfig(t, cfg)
candidate := h.createTxCandidate()
// Set the gas limit to zero to trigger gas estimation.
candidate.GasLimit = 0
// Craft a successful transaction.
tx, err := h.mgr.craftTx(context.Background(), candidate)
require.Nil(t, err)
lastNonce := tx.Nonce()
// Mock signer failure.
errorSigning = true
_, err = h.mgr.craftTx(context.Background(), candidate)
require.ErrorContains(t, err, "signer error")
// Ensure successful craft uses the correct nonce
errorSigning = false
tx, err = h.mgr.craftTx(context.Background(), candidate)
require.Nil(t, err)
require.Equal(t, lastNonce+1, tx.Nonce())
}
// TestTxMgrOnlyOnePublicationSucceeds asserts that the tx manager will return a
// receipt so long as at least one of the publications is able to succeed with a
// simulated failure.
func TestTxMgrOnlyOnePublicationSucceeds(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
gasTipCap, gasFeeCap, _ := h.gasPricer.sample()
tx := types.NewTx(&types.DynamicFeeTx{
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
})
sendTx := func(ctx context.Context, tx *types.Transaction) error {
// Fail all but the final attempt.
if !h.gasPricer.shouldMine(tx.GasFeeCap()) {
return txpool.ErrUnderpriced
}
txHash := tx.Hash()
h.backend.mine(&txHash, tx.GasFeeCap(), nil)
return nil
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, tx)
require.Nil(t, err)
require.NotNil(t, receipt)
require.Equal(t, h.gasPricer.expGasFeeCap().Uint64(), receipt.GasUsed)
}
// TestTxMgrConfirmsMinGasPriceAfterBumping delays the mining of the initial tx
// with the minimum gas price, and asserts that its receipt is returned even
// if the gas price has been bumped in other goroutines.
func TestTxMgrConfirmsMinGasPriceAfterBumping(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
gasTipCap, gasFeeCap, _ := h.gasPricer.sample()
tx := types.NewTx(&types.DynamicFeeTx{
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
})
sendTx := func(ctx context.Context, tx *types.Transaction) error {
// Delay mining the tx with the min gas price.
if h.gasPricer.shouldMine(tx.GasFeeCap()) {
time.AfterFunc(5*time.Second, func() {
txHash := tx.Hash()
h.backend.mine(&txHash, tx.GasFeeCap(), nil)
})
}
return nil
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, tx)
require.Nil(t, err)
require.NotNil(t, receipt)
require.Equal(t, h.gasPricer.expGasFeeCap().Uint64(), receipt.GasUsed)
}
// TestTxMgrRetriesUnbumpableTx tests that a tx whose fees cannot be bumped will still be
// re-published in case it had been dropped from the mempool.
func TestTxMgrRetriesUnbumpableTx(t *testing.T) {
t.Parallel()
cfg := configWithNumConfs(1)
cfg.FeeLimitMultiplier.Store(1) // don't allow fees to be bumped over the suggested values
h := newTestHarnessWithConfig(t, cfg)
// Make the fees unbumpable by starting with fees that will be WAY over the suggested values
gasTipCap, gasFeeCap, _ := h.gasPricer.feesForEpoch(100)
txToSend := types.NewTx(&types.DynamicFeeTx{
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
})
sameTxPublishAttempts := 0
sendTx := func(ctx context.Context, tx *types.Transaction) error {
// delay mining so several retries should be triggered
if tx.Hash().Cmp(txToSend.Hash()) == 0 {
sameTxPublishAttempts++
}
if h.gasPricer.shouldMine(tx.GasFeeCap()) {
// delay mining to give it enough time for ~3 retries
time.AfterFunc(3*time.Second, func() {
txHash := tx.Hash()
h.backend.mine(&txHash, tx.GasFeeCap(), nil)
})
}
return nil
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, txToSend)
require.NoError(t, err)
require.NotNil(t, receipt)
require.Greater(t, sameTxPublishAttempts, 1, "expected the original tx to be retried at least once")
}
// TestTxMgrDoesntAbortNonceTooLowAfterMiningTx
func TestTxMgrDoesntAbortNonceTooLowAfterMiningTx(t *testing.T) {
t.Parallel()
h := newTestHarnessWithConfig(t, configWithNumConfs(2))
gasTipCap, gasFeeCap, _ := h.gasPricer.sample()
tx := types.NewTx(&types.DynamicFeeTx{
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
})
sendTx := func(ctx context.Context, tx *types.Transaction) error {
switch {
// If the txn's gas fee cap is less than the one we expect to mine,
// accept the txn to the mempool.
case tx.GasFeeCap().Cmp(h.gasPricer.expGasFeeCap()) < 0:
return nil
// Accept and mine the actual txn we expect to confirm.
case h.gasPricer.shouldMine(tx.GasFeeCap()):
txHash := tx.Hash()
h.backend.mine(&txHash, tx.GasFeeCap(), nil)
time.AfterFunc(5*time.Second, func() {
h.backend.mine(nil, nil, nil)
})
return nil
// For gas prices greater than our expected, return ErrNonceTooLow since
// the prior txn confirmed and will invalidate subsequent publications.
default:
return core.ErrNonceTooLow
}
}
h.backend.setTxSender(sendTx)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
receipt, err := h.mgr.sendTx(ctx, tx)
require.Nil(t, err)
require.NotNil(t, receipt)
require.Equal(t, h.gasPricer.expGasFeeCap().Uint64(), receipt.GasUsed)
}
// TestWaitMinedReturnsReceiptOnFirstSuccess insta-mines a transaction and
// asserts that waitMined returns the appropriate receipt.
func TestWaitMinedReturnsReceiptOnFirstSuccess(t *testing.T) {
t.Parallel()
h := newTestHarnessWithConfig(t, configWithNumConfs(1))
// Create a tx and mine it immediately using the default backend.
tx := types.NewTx(&types.LegacyTx{})
txHash := tx.Hash()
h.backend.mine(&txHash, new(big.Int), nil)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
receipt, err := h.mgr.waitMined(ctx, tx, testSendState())
require.Nil(t, err)
require.NotNil(t, receipt)
require.Equal(t, receipt.TxHash, txHash)
}
// TestWaitMinedCanBeCanceled ensures that waitMined exits if the passed context
// is canceled before a receipt is found.
func TestWaitMinedCanBeCanceled(t *testing.T) {
t.Parallel()
h := newTestHarness(t)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
// Create an unimined tx.
tx := types.NewTx(&types.LegacyTx{})
receipt, err := h.mgr.waitMined(ctx, tx, NewSendState(10, time.Hour))
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Nil(t, receipt)
}
// TestWaitMinedMultipleConfs asserts that waitMined will properly wait for more
// than one confirmation.
func TestWaitMinedMultipleConfs(t *testing.T) {
t.Parallel()
const numConfs = 2
h := newTestHarnessWithConfig(t, configWithNumConfs(numConfs))
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// Create an unimined tx.
tx := types.NewTx(&types.LegacyTx{})
txHash := tx.Hash()
h.backend.mine(&txHash, new(big.Int), nil)
receipt, err := h.mgr.waitMined(ctx, tx, NewSendState(10, time.Hour))
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Nil(t, receipt)
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
defer cancel()
// Mine an empty block, tx should now be confirmed.
h.backend.mine(nil, nil, nil)
receipt, err = h.mgr.waitMined(ctx, tx, NewSendState(10, time.Hour))
require.Nil(t, err)
require.NotNil(t, receipt)
require.Equal(t, txHash, receipt.TxHash)
}
// TestManagerErrsOnZeroCLIConfs ensures that the NewSimpleTxManager will error
// when attempting to configure with NumConfirmations set to zero.
func TestManagerErrsOnZeroCLIConfs(t *testing.T) {
t.Parallel()
_, err := NewSimpleTxManager("TEST", testlog.Logger(t, log.LevelCrit), &metrics.NoopTxMetrics{}, CLIConfig{})
require.Error(t, err)
}
// TestManagerErrsOnZeroConfs ensures that the NewSimpleTxManager will error
// when attempting to configure with NumConfirmations set to zero.
func TestManagerErrsOnZeroConfs(t *testing.T) {
t.Parallel()
cfg := Config{
NumConfirmations: 0,
}
_, err := NewSimpleTxManagerFromConfig("TEST", testlog.Logger(t, log.LevelCrit), &metrics.NoopTxMetrics{}, &cfg)
require.Error(t, err)
}
// failingBackend implements ReceiptSource, returning a failure on the
// first call but a success on the second call. This allows us to test that the
// inner loop of WaitMined properly handles this case.
type failingBackend struct {
returnSuccessBlockNumber bool
returnSuccessHeader bool
returnSuccessReceipt bool
baseFee, gasTip *big.Int
excessBlobGas *uint64
}
// BlockNumber for the failingBackend returns errRpcFailure on the first
// invocation and a fixed block height on subsequent calls.
func (b *failingBackend) BlockNumber(ctx context.Context) (uint64, error) {
if !b.returnSuccessBlockNumber {
b.returnSuccessBlockNumber = true
return 0, errRpcFailure
}
return 1, nil
}
// TransactionReceipt for the failingBackend returns errRpcFailure on the first
// invocation, and a receipt containing the passed TxHash on the second.
func (b *failingBackend) TransactionReceipt(
ctx context.Context, txHash common.Hash,
) (*types.Receipt, error) {
if !b.returnSuccessReceipt {
b.returnSuccessReceipt = true
return nil, errRpcFailure
}
return &types.Receipt{
TxHash: txHash,
BlockNumber: big.NewInt(1),
}, nil
}