-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
eth_confirmer.go
1171 lines (1026 loc) · 48.3 KB
/
eth_confirmer.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"
"fmt"
"math/big"
"sort"
"strconv"
"sync"
"time"
"github.com/ethereum/go-ethereum"
gethCommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/rpc"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/multierr"
txmgrtypes "github.com/smartcontractkit/chainlink/common/txmgr/types"
"github.com/smartcontractkit/chainlink/core/assets"
evmclient "github.com/smartcontractkit/chainlink/core/chains/evm/client"
"github.com/smartcontractkit/chainlink/core/chains/evm/gas"
"github.com/smartcontractkit/chainlink/core/chains/evm/label"
evmtypes "github.com/smartcontractkit/chainlink/core/chains/evm/types"
"github.com/smartcontractkit/chainlink/core/logger"
"github.com/smartcontractkit/chainlink/core/services/keystore/keys/ethkey"
"github.com/smartcontractkit/chainlink/core/services/pg"
"github.com/smartcontractkit/chainlink/core/utils"
)
const (
// processHeadTimeout represents a sanity limit on how long ProcessHead
// should take to complete
processHeadTimeout = 10 * time.Minute
// logAfterNConsecutiveBlocksChainTooShort logs a warning if we go at least
// this many consecutive blocks with a re-org protection chain that is too
// short
//
// we don't log every time because on startup it can be lower, only if it
// persists does it indicate a serious problem
logAfterNConsecutiveBlocksChainTooShort = 10
)
var (
// ErrCouldNotGetReceipt is the error string we save if we reach our finality depth for a confirmed transaction without ever getting a receipt
// This most likely happened because an external wallet used the account for this nonce
ErrCouldNotGetReceipt = "could not get receipt"
promNumGasBumps = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tx_manager_num_gas_bumps",
Help: "Number of gas bumps",
}, []string{"evmChainID"})
promGasBumpExceedsLimit = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tx_manager_gas_bump_exceeds_limit",
Help: "Number of times gas bumping failed from exceeding the configured limit. Any counts of this type indicate a serious problem.",
}, []string{"evmChainID"})
promNumConfirmedTxs = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tx_manager_num_confirmed_transactions",
Help: "Total number of confirmed transactions. Note that this can err to be too high since transactions are counted on each confirmation, which can happen multiple times per transaction in the case of re-orgs",
}, []string{"evmChainID"})
promNumSuccessfulTxs = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tx_manager_num_successful_transactions",
Help: "Total number of successful transactions. Note that this can err to be too high since transactions are counted on each confirmation, which can happen multiple times per transaction in the case of re-orgs",
}, []string{"evmChainID"})
promRevertedTxCount = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tx_manager_num_tx_reverted",
Help: "Number of times a transaction reverted on-chain. Note that this can err to be too high since transactions are counted on each confirmation, which can happen multiple times per transaction in the case of re-orgs",
}, []string{"evmChainID"})
promFwdTxCount = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tx_manager_fwd_tx_count",
Help: "The number of forwarded transaction attempts labeled by status",
}, []string{"evmChainID", "successful"})
promTxAttemptCount = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "tx_manager_tx_attempt_count",
Help: "The number of transaction attempts that are currently being processed by the transaction manager",
}, []string{"evmChainID"})
promTimeUntilTxConfirmed = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "tx_manager_time_until_tx_confirmed",
Help: "The amount of time elapsed from a transaction being broadcast to being included in a block.",
Buckets: []float64{
float64(500 * time.Millisecond),
float64(time.Second),
float64(5 * time.Second),
float64(15 * time.Second),
float64(30 * time.Second),
float64(time.Minute),
float64(2 * time.Minute),
float64(5 * time.Minute),
float64(10 * time.Minute),
},
}, []string{"evmChainID"})
promBlocksUntilTxConfirmed = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "tx_manager_blocks_until_tx_confirmed",
Help: "The amount of blocks that have been mined from a transaction being broadcast to being included in a block.",
Buckets: []float64{
float64(1),
float64(5),
float64(10),
float64(20),
float64(50),
float64(100),
},
}, []string{"evmChainID"})
)
// EthConfirmer is a broad service which performs four different tasks in sequence on every new longest chain
// Step 1: Mark that all currently pending transaction attempts were broadcast before this block
// Step 2: Check pending transactions for receipts
// Step 3: See if any transactions have exceeded the gas bumping block threshold and, if so, bump them
// Step 4: Check confirmed transactions to make sure they are still in the longest chain (reorg protection)
type EthConfirmer struct {
utils.StartStopOnce
orm ORM
lggr logger.Logger
ethClient evmclient.Client
ChainKeyStore
estimator gas.Estimator
resumeCallback ResumeCallback
keyStates []ethkey.State
mb *utils.Mailbox[txmgrtypes.HeadView]
ctx context.Context
ctxCancel context.CancelFunc
wg sync.WaitGroup
nConsecutiveBlocksChainTooShort int
}
// NewEthConfirmer instantiates a new eth confirmer
func NewEthConfirmer(orm ORM, ethClient evmclient.Client, config Config, keystore KeyStore,
keyStates []ethkey.State, estimator gas.Estimator, resumeCallback ResumeCallback, lggr logger.Logger) *EthConfirmer {
ctx, cancel := context.WithCancel(context.Background())
lggr = lggr.Named("EthConfirmer")
return &EthConfirmer{
utils.StartStopOnce{},
orm,
lggr,
ethClient,
ChainKeyStore{
*ethClient.ChainID(),
config,
keystore,
},
estimator,
resumeCallback,
keyStates,
utils.NewSingleMailbox[txmgrtypes.HeadView](),
ctx,
cancel,
sync.WaitGroup{},
0,
}
}
// Start is a comment to appease the linter
func (ec *EthConfirmer) Start(_ context.Context) error {
return ec.StartOnce("EthConfirmer", func() error {
if ec.config.EvmGasBumpThreshold() == 0 {
ec.lggr.Infow("Gas bumping is disabled (ETH_GAS_BUMP_THRESHOLD set to 0)", "ethGasBumpThreshold", 0)
} else {
ec.lggr.Infow(fmt.Sprintf("Gas bumping is enabled, unconfirmed transactions will have their gas price bumped every %d blocks", ec.config.EvmGasBumpThreshold()), "ethGasBumpThreshold", ec.config.EvmGasBumpThreshold())
}
ec.wg.Add(1)
go ec.runLoop()
return nil
})
}
// Close is a comment to appease the linter
func (ec *EthConfirmer) Close() error {
return ec.StopOnce("EthConfirmer", func() error {
ec.ctxCancel()
ec.wg.Wait()
return nil
})
}
func (ec *EthConfirmer) Name() string {
return ec.lggr.Name()
}
func (ec *EthConfirmer) HealthReport() map[string]error {
return map[string]error{ec.Name(): ec.Healthy()}
}
func (ec *EthConfirmer) runLoop() {
defer ec.wg.Done()
for {
select {
case <-ec.mb.Notify():
for {
if ec.ctx.Err() != nil {
return
}
head, exists := ec.mb.Retrieve()
if !exists {
break
}
if err := ec.ProcessHead(ec.ctx, head); err != nil {
ec.lggr.Errorw("Error processing head", "err", err)
continue
}
}
case <-ec.ctx.Done():
return
}
}
}
// ProcessHead takes all required transactions for the confirmer on a new head
func (ec *EthConfirmer) ProcessHead(ctx context.Context, head txmgrtypes.HeadView) error {
ctx, cancel := context.WithTimeout(ctx, processHeadTimeout)
defer cancel()
return ec.processHead(ctx, head)
}
// NOTE: This SHOULD NOT be run concurrently or it could behave badly
func (ec *EthConfirmer) processHead(ctx context.Context, head txmgrtypes.HeadView) error {
mark := time.Now()
ec.lggr.Debugw("processHead start", "headNum", head.BlockNumber(), "id", "eth_confirmer")
if err := ec.orm.SetBroadcastBeforeBlockNum(head.BlockNumber(), ec.chainID); err != nil {
return errors.Wrap(err, "SetBroadcastBeforeBlockNum failed")
}
if err := ec.CheckConfirmedMissingReceipt(ctx); err != nil {
return errors.Wrap(err, "CheckConfirmedMissingReceipt failed")
}
if err := ec.CheckForReceipts(ctx, head.BlockNumber()); err != nil {
return errors.Wrap(err, "CheckForReceipts failed")
}
ec.lggr.Debugw("Finished CheckForReceipts", "headNum", head.BlockNumber(), "time", time.Since(mark), "id", "eth_confirmer")
mark = time.Now()
if err := ec.RebroadcastWhereNecessary(ctx, head.BlockNumber()); err != nil {
return errors.Wrap(err, "RebroadcastWhereNecessary failed")
}
ec.lggr.Debugw("Finished RebroadcastWhereNecessary", "headNum", head.BlockNumber(), "time", time.Since(mark), "id", "eth_confirmer")
mark = time.Now()
if err := ec.EnsureConfirmedTransactionsInLongestChain(ctx, head); err != nil {
return errors.Wrap(err, "EnsureConfirmedTransactionsInLongestChain failed")
}
ec.lggr.Debugw("Finished EnsureConfirmedTransactionsInLongestChain", "headNum", head.BlockNumber(), "time", time.Since(mark), "id", "eth_confirmer")
if ec.resumeCallback != nil {
mark = time.Now()
if err := ec.ResumePendingTaskRuns(ctx, head); err != nil {
return errors.Wrap(err, "ResumePendingTaskRuns failed")
}
ec.lggr.Debugw("Finished ResumePendingTaskRuns", "headNum", head.BlockNumber(), "time", time.Since(mark), "id", "eth_confirmer")
}
ec.lggr.Debugw("processHead finish", "headNum", head.BlockNumber(), "id", "eth_confirmer")
return nil
}
// CheckConfirmedMissingReceipt will attempt to re-send any transaction in the
// state of "confirmed_missing_receipt". If we get back any type of senderror
// other than "nonce too low" it means that this transaction isn't actually
// confirmed and needs to be put back into "unconfirmed" state, so that it can enter
// the gas bumping cycle. This is necessary in rare cases (e.g. Polygon) where
// network conditions are extremely hostile.
//
// For example, assume the following scenario:
//
// 0. We are connected to multiple primary nodes via load balancer
// 1. We send a transaction, it is confirmed and, we get a receipt
// 2. A new head comes in from RPC node 1 indicating that this transaction was re-org'd, so we put it back into unconfirmed state
// 3. We re-send that transaction to a RPC node 2 **which hasn't caught up to this re-org yet**
// 4. RPC node 2 still has an old view of the chain, so it returns us "nonce too low" indicating "no problem this transaction is already mined"
// 5. Now the transaction is marked "confirmed_missing_receipt" but the latest chain does not actually include it
// 6. Now we are reliant on the EthResender to propagate it, and this transaction will not be gas bumped, so in the event of gas spikes it could languish or even be evicted from the mempool and hold up the queue
// 7. Even if/when RPC node 2 catches up, the transaction is still stuck in state "confirmed_missing_receipt"
//
// This scenario might sound unlikely but has been observed to happen multiple times in the wild on Polygon.
func (ec *EthConfirmer) CheckConfirmedMissingReceipt(ctx context.Context) (err error) {
attempts, err := ec.orm.FindEtxAttemptsConfirmedMissingReceipt(ec.chainID)
if err != nil {
return err
}
if len(attempts) == 0 {
return nil
}
ec.lggr.Infow(fmt.Sprintf("Found %d transactions confirmed_missing_receipt. The RPC node did not give us a receipt for these transactions even though it should have been mined. This could be due to using the wallet with an external account, or if the primary node is not synced or not propagating transactions properly", len(attempts)), "attempts", attempts)
reqs, err := batchSendTransactions(ctx, ec.orm, attempts, int(ec.config.EvmRPCDefaultBatchSize()), ec.lggr, ec.ethClient)
if err != nil {
ec.lggr.Debugw("Batch sending transactions failed", err)
}
var ethTxIDsToUnconfirm []int64
for idx, req := range reqs {
// Add to Unconfirm array, all tx where error wasn't NonceTooLow.
if req.Error != nil {
err := evmclient.NewSendError(req.Error)
if err.IsNonceTooLowError() || err.IsTransactionAlreadyMined() {
continue
}
}
ethTxIDsToUnconfirm = append(ethTxIDsToUnconfirm, attempts[idx].EthTxID)
}
err = ec.orm.UpdateEthTxsUnconfirmed(ethTxIDsToUnconfirm)
if err != nil {
return err
}
return
}
// CheckForReceipts finds attempts that are still pending and checks to see if a receipt is present for the given block number
func (ec *EthConfirmer) CheckForReceipts(ctx context.Context, blockNum int64) error {
attempts, err := ec.orm.FindEthTxAttemptsRequiringReceiptFetch(ec.chainID)
if err != nil {
return errors.Wrap(err, "FindEthTxAttemptsRequiringReceiptFetch failed")
}
if len(attempts) == 0 {
return nil
}
ec.lggr.Debugw(fmt.Sprintf("Fetching receipts for %v transaction attempts", len(attempts)), "blockNum", blockNum)
attemptsByAddress := make(map[gethCommon.Address][]EthTxAttempt)
for _, att := range attempts {
attemptsByAddress[att.EthTx.FromAddress] = append(attemptsByAddress[att.EthTx.FromAddress], att)
}
for from, attempts := range attemptsByAddress {
minedTransactionCount, err := ec.getMinedTransactionCount(ctx, from)
if err != nil {
return errors.Wrapf(err, "unable to fetch pending nonce for address: %v", from)
}
// separateLikelyConfirmedAttempts is used as an optimisation: there is
// no point trying to fetch receipts for attempts with a nonce higher
// than the highest nonce the RPC node thinks it has seen
likelyConfirmed := ec.separateLikelyConfirmedAttempts(from, attempts, minedTransactionCount)
likelyConfirmedCount := len(likelyConfirmed)
if likelyConfirmedCount > 0 {
likelyUnconfirmedCount := len(attempts) - likelyConfirmedCount
ec.lggr.Debugf("Fetching and saving %v likely confirmed receipts. Skipping checking the others (%v)",
likelyConfirmedCount, likelyUnconfirmedCount)
start := time.Now()
err = ec.fetchAndSaveReceipts(ctx, likelyConfirmed, blockNum)
if err != nil {
return errors.Wrapf(err, "unable to fetch and save receipts for likely confirmed txs, for address: %v", from)
}
ec.lggr.Debugw(fmt.Sprintf("Fetching and saving %v likely confirmed receipts done", likelyConfirmedCount),
"time", time.Since(start))
}
}
if err := ec.orm.MarkAllConfirmedMissingReceipt(ec.chainID); err != nil {
return errors.Wrap(err, "unable to mark eth_txes as 'confirmed_missing_receipt'")
}
if err := ec.orm.MarkOldTxesMissingReceiptAsErrored(blockNum, ec.config.EvmFinalityDepth(), ec.chainID); err != nil {
return errors.Wrap(err, "unable to confirm buried unconfirmed eth_txes")
}
return nil
}
func (ec *EthConfirmer) separateLikelyConfirmedAttempts(from gethCommon.Address, attempts []EthTxAttempt, minedTransactionCount uint64) []EthTxAttempt {
if len(attempts) == 0 {
return attempts
}
firstAttemptNonce := *attempts[len(attempts)-1].EthTx.Nonce
lastAttemptNonce := *attempts[0].EthTx.Nonce
latestMinedNonce := int64(minedTransactionCount) - 1 // this can be -1 if a transaction has never been mined on this account
ec.lggr.Debugw(fmt.Sprintf("There are %d attempts from address %s, mined transaction count is %d (latest mined nonce is %d) and for the attempts' nonces: first = %d, last = %d",
len(attempts), from.Hex(), minedTransactionCount, latestMinedNonce, firstAttemptNonce, lastAttemptNonce), "nAttempts", len(attempts), "fromAddress", from, "minedTransactionCount", minedTransactionCount, "latestMinedNonce", latestMinedNonce, "firstAttemptNonce", firstAttemptNonce, "lastAttemptNonce", lastAttemptNonce)
likelyConfirmed := attempts
// attempts are ordered by nonce ASC
for i := 0; i < len(attempts); i++ {
// If the attempt nonce is lower or equal to the latestBlockNonce
// it must have been confirmed, we just didn't get a receipt yet
//
// Examples:
// 3 transactions confirmed, highest has nonce 2
// 5 total attempts, highest has nonce 4
// minedTransactionCount=3
// likelyConfirmed will be attempts[0:3] which gives the first 3 transactions, as expected
if *attempts[i].EthTx.Nonce > int64(minedTransactionCount) {
ec.lggr.Debugf("Marking attempts as likely confirmed just before index %v, at nonce: %v", i, *attempts[i].EthTx.Nonce)
likelyConfirmed = attempts[0:i]
break
}
}
if len(likelyConfirmed) == 0 {
ec.lggr.Debug("There are no likely confirmed attempts - so will skip checking any")
}
return likelyConfirmed
}
func (ec *EthConfirmer) fetchAndSaveReceipts(ctx context.Context, attempts []EthTxAttempt, blockNum int64) error {
promTxAttemptCount.WithLabelValues(ec.chainID.String()).Set(float64(len(attempts)))
batchSize := int(ec.config.EvmRPCDefaultBatchSize())
if batchSize == 0 {
batchSize = len(attempts)
}
var allReceipts []evmtypes.Receipt
for i := 0; i < len(attempts); i += batchSize {
j := i + batchSize
if j > len(attempts) {
j = len(attempts)
}
ec.lggr.Debugw(fmt.Sprintf("Batch fetching receipts at indexes %v until (excluded) %v", i, j), "blockNum", blockNum)
batch := attempts[i:j]
receipts, err := ec.batchFetchReceipts(ctx, batch, blockNum)
if err != nil {
return errors.Wrap(err, "batchFetchReceipts failed")
}
if err := ec.orm.SaveFetchedReceipts(receipts, ec.chainID); err != nil {
return errors.Wrap(err, "saveFetchedReceipts failed")
}
promNumConfirmedTxs.WithLabelValues(ec.chainID.String()).Add(float64(len(receipts)))
allReceipts = append(allReceipts, receipts...)
}
observeUntilTxConfirmed(ec.chainID, attempts, allReceipts)
return nil
}
func (ec *EthConfirmer) getMinedTransactionCount(ctx context.Context, from gethCommon.Address) (nonce uint64, err error) {
return ec.ethClient.NonceAt(ctx, from, nil)
}
// Note this function will increment promRevertedTxCount upon receiving
// a reverted transaction receipt. Should only be called with unconfirmed attempts.
func (ec *EthConfirmer) batchFetchReceipts(ctx context.Context, attempts []EthTxAttempt, blockNum int64) (receipts []evmtypes.Receipt, err error) {
var reqs []rpc.BatchElem
// Metadata is required to determine whether a tx is forwarded or not.
if ec.config.EvmUseForwarders() {
err = ec.orm.PreloadEthTxes(attempts)
if err != nil {
return nil, errors.Wrap(err, "EthConfirmer#batchFetchReceipts error loading txs for attempts")
}
}
for _, attempt := range attempts {
req := rpc.BatchElem{
Method: "eth_getTransactionReceipt",
Args: []interface{}{attempt.Hash},
Result: &evmtypes.Receipt{},
}
reqs = append(reqs, req)
}
lggr := ec.lggr.Named("batchFetchReceipts").With("blockNum", blockNum)
err = ec.ethClient.BatchCallContext(ctx, reqs)
if err != nil {
return nil, errors.Wrap(err, "EthConfirmer#batchFetchReceipts error fetching receipts with BatchCallContext")
}
for i, req := range reqs {
attempt := attempts[i]
result, err := req.Result, req.Error
receipt, is := result.(*evmtypes.Receipt)
if !is {
return nil, errors.Errorf("expected result to be a %T, got %T", (*evmtypes.Receipt)(nil), result)
}
l := logger.Sugared(attempt.EthTx.GetLogger(lggr).With(
"txHash", attempt.Hash.Hex(), "ethTxAttemptID", attempt.ID,
"ethTxID", attempt.EthTxID, "err", err, "nonce", attempt.EthTx.Nonce,
))
if err != nil {
l.Error("FetchReceipt failed")
continue
}
if receipt == nil {
// NOTE: This should never happen, but it seems safer to check
// regardless to avoid a potential panic
l.AssumptionViolation("got nil receipt")
continue
}
if receipt.IsZero() {
l.Debug("Still waiting for receipt")
continue
}
l = logger.Sugared(l.With("blockHash", receipt.BlockHash.Hex(), "status", receipt.Status, "transactionIndex", receipt.TransactionIndex))
if receipt.IsUnmined() {
l.Debug("Got receipt for transaction but it's still in the mempool and not included in a block yet")
continue
}
l.Debugw("Got receipt for transaction", "blockNumber", receipt.BlockNumber, "gasUsed", receipt.GasUsed)
if receipt.TxHash != attempt.Hash {
l.Errorf("Invariant violation, expected receipt with hash %s to have same hash as attempt with hash %s", receipt.TxHash.Hex(), attempt.Hash.Hex())
continue
}
if receipt.BlockNumber == nil {
l.Error("Invariant violation, receipt was missing block number")
continue
}
if receipt.Status == 0 {
// Do an eth call to obtain the revert reason.
_, errCall := ec.ethClient.CallContract(ctx, ethereum.CallMsg{
From: attempt.EthTx.FromAddress,
To: &attempt.EthTx.ToAddress,
Gas: uint64(attempt.EthTx.GasLimit),
GasPrice: attempt.GasPrice.ToInt(),
GasFeeCap: attempt.GasFeeCap.ToInt(),
GasTipCap: attempt.GasTipCap.ToInt(),
Value: nil,
Data: attempt.EthTx.EncodedPayload,
AccessList: nil,
}, receipt.BlockNumber)
rpcError, errExtract := evmclient.ExtractRPCError(errCall)
if errExtract == nil {
l.Warnw("transaction reverted on-chain", "hash", receipt.TxHash, "rpcError", rpcError.String())
} else {
l.Warnw("transaction reverted on-chain unable to extract revert reason", "hash", receipt.TxHash, "err", err)
}
// This might increment more than once e.g. in case of re-orgs going back and forth we might re-fetch the same receipt
promRevertedTxCount.WithLabelValues(ec.chainID.String()).Add(1)
} else {
promNumSuccessfulTxs.WithLabelValues(ec.chainID.String()).Add(1)
}
// This is only recording forwarded tx that were mined and have a status.
// Counters are prone to being inaccurate due to re-orgs.
if ec.config.EvmUseForwarders() {
meta, err := attempt.EthTx.GetMeta()
if err == nil && meta != nil && meta.FwdrDestAddress != nil {
// promFwdTxCount takes two labels, chainId and a boolean of whether a tx was successful or not.
promFwdTxCount.WithLabelValues(ec.chainID.String(), strconv.FormatBool(receipt.Status != 0)).Add(1)
}
}
receipts = append(receipts, *receipt)
}
return
}
// RebroadcastWhereNecessary bumps gas or resends transactions that were previously out-of-eth
func (ec *EthConfirmer) RebroadcastWhereNecessary(ctx context.Context, blockHeight int64) error {
var wg sync.WaitGroup
// It is safe to process separate keys concurrently
// NOTE: This design will block one key if another takes a really long time to execute
wg.Add(len(ec.keyStates))
errors := []error{}
var errMu sync.Mutex
for _, key := range ec.keyStates {
go func(fromAddress gethCommon.Address) {
if err := ec.rebroadcastWhereNecessary(ctx, fromAddress, blockHeight); err != nil {
errMu.Lock()
errors = append(errors, err)
errMu.Unlock()
ec.lggr.Errorw("Error in RebroadcastWhereNecessary", "error", err, "fromAddress", fromAddress)
}
wg.Done()
}(key.Address.Address())
}
wg.Wait()
return multierr.Combine(errors...)
}
func (ec *EthConfirmer) rebroadcastWhereNecessary(ctx context.Context, address gethCommon.Address, blockHeight int64) error {
if err := ec.handleAnyInProgressAttempts(ctx, address, blockHeight); err != nil {
return errors.Wrap(err, "handleAnyInProgressAttempts failed")
}
threshold := int64(ec.config.EvmGasBumpThreshold())
bumpDepth := int64(ec.config.EvmGasBumpTxDepth())
maxInFlightTransactions := ec.config.EvmMaxInFlightTransactions()
etxs, err := ec.FindEthTxsRequiringRebroadcast(ctx, ec.lggr, address, blockHeight, threshold, bumpDepth, maxInFlightTransactions, ec.chainID)
if err != nil {
return errors.Wrap(err, "FindEthTxsRequiringRebroadcast failed")
}
for _, etx := range etxs {
lggr := etx.GetLogger(ec.lggr)
attempt, err := ec.attemptForRebroadcast(ctx, lggr, *etx)
if err != nil {
return errors.Wrap(err, "attemptForRebroadcast failed")
}
lggr.Debugw("Rebroadcasting transaction", "nPreviousAttempts", len(etx.EthTxAttempts), "gasPrice", attempt.GasPrice, "gasTipCap", attempt.GasTipCap, "gasFeeCap", attempt.GasFeeCap)
if err := ec.orm.SaveInProgressAttempt(&attempt); err != nil {
return errors.Wrap(err, "saveInProgressAttempt failed")
}
if err := ec.handleInProgressAttempt(ctx, lggr, *etx, attempt, blockHeight); err != nil {
return errors.Wrap(err, "handleInProgressAttempt failed")
}
}
return nil
}
// "in_progress" attempts were left behind after a crash/restart and may or may not have been sent.
// We should try to ensure they get on-chain so we can fetch a receipt for them.
// NOTE: We also use this to mark attempts for rebroadcast in event of a
// re-org, so multiple attempts are allowed to be in in_progress state (but
// only one per eth_tx).
func (ec *EthConfirmer) handleAnyInProgressAttempts(ctx context.Context, address gethCommon.Address, blockHeight int64) error {
attempts, err := ec.orm.GetInProgressEthTxAttempts(ctx, address, ec.chainID)
if ctx.Err() != nil {
return nil
} else if err != nil {
return errors.Wrap(err, "GetInProgressEthTxAttempts failed")
}
for _, a := range attempts {
err := ec.handleInProgressAttempt(ctx, a.EthTx.GetLogger(ec.lggr), a.EthTx, a, blockHeight)
if ctx.Err() != nil {
break
} else if err != nil {
return errors.Wrap(err, "handleInProgressAttempt failed")
}
}
return nil
}
// FindEthTxsRequiringRebroadcast returns attempts that hit insufficient eth,
// and attempts that need bumping, in nonce ASC order
func (ec *EthConfirmer) FindEthTxsRequiringRebroadcast(ctx context.Context, lggr logger.Logger, address gethCommon.Address, blockNum, gasBumpThreshold, bumpDepth int64, maxInFlightTransactions uint32, chainID big.Int) (etxs []*EthTx, err error) {
// NOTE: These two queries could be combined into one using union but it
// becomes harder to read and difficult to test in isolation. KISS principle
etxInsufficientEths, err := ec.orm.FindEthTxsRequiringResubmissionDueToInsufficientEth(address, chainID, pg.WithParentCtx(ctx))
if err != nil {
return nil, err
}
if len(etxInsufficientEths) > 0 {
lggr.Infow(fmt.Sprintf("Found %d transactions to be re-sent that were previously rejected due to insufficient eth balance", len(etxInsufficientEths)), "blockNum", blockNum, "address", address)
}
// TODO: Just pass the Q through everything
etxBumps, err := ec.orm.FindEthTxsRequiringGasBump(ctx, address, blockNum, gasBumpThreshold, bumpDepth, chainID)
if ctx.Err() != nil {
return nil, nil
} else if err != nil {
return nil, err
}
if len(etxBumps) > 0 {
// txes are ordered by nonce asc so the first will always be the oldest
etx := etxBumps[0]
// attempts are ordered by time sent asc so first will always be the oldest
var oldestBlocksBehind int64 = -1 // It should never happen that the oldest attempt has no BroadcastBeforeBlockNum set, but in case it does, we shouldn't crash - log this sentinel value instead
if len(etx.EthTxAttempts) > 0 {
oldestBlockNum := etx.EthTxAttempts[0].BroadcastBeforeBlockNum
if oldestBlockNum != nil {
oldestBlocksBehind = blockNum - *oldestBlockNum
}
} else {
logger.Sugared(lggr).AssumptionViolationf("Expected eth_tx for gas bump to have at least one attempt", "etxID", etx.ID, "blockNum", blockNum, "address", address)
}
lggr.Infow(fmt.Sprintf("Found %d transactions to re-sent that have still not been confirmed after at least %d blocks. The oldest of these has not still not been confirmed after %d blocks. These transactions will have their gas price bumped. %s", len(etxBumps), gasBumpThreshold, oldestBlocksBehind, label.NodeConnectivityProblemWarning), "blockNum", blockNum, "address", address, "gasBumpThreshold", gasBumpThreshold)
}
seen := make(map[int64]struct{})
for _, etx := range etxInsufficientEths {
seen[etx.ID] = struct{}{}
etxs = append(etxs, etx)
}
for _, etx := range etxBumps {
if _, exists := seen[etx.ID]; !exists {
etxs = append(etxs, etx)
}
}
sort.Slice(etxs, func(i, j int) bool {
return *(etxs[i].Nonce) < *(etxs[j].Nonce)
})
if maxInFlightTransactions > 0 && len(etxs) > int(maxInFlightTransactions) {
lggr.Warnf("%d transactions to rebroadcast which exceeds limit of %d. %s", len(etxs), maxInFlightTransactions, label.MaxInFlightTransactionsWarning)
etxs = etxs[:maxInFlightTransactions]
}
return
}
func (ec *EthConfirmer) attemptForRebroadcast(ctx context.Context, lggr logger.Logger, etx EthTx) (attempt EthTxAttempt, err error) {
if len(etx.EthTxAttempts) > 0 {
etx.EthTxAttempts[0].EthTx = etx
previousAttempt := etx.EthTxAttempts[0]
logFields := ec.logFieldsPreviousAttempt(previousAttempt)
if previousAttempt.State == EthTxAttemptInsufficientEth {
// Do not create a new attempt if we ran out of eth last time since bumping gas is pointless
// Instead try to resubmit the same attempt at the same price, in the hope that the wallet was funded since our last attempt
lggr.Debugw("Rebroadcast InsufficientEth", logFields...)
previousAttempt.State = EthTxAttemptInProgress
return previousAttempt, nil
}
attempt, err = ec.bumpGas(ctx, etx, etx.EthTxAttempts)
if gas.IsBumpErr(err) {
lggr.Errorw("Failed to bump gas", append(logFields, "err", err)...)
// Do not create a new attempt if bumping gas would put us over the limit or cause some other problem
// Instead try to resubmit the previous attempt, and keep resubmitting until its accepted
previousAttempt.BroadcastBeforeBlockNum = nil
previousAttempt.State = EthTxAttemptInProgress
return previousAttempt, nil
}
return attempt, err
}
return attempt, errors.Errorf("invariant violation: EthTx %v was unconfirmed but didn't have any attempts. "+
"Falling back to default gas price instead."+
"This is a bug! Please report to https://github.com/smartcontractkit/chainlink/issues", etx.ID)
}
func (ec *EthConfirmer) logFieldsPreviousAttempt(attempt EthTxAttempt) []interface{} {
etx := attempt.EthTx
return []interface{}{
"etxID", etx.ID,
"txHash", attempt.Hash,
"previousAttempt", attempt,
"gasLimit", etx.GasLimit,
"maxGasPrice", ec.config.EvmMaxGasPriceWei(),
"nonce", etx.Nonce,
}
}
func (ec *EthConfirmer) bumpGas(ctx context.Context, etx EthTx, previousAttempts []EthTxAttempt) (bumpedAttempt EthTxAttempt, err error) {
priorAttempts := make([]gas.PriorAttempt, len(previousAttempts))
// This feels a bit useless but until we get iterators there is no other
// way to cast an array of structs to an array of interfaces
for i, attempt := range previousAttempts {
priorAttempts[i] = attempt
}
previousAttempt := previousAttempts[0]
logFields := ec.logFieldsPreviousAttempt(previousAttempt)
keySpecificMaxGasPriceWei := ec.config.KeySpecificMaxGasPriceWei(etx.FromAddress)
switch previousAttempt.TxType {
case 0x0: // Legacy
var bumpedGasPrice *assets.Wei
var bumpedGasLimit uint32
bumpedGasPrice, bumpedGasLimit, err = ec.estimator.BumpLegacyGas(ctx, previousAttempt.GasPrice, etx.GasLimit, keySpecificMaxGasPriceWei, priorAttempts)
if err == nil {
promNumGasBumps.WithLabelValues(ec.chainID.String()).Inc()
ec.lggr.Debugw("Rebroadcast bumping gas for Legacy tx", append(logFields, "bumpedGasPrice", bumpedGasPrice.String())...)
return ec.NewLegacyAttempt(etx, bumpedGasPrice, bumpedGasLimit)
}
case 0x2: // EIP1559
var bumpedFee gas.DynamicFee
var bumpedGasLimit uint32
original := previousAttempt.DynamicFee()
bumpedFee, bumpedGasLimit, err = ec.estimator.BumpDynamicFee(ctx, original, etx.GasLimit, keySpecificMaxGasPriceWei, priorAttempts)
if err == nil {
promNumGasBumps.WithLabelValues(ec.chainID.String()).Inc()
ec.lggr.Debugw("Rebroadcast bumping gas for DynamicFee tx", append(logFields, "bumpedTipCap", bumpedFee.TipCap.String(), "bumpedFeeCap", bumpedFee.FeeCap.String())...)
return ec.NewDynamicFeeAttempt(etx, bumpedFee, bumpedGasLimit)
}
default:
err = errors.Errorf("invariant violation: Attempt %v had unrecognised transaction type %v"+
"This is a bug! Please report to https://github.com/smartcontractkit/chainlink/issues", previousAttempt.ID, previousAttempt.TxType)
}
if errors.Is(errors.Cause(err), gas.ErrBumpGasExceedsLimit) {
promGasBumpExceedsLimit.WithLabelValues(ec.chainID.String()).Inc()
}
return bumpedAttempt, errors.Wrap(err, "error bumping gas")
}
func (ec *EthConfirmer) handleInProgressAttempt(ctx context.Context, lggr logger.Logger, etx EthTx, attempt EthTxAttempt, blockHeight int64) error {
if attempt.State != EthTxAttemptInProgress {
return errors.Errorf("invariant violation: expected eth_tx_attempt %v to be in_progress, it was %s", attempt.ID, attempt.State)
}
now := time.Now()
sendError := sendTransaction(ctx, ec.ethClient, attempt, etx, lggr)
if sendError.IsTerminallyUnderpriced() {
// This should really not ever happen in normal operation since we
// already bumped above the required minimum in ethBroadcaster.
ec.lggr.Warnw("Got terminally underpriced error for gas bump, this should never happen unless the remote RPC node changed its configuration on the fly, or you are using multiple RPC nodes with different minimum gas price requirements. This is not recommended", "err", sendError, "attempt", attempt)
// "Lazily" load attempts here since the overwhelmingly common case is
// that we don't need them unless we enter this path
if err := ec.orm.LoadEthTxAttempts(&etx, pg.WithParentCtx(ctx)); err != nil {
return errors.Wrap(err, "failed to load EthTxAttempts while bumping on terminally underpriced error")
}
if len(etx.EthTxAttempts) == 0 {
err := errors.New("expected to find at least 1 attempt")
logger.Sugared(ec.lggr).AssumptionViolationw(err.Error(), "err", err, "attempt", attempt)
return err
}
if attempt.ID != etx.EthTxAttempts[0].ID {
err := errors.New("expected highest priced attempt to be the current in_progress attempt")
logger.Sugared(ec.lggr).AssumptionViolationw(err.Error(), "err", err, "attempt", attempt, "ethTxAttempts", etx.EthTxAttempts)
return err
}
replacementAttempt, err := ec.bumpGas(ctx, etx, etx.EthTxAttempts)
if err != nil {
return errors.Wrap(err, "could not bump gas for terminally underpriced transaction")
}
promNumGasBumps.WithLabelValues(ec.chainID.String()).Inc()
lggr.With(
"sendError", sendError,
"maxGasPriceConfig", ec.config.EvmMaxGasPriceWei(),
"previousAttempt", attempt,
"replacementAttempt", replacementAttempt,
).Errorf("gas price was rejected by the eth node for being too low. Eth node returned: '%s'", sendError.Error())
if err := ec.orm.SaveReplacementInProgressAttempt(attempt, &replacementAttempt); err != nil {
return errors.Wrap(err, "saveReplacementInProgressAttempt failed")
}
return ec.handleInProgressAttempt(ctx, lggr, etx, replacementAttempt, blockHeight)
}
if sendError.IsTemporarilyUnderpriced() {
// Most likely scenario here is a parity node that is rejecting
// low-priced transactions due to mempool pressure
//
// In that case, the safest thing to do is to pretend the transaction
// was accepted and continue the normal gas bumping cycle until we can
// get it into the mempool
lggr.Debugw("Transaction temporarily underpriced", "attemptID", attempt.ID, "err", sendError.Error(), "gasPrice", attempt.GasPrice, "gasTipCap", attempt.GasTipCap, "gasFeeCap", attempt.GasFeeCap)
sendError = nil
}
if sendError.IsTxFeeExceedsCap() {
// The gas price was bumped too high. This transaction attempt cannot be accepted.
//
// Best thing we can do is to re-send the previous attempt at the old
// price and discard this bumped version.
lggr.Errorw(fmt.Sprintf("Transaction gas bump failed; %s", label.RPCTxFeeCapConfiguredIncorrectlyWarning),
"err", sendError,
"gasPrice", attempt.GasPrice,
"gasLimit", etx.GasLimit,
"signedRawTx", hexutil.Encode(attempt.SignedRawTx),
"blockHeight", blockHeight,
"id", "RPCTxFeeCapExceeded",
)
return ec.orm.DeleteInProgressAttempt(ctx, attempt)
}
if sendError.Fatal() {
// WARNING: This should never happen!
// Should NEVER be fatal this is an invariant violation. The
// EthBroadcaster can never create an EthTxAttempt that will
// fatally error.
//
// The only scenario imaginable where this might take place is if
// geth/parity have been updated between broadcasting and confirming steps.
lggr.Criticalw("Invariant violation: fatal error while re-attempting transaction",
"err", sendError,
"signedRawTx", hexutil.Encode(attempt.SignedRawTx),
"blockHeight", blockHeight,
)
// This will loop continuously on every new head so it must be handled manually by the node operator!
return ec.orm.DeleteInProgressAttempt(ctx, attempt)
}
if sendError.IsNonceTooLowError() || sendError.IsTransactionAlreadyMined() {
// Nonce too low indicated that a transaction at this nonce was confirmed already.
// Mark confirmed_missing_receipt and wait for the next cycle to try to get a receipt
sendError = nil
lggr.Debugw("Nonce already used", "ethTxAttemptID", attempt.ID, "txHash", attempt.Hash.Hex(), "err", sendError)
timeout := ec.config.DatabaseDefaultQueryTimeout()
return ec.orm.SaveConfirmedMissingReceiptAttempt(ctx, timeout, &attempt, now)
}
if sendError.IsReplacementUnderpriced() {
// Our system constraints guarantee that the attempt referenced in this
// function has the highest gas price of all attempts.
//
// Thus, there are only two possible scenarios where this can happen.
//
// 1. Our gas bump was insufficient compared to our previous attempt
// 2. An external wallet used the account to manually send a transaction
// at a higher gas price
//
// In this case the simplest and most robust way to recover is to ignore
// this attempt and wait until the next bump threshold is reached in
// order to bump again.
lggr.Errorw(fmt.Sprintf("Replacement transaction underpriced for eth_tx %v. "+
"Eth node returned error: '%s'. "+
"Either you have set ETH_GAS_BUMP_PERCENT (currently %v%%) too low or an external wallet used this account. "+
"Please note that using your node's private keys outside of the chainlink node is NOT SUPPORTED and can lead to missed transactions.",
etx.ID, sendError.Error(), ec.config.EvmGasBumpPercent()), "err", sendError, "gasPrice", attempt.GasPrice, "gasTipCap", attempt.GasTipCap, "gasFeeCap", attempt.GasFeeCap)
// Assume success and hand off to the next cycle.
sendError = nil
}
if sendError.IsInsufficientEth() {
lggr.Criticalw(fmt.Sprintf("Tx 0x%x with type 0x%d was rejected due to insufficient eth: %s\n"+
"ACTION REQUIRED: Chainlink wallet with address 0x%x is OUT OF FUNDS",
attempt.ID, attempt.Hash, sendError.Error(), etx.FromAddress,
), "err", sendError, "gasPrice", attempt.GasPrice, "gasTipCap", attempt.GasTipCap, "gasFeeCap", attempt.GasFeeCap)
timeout := ec.config.DatabaseDefaultQueryTimeout()
return ec.orm.SaveInsufficientEthAttempt(timeout, &attempt, now)
}
if sendError == nil {
lggr.Debugw("Successfully broadcast transaction", "ethTxAttemptID", attempt.ID, "txHash", attempt.Hash.Hex())
timeout := ec.config.DatabaseDefaultQueryTimeout()
return ec.orm.SaveSentAttempt(timeout, &attempt, now)
}
// Any other type of error is considered temporary or resolvable by the
// node operator. The node may have it in the mempool so we must keep the
// attempt (leave it in_progress). Safest thing to do is bail out and wait
// for the next head.
return errors.Wrapf(sendError, "unexpected error sending eth_tx %v with hash %s", etx.ID, attempt.Hash.Hex())
}
// EnsureConfirmedTransactionsInLongestChain finds all confirmed eth_txes up to the depth
// of the given chain and ensures that every one has a receipt with a block hash that is
// in the given chain.
//
// If any of the confirmed transactions does not have a receipt in the chain, it has been
// re-org'd out and will be rebroadcast.
func (ec *EthConfirmer) EnsureConfirmedTransactionsInLongestChain(ctx context.Context, head txmgrtypes.HeadView) error {
if head.ChainLength() < ec.config.EvmFinalityDepth() {
logArgs := []interface{}{
"chainLength", head.ChainLength(), "evmFinalityDepth", ec.config.EvmFinalityDepth(),
}
if ec.nConsecutiveBlocksChainTooShort > logAfterNConsecutiveBlocksChainTooShort {
warnMsg := "Chain length supplied for re-org detection was shorter than EvmFinalityDepth. Re-org protection is not working properly. This could indicate a problem with the remote RPC endpoint, a compatibility issue with a particular blockchain, a bug with this particular blockchain, heads table being truncated too early, remote node out of sync, or something else. If this happens a lot please raise a bug with the Chainlink team including a log output sample and details of the chain and RPC endpoint you are using."
ec.lggr.Warnw(warnMsg, append(logArgs, "nConsecutiveBlocksChainTooShort", ec.nConsecutiveBlocksChainTooShort)...)
} else {
logMsg := "Chain length supplied for re-org detection was shorter than EvmFinalityDepth"
ec.lggr.Debugw(logMsg, append(logArgs, "nConsecutiveBlocksChainTooShort", ec.nConsecutiveBlocksChainTooShort)...)
}
ec.nConsecutiveBlocksChainTooShort++
} else {
ec.nConsecutiveBlocksChainTooShort = 0
}
etxs, err := ec.orm.FindTransactionsConfirmedInBlockRange(head.BlockNumber(), head.EarliestInChain().BlockNumber(), ec.chainID)
if err != nil {
return errors.Wrap(err, "findTransactionsConfirmedInBlockRange failed")
}
for _, etx := range etxs {
if !hasReceiptInLongestChain(*etx, head) {
if err := ec.markForRebroadcast(*etx, head); err != nil {
return errors.Wrapf(err, "markForRebroadcast failed for etx %v", etx.ID)
}
}
}
// It is safe to process separate keys concurrently
// NOTE: This design will block one key if another takes a really long time to execute
var wg sync.WaitGroup
errors := []error{}
var errMu sync.Mutex
wg.Add(len(ec.keyStates))
for _, key := range ec.keyStates {
go func(fromAddress gethCommon.Address) {
if err := ec.handleAnyInProgressAttempts(ctx, fromAddress, head.BlockNumber()); err != nil {
errMu.Lock()
errors = append(errors, err)
errMu.Unlock()
ec.lggr.Errorw("Error in handleAnyInProgressAttempts", "err", err, "fromAddress", fromAddress)
}
wg.Done()
}(key.Address.Address())
}
wg.Wait()