forked from OffchainLabs/nitro
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsequencer.go
1236 lines (1135 loc) · 41.6 KB
/
sequencer.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
// Copyright 2021-2022, Offchain Labs, Inc.
// For license information, see https://github.com/nitro/blob/master/LICENSE
package gethexec
import (
"context"
"errors"
"fmt"
lightclient "github.com/EspressoSystems/espresso-sequencer-go/light-client"
"math"
"math/big"
"runtime/debug"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/offchainlabs/nitro/arbutil"
"github.com/offchainlabs/nitro/execution"
"github.com/offchainlabs/nitro/util/arbmath"
"github.com/offchainlabs/nitro/util/containers"
"github.com/offchainlabs/nitro/util/headerreader"
flag "github.com/spf13/pflag"
"github.com/ethereum/go-ethereum/arbitrum"
"github.com/ethereum/go-ethereum/arbitrum_types"
"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/state"
"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/metrics"
"github.com/ethereum/go-ethereum/params"
"github.com/offchainlabs/nitro/arbos"
"github.com/offchainlabs/nitro/arbos/arbosState"
"github.com/offchainlabs/nitro/arbos/arbostypes"
"github.com/offchainlabs/nitro/arbos/l1pricing"
"github.com/offchainlabs/nitro/util/stopwaiter"
)
var (
sequencerBacklogGauge = metrics.NewRegisteredGauge("arb/sequencer/backlog", nil)
nonceCacheHitCounter = metrics.NewRegisteredCounter("arb/sequencer/noncecache/hit", nil)
nonceCacheMissCounter = metrics.NewRegisteredCounter("arb/sequencer/noncecache/miss", nil)
nonceCacheRejectedCounter = metrics.NewRegisteredCounter("arb/sequencer/noncecache/rejected", nil)
nonceCacheClearedCounter = metrics.NewRegisteredCounter("arb/sequencer/noncecache/cleared", nil)
nonceFailureCacheSizeGauge = metrics.NewRegisteredGauge("arb/sequencer/noncefailurecache/size", nil)
nonceFailureCacheOverflowCounter = metrics.NewRegisteredGauge("arb/sequencer/noncefailurecache/overflow", nil)
blockCreationTimer = metrics.NewRegisteredTimer("arb/sequencer/block/creation", nil)
successfulBlocksCounter = metrics.NewRegisteredCounter("arb/sequencer/block/successful", nil)
conditionalTxRejectedBySequencerCounter = metrics.NewRegisteredCounter("arb/sequencer/condtionaltx/rejected", nil)
conditionalTxAcceptedBySequencerCounter = metrics.NewRegisteredCounter("arb/sequencer/condtionaltx/accepted", nil)
l1GasPriceGauge = metrics.NewRegisteredGauge("arb/sequencer/l1gasprice", nil)
callDataUnitsBacklogGauge = metrics.NewRegisteredGauge("arb/sequencer/calldataunitsbacklog", nil)
unusedL1GasChargeGauge = metrics.NewRegisteredGauge("arb/sequencer/unusedl1gascharge", nil)
currentSurplusGauge = metrics.NewRegisteredGauge("arb/sequencer/currentsurplus", nil)
expectedSurplusGauge = metrics.NewRegisteredGauge("arb/sequencer/expectedsurplus", nil)
)
type SequencerConfig struct {
Enable bool `koanf:"enable"`
MaxBlockSpeed time.Duration `koanf:"max-block-speed" reload:"hot"`
MaxRevertGasReject uint64 `koanf:"max-revert-gas-reject" reload:"hot"`
MaxAcceptableTimestampDelta time.Duration `koanf:"max-acceptable-timestamp-delta" reload:"hot"`
SenderWhitelist string `koanf:"sender-whitelist"`
Forwarder ForwarderConfig `koanf:"forwarder"`
QueueSize int `koanf:"queue-size"`
QueueTimeout time.Duration `koanf:"queue-timeout" reload:"hot"`
NonceCacheSize int `koanf:"nonce-cache-size" reload:"hot"`
MaxTxDataSize int `koanf:"max-tx-data-size" reload:"hot"`
NonceFailureCacheSize int `koanf:"nonce-failure-cache-size" reload:"hot"`
NonceFailureCacheExpiry time.Duration `koanf:"nonce-failure-cache-expiry" reload:"hot"`
ExpectedSurplusSoftThreshold string `koanf:"expected-surplus-soft-threshold" reload:"hot"`
ExpectedSurplusHardThreshold string `koanf:"expected-surplus-hard-threshold" reload:"hot"`
EnableProfiling bool `koanf:"enable-profiling" reload:"hot"`
expectedSurplusSoftThreshold int
expectedSurplusHardThreshold int
// Espresso specific flags
LightClientAddress string `koanf:"light-client-address"`
SwitchDelayThreshold uint64 `koanf:"switch-delay-threshold"`
EspressoFinalityNodeConfig EspressoFinalityNodeConfig `koanf:"espresso-finality-node-config"`
// Espresso Finality Node creates blocks with finalized hotshot transactions
EnableEspressoFinalityNode bool `koanf:"enable-espresso-finality-node"`
EnableEspressoSovereign bool `koanf:"enable-espresso-sovereign"`
}
func (c *SequencerConfig) Validate() error {
entries := strings.Split(c.SenderWhitelist, ",")
for _, address := range entries {
if len(address) == 0 {
continue
}
if !common.IsHexAddress(address) {
return fmt.Errorf("sequencer sender whitelist entry \"%v\" is not a valid address", address)
}
}
if c.MaxTxDataSize > arbostypes.MaxL2MessageSize-50000 {
return errors.New("max-tx-data-size too large for MaxL2MessageSize")
}
return nil
}
type SequencerConfigFetcher func() *SequencerConfig
type EspressoFinalityNodeConfig struct {
HotShotUrl string `koanf:"hotshot-url"`
StartBlock uint64 `koanf:"start-block"`
Namespace uint64 `koanf:"namespace"`
}
var DefaultSequencerConfig = SequencerConfig{
Enable: false,
MaxBlockSpeed: time.Millisecond * 250,
MaxRevertGasReject: 0,
MaxAcceptableTimestampDelta: time.Hour,
Forwarder: DefaultSequencerForwarderConfig,
QueueSize: 1024,
QueueTimeout: time.Second * 12,
NonceCacheSize: 1024,
// 95% of the default batch poster limit, leaving 5KB for headers and such
// This default is overridden for L3 chains in applyChainParameters in cmd/nitro/nitro.go
MaxTxDataSize: 95000,
NonceFailureCacheSize: 1024,
NonceFailureCacheExpiry: time.Second,
ExpectedSurplusSoftThreshold: "default",
ExpectedSurplusHardThreshold: "default",
EnableProfiling: false,
EnableEspressoFinalityNode: false,
EnableEspressoSovereign: false,
}
var TestSequencerConfig = SequencerConfig{
Enable: true,
MaxBlockSpeed: time.Millisecond * 10,
MaxRevertGasReject: params.TxGas + 10000,
MaxAcceptableTimestampDelta: time.Hour,
SenderWhitelist: "",
Forwarder: DefaultTestForwarderConfig,
QueueSize: 128,
QueueTimeout: time.Second * 5,
NonceCacheSize: 4,
MaxTxDataSize: 95000,
NonceFailureCacheSize: 1024,
NonceFailureCacheExpiry: time.Second,
ExpectedSurplusSoftThreshold: "default",
ExpectedSurplusHardThreshold: "default",
EnableProfiling: false,
EnableEspressoFinalityNode: false,
EnableEspressoSovereign: false,
}
func SequencerConfigAddOptions(prefix string, f *flag.FlagSet) {
f.Bool(prefix+".enable", DefaultSequencerConfig.Enable, "act and post to l1 as sequencer")
f.Duration(prefix+".max-block-speed", DefaultSequencerConfig.MaxBlockSpeed, "minimum delay between blocks (sets a maximum speed of block production)")
f.Uint64(prefix+".max-revert-gas-reject", DefaultSequencerConfig.MaxRevertGasReject, "maximum gas executed in a revert for the sequencer to reject the transaction instead of posting it (anti-DOS)")
f.Duration(prefix+".max-acceptable-timestamp-delta", DefaultSequencerConfig.MaxAcceptableTimestampDelta, "maximum acceptable time difference between the local time and the latest L1 block's timestamp")
f.String(prefix+".sender-whitelist", DefaultSequencerConfig.SenderWhitelist, "comma separated whitelist of authorized senders (if empty, everyone is allowed)")
AddOptionsForSequencerForwarderConfig(prefix+".forwarder", f)
f.Int(prefix+".queue-size", DefaultSequencerConfig.QueueSize, "size of the pending tx queue")
f.Duration(prefix+".queue-timeout", DefaultSequencerConfig.QueueTimeout, "maximum amount of time transaction can wait in queue")
f.Int(prefix+".nonce-cache-size", DefaultSequencerConfig.NonceCacheSize, "size of the tx sender nonce cache")
f.Int(prefix+".max-tx-data-size", DefaultSequencerConfig.MaxTxDataSize, "maximum transaction size the sequencer will accept")
f.Int(prefix+".nonce-failure-cache-size", DefaultSequencerConfig.NonceFailureCacheSize, "number of transactions with too high of a nonce to keep in memory while waiting for their predecessor")
f.Duration(prefix+".nonce-failure-cache-expiry", DefaultSequencerConfig.NonceFailureCacheExpiry, "maximum amount of time to wait for a predecessor before rejecting a tx with nonce too high")
f.String(prefix+".expected-surplus-soft-threshold", DefaultSequencerConfig.ExpectedSurplusSoftThreshold, "if expected surplus is lower than this value, warnings are posted")
f.String(prefix+".expected-surplus-hard-threshold", DefaultSequencerConfig.ExpectedSurplusHardThreshold, "if expected surplus is lower than this value, new incoming transactions will be denied")
f.Bool(prefix+".enable-profiling", DefaultSequencerConfig.EnableProfiling, "enable CPU profiling and tracing")
// Espresso specific flags
f.Bool(prefix+".enable-espresso-finality-node", DefaultSequencerConfig.EnableEspressoFinalityNode, "enable espresso finality node")
f.Bool(prefix+".enable-espresso-sovereign", DefaultSequencerConfig.EnableEspressoSovereign, "enable sovereign sequencer mode for the Espresso integration")
}
type txQueueItem struct {
tx *types.Transaction
txSize int // size in bytes of the marshalled transaction
options *arbitrum_types.ConditionalOptions
resultChan chan<- error
returnedResult *atomic.Bool
ctx context.Context
firstAppearance time.Time
}
func (i *txQueueItem) returnResult(err error) {
if i.returnedResult.Swap(true) {
log.Error("attempting to return result to already finished queue item", "err", err)
return
}
i.resultChan <- err
close(i.resultChan)
}
type nonceCache struct {
cache *containers.LruCache[common.Address, uint64]
block common.Hash
dirty *types.Header
}
func newNonceCache(size int) *nonceCache {
return &nonceCache{
cache: containers.NewLruCache[common.Address, uint64](size),
block: common.Hash{},
dirty: nil,
}
}
func (c *nonceCache) matches(header *types.Header) bool {
if c.dirty != nil {
// Note, even though the of the header changes, c.dirty points to the
// same header, hence hashes will be the same and this check will pass.
return headerreader.HeadersEqual(c.dirty, header)
}
return c.block == header.ParentHash
}
func (c *nonceCache) Reset(block common.Hash) {
if c.cache.Len() > 0 {
nonceCacheClearedCounter.Inc(1)
}
c.cache.Clear()
c.block = block
c.dirty = nil
}
func (c *nonceCache) BeginNewBlock() {
if c.dirty != nil {
c.Reset(common.Hash{})
}
}
func (c *nonceCache) Get(header *types.Header, statedb *state.StateDB, addr common.Address) uint64 {
if !c.matches(header) {
c.Reset(header.ParentHash)
}
nonce, ok := c.cache.Get(addr)
if ok {
nonceCacheHitCounter.Inc(1)
return nonce
}
nonceCacheMissCounter.Inc(1)
nonce = statedb.GetNonce(addr)
c.cache.Add(addr, nonce)
return nonce
}
func (c *nonceCache) Update(header *types.Header, addr common.Address, nonce uint64) {
if !c.matches(header) {
c.Reset(header.ParentHash)
}
c.dirty = header
c.cache.Add(addr, nonce)
}
func (c *nonceCache) Finalize(block *types.Block) {
// Note: we don't use c.matches here because the header will have changed
if c.block == block.ParentHash() {
c.block = block.Hash()
c.dirty = nil
} else {
c.Reset(block.Hash())
}
}
func (c *nonceCache) Caching() bool {
return c.cache != nil && c.cache.Size() > 0
}
func (c *nonceCache) Resize(newSize int) {
c.cache.Resize(newSize)
}
type addressAndNonce struct {
address common.Address
nonce uint64
}
type nonceFailure struct {
queueItem txQueueItem
nonceErr error
expiry time.Time
revived bool
}
type nonceFailureCache struct {
*containers.LruCache[addressAndNonce, *nonceFailure]
getExpiry func() time.Duration
}
func (c nonceFailureCache) Contains(err NonceError) bool {
key := addressAndNonce{err.sender, err.txNonce}
return c.LruCache.Contains(key)
}
func (c nonceFailureCache) Add(err NonceError, queueItem txQueueItem) {
expiry := queueItem.firstAppearance.Add(c.getExpiry())
if c.Contains(err) || time.Now().After(expiry) {
queueItem.returnResult(err)
return
}
key := addressAndNonce{err.sender, err.txNonce}
val := &nonceFailure{
queueItem: queueItem,
nonceErr: err,
expiry: expiry,
revived: false,
}
evicted := c.LruCache.Add(key, val)
if evicted {
nonceFailureCacheOverflowCounter.Inc(1)
}
}
type Sequencer struct {
stopwaiter.StopWaiter
execEngine *ExecutionEngine
txQueue chan txQueueItem
txRetryQueue containers.Queue[txQueueItem]
l1Reader *headerreader.HeaderReader
config SequencerConfigFetcher
senderWhitelist map[common.Address]struct{}
nonceCache *nonceCache
nonceFailures *nonceFailureCache
onForwarderSet chan struct{}
L1BlockAndTimeMutex sync.Mutex
l1BlockNumber uint64
l1Timestamp uint64
// activeMutex manages pauseChan (pauses execution) and forwarder
// at most one of these is non-nil at any given time
// both are nil for the active sequencer
activeMutex sync.Mutex
pauseChan chan struct{}
forwarder *TxForwarder
expectedSurplusMutex sync.RWMutex
expectedSurplus int64
expectedSurplusUpdated bool
lightClientReader *lightclient.LightClientReader
}
func NewSequencer(execEngine *ExecutionEngine, l1Reader *headerreader.HeaderReader, configFetcher SequencerConfigFetcher) (*Sequencer, error) {
config := configFetcher()
if err := config.Validate(); err != nil {
return nil, err
}
senderWhitelist := make(map[common.Address]struct{})
entries := strings.Split(config.SenderWhitelist, ",")
for _, address := range entries {
if len(address) == 0 {
continue
}
senderWhitelist[common.HexToAddress(address)] = struct{}{}
}
// For the sovereign sequencer to have an escape hatch, we need to be able to read the state of the light client.
// To accomplish this, we introduce a requirement on the l1Reader/ParentChainReader to not be null. This is a soft
// requirement as the sequencer will still run if we don't have this reader, but it will not create espresso messages.
var (
lightClientReader *lightclient.LightClientReader
err error
)
if l1Reader == nil && config.EnableEspressoSovereign {
return nil, fmt.Errorf("Cannot enable espresso sequencing mode in the sovereign sequencer with no l1 reader")
}
if l1Reader != nil {
lightClientReader, err = lightclient.NewLightClientReader(common.HexToAddress(config.LightClientAddress), l1Reader.Client())
if err != nil {
log.Error("Could not construct light client reader for sequencer. Failing.", "err", err)
return nil, err
}
}
s := &Sequencer{
execEngine: execEngine,
txQueue: make(chan txQueueItem, config.QueueSize),
l1Reader: l1Reader,
config: configFetcher,
senderWhitelist: senderWhitelist,
nonceCache: newNonceCache(config.NonceCacheSize),
l1BlockNumber: 0,
l1Timestamp: 0,
pauseChan: nil,
onForwarderSet: make(chan struct{}, 1),
lightClientReader: lightClientReader,
}
s.nonceFailures = &nonceFailureCache{
containers.NewLruCacheWithOnEvict(config.NonceCacheSize, s.onNonceFailureEvict),
func() time.Duration { return configFetcher().NonceFailureCacheExpiry },
}
s.Pause()
execEngine.EnableReorgSequencing()
return s, nil
}
func (s *Sequencer) onNonceFailureEvict(_ addressAndNonce, failure *nonceFailure) {
if failure.revived {
return
}
queueItem := failure.queueItem
err := queueItem.ctx.Err()
if err != nil {
queueItem.returnResult(err)
return
}
_, forwarder := s.GetPauseAndForwarder()
if forwarder != nil {
// We might not have gotten the predecessor tx because our forwarder did. Let's try there instead.
// We run this in a background goroutine because LRU eviction needs to be quick.
// We use an untracked thread for a few reasons:
// - It's guaranteed to run even when stopped (we need to return *some* result).
// - It acquires mutexes and this might need to happen a lot.
// - We don't need the context because queueItem has its own.
// - The RPC handler is on a separate StopWaiter anyways -- we should respect its context.
s.LaunchUntrackedThread(func() {
err = forwarder.PublishTransaction(queueItem.ctx, queueItem.tx, queueItem.options)
queueItem.returnResult(err)
})
} else {
queueItem.returnResult(failure.nonceErr)
}
}
// ctxWithTimeout is like context.WithTimeout except a timeout of 0 means unlimited instead of instantly expired.
func ctxWithTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
if timeout == time.Duration(0) {
return context.WithCancel(ctx)
}
return context.WithTimeout(ctx, timeout)
}
func (s *Sequencer) PublishTransaction(parentCtx context.Context, tx *types.Transaction, options *arbitrum_types.ConditionalOptions) error {
config := s.config()
// Only try to acquire Rlock and check for hard threshold if l1reader is not nil
// And hard threshold was enabled, this prevents spamming of read locks when not needed
if s.l1Reader != nil && config.ExpectedSurplusHardThreshold != "default" {
s.expectedSurplusMutex.RLock()
if s.expectedSurplusUpdated && s.expectedSurplus < int64(config.expectedSurplusHardThreshold) {
return errors.New("currently not accepting transactions due to expected surplus being below threshold")
}
s.expectedSurplusMutex.RUnlock()
}
sequencerBacklogGauge.Inc(1)
defer sequencerBacklogGauge.Dec(1)
_, forwarder := s.GetPauseAndForwarder()
if forwarder != nil {
err := forwarder.PublishTransaction(parentCtx, tx, options)
if !errors.Is(err, ErrNoSequencer) {
return err
}
}
if len(s.senderWhitelist) > 0 {
signer := types.LatestSigner(s.execEngine.bc.Config())
sender, err := types.Sender(signer, tx)
if err != nil {
return err
}
_, authorized := s.senderWhitelist[sender]
if !authorized {
return errors.New("transaction sender is not on the whitelist")
}
}
if tx.Type() >= types.ArbitrumDepositTxType || tx.Type() == types.BlobTxType {
// Should be unreachable for Arbitrum types due to UnmarshalBinary not accepting Arbitrum internal txs
// and we want to disallow BlobTxType since Arbitrum doesn't support EIP-4844 txs yet.
return types.ErrTxTypeNotSupported
}
txBytes, err := tx.MarshalBinary()
if err != nil {
return err
}
queueTimeout := config.QueueTimeout
queueCtx, cancelFunc := ctxWithTimeout(parentCtx, queueTimeout)
defer cancelFunc()
// Just to be safe, make sure we don't run over twice the queue timeout
abortCtx, cancel := ctxWithTimeout(parentCtx, queueTimeout*2)
defer cancel()
resultChan := make(chan error, 1)
queueItem := txQueueItem{
tx,
len(txBytes),
options,
resultChan,
&atomic.Bool{},
queueCtx,
time.Now(),
}
select {
case s.txQueue <- queueItem:
case <-queueCtx.Done():
return queueCtx.Err()
}
select {
case res := <-resultChan:
return res
case <-abortCtx.Done():
// We use abortCtx here and not queueCtx, because the QueueTimeout only applies to the background queue.
// We want to give the background queue as much time as possible to make a response.
err := abortCtx.Err()
if parentCtx.Err() == nil {
// If we've hit the abort deadline (as opposed to parentCtx being canceled), something went wrong.
log.Warn("Transaction sequencing hit abort deadline", "err", err, "submittedAt", queueItem.firstAppearance, "queueTimeout", queueTimeout, "txHash", tx.Hash())
}
return err
}
}
func (s *Sequencer) preTxFilter(_ *params.ChainConfig, header *types.Header, statedb *state.StateDB, _ *arbosState.ArbosState, tx *types.Transaction, options *arbitrum_types.ConditionalOptions, sender common.Address, l1Info *arbos.L1Info) error {
if s.nonceCache.Caching() {
stateNonce := s.nonceCache.Get(header, statedb, sender)
err := MakeNonceError(sender, tx.Nonce(), stateNonce)
if err != nil {
nonceCacheRejectedCounter.Inc(1)
return err
}
}
if options != nil {
err := options.Check(l1Info.L1BlockNumber(), header.Time, statedb)
if err != nil {
conditionalTxRejectedBySequencerCounter.Inc(1)
return err
}
conditionalTxAcceptedBySequencerCounter.Inc(1)
}
return nil
}
func (s *Sequencer) postTxFilter(header *types.Header, _ *arbosState.ArbosState, tx *types.Transaction, sender common.Address, dataGas uint64, result *core.ExecutionResult) error {
if result.Err != nil && result.UsedGas > dataGas && result.UsedGas-dataGas <= s.config().MaxRevertGasReject {
return arbitrum.NewRevertReason(result)
}
newNonce := tx.Nonce() + 1
s.nonceCache.Update(header, sender, newNonce)
newAddrAndNonce := addressAndNonce{sender, newNonce}
nonceFailure, haveNonceFailure := s.nonceFailures.Get(newAddrAndNonce)
if haveNonceFailure {
nonceFailure.revived = true // prevent the expiry hook from taking effect
s.nonceFailures.Remove(newAddrAndNonce)
// Immediately check if the transaction submission has been canceled
err := nonceFailure.queueItem.ctx.Err()
if err != nil {
nonceFailure.queueItem.returnResult(err)
} else {
// Add this transaction (whose nonce is now correct) back into the queue
s.txRetryQueue.Push(nonceFailure.queueItem)
}
}
return nil
}
func (s *Sequencer) CheckHealth(ctx context.Context) error {
pauseChan, forwarder := s.GetPauseAndForwarder()
if forwarder != nil {
return forwarder.CheckHealth(ctx)
}
if pauseChan != nil {
return nil
}
return s.execEngine.consensus.ExpectChosenSequencer()
}
func (s *Sequencer) ForwardTarget() string {
s.activeMutex.Lock()
defer s.activeMutex.Unlock()
if s.forwarder == nil {
return ""
}
return s.forwarder.PrimaryTarget()
}
func (s *Sequencer) ForwardTo(url string) error {
s.activeMutex.Lock()
defer s.activeMutex.Unlock()
if s.forwarder != nil {
if s.forwarder.PrimaryTarget() == url {
log.Warn("attempted to update sequencer forward target with existing target", "url", url)
return nil
}
s.forwarder.Disable()
}
s.forwarder = NewForwarder([]string{url}, &s.config().Forwarder)
err := s.forwarder.Initialize(s.GetContext())
if err != nil {
log.Error("failed to set forward agent", "err", err)
s.forwarder = nil
}
if s.pauseChan != nil {
close(s.pauseChan)
s.pauseChan = nil
}
if err == nil {
// If createBlocks is waiting for a new queue item, notify it that it needs to clear the nonceFailures.
select {
case s.onForwarderSet <- struct{}{}:
default:
}
}
return err
}
func (s *Sequencer) Activate() {
s.activeMutex.Lock()
defer s.activeMutex.Unlock()
if s.forwarder != nil {
s.forwarder.Disable()
s.forwarder = nil
}
if s.pauseChan != nil {
close(s.pauseChan)
s.pauseChan = nil
}
}
func (s *Sequencer) Pause() {
s.activeMutex.Lock()
defer s.activeMutex.Unlock()
if s.forwarder != nil {
s.forwarder.Disable()
s.forwarder = nil
}
if s.pauseChan == nil {
s.pauseChan = make(chan struct{})
}
}
var ErrNoSequencer = errors.New("sequencer temporarily not available")
func (s *Sequencer) GetPauseAndForwarder() (chan struct{}, *TxForwarder) {
s.activeMutex.Lock()
defer s.activeMutex.Unlock()
return s.pauseChan, s.forwarder
}
// only called from createBlock, may be paused
func (s *Sequencer) handleInactive(ctx context.Context, queueItems []txQueueItem) bool {
var forwarder *TxForwarder
for {
var pause chan struct{}
pause, forwarder = s.GetPauseAndForwarder()
if pause == nil {
if forwarder == nil {
return false
}
// if forwarding: jump to next loop
break
}
// if paused: wait till unpaused
select {
case <-ctx.Done():
return true
case <-pause:
}
}
publishResults := make(chan *txQueueItem, len(queueItems))
for _, item := range queueItems {
item := item
go func() {
res := forwarder.PublishTransaction(item.ctx, item.tx, item.options)
if errors.Is(res, ErrNoSequencer) {
publishResults <- &item
} else {
publishResults <- nil
item.returnResult(res)
}
}()
}
for range queueItems {
remainingItem := <-publishResults
if remainingItem != nil {
s.txRetryQueue.Push(*remainingItem)
}
}
// Evict any leftover nonce failures, forwarding them
s.nonceFailures.Clear()
return true
}
var sequencerInternalError = errors.New("sequencer internal error")
func (s *Sequencer) makeSequencingHooks() *arbos.SequencingHooks {
return &arbos.SequencingHooks{
PreTxFilter: s.preTxFilter,
PostTxFilter: s.postTxFilter,
DiscardInvalidTxsEarly: true,
TxErrors: []error{},
ConditionalOptionsForTx: nil,
}
}
func (s *Sequencer) expireNonceFailures() *time.Timer {
defer nonceFailureCacheSizeGauge.Update(int64(s.nonceFailures.Len()))
for {
_, failure, ok := s.nonceFailures.GetOldest()
if !ok {
return nil
}
untilExpiry := time.Until(failure.expiry)
if untilExpiry > 0 {
return time.NewTimer(untilExpiry)
}
s.nonceFailures.RemoveOldest()
}
}
// There's no guarantee that returned tx nonces will be correct
func (s *Sequencer) precheckNonces(queueItems []txQueueItem, totalBlockSize int) []txQueueItem {
config := s.config()
bc := s.execEngine.bc
latestHeader := bc.CurrentBlock()
latestState, err := bc.StateAt(latestHeader.Root)
if err != nil {
log.Error("failed to get current state to pre-check nonces", "err", err)
return queueItems
}
nextHeaderNumber := arbmath.BigAdd(latestHeader.Number, common.Big1)
signer := types.MakeSigner(bc.Config(), nextHeaderNumber, latestHeader.Time)
outputQueueItems := make([]txQueueItem, 0, len(queueItems))
var nextQueueItem *txQueueItem
var queueItemsIdx int
pendingNonces := make(map[common.Address]uint64)
for {
var queueItem txQueueItem
if nextQueueItem != nil {
queueItem = *nextQueueItem
nextQueueItem = nil
} else if queueItemsIdx < len(queueItems) {
queueItem = queueItems[queueItemsIdx]
queueItemsIdx++
} else {
break
}
tx := queueItem.tx
sender, err := types.Sender(signer, tx)
if err != nil {
queueItem.returnResult(err)
continue
}
stateNonce := s.nonceCache.Get(latestHeader, latestState, sender)
pendingNonce, pending := pendingNonces[sender]
if !pending {
pendingNonce = stateNonce
}
txNonce := tx.Nonce()
if txNonce == pendingNonce {
pendingNonces[sender] = txNonce + 1
nextKey := addressAndNonce{sender, txNonce + 1}
revivingFailure, exists := s.nonceFailures.Get(nextKey)
if exists {
// This tx was the predecessor to one that had failed its nonce check
// Re-enqueue the tx whose nonce should now be correct, unless it expired
revivingFailure.revived = true
s.nonceFailures.Remove(nextKey)
err := revivingFailure.queueItem.ctx.Err()
if err != nil {
revivingFailure.queueItem.returnResult(err)
} else {
if arbmath.SaturatingAdd(totalBlockSize, revivingFailure.queueItem.txSize) > config.MaxTxDataSize {
// This tx would be too large to add to this block
s.txRetryQueue.Push(revivingFailure.queueItem)
} else {
nextQueueItem = &revivingFailure.queueItem
totalBlockSize += revivingFailure.queueItem.txSize
}
}
}
} else if txNonce < stateNonce || txNonce > pendingNonce {
// It's impossible for this tx to succeed so far,
// because its nonce is lower than the state nonce
// or higher than the highest tx nonce we've seen.
err := MakeNonceError(sender, txNonce, stateNonce)
if errors.Is(err, core.ErrNonceTooHigh) {
var nonceError NonceError
if !errors.As(err, &nonceError) {
log.Warn("unreachable nonce error is not nonceError")
continue
}
// Retry this transaction if its predecessor appears
s.nonceFailures.Add(nonceError, queueItem)
continue
} else if err != nil {
nonceCacheRejectedCounter.Inc(1)
queueItem.returnResult(err)
continue
} else {
log.Warn("unreachable nonce err == nil condition hit in precheckNonces")
}
}
// If neither if condition was hit, then txNonce >= stateNonce && txNonce < pendingNonce
// This tx might still go through if previous txs fail.
// We'll include it in the output queue in case that happens.
outputQueueItems = append(outputQueueItems, queueItem)
}
nonceFailureCacheSizeGauge.Update(int64(s.nonceFailures.Len()))
return outputQueueItems
}
func (s *Sequencer) createBlock(ctx context.Context) (returnValue bool) {
var queueItems []txQueueItem
var totalBlockSize int
defer func() {
panicErr := recover()
if panicErr != nil {
log.Error("sequencer block creation panicked", "panic", panicErr, "backtrace", string(debug.Stack()))
// Return an internal error to any queue items we were trying to process
for _, item := range queueItems {
// This can race, but that's alright, worst case is a log line in returnResult
if !item.returnedResult.Load() {
item.returnResult(sequencerInternalError)
}
}
// Wait for the MaxBlockSpeed until attempting to create a block again
returnValue = true
}
}()
defer nonceFailureCacheSizeGauge.Update(int64(s.nonceFailures.Len()))
config := s.config()
// Clear out old nonceFailures
s.nonceFailures.Resize(config.NonceFailureCacheSize)
nextNonceExpiryTimer := s.expireNonceFailures()
defer func() {
// We wrap this in a closure as to not cache the current value of nextNonceExpiryTimer
if nextNonceExpiryTimer != nil {
nextNonceExpiryTimer.Stop()
}
}()
for {
var queueItem txQueueItem
if s.txRetryQueue.Len() > 0 {
queueItem = s.txRetryQueue.Pop()
} else if len(queueItems) == 0 {
var nextNonceExpiryChan <-chan time.Time
if nextNonceExpiryTimer != nil {
nextNonceExpiryChan = nextNonceExpiryTimer.C
}
select {
case queueItem = <-s.txQueue:
case <-nextNonceExpiryChan:
// No need to stop the previous timer since it already elapsed
nextNonceExpiryTimer = s.expireNonceFailures()
continue
case <-s.onForwarderSet:
// Make sure this notification isn't outdated
_, forwarder := s.GetPauseAndForwarder()
if forwarder != nil {
s.nonceFailures.Clear()
}
continue
case <-ctx.Done():
return false
}
} else {
done := false
select {
case queueItem = <-s.txQueue:
default:
done = true
}
if done {
break
}
}
err := queueItem.ctx.Err()
if err != nil {
queueItem.returnResult(err)
continue
}
if queueItem.txSize > config.MaxTxDataSize {
// This tx is too large
queueItem.returnResult(txpool.ErrOversizedData)
continue
}
if totalBlockSize+queueItem.txSize > config.MaxTxDataSize {
// This tx would be too large to add to this batch
s.txRetryQueue.Push(queueItem)
// End the batch here to put this tx in the next one
break
}
totalBlockSize += queueItem.txSize
queueItems = append(queueItems, queueItem)
}
s.nonceCache.Resize(config.NonceCacheSize) // Would probably be better in a config hook but this is basically free
s.nonceCache.BeginNewBlock()
queueItems = s.precheckNonces(queueItems, totalBlockSize)
txes := make([]*types.Transaction, len(queueItems))
hooks := s.makeSequencingHooks()
hooks.ConditionalOptionsForTx = make([]*arbitrum_types.ConditionalOptions, len(queueItems))
totalBlockSize = 0 // recompute the totalBlockSize to double check it
for i, queueItem := range queueItems {
txes[i] = queueItem.tx
totalBlockSize = arbmath.SaturatingAdd(totalBlockSize, queueItem.txSize)
hooks.ConditionalOptionsForTx[i] = queueItem.options
}
if totalBlockSize > config.MaxTxDataSize {
for _, queueItem := range queueItems {
s.txRetryQueue.Push(queueItem)
}
log.Error(
"put too many transactions in a block",
"numTxes", len(queueItems),
"totalBlockSize", totalBlockSize,
"maxTxDataSize", config.MaxTxDataSize,
)
return false
}
if s.handleInactive(ctx, queueItems) {
return false
}
timestamp := time.Now().Unix()
s.L1BlockAndTimeMutex.Lock()
l1Block := s.l1BlockNumber
l1Timestamp := s.l1Timestamp
s.L1BlockAndTimeMutex.Unlock()
if s.l1Reader != nil && (l1Block == 0 || math.Abs(float64(l1Timestamp)-float64(timestamp)) > config.MaxAcceptableTimestampDelta.Seconds()) {
for _, queueItem := range queueItems {
s.txRetryQueue.Push(queueItem)
}
log.Error(
"cannot sequence: unknown L1 block or L1 timestamp too far from local clock time",
"l1Block", l1Block,
"l1Timestamp", time.Unix(int64(l1Timestamp), 0),
"localTimestamp", time.Unix(int64(timestamp), 0),
)
return true
}
header := &arbostypes.L1IncomingMessageHeader{
Kind: arbostypes.L1MessageType_L2Message,
Poster: l1pricing.BatchPosterAddress,
BlockNumber: l1Block,
Timestamp: uint64(timestamp),
RequestId: nil,
L1BaseFee: nil,
}
start := time.Now()
var (
block *types.Block
err error
shouldSequenceWithEspresso bool
)
// Initialize shouldSequenceWithEspresso to false and if we have a light client reader then give it a value based on hotshot liveness
// This is a side effect of the sequencer having the capability to run without an L1 reader. For the Espresso integration this is a necessary component of the sequencer.
// However, many tests use the case of having a nil l1 reader
if s.lightClientReader != nil {
shouldSequenceWithEspresso, err = s.lightClientReader.IsHotShotLiveAtHeight(l1Block, s.config().SwitchDelayThreshold)
}
if err != nil {
log.Warn("An error occurred while attempting to determine if hotshot is live at l1 block, sequencing transactions without espresso", "l1Block", l1Block, "err", err)
shouldSequenceWithEspresso = false
}
if config.EnableProfiling {
block, err = s.execEngine.SequenceTransactionsWithProfiling(header, txes, hooks, shouldSequenceWithEspresso)
} else {
block, err = s.execEngine.SequenceTransactions(header, txes, hooks, shouldSequenceWithEspresso)
}
elapsed := time.Since(start)
blockCreationTimer.Update(elapsed)
if elapsed >= time.Second*5 {
var blockNum *big.Int
if block != nil {
blockNum = block.Number()
}
log.Warn("took over 5 seconds to sequence a block", "elapsed", elapsed, "numTxes", len(txes), "success", block != nil, "l2Block", blockNum)
}
if err == nil && len(hooks.TxErrors) != len(txes) {
err = fmt.Errorf("unexpected number of error results: %v vs number of txes %v", len(hooks.TxErrors), len(txes))
}
if errors.Is(err, execution.ErrRetrySequencer) {
log.Warn("error sequencing transactions", "err", err)