forked from ethereum-optimism/optimism
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathespresso.go
More file actions
1518 lines (1320 loc) · 50.4 KB
/
Copy pathespresso.go
File metadata and controls
1518 lines (1320 loc) · 50.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package batcher
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
espressoClient "github.com/EspressoSystems/espresso-network/sdks/go/client"
tagged_base64 "github.com/EspressoSystems/espresso-network/sdks/go/tagged-base64"
espressoCommon "github.com/EspressoSystems/espresso-network/sdks/go/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/signer/core/apitypes"
"github.com/ethereum-optimism/optimism/espresso"
"github.com/ethereum-optimism/optimism/espresso/bindings"
"github.com/ethereum-optimism/optimism/espresso/logmodule"
"github.com/ethereum-optimism/optimism/op-node/rollup/derive"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum-optimism/optimism/op-service/txmgr"
)
// EspressoOnchainProof is the proof structure returned by the attestation service for onchain verification.
type EspressoOnchainProof struct {
Proof json.RawMessage `json:"proof,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
RawProof struct {
Journal string `json:"journal"`
} `json:"raw_proof"`
OnchainProof string `json:"onchain_proof"`
}
// espressoSubmitTransactionJob is a struct that holds the state required to
// submit a transaction to Espresso.
// It contains the transaction to be submitted itself, and a number to
// track the total number of attempts to submit this transaction to Espresso.
type espressoSubmitTransactionJob struct {
attempts int
transaction *espressoCommon.Transaction
}
// espressoSubmitTransactionJobResponse is a struct that holds the
// response from the Espresso client after submitting a transaction.
// It contains the job that was submitted, the hash of the transaction
// that was submitted (if successful), and any error that occurred during the
// submission (if unsuccessful).
type espressoSubmitTransactionJobResponse struct {
job espressoSubmitTransactionJob
hash *espressoCommon.TaggedBase64
err error
}
// espressoTransactionJobAttempt is a struct that holds the job and
// response channel for a transaction submission job.
//
// This is the unit of work that is submitted to the worker to process
// for transaction submissions.
type espressoTransactionJobAttempt struct {
job espressoSubmitTransactionJob
resp chan espressoSubmitTransactionJobResponse
}
// espressoVerifyReceiptJob is a struct that holds the state required to
// verify a receipt for a transaction that was submitted to Espresso.
// It contains the transaction that was submitted, the hash of the
// transaction, and the number of attempts to verify the receipt.
type espressoVerifyReceiptJob struct {
attempts int
startHeight uint64 // HotShot block height when verification began (set on first attempt)
startTime time.Time // wall-clock time when verification began (safety backstop)
transaction espressoSubmitTransactionJob
hash *espressoCommon.TaggedBase64
}
// espressoVerifyReceiptJobResponse is a struct that holds the
// response from the Espresso client after verifying a receipt.
// It contains the job that was submitted, and any error that occurred
// during the verification (if unsuccessful).
type espressoVerifyReceiptJobResponse struct {
job espressoVerifyReceiptJob
err error
currentHeight uint64 // latest known HotShot block height at time of verification attempt
}
// espressoVerifyReceiptJobAttempt is a struct that holds the job and
// response channel for a receipt verification job.
//
// This is the unit of work that is submitted to the worker to process
// for receipt verifications.
type espressoVerifyReceiptJobAttempt struct {
job espressoVerifyReceiptJob
resp chan espressoVerifyReceiptJobResponse
}
// espressoTransactionSubmitter is a struct that holds the state that governs
// the worker queue processing details for submitting transactions to Espresso
// without spawning arbitrarily many goroutines.
type espressoTransactionSubmitter struct {
ctx context.Context
wg *sync.WaitGroup
submitJobQueue chan espressoSubmitTransactionJob
submitRespQueue chan espressoSubmitTransactionJobResponse
submitWorkerQueue chan chan espressoTransactionJobAttempt
verifyReceiptJobQueue chan espressoVerifyReceiptJob
verifyReceiptRespQueue chan espressoVerifyReceiptJobResponse
verifyReceiptWorkerQueue chan chan espressoVerifyReceiptJobAttempt
espresso espressoClient.EspressoClient
latestBlockHeight atomic.Uint64 // shared HotShot block height, updated by trackBlockHeight
verifyReceiptMaxBlocks uint64
verifyReceiptSafetyTimeout time.Duration
verifyReceiptRetryDelay time.Duration
numInFlightJobs atomic.Int64
numMaxInFlightJobs int
}
// EspressoTransactionSubmitterConfig is a configuration struct for the
// EspressoTransactionSubmitter. It contains the configurable details for
// creating the EspressoTransactionSubmitter.
type EspressoTransactionSubmitterConfig struct {
Ctx context.Context
EspressoClient espressoClient.EspressoClient
Wg *sync.WaitGroup
SubmitJobQueueCapacity int
SubmitResponseQueueCapacity int
VerifyReceiptJobQueueCapacity int
VerifyReceiptResponseQueueCapacity int
VerifyReceiptMaxBlocks uint64
VerifyReceiptSafetyTimeout time.Duration
VerifyReceiptRetryDelay time.Duration
MaxInFlightJobs int
}
// EspressoTransactionSubmitterOption is a function that can be used to
// configure the EspressoTransactionSubmitterConfig.
type EspressoTransactionSubmitterOption func(*EspressoTransactionSubmitterConfig)
// WithContext is an option that can be used to set the Espresso client
// for the EspressoTransactionSubmitterConfig.
func WithContext(ctx context.Context) EspressoTransactionSubmitterOption {
return func(config *EspressoTransactionSubmitterConfig) {
config.Ctx = ctx
}
}
// WithEspressoClient is an option that can be used to set the Espresso client
// for the EspressoTransactionSubmitterConfig.
func WithEspressoClient(client espressoClient.EspressoClient) EspressoTransactionSubmitterOption {
return func(config *EspressoTransactionSubmitterConfig) {
config.EspressoClient = client
}
}
// WithWaitGroup is an option that can be used to set the wait group
// for the EspressoTransactionSubmitterConfig.
func WithWaitGroup(wg *sync.WaitGroup) EspressoTransactionSubmitterOption {
return func(config *EspressoTransactionSubmitterConfig) {
config.Wg = wg
}
}
// WithVerifyReceiptMaxBlocks sets the number of HotShot blocks to wait for a
// submitted transaction to become queryable before re-submitting.
func WithVerifyReceiptMaxBlocks(n uint64) EspressoTransactionSubmitterOption {
return func(config *EspressoTransactionSubmitterConfig) {
config.VerifyReceiptMaxBlocks = n
}
}
// WithVerifyReceiptSafetyTimeout sets the wall-clock backstop for receipt
// verification. If the block height tracker is stale or broken, re-submission
// is triggered after this duration.
func WithVerifyReceiptSafetyTimeout(d time.Duration) EspressoTransactionSubmitterOption {
return func(config *EspressoTransactionSubmitterConfig) {
config.VerifyReceiptSafetyTimeout = d
}
}
// WithVerifyReceiptRetryDelay sets the delay between receipt verification retries.
func WithVerifyReceiptRetryDelay(d time.Duration) EspressoTransactionSubmitterOption {
return func(config *EspressoTransactionSubmitterConfig) {
config.VerifyReceiptRetryDelay = d
}
}
// WithMaxInFlightJobs sets the maximum number of inflight requests to
// have at once. Once at capacity all new submission attempts will
// automatically fail.
func WithMaxInFlightJobs(n int) EspressoTransactionSubmitterOption {
return func(config *EspressoTransactionSubmitterConfig) {
config.MaxInFlightJobs = n
}
}
// NewEspressoTransactionSubmitter creates a new EspressoTransactionSubmitter
// throttle with the given context and espresso client. It will create a new
// transaction submitter with some default options, and apply those options to
// the configuration.
//
// The resulting instance should reflect the given configuration.
// After returning, the caller should call SpawnWorkers to start the workers,
// and Start to start the job scheduling and response handling portions of the
// transaction submitter. After that, the user should be able to submit
// transactions to the submitter via the SubmitTransaction method.
func NewEspressoTransactionSubmitter(options ...EspressoTransactionSubmitterOption) *espressoTransactionSubmitter {
config := EspressoTransactionSubmitterConfig{
Ctx: context.Background(),
Wg: new(sync.WaitGroup),
SubmitJobQueueCapacity: espresso.DefaultMaxInFlightRequestsToEspresso,
SubmitResponseQueueCapacity: 10,
VerifyReceiptJobQueueCapacity: espresso.DefaultMaxInFlightRequestsToEspresso,
VerifyReceiptResponseQueueCapacity: 10,
VerifyReceiptMaxBlocks: espresso.DefaultVerifyReceiptMaxBlocks,
VerifyReceiptSafetyTimeout: espresso.DefaultVerifyReceiptSafetyTimeout,
VerifyReceiptRetryDelay: espresso.DefaultVerifyReceiptRetryDelay,
MaxInFlightJobs: espresso.DefaultMaxInFlightRequestsToEspresso,
}
for _, option := range options {
option(&config)
}
if config.EspressoClient == nil {
panic("Espresso client is required")
}
return &espressoTransactionSubmitter{
ctx: config.Ctx,
wg: config.Wg,
submitJobQueue: make(chan espressoSubmitTransactionJob, config.SubmitJobQueueCapacity),
submitRespQueue: make(chan espressoSubmitTransactionJobResponse, config.SubmitResponseQueueCapacity),
submitWorkerQueue: make(chan chan espressoTransactionJobAttempt),
verifyReceiptJobQueue: make(chan espressoVerifyReceiptJob, config.VerifyReceiptJobQueueCapacity),
verifyReceiptRespQueue: make(chan espressoVerifyReceiptJobResponse, config.VerifyReceiptResponseQueueCapacity),
verifyReceiptWorkerQueue: make(chan chan espressoVerifyReceiptJobAttempt),
espresso: config.EspressoClient,
verifyReceiptMaxBlocks: config.VerifyReceiptMaxBlocks,
verifyReceiptSafetyTimeout: config.VerifyReceiptSafetyTimeout,
verifyReceiptRetryDelay: config.VerifyReceiptRetryDelay,
numInFlightJobs: atomic.Int64{},
numMaxInFlightJobs: config.MaxInFlightJobs,
}
}
// ErrTooManyInFlightRequests is an error that is returned when there are
// too many requests in flight at once right now.
type ErrTooManyInFlightRequests struct {
NumInFlightRequests int
MaxInFlightRequests int
}
// Error implements error
func (e ErrTooManyInFlightRequests) Error() string {
return fmt.Sprintf("too many requests in flight to espresso, in flight requests: %d, maximum allowed: %d", e.NumInFlightRequests, e.MaxInFlightRequests)
}
// ErrSubmitToEspressoChannelFull is an error that is returned when the channel
// to submit a transaction to the espresso job channel is full.
//
// This ultimately means that the channel buffer size of the job channel is
// smaller than the max number of in flight requests allowed.
type ErrSubmitToEspressoChannelFull struct {
Capacity int
Len int
}
// Error implements error
func (e ErrSubmitToEspressoChannelFull) Error() string {
return fmt.Sprintf("submit transaction to espresso job channel is full, len: %d, capacity: %d", e.Len, e.Capacity)
}
// SubmitTransaction will submit a transaction to the Job queue.
//
// NOTE: There is a limit on the maximum number of inflight requests we allow
// at once. If we're over or at capacity, we'll return an error indicating so.
// If we have capacity available, we'll attempt to submit to the channel, and
// if we're unable to, we'll return an error. This will **NOT** block.
func (s *espressoTransactionSubmitter) SubmitTransaction(job *espressoCommon.Transaction) error {
// Check to see if we're over capacity, and if we are, then immediately
// return an error.
if numInFlightRequests, numMaxInFlightRequests := s.numInFlightJobs.Load(), int64(s.numMaxInFlightJobs); numInFlightRequests >= numMaxInFlightRequests {
return ErrTooManyInFlightRequests{
NumInFlightRequests: int(numInFlightRequests),
MaxInFlightRequests: int(numMaxInFlightRequests),
}
}
// Construct the job submission
jobSubmission := espressoSubmitTransactionJob{
transaction: job,
}
select {
default:
return ErrSubmitToEspressoChannelFull{
Len: len(s.submitJobQueue),
Capacity: cap(s.submitJobQueue),
}
case s.submitJobQueue <- jobSubmission:
// increment in flight requests
s.numInFlightJobs.Add(1)
return nil
}
}
// Evaluation result for a job.
type JobEvaluation int
const (
// Continue handling the current job.
Handle JobEvaluation = iota
// Retry the submission.
RetrySubmission
// Retry the verification.
RetryVerification
// Skip the current job and proceed to the next one.
Skip
)
// Evaluate the submission job.
//
// # Returns
//
// * If there is no error: Handle.
//
// * If there is a permanent issue that won't be fixed by a retry: Skip.
//
// * Otherwise: RetrySubmission.
func evaluateSubmission(jobResp espressoSubmitTransactionJobResponse) JobEvaluation {
err := jobResp.err
// If there's no error, continue handling the submission.
if err == nil {
return Handle
}
if errors.Is(err, espressoClient.ErrPermanent) {
return Skip
}
if !errors.Is(err, espressoClient.ErrEphemeral) {
// Log the warning for a potentially missed error handling, but still retry it.
log.Warn("error not explicitly marked as retryable or not", "err", err)
}
// Otherwise, retry the submission.
return RetrySubmission
}
// handleTransactionSubmitJobResponse is a function that is meant to be run in a
// goroutine.
//
// It handles the responses from the submit transaction jobs. It will
// determine if the transaction was successfully submitted to Espresso, and
// if not, it will retry the transaction. If the transaction was successfully
// submitted, it will then submit a job to the verify receipt job queue to
// verify the receipt of the transaction.
func (s *espressoTransactionSubmitter) handleTransactionSubmitJobResponse() {
ticker := time.NewTicker(10 * time.Minute)
defer ticker.Stop()
for {
var jobResp espressoSubmitTransactionJobResponse
var ok bool
select {
case <-s.ctx.Done():
return
case <-ticker.C:
log.Debug("Espresso transaction submitter queue status",
"submitJobQueue", len(s.submitJobQueue),
"submitRespQueue", len(s.submitRespQueue),
"verifyReceiptJobQueue", len(s.verifyReceiptJobQueue),
"verifyReceiptRespQueue", len(s.verifyReceiptRespQueue))
continue
case jobResp, ok = <-s.submitRespQueue:
if !ok {
// Our channel is closed, and we are done
return
}
}
switch evaluation := evaluateSubmission(jobResp); evaluation {
case Skip:
s.numInFlightJobs.Add(-1)
continue
case RetrySubmission:
s.submitJobQueue <- jobResp.job
continue
}
verifyJob := espressoVerifyReceiptJob{
startTime: time.Now(),
transaction: jobResp.job,
hash: jobResp.hash,
}
select {
case <-s.ctx.Done():
return
// Move to verifying the receipt
case s.verifyReceiptJobQueue <- verifyJob:
}
}
}
// Default values for receipt verification tuning are defined as exported
// constants in the espresso package (espresso.DefaultVerifyReceipt*) so that
// the CLI flag defaults and this batcher logic share a single source of truth.
// evaluateVerification evaluates the verification job response.
//
// # Returns
//
// * If there is no error: Handle.
//
// * If there is a permanent issue that won't be fixed by a retry: Skip.
//
// * If enough HotShot blocks have passed since verification started: RetrySubmission.
//
// * If the wall-clock safety timeout is exceeded: RetrySubmission.
//
// * Otherwise: RetryVerification.
func (s *espressoTransactionSubmitter) evaluateVerification(jobResp espressoVerifyReceiptJobResponse) JobEvaluation {
err := jobResp.err
// If there's no error, continue handling the verification.
if err == nil {
return Handle
}
if errors.Is(err, espressoClient.ErrPermanent) {
return Skip
}
if !errors.Is(err, espressoClient.ErrEphemeral) {
// Log the warning for a potentially missed error handling, but still retry it.
log.Warn("error not explicitly marked as retryable or not", "err", err)
}
// Block-count-based timeout: re-submit if enough HotShot blocks have
// passed since verification started. The startHeight guard handles the
// edge case where the height tracker hasn't fetched its first value yet.
if jobResp.job.startHeight > 0 && jobResp.currentHeight >= jobResp.job.startHeight+s.verifyReceiptMaxBlocks {
log.Info("Verification timed out by block count, re-submitting",
"startHeight", jobResp.job.startHeight,
"currentHeight", jobResp.currentHeight,
"maxBlocks", s.verifyReceiptMaxBlocks)
return RetrySubmission
}
// Wall-clock safety backstop in case the block height tracker is stale
// or broken (e.g., query service returning old data).
if elapsed := time.Since(jobResp.job.startTime); elapsed > s.verifyReceiptSafetyTimeout {
log.Warn("Verification timed out by safety timeout, re-submitting",
"elapsed", elapsed,
"safetyTimeout", s.verifyReceiptSafetyTimeout)
return RetrySubmission
}
// Otherwise, retry the verification.
return RetryVerification
}
// handleVerifyReceiptJobResponse is a function that is meant to be run in a
// goroutine.
//
// This function handles responses from the verify receipt job queue. It will
// check the results for any errors, and if there are any errors that are
// applicable to retry, it will requeue the job for another attempt.
// If the the job is successful, no further processing is needed and it is
// considered complete.
// If the job has taken too long to verify, then it will re-submit the job
// back to the submit transaction queue for another attempt.
//
// NOTE: This function currently will loop forever if the transaction is
// never going to be available.
func (s *espressoTransactionSubmitter) handleVerifyReceiptJobResponse() {
for {
var jobResp espressoVerifyReceiptJobResponse
var ok bool
select {
case <-s.ctx.Done():
return
case jobResp, ok = <-s.verifyReceiptRespQueue:
if !ok {
// Our channel is closed, and we are done
return
}
}
switch evaluation := s.evaluateVerification(jobResp); evaluation {
case Skip:
// decrement in flight jobs on skip, since we're done with this job
s.numInFlightJobs.Add(-1)
continue
case RetrySubmission:
s.submitJobQueue <- jobResp.job.transaction
continue
case RetryVerification:
s.verifyReceiptJobQueue <- jobResp.job
continue
}
s.numInFlightJobs.Add(-1)
// We're done with this job and transaction, we have successfully
// confirmed that the transaction was submitted to Espresso
commitment := jobResp.job.transaction.transaction.Commit()
hash, _ := tagged_base64.New("TX", commitment[:])
log.Info(logmodule.TransactionConfirmedOnEspresso, "hash", hash.String())
}
}
// scheduleSubmitTransactionJobs is a function that is meant to be run in a
// goroutine.
//
// It handles the scheduling of submit transaction jobs so that the submit
// transaction workers can process them.
func (s *espressoTransactionSubmitter) scheduleSubmitTransactionJobs() {
for {
var ok bool
// Get a worker from the worker queue
var worker chan espressoTransactionJobAttempt
select {
case <-s.ctx.Done():
return
case worker, ok = <-s.submitWorkerQueue:
if !ok {
// Our channel is closed, and we are done
return
}
}
// Get a job from the job queue
var job espressoSubmitTransactionJob
select {
case <-s.ctx.Done():
return
case job, ok = <-s.submitJobQueue:
if !ok {
// Our channel is closed, and we are done
return
}
}
// Submit the job to the worker
select {
case <-s.ctx.Done():
return
case worker <- espressoTransactionJobAttempt{job: job, resp: s.submitRespQueue}:
}
}
}
// scheduleVerifyReceiptJobs is a function that is meant to be run in a
// goroutine.
//
// It handles the scheduling of verify receipt jobs so that the verify receipt
// workers can process them.
func (s *espressoTransactionSubmitter) scheduleVerifyReceiptsJobs() {
for {
var ok bool
// Get a worker from the worker queue
var worker chan espressoVerifyReceiptJobAttempt
select {
case <-s.ctx.Done():
return
case worker, ok = <-s.verifyReceiptWorkerQueue:
if !ok {
// Our channel is closed, and we are done
return
}
}
// Get a job from the job queue
var job espressoVerifyReceiptJob
select {
case <-s.ctx.Done():
return
case job, ok = <-s.verifyReceiptJobQueue:
if !ok {
// Our channel is closed, and we are done
return
}
}
// Submit the job to the worker
select {
case <-s.ctx.Done():
return
case worker <- espressoVerifyReceiptJobAttempt{job: job, resp: s.verifyReceiptRespQueue}:
}
}
}
// espressoSubmitTransactionWorker is a function that is meant to be run as a
// goroutine. It will create a channel for it's job queue, and submit those to
// the worker queue in order to wait for work. It will then take that job and
// attempt to submit the transaction contained within to espresso using the
// given espresso client. It will submit the response back to the channel
// contained within the job attempt it received.
//
// It's lifetime is governed by the context passed to it, and it will stop
// processing when that context is cancelled.
//
// NOTE: If the context is cancelled after a job has been received, but before
// it is able to submit the transaction, or report about it's result, the job
// may be lost.
func espressoSubmitTransactionWorker(
ctx context.Context,
wg *sync.WaitGroup,
cli espressoClient.EspressoClient,
workerQueue chan<- chan espressoTransactionJobAttempt,
) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer wg.Done()
ch := make(chan espressoTransactionJobAttempt)
defer close(ch)
for {
var ok bool
select {
case <-ctx.Done():
return
// Queue our job queue, asking for work
case workerQueue <- ch:
}
// Wait for a job to run
var jobAttempt espressoTransactionJobAttempt
select {
case <-ctx.Done():
return
case jobAttempt, ok = <-ch:
if !ok {
// Our channel is closed, and we are done
return
}
}
// Submit the transaction to Espresso
hash, err := cli.SubmitTransaction(ctx, *jobAttempt.job.transaction)
if err == nil {
log.Info(logmodule.SubmittedTransactionToEspresso, "hash", hash)
}
jobAttempt.job.attempts++
resp := espressoSubmitTransactionJobResponse{
job: jobAttempt.job,
hash: hash,
err: err,
}
select {
case <-ctx.Done():
return
// Send the response back via the channel in the job attempt struct
case jobAttempt.resp <- resp:
}
}
}
// espressoVerifyTransactionWorker is a function that is meant to be run as a
// goroutine. It will create a channel for it's job queue, and submit those to
// the worker queue in order to wait for work. It will then take that job and
// attempt to verify the transaction contained within to espresso using the
// given espresso client. It will submit the response back to the channel
// contained within the job attempt it received.
func espressoVerifyTransactionWorker(
ctx context.Context,
wg *sync.WaitGroup,
cli espressoClient.EspressoClient,
workerQueue chan<- chan espressoVerifyReceiptJobAttempt,
latestHeight *atomic.Uint64,
retryDelay time.Duration,
) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer wg.Done()
ch := make(chan espressoVerifyReceiptJobAttempt)
defer close(ch)
for {
var ok bool
select {
case <-ctx.Done():
return
// Queue our job queue, asking for work
case workerQueue <- ch:
}
// Wait for a job to run
var jobAttempt espressoVerifyReceiptJobAttempt
select {
case <-ctx.Done():
return
case jobAttempt, ok = <-ch:
if !ok {
// Our channel is closed, and we are done
return
}
}
// On the first attempt, snapshot the current block height so we
// can measure how many blocks pass during verification.
if jobAttempt.job.attempts == 0 {
jobAttempt.job.startHeight = latestHeight.Load()
}
if jobAttempt.job.attempts > 0 {
// We have already attempted this job, so we will wait a bit
// NOTE: this prevents this worker from being able to process
// other jobs while we wait for this delay.
time.Sleep(retryDelay)
}
_, err := cli.FetchTransactionByHash(ctx, jobAttempt.job.hash)
jobAttempt.job.attempts++
resp := espressoVerifyReceiptJobResponse{
job: jobAttempt.job,
err: err,
currentHeight: latestHeight.Load(),
}
select {
case <-ctx.Done():
return
case jobAttempt.resp <- resp:
}
}
}
// SpawnWorkers spawns the given number of workers to process the
// submit transaction jobs and verify receipt jobs.
func (s *espressoTransactionSubmitter) SpawnWorkers(numSubmitTransactionWorkers, numVerifyReceiptWorkers int) {
workersCtx := s.ctx
for i := 0; i < numSubmitTransactionWorkers; i++ {
s.wg.Add(1)
go espressoSubmitTransactionWorker(workersCtx, s.wg, s.espresso, s.submitWorkerQueue)
}
for i := 0; i < numVerifyReceiptWorkers; i++ {
s.wg.Add(1)
go espressoVerifyTransactionWorker(workersCtx, s.wg, s.espresso, s.verifyReceiptWorkerQueue, &s.latestBlockHeight, s.verifyReceiptRetryDelay)
}
}
// trackBlockHeight periodically polls FetchLatestBlockHeight and stores
// the result in s.latestBlockHeight for verify jobs to compare against.
// This avoids redundant height queries from individual verify workers.
func (s *espressoTransactionSubmitter) trackBlockHeight() {
for {
height, err := s.espresso.FetchLatestBlockHeight(s.ctx)
if err == nil {
s.latestBlockHeight.Store(height)
} else if s.ctx.Err() == nil {
log.Debug("failed to fetch latest block height for verification tracking", "err", err)
}
// Wait for the next interval or until context is done.
select {
case <-time.After(s.verifyReceiptRetryDelay):
case <-s.ctx.Done():
return
}
}
}
func (s *espressoTransactionSubmitter) Start() {
// Block height tracker for verify receipt timeout
go s.trackBlockHeight()
// Submit Transaction Jobs
go s.scheduleSubmitTransactionJobs()
go s.handleTransactionSubmitJobResponse()
// Verify Receipt Jobs
go s.scheduleVerifyReceiptsJobs()
go s.handleVerifyReceiptJobResponse()
}
// Converts a block to an EspressoBatch and starts a goroutine that publishes it to Espresso
// Returns error only if batch conversion fails, otherwise it is infallible, as the goroutine
// will retry publishing until successful.
func (l *BatchSubmitter) queueBlockToEspresso(ctx context.Context, block *types.Block) error {
espressoBatch, err := derive.BlockToEspressoBatch(l.RollupConfig, block)
if err != nil {
l.Log.Warn(logmodule.FailedToDeriveBatchFromBlock, "err", err)
return fmt.Errorf("failed to derive batch from block: %w", err)
}
transaction, err := espressoBatch.ToEspressoTransaction(ctx, l.RollupConfig.L2ChainID.Uint64(), l.Espresso.ChainSigner)
if err != nil {
l.Log.Warn("Failed to create Espresso transaction from a batch", "err", err)
return fmt.Errorf("failed to create Espresso transaction from a batch: %w", err)
}
commitment := transaction.Commit()
hash, _ := tagged_base64.New("TX", commitment[:])
l.Log.Info("Created Espresso transaction from batch", "hash", hash, "batchNr", espressoBatch.BatchHeader.Number.Uint64())
if err := l.espressoSubmitter.SubmitTransaction(transaction); err != nil {
return fmt.Errorf("failed to submit job to espresso: %w", err)
}
return nil
}
func (l *BatchSubmitter) espressoSyncAndRefresh(ctx context.Context, newSyncStatus *eth.SyncStatus) {
err := l.EspressoStreamer().Refresh(ctx, newSyncStatus.FinalizedL1, newSyncStatus.SafeL2.Number, newSyncStatus.FinalizedL2.L1Origin)
if err != nil {
l.degradedLog.Warn(l.Log, "espressoStreamerRefreshErr", "Failed to refresh Espresso streamer", "err", err)
} else {
l.degradedLog.Clear(l.Log, "espressoStreamerRefreshErr", "Espresso streamer refresh recovered")
}
l.channelMgrMutex.Lock()
defer l.channelMgrMutex.Unlock()
syncActions, outOfSync := computeSyncActions(*newSyncStatus, l.prevCurrentL1, l.channelMgr.blocks, l.channelMgr.channelQueue, l.Log)
if outOfSync {
l.degradedLog.Warn(l.Log, "sequencerOutOfSync", "Sequencer is out of sync, retrying next tick.")
return
}
l.degradedLog.Clear(l.Log, "sequencerOutOfSync", "Sequencer back in sync")
l.prevCurrentL1 = newSyncStatus.CurrentL1
if syncActions.clearState != nil {
l.channelMgr.Clear(*syncActions.clearState)
l.EspressoStreamer().Reset()
} else {
l.channelMgr.PruneSafeBlocks(syncActions.blocksToPrune)
l.channelMgr.PruneChannels(syncActions.channelsToPrune)
}
}
// skipStreamerToTargetBlockHeight will consume batches from the
// `EspressoStreamer` until we reach the target block height, or run out
// of batches to consume.
//
// NOTE: this is **NOT** guaranteed to ensure that the next `Batch` will
// be the expected height, it's just a best effort.
func (l *BatchSubmitter) skipStreamerToTargetBlockHeight(ctx context.Context, targetHeight uint64) {
streamer := l.EspressoStreamer()
batch := streamer.Peek(ctx)
for batch != nil && batch.Number() < targetHeight {
// Consume the Batch
streamer.Next(ctx)
batch = streamer.Peek(ctx)
}
}
// isHashNoptSet is a helper function to check if a hash is the zero
// value (not set).
func isHashEmpty(hash common.Hash) bool {
return hash == (common.Hash{})
}
// peekNextBatch returns the next batch from the streamer, performing a fork check
// against an expected parent hash.
//
// The expected parent is tip when tip is set. When tip is zero (channel manager was
// just cleared), we fall back to safeL2.Hash if the batch is at exactly safeL2+1 —
// the one position where we can set tip to the known safe head. Otherwise we accept the batch as-is.
func (l *BatchSubmitter) peekNextBatch(ctx context.Context, syncStatus *eth.SyncStatus) *derive.EspressoBatch {
l.channelMgrMutex.Lock()
var tipBlock SizedBlock
if len(l.channelMgr.blocks) > 0 {
tipBlock = l.channelMgr.blocks[len(l.channelMgr.blocks)-1]
}
l.channelMgrMutex.Unlock()
targetBlock := syncStatus.SafeL2.Number + 1
tipHash := syncStatus.SafeL2.Hash
if tipBlock != (SizedBlock{}) && tipBlock.Block != nil {
targetBlock = tipBlock.NumberU64() + 1
tipHash = tipBlock.Hash()
} else if batch := l.EspressoStreamer().Peek(ctx); batch != nil && batch.Number() == targetBlock {
// Log indicating that we utilized the SafeL2 Hash as the next
// Streamer entry matched our expected Safe L2, and we didn't
// have any tip information from the Channel Manager.
l.Log.Debug(
"setting tip to safe l2 hash",
"batchNr", batch.Number(),
"batchParent", batch.Header().ParentHash.Hex(),
"tip", tipHash,
)
}
l.skipStreamerToTargetBlockHeight(ctx, targetBlock)
batch := l.EspressoStreamer().Peek(ctx)
if batch == nil {
return nil
}
if isHashEmpty(tipHash) {
l.Log.Warn(
"tip is not set, taking available batch",
"blockParentHash", (*batch).Header().ParentHash.Hex(),
"blockHash", (*batch).Header().Hash().Hex(),
)
return batch
}
if batch.Header().ParentHash != tipHash {
l.Log.Warn(
"head batch fork mismatch, seeking to proper head",
"batchNr", (*batch).Number(),
"batchParent", (*batch).Header().ParentHash,
"tip", tipHash,
)
l.EspressoStreamer().SetProperHead(tipHash)
return nil
}
return batch
}
// Periodically refreshes the sync status and polls Espresso streamer for new batches
func (l *BatchSubmitter) espressoBatchLoadingLoop(ctx context.Context, wg *sync.WaitGroup, publishSignal chan pubInfo) {
l.Log.Info("Starting EspressoBatchLoadingLoop", "polling interval", l.Config.Espresso.PollInterval)
defer wg.Done()
ticker := time.NewTicker(l.Config.Espresso.PollInterval)
defer ticker.Stop()
defer close(publishSignal)
for {
select {
case <-ticker.C:
newSyncStatus, err := l.getSyncStatus(ctx)
if err != nil {
l.degradedLog.Warn(l.Log, "syncStatusErr/espressoBatchLoading", "failed to refresh sync status", "err", err)
continue
}
l.degradedLog.Clear(l.Log, "syncStatusErr/espressoBatchLoading", "sync status fetch recovered")
l.espressoSyncAndRefresh(ctx, newSyncStatus)
err = l.EspressoStreamer().Update(ctx)
var batch *derive.EspressoBatch
for {
batch = l.peekNextBatch(ctx, newSyncStatus)
if batch == nil {
break
}
// This should happen ONLY if the batch is malformed. ToBlock has to guarantee no
// transient errors.
block, err := batch.ToBlock(l.RollupConfig)
if err != nil {
l.Log.Error("failed to convert singular batch to block", "err", err)
l.EspressoStreamer().Next(ctx)
continue
}
l.Log.Info(
logmodule.ReceivedBlockFromEspresso,
"blockNr", block.NumberU64(),
"blockHash", block.Hash(),
"parentHash", block.ParentHash(),
)
l.channelMgrMutex.Lock()
err = l.channelMgr.AddL2Block(block)
l.channelMgrMutex.Unlock()
if err != nil {
l.Log.Error("failed to add L2 block to channel manager", "err", err)
l.clearState(ctx)
l.EspressoStreamer().Reset()