@aztec/prover-node 0.0.1-commit.2ed92850 → 0.0.1-commit.3100065

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +511 -0
  2. package/dest/actions/download-epoch-proving-job.js +1 -1
  3. package/dest/actions/rerun-epoch-proving-job.d.ts +5 -4
  4. package/dest/actions/rerun-epoch-proving-job.d.ts.map +1 -1
  5. package/dest/actions/rerun-epoch-proving-job.js +102 -22
  6. package/dest/actions/upload-epoch-proof-failure.d.ts +2 -2
  7. package/dest/actions/upload-epoch-proof-failure.d.ts.map +1 -1
  8. package/dest/bin/run-failed-epoch.js +6 -5
  9. package/dest/checkpoint-store.d.ts +88 -0
  10. package/dest/checkpoint-store.d.ts.map +1 -0
  11. package/dest/checkpoint-store.js +169 -0
  12. package/dest/config.d.ts +5 -8
  13. package/dest/config.d.ts.map +1 -1
  14. package/dest/config.js +17 -20
  15. package/dest/factory.d.ts +19 -13
  16. package/dest/factory.d.ts.map +1 -1
  17. package/dest/factory.js +40 -65
  18. package/dest/index.d.ts +2 -1
  19. package/dest/index.d.ts.map +1 -1
  20. package/dest/index.js +1 -0
  21. package/dest/job/checkpoint-prover.d.ts +124 -0
  22. package/dest/job/checkpoint-prover.d.ts.map +1 -0
  23. package/dest/job/checkpoint-prover.js +330 -0
  24. package/dest/job/epoch-session.d.ts +146 -0
  25. package/dest/job/epoch-session.d.ts.map +1 -0
  26. package/dest/job/{epoch-proving-job.js → epoch-session.js} +277 -295
  27. package/dest/job/top-tree-job.d.ts +82 -0
  28. package/dest/job/top-tree-job.d.ts.map +1 -0
  29. package/dest/job/top-tree-job.js +152 -0
  30. package/dest/metrics.d.ts +40 -3
  31. package/dest/metrics.d.ts.map +1 -1
  32. package/dest/metrics.js +112 -7
  33. package/dest/monitors/epoch-monitor.d.ts +1 -1
  34. package/dest/monitors/epoch-monitor.d.ts.map +1 -1
  35. package/dest/monitors/epoch-monitor.js +11 -9
  36. package/dest/proof-publishing-service.d.ts +161 -0
  37. package/dest/proof-publishing-service.d.ts.map +1 -0
  38. package/dest/proof-publishing-service.js +335 -0
  39. package/dest/prover-node-publisher.d.ts +25 -17
  40. package/dest/prover-node-publisher.d.ts.map +1 -1
  41. package/dest/prover-node-publisher.js +201 -63
  42. package/dest/prover-node.d.ts +118 -70
  43. package/dest/prover-node.d.ts.map +1 -1
  44. package/dest/prover-node.js +487 -226
  45. package/dest/prover-publisher-factory.d.ts +7 -5
  46. package/dest/prover-publisher-factory.d.ts.map +1 -1
  47. package/dest/prover-publisher-factory.js +7 -5
  48. package/dest/session-manager.d.ts +158 -0
  49. package/dest/session-manager.d.ts.map +1 -0
  50. package/dest/session-manager.js +482 -0
  51. package/dest/test/index.d.ts +7 -6
  52. package/dest/test/index.d.ts.map +1 -1
  53. package/package.json +23 -22
  54. package/src/actions/download-epoch-proving-job.ts +1 -1
  55. package/src/actions/rerun-epoch-proving-job.ts +115 -28
  56. package/src/actions/upload-epoch-proof-failure.ts +1 -1
  57. package/src/bin/run-failed-epoch.ts +5 -3
  58. package/src/checkpoint-store.ts +194 -0
  59. package/src/config.ts +25 -32
  60. package/src/factory.ts +68 -111
  61. package/src/index.ts +1 -0
  62. package/src/job/checkpoint-prover.ts +442 -0
  63. package/src/job/epoch-session.ts +436 -0
  64. package/src/job/top-tree-job.ts +227 -0
  65. package/src/metrics.ts +129 -12
  66. package/src/monitors/epoch-monitor.ts +5 -6
  67. package/src/proof-publishing-service.ts +427 -0
  68. package/src/prover-node-publisher.ts +236 -80
  69. package/src/prover-node.ts +562 -254
  70. package/src/prover-publisher-factory.ts +16 -10
  71. package/src/session-manager.ts +583 -0
  72. package/src/test/index.ts +6 -6
  73. package/dest/job/epoch-proving-job.d.ts +0 -62
  74. package/dest/job/epoch-proving-job.d.ts.map +0 -1
  75. package/src/job/epoch-proving-job.ts +0 -430
@@ -370,28 +370,40 @@ function applyDecs2203RFactory() {
370
370
  function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
371
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
372
  }
373
- var _dec, _dec1, _initProto;
374
- import { BlockNumber } from '@aztec/foundation/branded-types';
375
- import { assertRequired, compact, pick, sum } from '@aztec/foundation/collection';
373
+ var _initProto;
374
+ import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
375
+ import { assertRequired, compact, pick } from '@aztec/foundation/collection';
376
376
  import { memoize } from '@aztec/foundation/decorators';
377
377
  import { createLogger } from '@aztec/foundation/log';
378
- import { DateProvider } from '@aztec/foundation/timer';
378
+ import { RunningPromise } from '@aztec/foundation/running-promise';
379
+ import { DateProvider, executeTimeout } from '@aztec/foundation/timer';
380
+ import { getLastSiblingPath } from '@aztec/prover-client/helpers';
381
+ import { ChonkCache } from '@aztec/prover-client/orchestrator';
379
382
  import { PublicProcessorFactory } from '@aztec/simulator/server';
380
- import { getProofSubmissionDeadlineTimestamp } from '@aztec/stdlib/epoch-helpers';
383
+ import { EventDrivenL2BlockStream, L2TipsMemoryStore } from '@aztec/stdlib/block';
384
+ import { getEpochAtSlot, getProofSubmissionDeadlineEpoch } from '@aztec/stdlib/epoch-helpers';
381
385
  import { EpochProvingJobTerminalState, tryStop } from '@aztec/stdlib/interfaces/server';
382
- import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
386
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
387
+ import { getTelemetryClient } from '@aztec/telemetry-client';
383
388
  import { uploadEpochProofFailure } from './actions/upload-epoch-proof-failure.js';
384
- import { EpochProvingJob } from './job/epoch-proving-job.js';
389
+ import { CheckpointStore } from './checkpoint-store.js';
385
390
  import { ProverNodeJobMetrics, ProverNodeRewardsMetrics } from './metrics.js';
386
- _dec = trackSpan('ProverNode.createProvingJob', (epochNumber)=>({
387
- [Attributes.EPOCH_NUMBER]: epochNumber
388
- })), _dec1 = trackSpan('ProverNode.gatherEpochData', (epochNumber)=>({
389
- [Attributes.EPOCH_NUMBER]: epochNumber
390
- }));
391
+ import { ProofPublishingService } from './proof-publishing-service.js';
392
+ import { SessionManager } from './session-manager.js';
391
393
  /**
392
- * An Aztec Prover Node is a standalone process that monitors the unfinalized chain on L1 for unproven epochs,
393
- * fetches their txs from the p2p network or external nodes, re-executes their public functions, creates a rollup
394
- * proof for the epoch, and submits it to L1.
394
+ * Grace period for the proof-publishing service to settle during shutdown. The service waits for
395
+ * any in-flight L1 proof-submission tx to finish; that tx can take a long time to mine, so we cap
396
+ * the wait rather than letting `stop()` hang indefinitely.
397
+ */ const PUBLISHING_SERVICE_STOP_TIMEOUT_MS = 30_000;
398
+ /**
399
+ * An Aztec Prover Node is a standalone process that monitors the chain for new checkpoints,
400
+ * starts proving them optimistically as they arrive, and submits epoch proofs to L1 once
401
+ * complete.
402
+ *
403
+ * The class is intentionally thin: it owns the long-lived collections (`CheckpointStore`,
404
+ * `ChonkCache`, `SessionManager`), the L2BlockStream, and a periodic ticker that nudges the
405
+ * manager to pick up newly-complete epochs. Every session lifecycle decision is delegated to
406
+ * the `SessionManager`. Each chain event is translated here into a single method call on it.
395
407
  */ export class ProverNode {
396
408
  prover;
397
409
  publisherFactory;
@@ -400,38 +412,45 @@ _dec = trackSpan('ProverNode.createProvingJob', (epochNumber)=>({
400
412
  contractDataSource;
401
413
  worldState;
402
414
  p2pClient;
403
- epochsMonitor;
404
415
  rollupContract;
405
416
  l1Metrics;
406
417
  telemetryClient;
418
+ delayer;
419
+ dateProvider;
407
420
  static{
408
421
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
409
- [
410
- _dec,
411
- 2,
412
- "createProvingJob"
413
- ],
414
422
  [
415
423
  memoize,
416
424
  2,
417
425
  "getL1Constants"
418
- ],
419
- [
420
- _dec1,
421
- 2,
422
- "gatherEpochData"
423
426
  ]
424
427
  ], []));
425
428
  }
426
429
  log;
427
- dateProvider;
428
- jobs;
430
+ checkpointStore;
431
+ chonkCache;
432
+ sessionManager;
429
433
  config;
430
434
  jobMetrics;
431
435
  rewardsMetrics;
436
+ /** In-memory store for the L2BlockStream's local data provider. */ tipsStore;
437
+ /** Block stream for checkpoint and reorg detection. */ blockStream;
438
+ /**
439
+ * Highest epoch whose proof-submission window has passed. Monotonic high-water mark.
440
+ * Seeded from the last fully-proven epoch at start(); advanced on every block-stream
441
+ * event by comparing the archiver's latest synced L2 slot against each epoch's
442
+ * submission deadline. Protected so tests can verify the start() seeding.
443
+ */ lastExpiredEpoch;
444
+ /**
445
+ * Highest checkpoint number whose proving-side handling has completed (or that was legitimately skipped).
446
+ * The catch-up loop walks from here to each `chain-checkpointed` tip event. Seeded at start() from the last
447
+ * checkpoint of the last fully-proven epoch (or 0), so a restart reprocesses the partially-proven epoch rather
448
+ * than trusting a checkpointed tip that may sit ahead of unproven checkpoints. Clamped down on a prune.
449
+ */ lastProcessedCheckpoint;
450
+ /** Periodic tick that runs the epoch-expiry sweep during idle periods when no block-stream events arrive. */ expiryTicker;
432
451
  tracer;
433
- publisher;
434
- constructor(prover, publisherFactory, l2BlockSource, l1ToL2MessageSource, contractDataSource, worldState, p2pClient, epochsMonitor, rollupContract, l1Metrics, config = {}, telemetryClient = getTelemetryClient()){
452
+ publishingService;
453
+ constructor(prover, publisherFactory, l2BlockSource, l1ToL2MessageSource, contractDataSource, worldState, p2pClient, rollupContract, l1Metrics, config = {}, telemetryClient = getTelemetryClient(), delayer, dateProvider = new DateProvider()){
435
454
  this.prover = prover;
436
455
  this.publisherFactory = publisherFactory;
437
456
  this.l2BlockSource = l2BlockSource;
@@ -439,17 +458,17 @@ _dec = trackSpan('ProverNode.createProvingJob', (epochNumber)=>({
439
458
  this.contractDataSource = contractDataSource;
440
459
  this.worldState = worldState;
441
460
  this.p2pClient = p2pClient;
442
- this.epochsMonitor = epochsMonitor;
443
461
  this.rollupContract = rollupContract;
444
462
  this.l1Metrics = l1Metrics;
445
463
  this.telemetryClient = telemetryClient;
464
+ this.delayer = delayer;
465
+ this.dateProvider = dateProvider;
446
466
  this.log = (_initProto(this), createLogger('prover-node'));
447
- this.dateProvider = new DateProvider();
448
- this.jobs = new Map();
467
+ this.lastProcessedCheckpoint = CheckpointNumber.ZERO;
449
468
  this.config = {
450
469
  proverNodePollingIntervalMs: 1_000,
451
470
  proverNodeMaxPendingJobs: 100,
452
- proverNodeMaxParallelBlocksPerEpoch: 32,
471
+ proverNodeMaxParallelBlocksPerEpoch: 0,
453
472
  txGatheringIntervalMs: 1_000,
454
473
  txGatheringBatchSize: 10,
455
474
  txGatheringMaxParallelRequestsPerNode: 100,
@@ -463,6 +482,20 @@ _dec = trackSpan('ProverNode.createProvingJob', (epochNumber)=>({
463
482
  this.tracer = telemetryClient.getTracer('ProverNode');
464
483
  this.jobMetrics = new ProverNodeJobMetrics(meter, telemetryClient.getTracer('EpochProvingJob'));
465
484
  this.rewardsMetrics = new ProverNodeRewardsMetrics(meter, this.prover.getProverId(), rollupContract);
485
+ this.tipsStore = new L2TipsMemoryStore(this.l2BlockSource.getGenesisBlockHash());
486
+ this.chonkCache = new ChonkCache(this.log.getBindings());
487
+ this.checkpointStore = new CheckpointStore(this.l2BlockSource, {
488
+ proverFactory: this.prover,
489
+ chonkCache: this.chonkCache,
490
+ publicProcessorFactory: new PublicProcessorFactory(this.contractDataSource, this.dateProvider, this.telemetryClient, this.log.getBindings()),
491
+ dbProvider: this.worldState,
492
+ txProvider: this.p2pClient.getTxProvider(),
493
+ dateProvider: this.dateProvider,
494
+ proverId: this.prover.getProverId(),
495
+ metrics: this.jobMetrics,
496
+ txGatheringTimeoutMs: this.config.txGatheringTimeoutMs,
497
+ deadline: undefined
498
+ }, this.log.getBindings());
466
499
  }
467
500
  getProverId() {
468
501
  return this.prover.getProverId();
@@ -470,230 +503,462 @@ _dec = trackSpan('ProverNode.createProvingJob', (epochNumber)=>({
470
503
  getP2P() {
471
504
  return this.p2pClient;
472
505
  }
506
+ /** Test-only: the shared L1 tx delayer, if enabled. */ getDelayer() {
507
+ return this.delayer;
508
+ }
509
+ /** Observability summary for the ProverNodeApi. */ getJobs() {
510
+ return Promise.resolve(this.sessionManager?.getJobs() ?? []);
511
+ }
512
+ /** Tests inspect this when validating reconcile behaviour. */ getCheckpointStore() {
513
+ return this.checkpointStore;
514
+ }
515
+ /** Tests inspect this to verify chonk-cache release semantics. */ getChonkCache() {
516
+ return this.chonkCache;
517
+ }
518
+ /** Tests inspect this when looking up live sessions. */ getSessionManager() {
519
+ if (!this.sessionManager) {
520
+ throw new Error('SessionManager not yet constructed — start() must be called first.');
521
+ }
522
+ return this.sessionManager;
523
+ }
524
+ /** Returns the underlying prover instance. */ getProver() {
525
+ return this.prover;
526
+ }
527
+ // ---------------- L2BlockStream handler ----------------
528
+ async handleBlockStreamEvent(event) {
529
+ switch(event.type){
530
+ case 'chain-checkpointed':
531
+ await this.processCheckpointJump(event.checkpoint.number);
532
+ break;
533
+ case 'chain-pruned':
534
+ await this.handlePruneEvent(event.block);
535
+ break;
536
+ case 'chain-proven':
537
+ this.publishingService?.onChainProven(BlockNumber(event.block.number));
538
+ break;
539
+ // The proposed tip drives only the tips store's walk-back history (recorded below); the prover-node
540
+ // tracks checkpoints, not proposed blocks. `blocks-added` is never emitted in tips-only mode, and
541
+ // `chain-finalized` carries nothing the prover-node acts on.
542
+ case 'chain-proposed':
543
+ case 'chain-finalized':
544
+ case 'blocks-added':
545
+ break;
546
+ default:
547
+ {
548
+ const _ = event;
549
+ break;
550
+ }
551
+ }
552
+ // Expiry is driven by the archiver's latest synced L2 slot
553
+ await this.checkEpochExpiry();
554
+ // Advance the local tips store only after the proving-side handling has succeeded. Any
555
+ // failure above propagates to the L2BlockStream (which logs and stops this poll pass) and
556
+ // skips this update, so the event is re-emitted on the next poll rather than skipped (A-1041).
557
+ await this.tipsStore.handleBlockStreamEvent(event);
558
+ }
473
559
  /**
474
- * Handles an epoch being completed by starting a proof for it if there are no active jobs for it.
475
- * @param epochNumber - The epoch number that was just completed.
476
- * @returns false if there is an error, true otherwise
477
- */ async handleEpochReadyToProve(epochNumber) {
478
- try {
479
- this.log.debug(`Running jobs as ${epochNumber} is ready to prove`, {
480
- jobs: Array.from(this.jobs.values()).map((job)=>`${job.getEpochNumber()}:${job.getId()}`)
560
+ * Walks every checkpoint between the local cursor and the newly-reported checkpointed tip, registering
561
+ * each one that belongs to an epoch that can still be proven. The block stream now delivers a single thin
562
+ * `chain-checkpointed` tip event per pass rather than one fat event per checkpoint, so this drives the
563
+ * catch-up itself: light metadata first (`getCheckpointsData`) to decide relevance per epoch, then a heavy
564
+ * `getCheckpoints` fetch only for checkpoints in provable epochs.
565
+ *
566
+ * The cursor advances one checkpoint at a time and only after that checkpoint's proving-side handling has
567
+ * fully succeeded, preserving the A-1041 at-least-once semantics: a mid-jump failure leaves the cursor
568
+ * behind so the next pass retries from the first checkpoint that did not complete.
569
+ */ async processCheckpointJump(targetCheckpoint) {
570
+ if (targetCheckpoint <= this.lastProcessedCheckpoint) {
571
+ return;
572
+ }
573
+ const l1Constants = await this.getL1Constants();
574
+ // Cap the catch-up at the `(proofSubmissionEpochs + 1) * epochDuration` most recent checkpoints.
575
+ // When the cursor is much further behind (e.g. resyncing after a long time offline), fetching the whole gap could
576
+ // load thousands of checkpoints we cannot act on: anything older than the last two epochs is already past
577
+ // its proof-submission window, so we skip it and jump the cursor forward to the start of the capped range.
578
+ const maxCheckpoints = (l1Constants.proofSubmissionEpochs + 1) * l1Constants.epochDuration;
579
+ let from = CheckpointNumber(this.lastProcessedCheckpoint + 1);
580
+ if (Number(targetCheckpoint - from) + 1 > maxCheckpoints) {
581
+ const cappedFrom = CheckpointNumber(targetCheckpoint - maxCheckpoints + 1);
582
+ this.log.warn(`Skipping unprovable checkpoints during catch-up; the prover node is far behind`, {
583
+ from,
584
+ cappedFrom,
585
+ targetCheckpoint,
586
+ maxCheckpoints
481
587
  });
482
- const activeJobs = await this.getActiveJobsForEpoch(epochNumber);
483
- if (activeJobs.length > 0) {
484
- this.log.warn(`Not starting proof for ${epochNumber} since there are active jobs for the epoch`, {
485
- activeJobs: activeJobs.map((job)=>job.uuid)
486
- });
487
- return true;
588
+ // Advance the cursor past the skipped checkpoints so they are never retried.
589
+ this.lastProcessedCheckpoint = CheckpointNumber(cappedFrom - 1);
590
+ from = cappedFrom;
591
+ }
592
+ const limit = Number(targetCheckpoint - from) + 1;
593
+ const metadatas = await this.l2BlockSource.getCheckpointsData({
594
+ from,
595
+ limit
596
+ });
597
+ // Per-epoch relevance is cached so a multi-checkpoint epoch resolves it once. Skipping is whole-epoch
598
+ // only: the SessionManager requires an epoch's checkpoints fully covered before it opens a session, so we
599
+ // never drop an individual checkpoint inside an epoch we will prove.
600
+ const epochSkippable = new Map();
601
+ for (const metadata of metadatas){
602
+ const epochNumber = getEpochAtSlot(metadata.header.slotNumber, l1Constants);
603
+ let skippable = epochSkippable.get(epochNumber);
604
+ if (skippable === undefined) {
605
+ skippable = await this.isEpochFullyProven(epochNumber, l1Constants) || await this.isEpochPastProofSubmissionWindow(epochNumber, l1Constants);
606
+ epochSkippable.set(epochNumber, skippable);
488
607
  }
489
- await this.startProof(epochNumber);
490
- return true;
491
- } catch (err) {
492
- if (err instanceof EmptyEpochError) {
493
- this.log.info(`Not starting proof for ${epochNumber} since no blocks were found`);
608
+ if (skippable) {
609
+ this.log.debug(`Skipping checkpoint ${metadata.checkpointNumber} for unprovable epoch ${epochNumber}`);
494
610
  } else {
495
- this.log.error(`Error handling epoch completed`, err);
611
+ await this.registerCheckpoint(metadata.checkpointNumber, epochNumber);
496
612
  }
613
+ // Advance only after the checkpoint's handling succeeded (or it was legitimately skipped). registerCheckpoint
614
+ // throws on failure, which leaves the cursor here for the next pass to retry (A-1041).
615
+ this.lastProcessedCheckpoint = metadata.checkpointNumber;
616
+ }
617
+ }
618
+ /** Heavy-fetch a single checkpoint, register it with the store, and notify the session manager. */ async registerCheckpoint(checkpointNumber, epochNumber) {
619
+ const published = await this.l2BlockSource.getCheckpoint({
620
+ number: checkpointNumber
621
+ });
622
+ if (!published) {
623
+ throw new Error(`Checkpoint ${checkpointNumber} not found in block source during catch-up`);
624
+ }
625
+ const checkpoint = published.checkpoint;
626
+ this.log.info(`New checkpoint ${checkpoint.number} for epoch ${epochNumber}`, {
627
+ checkpointNumber: checkpoint.number,
628
+ epochNumber,
629
+ slotNumber: checkpoint.header.slotNumber
630
+ });
631
+ const registerData = await this.collectRegisterData(checkpoint, published.attestations);
632
+ await this.checkpointStore.addOrUpdate(checkpoint, registerData);
633
+ await this.sessionManager?.onCheckpointAdded(epochNumber);
634
+ // Tips-only mode delivers no blocks, so record one witness per checkpointed block: a reorg into the checkpoint's
635
+ // range then prunes at the true divergence instead of the nearest sparse tip anchor.
636
+ await this.tipsStore.recordBlockHashes(await Promise.all(checkpoint.blocks.map(async (block)=>({
637
+ number: block.number,
638
+ hash: (await block.header.hash()).toString()
639
+ }))));
640
+ }
641
+ /**
642
+ * Gathers register-time data for a checkpoint: previous block header, L1-to-L2 messages,
643
+ * and the archive sibling path.
644
+ */ async collectRegisterData(checkpoint, attestations) {
645
+ const previousBlockNumber = BlockNumber(checkpoint.blocks[0].number - 1);
646
+ const previousBlockHeader = await this.gatherPreviousBlockHeader(previousBlockNumber);
647
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpoint.number);
648
+ const lastBlock = checkpoint.blocks.at(-1);
649
+ const lastBlockHash = await lastBlock.header.hash();
650
+ await this.worldState.syncImmediate(lastBlock.number, lastBlockHash);
651
+ const previousArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, this.worldState.getSnapshot(previousBlockNumber));
652
+ return {
653
+ attestations,
654
+ previousBlockHeader,
655
+ l1ToL2Messages,
656
+ previousArchiveSiblingPath
657
+ };
658
+ }
659
+ /**
660
+ * Marks every prover orphaned by the prune as pruned, clamps the catch-up cursor below the prune target's
661
+ * checkpoint, and notifies the session manager. Keyed off the prune target block (the highest surviving block)
662
+ * rather than the source's checkpointed tip, which can sit above the target after a re-checkpoint and would leave
663
+ * orphaned provers canonical. Throws (rather than warning) if the cursor floor cannot be resolved, so the pass
664
+ * fails and the prune is retried next iteration.
665
+ */ async handlePruneEvent(prunedToBlock) {
666
+ this.log.warn(`Chain pruned to block ${prunedToBlock.number}`, {
667
+ prunedToBlock
668
+ });
669
+ // Resolve the cursor floor BEFORE removing provers: cancelAndRemoveAboveBlock returns only the provers it removed,
670
+ // so a throw after removing would leave a retry pass with nothing to act on. Resolving first means a throw leaves
671
+ // everything untouched and the next pass retries the whole handler (the tips cursor only advances on success).
672
+ let cursorFloor;
673
+ if (prunedToBlock.number === 0) {
674
+ cursorFloor = CheckpointNumber.ZERO;
675
+ } else {
676
+ const targetData = await this.l2BlockSource.getBlockData({
677
+ number: prunedToBlock.number
678
+ });
679
+ if (targetData === undefined) {
680
+ throw new Error(`No block data found for prune target block ${prunedToBlock.number}; cannot clamp checkpoint cursor`);
681
+ }
682
+ // Clamp to `cpAtTarget - 1`: a mid-checkpoint target leaves that checkpoint partially orphaned and it must be
683
+ // reprocessed. Over-clamping merely re-registers a checkpoint (at-least-once by design — A-1041); under-clamping
684
+ // would permanently skip a rebuilt same-number checkpoint.
685
+ cursorFloor = CheckpointNumber(Math.max(0, Number(targetData.checkpointNumber) - 1));
686
+ }
687
+ const affected = this.checkpointStore.cancelAndRemoveAboveBlock(prunedToBlock.number);
688
+ if (this.lastProcessedCheckpoint > cursorFloor) {
689
+ this.lastProcessedCheckpoint = cursorFloor;
690
+ }
691
+ if (affected.length === 0) {
692
+ return;
693
+ }
694
+ const l1Constants = await this.getL1Constants();
695
+ const affectedEpochs = Array.from(new Set(affected.map((p)=>Number(getEpochAtSlot(p.slotNumber, l1Constants))))).map((n)=>EpochNumber(n));
696
+ // The session manager cancels every affected session, which in turn calls
697
+ // publishingService.withdraw(uuid) for each candidate; no separate notification to the
698
+ // publishing service is needed.
699
+ await this.sessionManager?.onPrune(affectedEpochs);
700
+ }
701
+ /**
702
+ * Returns true once the chain has advanced past the given epoch's proof-submission window.
703
+ * Used to ignore checkpoints whose epoch can no longer be proven in time — chiefly while the
704
+ * archiver replays old blocks after a restart. Compares the archiver's latest synced L2 slot
705
+ * against the epoch's submission-deadline epoch; conservatively returns false if the slot can't
706
+ * be read yet.
707
+ */ async isEpochPastProofSubmissionWindow(epochNumber, l1Constants) {
708
+ const latestSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
709
+ if (latestSlot === undefined) {
497
710
  return false;
498
711
  }
712
+ const latestEpoch = getEpochAtSlot(latestSlot, l1Constants);
713
+ return latestEpoch >= getProofSubmissionDeadlineEpoch(epochNumber, l1Constants);
714
+ }
715
+ /**
716
+ * Compares the archiver's latest synced L2 slot against `lastExpiredEpoch` and, for each
717
+ * newly-expired epoch, releases the chonk-cache entries for its blocks and reaps any
718
+ * CheckpointProvers in the store. An epoch E is expired once the chain reaches the start
719
+ * of epoch `E + proofSubmissionEpochs + 1`. Silently no-ops if nothing has expired since
720
+ * the last check or the archiver's slot can't be read.
721
+ */ async checkEpochExpiry() {
722
+ const latestSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
723
+ if (latestSlot === undefined) {
724
+ return;
725
+ }
726
+ const l1Constants = await this.getL1Constants();
727
+ const latestEpoch = getEpochAtSlot(latestSlot, l1Constants);
728
+ const offset = l1Constants.proofSubmissionEpochs + 1;
729
+ if (latestEpoch < offset) {
730
+ return;
731
+ }
732
+ const newlyExpiredUpTo = EpochNumber(latestEpoch - offset);
733
+ const from = this.lastExpiredEpoch === undefined ? EpochNumber(0) : EpochNumber(this.lastExpiredEpoch + 1);
734
+ if (newlyExpiredUpTo < from) {
735
+ return;
736
+ }
737
+ for(let e = from; e <= newlyExpiredUpTo; e = EpochNumber(e + 1)){
738
+ await this.expireEpoch(e);
739
+ }
740
+ this.lastExpiredEpoch = newlyExpiredUpTo;
741
+ }
742
+ /**
743
+ * Releases chonk-cache entries for every block in the supplied epoch (best-effort) and
744
+ * reaps every CheckpointProver in the store whose epoch number matches.
745
+ */ async expireEpoch(epoch) {
746
+ try {
747
+ const blocks = await this.l2BlockSource.getBlocks({
748
+ epoch,
749
+ onlyCheckpointed: true
750
+ });
751
+ if (blocks.length > 0) {
752
+ this.chonkCache.releaseForBlocks(blocks);
753
+ }
754
+ } catch (err) {
755
+ this.log.warn(`Could not release chonk-cache entries for expired epoch ${epoch}`, err);
756
+ }
757
+ this.checkpointStore.reapExpired(epoch);
499
758
  }
759
+ // ---------------- public API ----------------
500
760
  /**
501
- * Starts the prover node so it periodically checks for unproven epochs in the unfinalized chain from L1 and
502
- * starts proving jobs for them.
503
- */ async start() {
504
- this.epochsMonitor.start(this);
761
+ * Schedules proving for the given epoch and returns the job id without waiting for completion.
762
+ */ async startProof(epochNumber) {
763
+ if (!this.sessionManager) {
764
+ throw new Error('ProverNode not started');
765
+ }
766
+ return await this.sessionManager.startProof(epochNumber);
767
+ }
768
+ // ---------------- Service lifecycle ----------------
769
+ async start() {
770
+ await this.checkpointStore.start();
505
771
  await this.publisherFactory.start();
506
- this.publisher = await this.publisherFactory.create();
772
+ this.publishingService = new ProofPublishingService({
773
+ publisherFactory: this.publisherFactory,
774
+ l2BlockSource: this.l2BlockSource,
775
+ dateProvider: this.dateProvider,
776
+ config: {
777
+ skipSubmitProof: !!this.config.proverNodeDisableProofPublish
778
+ },
779
+ bindings: this.log.getBindings()
780
+ });
781
+ this.sessionManager = this.createSessionManager(this.publishingService);
782
+ // SessionManager owns its own periodic tick; start it here so it begins picking up
783
+ // epochs that become complete by time (no fresh checkpoint event) and advances once
784
+ // the previous epoch is proven on L1.
785
+ this.sessionManager.start();
786
+ // Now that the store + manager exist, arm the live-state observable gauges.
787
+ this.jobMetrics.observeState(this.checkpointStore, this.sessionManager);
788
+ const { lastFullyProvenEpoch } = await this.resolveLastFullyProvenEpoch();
789
+ this.lastExpiredEpoch = lastFullyProvenEpoch;
790
+ this.lastProcessedCheckpoint = await this.computeStartingCheckpoint(lastFullyProvenEpoch);
791
+ this.blockStream = new EventDrivenL2BlockStream(this.l2BlockSource, this.tipsStore, this, this.log, {
792
+ pollIntervalMS: this.config.proverNodePollingIntervalMs,
793
+ tipsOnly: true
794
+ });
795
+ this.blockStream.start();
796
+ // With thin once-per-pass tip events, the expiry sweep no longer fires once per checkpoint; drive it
797
+ // from a periodic tick so epochs still expire during idle/no-event periods.
798
+ this.expiryTicker = new RunningPromise(()=>this.checkEpochExpiry(), this.log, this.config.proverNodePollingIntervalMs);
799
+ this.expiryTicker.start();
507
800
  await this.rewardsMetrics.start();
508
801
  this.l1Metrics.start();
509
802
  this.log.info(`Started Prover Node with prover id ${this.prover.getProverId().toString()}`, this.config);
510
803
  }
511
- /**
512
- * Stops the prover node and all its dependencies.
513
- */ async stop() {
804
+ async stop() {
514
805
  this.log.info('Stopping ProverNode');
515
- await this.epochsMonitor.stop();
806
+ this.jobMetrics.stopObservingState();
807
+ await this.blockStream?.stop();
808
+ await this.expiryTicker?.stop();
809
+ if (this.sessionManager) {
810
+ await this.sessionManager.stop();
811
+ }
812
+ if (this.publishingService) {
813
+ // Bound the wait: the publishing service blocks until any in-flight L1 proof-submission tx
814
+ // settles, which can outlast a reasonable shutdown window. On timeout we log and move on —
815
+ // the tx may still mine, but shutdown must not hang on it.
816
+ const publishingService = this.publishingService;
817
+ await executeTimeout(()=>publishingService.stop(), PUBLISHING_SERVICE_STOP_TIMEOUT_MS, 'prover-node publishing-service stop').catch((err)=>this.log.warn(`Timed out stopping proof publishing service`, err));
818
+ }
819
+ await this.checkpointStore.stop();
820
+ this.chonkCache.stop();
516
821
  await this.prover.stop();
517
- await tryStop(this.p2pClient);
518
- await tryStop(this.l2BlockSource);
519
822
  await tryStop(this.publisherFactory);
520
- this.publisher?.interrupt();
521
- await Promise.all(Array.from(this.jobs.values()).map((job)=>job.stop()));
522
- await this.worldState.stop();
523
823
  this.rewardsMetrics.stop();
524
824
  this.l1Metrics.stop();
525
825
  await this.telemetryClient.stop();
526
826
  this.log.info('Stopped ProverNode');
527
827
  }
528
- /** Returns world state status. */ async getWorldStateSyncStatus() {
529
- const { syncSummary } = await this.worldState.status();
530
- return syncSummary;
531
- }
532
- /** Returns archiver status. */ getL2Tips() {
533
- return this.l2BlockSource.getL2Tips();
534
- }
535
828
  /**
536
- * Starts a proving process and returns immediately.
537
- */ async startProof(epochNumber) {
538
- const job = await this.createProvingJob(epochNumber, {
539
- skipEpochCheck: true
829
+ * Constructs the session manager. Extracted so subclasses (test harness) can swap
830
+ * the implementation. Wired to `tryUploadSessionFailure` so failed sessions get
831
+ * their proving data uploaded.
832
+ */ createSessionManager(publishingService) {
833
+ return new SessionManager({
834
+ checkpointStore: this.checkpointStore,
835
+ l2BlockSource: this.l2BlockSource,
836
+ proverFactory: this.prover,
837
+ proverId: this.prover.getProverId(),
838
+ publishingService,
839
+ metrics: this.jobMetrics,
840
+ dateProvider: this.dateProvider,
841
+ config: {
842
+ maxPendingJobs: this.config.proverNodeMaxPendingJobs,
843
+ tickIntervalMs: this.config.proverNodePollingIntervalMs,
844
+ finalizationDelayMs: this.config.proverNodeEpochProvingDelayMs
845
+ },
846
+ onSessionFailed: async (session)=>{
847
+ await this.tryUploadSessionFailure(session);
848
+ },
849
+ bindings: this.log.getBindings()
540
850
  });
541
- void this.runJob(job);
542
851
  }
543
- async runJob(job) {
544
- const epochNumber = job.getEpochNumber();
545
- const ctx = {
546
- id: job.getId(),
547
- epochNumber,
548
- state: undefined
549
- };
550
- try {
551
- await job.run();
552
- const state = job.getState();
553
- ctx.state = state;
554
- if (state === 'reorg') {
555
- this.log.warn(`Running new job for epoch ${epochNumber} due to reorg`, ctx);
556
- await this.createProvingJob(epochNumber);
557
- } else if (state === 'failed') {
558
- this.log.error(`Job for ${epochNumber} exited with state ${state}`, ctx);
559
- await this.tryUploadEpochFailure(job);
560
- } else {
561
- this.log.verbose(`Job for ${epochNumber} exited with state ${state}`, ctx);
562
- }
563
- } catch (err) {
564
- this.log.error(`Error proving epoch ${epochNumber}`, err, ctx);
565
- } finally{
566
- this.jobs.delete(job.getId());
852
+ /**
853
+ * Installs session hooks for the e2e harness to interpose around top-tree proving
854
+ * (gate, override, or observe it) without monkey-patching the orchestrator factory.
855
+ * Applies to every session constructed after this call.
856
+ */ setSessionHooks(hooks) {
857
+ if (!this.sessionManager) {
858
+ throw new Error('ProverNode not started; call start() before setting session hooks.');
567
859
  }
860
+ this.sessionManager.setSessionHooks(hooks);
568
861
  }
569
- async tryUploadEpochFailure(job) {
570
- if (this.config.proverNodeFailedEpochStore) {
571
- return await uploadEpochProofFailure(this.config.proverNodeFailedEpochStore, job.getId(), job.getProvingData(), this.l2BlockSource, this.worldState, assertRequired(pick(this.config, 'l1ChainId', 'rollupVersion', 'dataDirectory')), this.log);
862
+ /** Uploads failure snapshots when sessions exit with `failed`. Exposed as a method so tests can spy on it. */ async tryUploadSessionFailure(session) {
863
+ if (!this.config.proverNodeFailedEpochStore) {
864
+ return undefined;
572
865
  }
866
+ const data = SessionManager.buildSessionProvingData(session);
867
+ return await uploadEpochProofFailure(this.config.proverNodeFailedEpochStore, session.getId(), data, this.l2BlockSource, this.worldState, assertRequired(pick(this.config, 'l1ChainId', 'rollupVersion', 'dataDirectory')), this.log);
573
868
  }
574
- /**
575
- * Returns the prover instance.
576
- */ getProver() {
577
- return this.prover;
578
- }
579
- /**
580
- * Returns an array of jobs being processed.
581
- */ getJobs() {
582
- return Promise.resolve(Array.from(this.jobs.entries()).map(([uuid, job])=>({
583
- uuid,
584
- status: job.getState(),
585
- epochNumber: job.getEpochNumber()
586
- })));
587
- }
588
- async getActiveJobsForEpoch(epochNumber) {
589
- const jobs = await this.getJobs();
590
- return jobs.filter((job)=>job.epochNumber === epochNumber && !EpochProvingJobTerminalState.includes(job.status));
591
- }
592
- checkMaximumPendingJobs() {
593
- const { proverNodeMaxPendingJobs: maxPendingJobs } = this.config;
594
- if (maxPendingJobs > 0 && this.jobs.size >= maxPendingJobs) {
595
- throw new Error(`Maximum pending proving jobs ${maxPendingJobs} reached. Cannot create new job.`);
596
- }
597
- }
598
- async createProvingJob(epochNumber, opts = {}) {
599
- this.checkMaximumPendingJobs();
600
- this.publisher = await this.publisherFactory.create();
601
- // Gather all data for this epoch
602
- const epochData = await this.gatherEpochData(epochNumber);
603
- const fromCheckpoint = epochData.checkpoints[0].number;
604
- const toCheckpoint = epochData.checkpoints.at(-1).number;
605
- const fromBlock = epochData.checkpoints[0].blocks[0].number;
606
- const toBlock = epochData.checkpoints.at(-1).blocks.at(-1).number;
607
- this.log.verbose(`Creating proving job for epoch ${epochNumber} for checkpoint range ${fromCheckpoint} to ${toCheckpoint} and block range ${fromBlock} to ${toBlock}`);
608
- // Fast forward world state to right before the target block and get a fork
609
- await this.worldState.syncImmediate(toBlock);
610
- // Create a processor factory
611
- const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, this.dateProvider, this.telemetryClient);
612
- // Set deadline for this job to run. It will abort if it takes too long.
613
- const deadlineTs = getProofSubmissionDeadlineTimestamp(epochNumber, await this.getL1Constants());
614
- const deadline = new Date(Number(deadlineTs) * 1000);
615
- const job = this.doCreateEpochProvingJob(epochData, deadline, publicProcessorFactory, this.publisher, opts);
616
- this.jobs.set(job.getId(), job);
617
- return job;
618
- }
869
+ // ---------------- helpers ----------------
619
870
  getL1Constants() {
620
871
  return this.l2BlockSource.getL1Constants();
621
872
  }
622
- async gatherEpochData(epochNumber) {
623
- const checkpoints = await this.gatherCheckpoints(epochNumber);
624
- const txArray = await this.gatherTxs(epochNumber, checkpoints);
625
- const txs = new Map(txArray.map((tx)=>[
626
- tx.getTxHash().toString(),
627
- tx
628
- ]));
629
- const l1ToL2Messages = await this.gatherMessages(epochNumber, checkpoints);
630
- const [firstBlock] = checkpoints[0].blocks;
631
- const previousBlockHeader = await this.gatherPreviousBlockHeader(epochNumber, firstBlock.number - 1);
632
- const [lastPublishedCheckpoint] = await this.l2BlockSource.getCheckpoints(checkpoints.at(-1).number, 1);
633
- const attestations = lastPublishedCheckpoint?.attestations ?? [];
873
+ /**
874
+ * Returns true if every block in the given epoch is proven on L1. An epoch is only
875
+ * fully proven when its *last* block is proven. Protected for direct unit-test access.
876
+ */ async isEpochFullyProven(epochNumber, l1Constants) {
877
+ const provenBlockNumber = await this.l2BlockSource.getBlockNumber({
878
+ tag: 'proven'
879
+ });
880
+ if (!provenBlockNumber || provenBlockNumber <= 0) {
881
+ return false;
882
+ }
883
+ const provenHeader = (await this.l2BlockSource.getBlockData({
884
+ number: BlockNumber(provenBlockNumber)
885
+ }))?.header;
886
+ if (!provenHeader) {
887
+ return false;
888
+ }
889
+ const provenEpoch = getEpochAtSlot(provenHeader.getSlot(), l1Constants);
890
+ if (epochNumber < provenEpoch) {
891
+ return true;
892
+ }
893
+ if (epochNumber > provenEpoch) {
894
+ return false;
895
+ }
896
+ return this.isProvenBlockLastOfItsEpoch(BlockNumber(provenBlockNumber), provenEpoch, l1Constants);
897
+ }
898
+ /** Protected for direct unit-test access. */ async isProvenBlockLastOfItsEpoch(provenBlockNumber, provenEpoch, l1Constants) {
899
+ const nextHeader = (await this.l2BlockSource.getBlockData({
900
+ number: BlockNumber(provenBlockNumber + 1)
901
+ }))?.header;
902
+ if (nextHeader) {
903
+ return getEpochAtSlot(nextHeader.getSlot(), l1Constants) > provenEpoch;
904
+ }
905
+ return this.l2BlockSource.isEpochComplete(provenEpoch);
906
+ }
907
+ /**
908
+ * Resolves the last fully-proven epoch from L1 proven state, used to seed the catch-up cursor (via
909
+ * `computeStartingCheckpoint`) and `lastExpiredEpoch`. The fully-proven epoch is `provenEpoch` when the
910
+ * proven tip is the last block of its epoch, otherwise `provenEpoch - 1`, or `undefined` if no block is
911
+ * proven yet (so a restart reprocesses the partially-proven epoch rather than trusting a stale tip).
912
+ */ async resolveLastFullyProvenEpoch() {
913
+ const provenBlockNumber = await this.l2BlockSource.getBlockNumber({
914
+ tag: 'proven'
915
+ });
916
+ if (!provenBlockNumber || provenBlockNumber <= 0) {
917
+ return {
918
+ lastFullyProvenEpoch: undefined
919
+ };
920
+ }
921
+ const l1Constants = await this.getL1Constants();
922
+ const provenHeader = (await this.l2BlockSource.getBlockData({
923
+ number: BlockNumber(provenBlockNumber)
924
+ }))?.header;
925
+ if (!provenHeader) {
926
+ return {
927
+ lastFullyProvenEpoch: undefined
928
+ };
929
+ }
930
+ const provenEpoch = getEpochAtSlot(provenHeader.getSlot(), l1Constants);
931
+ if (await this.isProvenBlockLastOfItsEpoch(BlockNumber(provenBlockNumber), provenEpoch, l1Constants)) {
932
+ return {
933
+ lastFullyProvenEpoch: provenEpoch
934
+ };
935
+ }
936
+ const lastFullyProvenEpoch = provenEpoch > 0 ? EpochNumber(provenEpoch - 1) : undefined;
634
937
  return {
635
- checkpoints,
636
- txs,
637
- l1ToL2Messages,
638
- epochNumber,
639
- previousBlockHeader,
640
- attestations
938
+ lastFullyProvenEpoch
641
939
  };
642
940
  }
643
- async gatherCheckpoints(epochNumber) {
644
- const checkpoints = await this.l2BlockSource.getCheckpointsForEpoch(epochNumber);
645
- if (checkpoints.length === 0) {
646
- throw new EmptyEpochError(epochNumber);
647
- }
648
- return checkpoints;
649
- }
650
- async gatherTxs(epochNumber, checkpoints) {
651
- const deadline = new Date(this.dateProvider.now() + this.config.txGatheringTimeoutMs);
652
- const txProvider = this.p2pClient.getTxProvider();
653
- const blocks = checkpoints.flatMap((checkpoint)=>checkpoint.blocks);
654
- const txsByBlock = await Promise.all(blocks.map((block)=>txProvider.getTxsForBlock(block, {
655
- deadline
656
- })));
657
- const txs = txsByBlock.map(({ txs })=>txs).flat();
658
- const missingTxs = txsByBlock.map(({ missingTxs })=>missingTxs).flat();
659
- if (missingTxs.length === 0) {
660
- this.log.verbose(`Gathered all ${txs.length} txs for epoch ${epochNumber}`, {
661
- epochNumber
662
- });
663
- return txs;
941
+ /**
942
+ * Resolves the catch-up cursor seed: the last checkpoint of the last fully-proven epoch, or 0 if none. Seeding
943
+ * from a checkpoint (rather than a checkpointed tip) guarantees a restart reprocesses every checkpoint of the
944
+ * partially-proven epoch, since the checkpointed tip can sit ahead of the last fully-proven checkpoint.
945
+ */ async computeStartingCheckpoint(lastFullyProvenEpoch) {
946
+ if (lastFullyProvenEpoch === undefined) {
947
+ return CheckpointNumber.ZERO;
664
948
  }
665
- throw new Error(`Txs not found for epoch ${epochNumber}: ${missingTxs.map((hash)=>hash.toString()).join(', ')}`);
666
- }
667
- async gatherMessages(epochNumber, checkpoints) {
668
- const messages = await Promise.all(checkpoints.map((c)=>this.l1ToL2MessageSource.getL1ToL2Messages(c.number)));
669
- const messageCount = sum(messages.map((m)=>m.length));
670
- this.log.verbose(`Gathered all ${messageCount} messages for epoch ${epochNumber}`, {
671
- epochNumber
672
- });
673
- const messagesByCheckpoint = {};
674
- for(let i = 0; i < checkpoints.length; i++){
675
- messagesByCheckpoint[checkpoints[i].number] = messages[i];
676
- }
677
- return messagesByCheckpoint;
678
- }
679
- async gatherPreviousBlockHeader(epochNumber, previousBlockNumber) {
680
- const header = await (previousBlockNumber === 0 ? this.worldState.getCommitted().getInitialHeader() : this.l2BlockSource.getBlockHeader(BlockNumber(previousBlockNumber)));
681
- if (!header) {
682
- throw new Error(`Previous block header ${previousBlockNumber} not found for proving epoch ${epochNumber}`);
683
- }
684
- this.log.verbose(`Gathered previous block header ${header.getBlockNumber()} for epoch ${epochNumber}`);
685
- return header;
686
- }
687
- /** Extracted for testing purposes. */ doCreateEpochProvingJob(data, deadline, publicProcessorFactory, publisher, opts = {}) {
688
- const { proverNodeMaxParallelBlocksPerEpoch: parallelBlockLimit, proverNodeDisableProofPublish } = this.config;
689
- return new EpochProvingJob(data, this.worldState, this.prover.createEpochProver(), publicProcessorFactory, publisher, this.l2BlockSource, this.jobMetrics, deadline, {
690
- parallelBlockLimit,
691
- skipSubmitProof: proverNodeDisableProofPublish,
692
- ...opts
949
+ const checkpoints = await this.l2BlockSource.getCheckpointsData({
950
+ epoch: lastFullyProvenEpoch
693
951
  });
952
+ return checkpoints.at(-1)?.checkpointNumber ?? CheckpointNumber.ZERO;
694
953
  }
695
- /** Extracted for testing purposes. */ async triggerMonitors() {
696
- await this.epochsMonitor.work();
954
+ async gatherPreviousBlockHeader(previousBlockNumber) {
955
+ const data = await this.l2BlockSource.getBlockData({
956
+ number: BlockNumber(previousBlockNumber)
957
+ });
958
+ if (!data?.header) {
959
+ throw new Error(`Previous block header ${previousBlockNumber} not found`);
960
+ }
961
+ return data.header;
697
962
  }
698
963
  validateConfig() {
699
964
  if (this.config.proverNodeFailedEpochStore && (!this.config.dataDirectory || !this.config.l1ChainId || this.config.rollupVersion === undefined)) {
@@ -702,9 +967,5 @@ _dec = trackSpan('ProverNode.createProvingJob', (epochNumber)=>({
702
967
  }
703
968
  }
704
969
  }
705
- class EmptyEpochError extends Error {
706
- constructor(epochNumber){
707
- super(`No blocks found for epoch ${epochNumber}`);
708
- this.name = 'EmptyEpochError';
709
- }
710
- }
970
+ // Re-export so handlers can compare states externally.
971
+ export { EpochProvingJobTerminalState };