@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
@@ -1,89 +1,135 @@
1
1
  import type { Archiver } from '@aztec/archiver';
2
2
  import type { RollupContract } from '@aztec/ethereum/contracts';
3
+ import type { Delayer } from '@aztec/ethereum/l1-tx-utils';
3
4
  import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
4
- import { assertRequired, compact, pick, sum } from '@aztec/foundation/collection';
5
- import type { Fr } from '@aztec/foundation/curves/bn254';
5
+ import { assertRequired, compact, pick } from '@aztec/foundation/collection';
6
6
  import { memoize } from '@aztec/foundation/decorators';
7
7
  import { createLogger } from '@aztec/foundation/log';
8
- import { DateProvider } from '@aztec/foundation/timer';
9
- import type { DataStoreConfig } from '@aztec/kv-store/config';
10
- import type { P2PClient } from '@aztec/p2p';
8
+ import { RunningPromise } from '@aztec/foundation/running-promise';
9
+ import { DateProvider, executeTimeout } from '@aztec/foundation/timer';
10
+ import type { EpochProverFactory } from '@aztec/prover-client';
11
+ import { getLastSiblingPath } from '@aztec/prover-client/helpers';
12
+ import { ChonkCache } from '@aztec/prover-client/orchestrator';
11
13
  import { PublicProcessorFactory } from '@aztec/simulator/server';
12
- import type { L2BlockSource } from '@aztec/stdlib/block';
13
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
14
+ import {
15
+ EventDrivenL2BlockStream,
16
+ type L2BlockId,
17
+ type L2BlockSource,
18
+ type L2BlockStreamEvent,
19
+ type L2BlockStreamEventHandler,
20
+ L2TipsMemoryStore,
21
+ } from '@aztec/stdlib/block';
22
+ import type { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
14
23
  import type { ChainConfig } from '@aztec/stdlib/config';
15
24
  import type { ContractDataSource } from '@aztec/stdlib/contract';
16
- import { getProofSubmissionDeadlineTimestamp } from '@aztec/stdlib/epoch-helpers';
25
+ import { type L1RollupConstants, getEpochAtSlot, getProofSubmissionDeadlineEpoch } from '@aztec/stdlib/epoch-helpers';
17
26
  import {
18
27
  type EpochProverManager,
28
+ type EpochProvingJobState,
19
29
  EpochProvingJobTerminalState,
30
+ type ITxProvider,
20
31
  type ProverNodeApi,
21
32
  type Service,
22
- type WorldStateSyncStatus,
23
33
  type WorldStateSynchronizer,
24
34
  tryStop,
25
35
  } from '@aztec/stdlib/interfaces/server';
36
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
26
37
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
27
- import type { P2PClientType } from '@aztec/stdlib/p2p';
28
- import type { Tx } from '@aztec/stdlib/tx';
38
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
29
39
  import {
30
- Attributes,
31
40
  L1Metrics,
32
41
  type TelemetryClient,
33
42
  type Traceable,
34
43
  type Tracer,
35
44
  getTelemetryClient,
36
- trackSpan,
37
45
  } from '@aztec/telemetry-client';
38
46
 
39
47
  import { uploadEpochProofFailure } from './actions/upload-epoch-proof-failure.js';
48
+ import { CheckpointStore, type RegisterCheckpointData } from './checkpoint-store.js';
40
49
  import type { SpecificProverNodeConfig } from './config.js';
41
- import type { EpochProvingJobData } from './job/epoch-proving-job-data.js';
42
- import { EpochProvingJob, type EpochProvingJobState } from './job/epoch-proving-job.js';
50
+ import type { EpochSession, EpochSessionHooks } from './job/epoch-session.js';
43
51
  import { ProverNodeJobMetrics, ProverNodeRewardsMetrics } from './metrics.js';
44
- import type { EpochMonitor, EpochMonitorHandler } from './monitors/epoch-monitor.js';
45
- import type { ProverNodePublisher } from './prover-node-publisher.js';
52
+ import { ProofPublishingService } from './proof-publishing-service.js';
46
53
  import type { ProverPublisherFactory } from './prover-publisher-factory.js';
54
+ import { SessionManager } from './session-manager.js';
47
55
 
48
56
  type ProverNodeOptions = SpecificProverNodeConfig & Partial<DataStoreOptions>;
49
57
  type DataStoreOptions = Pick<DataStoreConfig, 'dataDirectory'> & Pick<ChainConfig, 'l1ChainId' | 'rollupVersion'>;
50
58
 
51
59
  /**
52
- * An Aztec Prover Node is a standalone process that monitors the unfinalized chain on L1 for unproven epochs,
53
- * fetches their txs from the p2p network or external nodes, re-executes their public functions, creates a rollup
54
- * proof for the epoch, and submits it to L1.
60
+ * Grace period for the proof-publishing service to settle during shutdown. The service waits for
61
+ * any in-flight L1 proof-submission tx to finish; that tx can take a long time to mine, so we cap
62
+ * the wait rather than letting `stop()` hang indefinitely.
55
63
  */
56
- export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable {
64
+ const PUBLISHING_SERVICE_STOP_TIMEOUT_MS = 30_000;
65
+
66
+ /**
67
+ * An Aztec Prover Node is a standalone process that monitors the chain for new checkpoints,
68
+ * starts proving them optimistically as they arrive, and submits epoch proofs to L1 once
69
+ * complete.
70
+ *
71
+ * The class is intentionally thin: it owns the long-lived collections (`CheckpointStore`,
72
+ * `ChonkCache`, `SessionManager`), the L2BlockStream, and a periodic ticker that nudges the
73
+ * manager to pick up newly-complete epochs. Every session lifecycle decision is delegated to
74
+ * the `SessionManager`. Each chain event is translated here into a single method call on it.
75
+ */
76
+ export class ProverNode implements L2BlockStreamEventHandler, ProverNodeApi, Traceable {
57
77
  private log = createLogger('prover-node');
58
- private dateProvider = new DateProvider();
59
78
 
60
- private jobs: Map<string, EpochProvingJob> = new Map();
61
- private config: ProverNodeOptions;
62
- private jobMetrics: ProverNodeJobMetrics;
63
- private rewardsMetrics: ProverNodeRewardsMetrics;
79
+ protected readonly checkpointStore: CheckpointStore;
80
+ protected readonly chonkCache: ChonkCache;
81
+ protected sessionManager: SessionManager | undefined;
82
+
83
+ private readonly config: ProverNodeOptions;
84
+ private readonly jobMetrics: ProverNodeJobMetrics;
85
+ private readonly rewardsMetrics: ProverNodeRewardsMetrics;
86
+
87
+ /** In-memory store for the L2BlockStream's local data provider. */
88
+ private tipsStore: L2TipsMemoryStore;
89
+ /** Block stream for checkpoint and reorg detection. */
90
+ private blockStream: EventDrivenL2BlockStream | undefined;
91
+ /**
92
+ * Highest epoch whose proof-submission window has passed. Monotonic high-water mark.
93
+ * Seeded from the last fully-proven epoch at start(); advanced on every block-stream
94
+ * event by comparing the archiver's latest synced L2 slot against each epoch's
95
+ * submission deadline. Protected so tests can verify the start() seeding.
96
+ */
97
+ protected lastExpiredEpoch: EpochNumber | undefined;
98
+
99
+ /**
100
+ * Highest checkpoint number whose proving-side handling has completed (or that was legitimately skipped).
101
+ * The catch-up loop walks from here to each `chain-checkpointed` tip event. Seeded at start() from the last
102
+ * checkpoint of the last fully-proven epoch (or 0), so a restart reprocesses the partially-proven epoch rather
103
+ * than trusting a checkpointed tip that may sit ahead of unproven checkpoints. Clamped down on a prune.
104
+ */
105
+ protected lastProcessedCheckpoint: CheckpointNumber = CheckpointNumber.ZERO;
106
+
107
+ /** Periodic tick that runs the epoch-expiry sweep during idle periods when no block-stream events arrive. */
108
+ private expiryTicker: RunningPromise | undefined;
64
109
 
65
110
  public readonly tracer: Tracer;
66
111
 
67
- protected publisher: ProverNodePublisher | undefined;
112
+ protected publishingService: ProofPublishingService | undefined;
68
113
 
69
114
  constructor(
70
- protected readonly prover: EpochProverManager,
115
+ protected readonly prover: EpochProverManager & EpochProverFactory,
71
116
  protected readonly publisherFactory: ProverPublisherFactory,
72
117
  protected readonly l2BlockSource: L2BlockSource & Partial<Service>,
73
118
  protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
74
119
  protected readonly contractDataSource: ContractDataSource,
75
120
  protected readonly worldState: WorldStateSynchronizer,
76
- protected readonly p2pClient: Pick<P2PClient<P2PClientType.Prover>, 'getTxProvider'> & Partial<Service>,
77
- protected readonly epochsMonitor: EpochMonitor,
121
+ protected readonly p2pClient: { getTxProvider(): ITxProvider } & Partial<Service>,
78
122
  protected readonly rollupContract: RollupContract,
79
123
  protected readonly l1Metrics: L1Metrics,
80
124
  config: Partial<ProverNodeOptions> = {},
81
125
  protected readonly telemetryClient: TelemetryClient = getTelemetryClient(),
126
+ private delayer?: Delayer,
127
+ private readonly dateProvider: DateProvider = new DateProvider(),
82
128
  ) {
83
129
  this.config = {
84
130
  proverNodePollingIntervalMs: 1_000,
85
131
  proverNodeMaxPendingJobs: 100,
86
- proverNodeMaxParallelBlocksPerEpoch: 32,
132
+ proverNodeMaxParallelBlocksPerEpoch: 0,
87
133
  txGatheringIntervalMs: 1_000,
88
134
  txGatheringBatchSize: 10,
89
135
  txGatheringMaxParallelRequestsPerNode: 100,
@@ -99,8 +145,32 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
99
145
  this.tracer = telemetryClient.getTracer('ProverNode');
100
146
 
101
147
  this.jobMetrics = new ProverNodeJobMetrics(meter, telemetryClient.getTracer('EpochProvingJob'));
102
-
103
148
  this.rewardsMetrics = new ProverNodeRewardsMetrics(meter, this.prover.getProverId(), rollupContract);
149
+
150
+ this.tipsStore = new L2TipsMemoryStore(this.l2BlockSource.getGenesisBlockHash());
151
+
152
+ this.chonkCache = new ChonkCache(this.log.getBindings());
153
+ this.checkpointStore = new CheckpointStore(
154
+ this.l2BlockSource,
155
+ {
156
+ proverFactory: this.prover,
157
+ chonkCache: this.chonkCache,
158
+ publicProcessorFactory: new PublicProcessorFactory(
159
+ this.contractDataSource,
160
+ this.dateProvider,
161
+ this.telemetryClient,
162
+ this.log.getBindings(),
163
+ ),
164
+ dbProvider: this.worldState,
165
+ txProvider: this.p2pClient.getTxProvider(),
166
+ dateProvider: this.dateProvider,
167
+ proverId: this.prover.getProverId(),
168
+ metrics: this.jobMetrics,
169
+ txGatheringTimeoutMs: this.config.txGatheringTimeoutMs,
170
+ deadline: undefined,
171
+ },
172
+ this.log.getBindings(),
173
+ );
104
174
  }
105
175
 
106
176
  public getProverId() {
@@ -111,285 +181,527 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
111
181
  return this.p2pClient;
112
182
  }
113
183
 
114
- /**
115
- * Handles an epoch being completed by starting a proof for it if there are no active jobs for it.
116
- * @param epochNumber - The epoch number that was just completed.
117
- * @returns false if there is an error, true otherwise
118
- */
119
- async handleEpochReadyToProve(epochNumber: EpochNumber): Promise<boolean> {
120
- try {
121
- this.log.debug(`Running jobs as ${epochNumber} is ready to prove`, {
122
- jobs: Array.from(this.jobs.values()).map(job => `${job.getEpochNumber()}:${job.getId()}`),
123
- });
124
- const activeJobs = await this.getActiveJobsForEpoch(epochNumber);
125
- if (activeJobs.length > 0) {
126
- this.log.warn(`Not starting proof for ${epochNumber} since there are active jobs for the epoch`, {
127
- activeJobs: activeJobs.map(job => job.uuid),
128
- });
129
- return true;
130
- }
131
- await this.startProof(epochNumber);
132
- return true;
133
- } catch (err) {
134
- if (err instanceof EmptyEpochError) {
135
- this.log.info(`Not starting proof for ${epochNumber} since no blocks were found`);
136
- } else {
137
- this.log.error(`Error handling epoch completed`, err);
138
- }
139
- return false;
140
- }
184
+ /** Test-only: the shared L1 tx delayer, if enabled. */
185
+ public getDelayer(): Delayer | undefined {
186
+ return this.delayer;
141
187
  }
142
188
 
143
- /**
144
- * Starts the prover node so it periodically checks for unproven epochs in the unfinalized chain from L1 and
145
- * starts proving jobs for them.
146
- */
147
- async start() {
148
- this.epochsMonitor.start(this);
149
- await this.publisherFactory.start();
150
- this.publisher = await this.publisherFactory.create();
151
- await this.rewardsMetrics.start();
152
- this.l1Metrics.start();
153
- this.log.info(`Started Prover Node with prover id ${this.prover.getProverId().toString()}`, this.config);
189
+ /** Observability summary for the ProverNodeApi. */
190
+ public getJobs(): Promise<{ uuid: string; status: EpochProvingJobState; epochNumber: EpochNumber }[]> {
191
+ return Promise.resolve(this.sessionManager?.getJobs() ?? []);
154
192
  }
155
193
 
156
- /**
157
- * Stops the prover node and all its dependencies.
158
- */
159
- async stop() {
160
- this.log.info('Stopping ProverNode');
161
- await this.epochsMonitor.stop();
162
- await this.prover.stop();
163
- await tryStop(this.p2pClient);
164
- await tryStop(this.l2BlockSource);
165
- await tryStop(this.publisherFactory);
166
- this.publisher?.interrupt();
167
- await Promise.all(Array.from(this.jobs.values()).map(job => job.stop()));
168
- await this.worldState.stop();
169
- this.rewardsMetrics.stop();
170
- this.l1Metrics.stop();
171
- await this.telemetryClient.stop();
172
- this.log.info('Stopped ProverNode');
194
+ /** Tests inspect this when validating reconcile behaviour. */
195
+ public getCheckpointStore(): CheckpointStore {
196
+ return this.checkpointStore;
173
197
  }
174
198
 
175
- /** Returns world state status. */
176
- public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
177
- const { syncSummary } = await this.worldState.status();
178
- return syncSummary;
199
+ /** Tests inspect this to verify chonk-cache release semantics. */
200
+ public getChonkCache(): ChonkCache {
201
+ return this.chonkCache;
179
202
  }
180
203
 
181
- /** Returns archiver status. */
182
- public getL2Tips() {
183
- return this.l2BlockSource.getL2Tips();
204
+ /** Tests inspect this when looking up live sessions. */
205
+ public getSessionManager(): SessionManager {
206
+ if (!this.sessionManager) {
207
+ throw new Error('SessionManager not yet constructed — start() must be called first.');
208
+ }
209
+ return this.sessionManager;
184
210
  }
185
211
 
186
- /**
187
- * Starts a proving process and returns immediately.
188
- */
189
- public async startProof(epochNumber: EpochNumber) {
190
- const job = await this.createProvingJob(epochNumber, { skipEpochCheck: true });
191
- void this.runJob(job);
212
+ /** Returns the underlying prover instance. */
213
+ public getProver() {
214
+ return this.prover;
192
215
  }
193
216
 
194
- private async runJob(job: EpochProvingJob) {
195
- const epochNumber = job.getEpochNumber();
196
- const ctx = { id: job.getId(), epochNumber, state: undefined as EpochProvingJobState | undefined };
217
+ // ---------------- L2BlockStream handler ----------------
218
+
219
+ public async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise<void> {
220
+ switch (event.type) {
221
+ case 'chain-checkpointed':
222
+ await this.processCheckpointJump(event.checkpoint.number);
223
+ break;
224
+ case 'chain-pruned':
225
+ await this.handlePruneEvent(event.block);
226
+ break;
227
+ case 'chain-proven':
228
+ this.publishingService?.onChainProven(BlockNumber(event.block.number));
229
+ break;
230
+ // The proposed tip drives only the tips store's walk-back history (recorded below); the prover-node
231
+ // tracks checkpoints, not proposed blocks. `blocks-added` is never emitted in tips-only mode, and
232
+ // `chain-finalized` carries nothing the prover-node acts on.
233
+ case 'chain-proposed':
234
+ case 'chain-finalized':
235
+ case 'blocks-added':
236
+ break;
237
+ default: {
238
+ const _: never = event;
239
+ break;
240
+ }
241
+ }
242
+ // Expiry is driven by the archiver's latest synced L2 slot
243
+ await this.checkEpochExpiry();
244
+ // Advance the local tips store only after the proving-side handling has succeeded. Any
245
+ // failure above propagates to the L2BlockStream (which logs and stops this poll pass) and
246
+ // skips this update, so the event is re-emitted on the next poll rather than skipped (A-1041).
247
+ await this.tipsStore.handleBlockStreamEvent(event);
248
+ }
197
249
 
198
- try {
199
- await job.run();
200
- const state = job.getState();
201
- ctx.state = state;
202
-
203
- if (state === 'reorg') {
204
- this.log.warn(`Running new job for epoch ${epochNumber} due to reorg`, ctx);
205
- await this.createProvingJob(epochNumber);
206
- } else if (state === 'failed') {
207
- this.log.error(`Job for ${epochNumber} exited with state ${state}`, ctx);
208
- await this.tryUploadEpochFailure(job);
250
+ /**
251
+ * Walks every checkpoint between the local cursor and the newly-reported checkpointed tip, registering
252
+ * each one that belongs to an epoch that can still be proven. The block stream now delivers a single thin
253
+ * `chain-checkpointed` tip event per pass rather than one fat event per checkpoint, so this drives the
254
+ * catch-up itself: light metadata first (`getCheckpointsData`) to decide relevance per epoch, then a heavy
255
+ * `getCheckpoints` fetch only for checkpoints in provable epochs.
256
+ *
257
+ * The cursor advances one checkpoint at a time and only after that checkpoint's proving-side handling has
258
+ * fully succeeded, preserving the A-1041 at-least-once semantics: a mid-jump failure leaves the cursor
259
+ * behind so the next pass retries from the first checkpoint that did not complete.
260
+ */
261
+ private async processCheckpointJump(targetCheckpoint: CheckpointNumber): Promise<void> {
262
+ if (targetCheckpoint <= this.lastProcessedCheckpoint) {
263
+ return;
264
+ }
265
+ const l1Constants = await this.getL1Constants();
266
+
267
+ // Cap the catch-up at the `(proofSubmissionEpochs + 1) * epochDuration` most recent checkpoints.
268
+ // When the cursor is much further behind (e.g. resyncing after a long time offline), fetching the whole gap could
269
+ // load thousands of checkpoints we cannot act on: anything older than the last two epochs is already past
270
+ // its proof-submission window, so we skip it and jump the cursor forward to the start of the capped range.
271
+ const maxCheckpoints = (l1Constants.proofSubmissionEpochs + 1) * l1Constants.epochDuration;
272
+ let from = CheckpointNumber(this.lastProcessedCheckpoint + 1);
273
+ if (Number(targetCheckpoint - from) + 1 > maxCheckpoints) {
274
+ const cappedFrom = CheckpointNumber(targetCheckpoint - maxCheckpoints + 1);
275
+ this.log.warn(`Skipping unprovable checkpoints during catch-up; the prover node is far behind`, {
276
+ from,
277
+ cappedFrom,
278
+ targetCheckpoint,
279
+ maxCheckpoints,
280
+ });
281
+ // Advance the cursor past the skipped checkpoints so they are never retried.
282
+ this.lastProcessedCheckpoint = CheckpointNumber(cappedFrom - 1);
283
+ from = cappedFrom;
284
+ }
285
+ const limit = Number(targetCheckpoint - from) + 1;
286
+ const metadatas = await this.l2BlockSource.getCheckpointsData({ from, limit });
287
+
288
+ // Per-epoch relevance is cached so a multi-checkpoint epoch resolves it once. Skipping is whole-epoch
289
+ // only: the SessionManager requires an epoch's checkpoints fully covered before it opens a session, so we
290
+ // never drop an individual checkpoint inside an epoch we will prove.
291
+ const epochSkippable = new Map<EpochNumber, boolean>();
292
+ for (const metadata of metadatas) {
293
+ const epochNumber = getEpochAtSlot(metadata.header.slotNumber, l1Constants);
294
+ let skippable = epochSkippable.get(epochNumber);
295
+ if (skippable === undefined) {
296
+ skippable =
297
+ (await this.isEpochFullyProven(epochNumber, l1Constants)) ||
298
+ (await this.isEpochPastProofSubmissionWindow(epochNumber, l1Constants));
299
+ epochSkippable.set(epochNumber, skippable);
300
+ }
301
+ if (skippable) {
302
+ this.log.debug(`Skipping checkpoint ${metadata.checkpointNumber} for unprovable epoch ${epochNumber}`);
209
303
  } else {
210
- this.log.verbose(`Job for ${epochNumber} exited with state ${state}`, ctx);
304
+ await this.registerCheckpoint(metadata.checkpointNumber, epochNumber);
211
305
  }
212
- } catch (err) {
213
- this.log.error(`Error proving epoch ${epochNumber}`, err, ctx);
214
- } finally {
215
- this.jobs.delete(job.getId());
306
+ // Advance only after the checkpoint's handling succeeded (or it was legitimately skipped). registerCheckpoint
307
+ // throws on failure, which leaves the cursor here for the next pass to retry (A-1041).
308
+ this.lastProcessedCheckpoint = metadata.checkpointNumber;
216
309
  }
217
310
  }
218
311
 
219
- protected async tryUploadEpochFailure(job: EpochProvingJob) {
220
- if (this.config.proverNodeFailedEpochStore) {
221
- return await uploadEpochProofFailure(
222
- this.config.proverNodeFailedEpochStore,
223
- job.getId(),
224
- job.getProvingData(),
225
- this.l2BlockSource as Archiver,
226
- this.worldState,
227
- assertRequired(pick(this.config, 'l1ChainId', 'rollupVersion', 'dataDirectory')),
228
- this.log,
229
- );
312
+ /** Heavy-fetch a single checkpoint, register it with the store, and notify the session manager. */
313
+ private async registerCheckpoint(checkpointNumber: CheckpointNumber, epochNumber: EpochNumber): Promise<void> {
314
+ const published = await this.l2BlockSource.getCheckpoint({ number: checkpointNumber });
315
+ if (!published) {
316
+ throw new Error(`Checkpoint ${checkpointNumber} not found in block source during catch-up`);
230
317
  }
318
+ const checkpoint = published.checkpoint;
319
+ this.log.info(`New checkpoint ${checkpoint.number} for epoch ${epochNumber}`, {
320
+ checkpointNumber: checkpoint.number,
321
+ epochNumber,
322
+ slotNumber: checkpoint.header.slotNumber,
323
+ });
324
+
325
+ const registerData = await this.collectRegisterData(checkpoint, published.attestations);
326
+ await this.checkpointStore.addOrUpdate(checkpoint, registerData);
327
+ await this.sessionManager?.onCheckpointAdded(epochNumber);
328
+
329
+ // Tips-only mode delivers no blocks, so record one witness per checkpointed block: a reorg into the checkpoint's
330
+ // range then prunes at the true divergence instead of the nearest sparse tip anchor.
331
+ await this.tipsStore.recordBlockHashes(
332
+ await Promise.all(
333
+ checkpoint.blocks.map(async block => ({ number: block.number, hash: (await block.header.hash()).toString() })),
334
+ ),
335
+ );
231
336
  }
232
337
 
233
338
  /**
234
- * Returns the prover instance.
339
+ * Gathers register-time data for a checkpoint: previous block header, L1-to-L2 messages,
340
+ * and the archive sibling path.
235
341
  */
236
- public getProver() {
237
- return this.prover;
342
+ private async collectRegisterData(
343
+ checkpoint: Checkpoint,
344
+ attestations: PublishedCheckpoint['attestations'],
345
+ ): Promise<RegisterCheckpointData> {
346
+ const previousBlockNumber = BlockNumber(checkpoint.blocks[0].number - 1);
347
+ const previousBlockHeader = await this.gatherPreviousBlockHeader(previousBlockNumber);
348
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpoint.number);
349
+ const lastBlock = checkpoint.blocks.at(-1)!;
350
+ const lastBlockHash = await lastBlock.header.hash();
351
+ await this.worldState.syncImmediate(lastBlock.number, lastBlockHash);
352
+ const previousArchiveSiblingPath = await getLastSiblingPath(
353
+ MerkleTreeId.ARCHIVE,
354
+ this.worldState.getSnapshot(previousBlockNumber),
355
+ );
356
+ return {
357
+ attestations,
358
+ previousBlockHeader,
359
+ l1ToL2Messages,
360
+ previousArchiveSiblingPath,
361
+ };
238
362
  }
239
363
 
240
364
  /**
241
- * Returns an array of jobs being processed.
365
+ * Marks every prover orphaned by the prune as pruned, clamps the catch-up cursor below the prune target's
366
+ * checkpoint, and notifies the session manager. Keyed off the prune target block (the highest surviving block)
367
+ * rather than the source's checkpointed tip, which can sit above the target after a re-checkpoint and would leave
368
+ * orphaned provers canonical. Throws (rather than warning) if the cursor floor cannot be resolved, so the pass
369
+ * fails and the prune is retried next iteration.
242
370
  */
243
- public getJobs(): Promise<{ uuid: string; status: EpochProvingJobState; epochNumber: EpochNumber }[]> {
244
- return Promise.resolve(
245
- Array.from(this.jobs.entries()).map(([uuid, job]) => ({
246
- uuid,
247
- status: job.getState(),
248
- epochNumber: job.getEpochNumber(),
249
- })),
250
- );
371
+ private async handlePruneEvent(prunedToBlock: L2BlockId) {
372
+ this.log.warn(`Chain pruned to block ${prunedToBlock.number}`, { prunedToBlock });
373
+
374
+ // Resolve the cursor floor BEFORE removing provers: cancelAndRemoveAboveBlock returns only the provers it removed,
375
+ // so a throw after removing would leave a retry pass with nothing to act on. Resolving first means a throw leaves
376
+ // everything untouched and the next pass retries the whole handler (the tips cursor only advances on success).
377
+ let cursorFloor: CheckpointNumber;
378
+ if (prunedToBlock.number === 0) {
379
+ cursorFloor = CheckpointNumber.ZERO;
380
+ } else {
381
+ const targetData = await this.l2BlockSource.getBlockData({ number: prunedToBlock.number });
382
+ if (targetData === undefined) {
383
+ throw new Error(
384
+ `No block data found for prune target block ${prunedToBlock.number}; cannot clamp checkpoint cursor`,
385
+ );
386
+ }
387
+ // Clamp to `cpAtTarget - 1`: a mid-checkpoint target leaves that checkpoint partially orphaned and it must be
388
+ // reprocessed. Over-clamping merely re-registers a checkpoint (at-least-once by design — A-1041); under-clamping
389
+ // would permanently skip a rebuilt same-number checkpoint.
390
+ cursorFloor = CheckpointNumber(Math.max(0, Number(targetData.checkpointNumber) - 1));
391
+ }
392
+
393
+ const affected = this.checkpointStore.cancelAndRemoveAboveBlock(prunedToBlock.number);
394
+
395
+ if (this.lastProcessedCheckpoint > cursorFloor) {
396
+ this.lastProcessedCheckpoint = cursorFloor;
397
+ }
398
+
399
+ if (affected.length === 0) {
400
+ return;
401
+ }
402
+ const l1Constants = await this.getL1Constants();
403
+ const affectedEpochs = Array.from(
404
+ new Set(affected.map(p => Number(getEpochAtSlot(p.slotNumber, l1Constants)))),
405
+ ).map(n => EpochNumber(n));
406
+ // The session manager cancels every affected session, which in turn calls
407
+ // publishingService.withdraw(uuid) for each candidate; no separate notification to the
408
+ // publishing service is needed.
409
+ await this.sessionManager?.onPrune(affectedEpochs);
251
410
  }
252
411
 
253
- protected async getActiveJobsForEpoch(
412
+ /**
413
+ * Returns true once the chain has advanced past the given epoch's proof-submission window.
414
+ * Used to ignore checkpoints whose epoch can no longer be proven in time — chiefly while the
415
+ * archiver replays old blocks after a restart. Compares the archiver's latest synced L2 slot
416
+ * against the epoch's submission-deadline epoch; conservatively returns false if the slot can't
417
+ * be read yet.
418
+ */
419
+ private async isEpochPastProofSubmissionWindow(
254
420
  epochNumber: EpochNumber,
255
- ): Promise<{ uuid: string; status: EpochProvingJobState }[]> {
256
- const jobs = await this.getJobs();
257
- return jobs.filter(job => job.epochNumber === epochNumber && !EpochProvingJobTerminalState.includes(job.status));
421
+ l1Constants: L1RollupConstants,
422
+ ): Promise<boolean> {
423
+ const latestSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
424
+ if (latestSlot === undefined) {
425
+ return false;
426
+ }
427
+ const latestEpoch = getEpochAtSlot(latestSlot, l1Constants);
428
+ return latestEpoch >= getProofSubmissionDeadlineEpoch(epochNumber, l1Constants);
258
429
  }
259
430
 
260
- private checkMaximumPendingJobs() {
261
- const { proverNodeMaxPendingJobs: maxPendingJobs } = this.config;
262
- if (maxPendingJobs > 0 && this.jobs.size >= maxPendingJobs) {
263
- throw new Error(`Maximum pending proving jobs ${maxPendingJobs} reached. Cannot create new job.`);
431
+ /**
432
+ * Compares the archiver's latest synced L2 slot against `lastExpiredEpoch` and, for each
433
+ * newly-expired epoch, releases the chonk-cache entries for its blocks and reaps any
434
+ * CheckpointProvers in the store. An epoch E is expired once the chain reaches the start
435
+ * of epoch `E + proofSubmissionEpochs + 1`. Silently no-ops if nothing has expired since
436
+ * the last check or the archiver's slot can't be read.
437
+ */
438
+ private async checkEpochExpiry(): Promise<void> {
439
+ const latestSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
440
+ if (latestSlot === undefined) {
441
+ return;
264
442
  }
443
+ const l1Constants = await this.getL1Constants();
444
+ const latestEpoch = getEpochAtSlot(latestSlot, l1Constants);
445
+ const offset = l1Constants.proofSubmissionEpochs + 1;
446
+ if (latestEpoch < offset) {
447
+ return;
448
+ }
449
+ const newlyExpiredUpTo = EpochNumber(latestEpoch - offset);
450
+ const from = this.lastExpiredEpoch === undefined ? EpochNumber(0) : EpochNumber(this.lastExpiredEpoch + 1);
451
+ if (newlyExpiredUpTo < from) {
452
+ return;
453
+ }
454
+ for (let e = from; e <= newlyExpiredUpTo; e = EpochNumber(e + 1)) {
455
+ await this.expireEpoch(e);
456
+ }
457
+ this.lastExpiredEpoch = newlyExpiredUpTo;
265
458
  }
266
459
 
267
- @trackSpan('ProverNode.createProvingJob', epochNumber => ({ [Attributes.EPOCH_NUMBER]: epochNumber }))
268
- private async createProvingJob(epochNumber: EpochNumber, opts: { skipEpochCheck?: boolean } = {}) {
269
- this.checkMaximumPendingJobs();
460
+ /**
461
+ * Releases chonk-cache entries for every block in the supplied epoch (best-effort) and
462
+ * reaps every CheckpointProver in the store whose epoch number matches.
463
+ */
464
+ private async expireEpoch(epoch: EpochNumber): Promise<void> {
465
+ try {
466
+ const blocks = await this.l2BlockSource.getBlocks({ epoch, onlyCheckpointed: true });
467
+ if (blocks.length > 0) {
468
+ this.chonkCache.releaseForBlocks(blocks);
469
+ }
470
+ } catch (err) {
471
+ this.log.warn(`Could not release chonk-cache entries for expired epoch ${epoch}`, err);
472
+ }
473
+ this.checkpointStore.reapExpired(epoch);
474
+ }
270
475
 
271
- this.publisher = await this.publisherFactory.create();
476
+ // ---------------- public API ----------------
272
477
 
273
- // Gather all data for this epoch
274
- const epochData = await this.gatherEpochData(epochNumber);
275
- const fromCheckpoint = epochData.checkpoints[0].number;
276
- const toCheckpoint = epochData.checkpoints.at(-1)!.number;
277
- const fromBlock = epochData.checkpoints[0].blocks[0].number;
278
- const toBlock = epochData.checkpoints.at(-1)!.blocks.at(-1)!.number;
279
- this.log.verbose(
280
- `Creating proving job for epoch ${epochNumber} for checkpoint range ${fromCheckpoint} to ${toCheckpoint} and block range ${fromBlock} to ${toBlock}`,
281
- );
478
+ /**
479
+ * Schedules proving for the given epoch and returns the job id without waiting for completion.
480
+ */
481
+ public async startProof(epochNumber: EpochNumber): Promise<string> {
482
+ if (!this.sessionManager) {
483
+ throw new Error('ProverNode not started');
484
+ }
485
+ return await this.sessionManager.startProof(epochNumber);
486
+ }
282
487
 
283
- // Fast forward world state to right before the target block and get a fork
284
- await this.worldState.syncImmediate(toBlock);
488
+ // ---------------- Service lifecycle ----------------
285
489
 
286
- // Create a processor factory
287
- const publicProcessorFactory = new PublicProcessorFactory(
288
- this.contractDataSource,
289
- this.dateProvider,
290
- this.telemetryClient,
490
+ async start() {
491
+ await this.checkpointStore.start();
492
+
493
+ await this.publisherFactory.start();
494
+ this.publishingService = new ProofPublishingService({
495
+ publisherFactory: this.publisherFactory,
496
+ l2BlockSource: this.l2BlockSource,
497
+ dateProvider: this.dateProvider,
498
+ config: { skipSubmitProof: !!this.config.proverNodeDisableProofPublish },
499
+ bindings: this.log.getBindings(),
500
+ });
501
+ this.sessionManager = this.createSessionManager(this.publishingService);
502
+ // SessionManager owns its own periodic tick; start it here so it begins picking up
503
+ // epochs that become complete by time (no fresh checkpoint event) and advances once
504
+ // the previous epoch is proven on L1.
505
+ this.sessionManager.start();
506
+ // Now that the store + manager exist, arm the live-state observable gauges.
507
+ this.jobMetrics.observeState(this.checkpointStore, this.sessionManager);
508
+
509
+ const { lastFullyProvenEpoch } = await this.resolveLastFullyProvenEpoch();
510
+ this.lastExpiredEpoch = lastFullyProvenEpoch;
511
+ this.lastProcessedCheckpoint = await this.computeStartingCheckpoint(lastFullyProvenEpoch);
512
+ this.blockStream = new EventDrivenL2BlockStream(this.l2BlockSource, this.tipsStore, this, this.log, {
513
+ pollIntervalMS: this.config.proverNodePollingIntervalMs,
514
+ tipsOnly: true,
515
+ });
516
+ this.blockStream.start();
517
+
518
+ // With thin once-per-pass tip events, the expiry sweep no longer fires once per checkpoint; drive it
519
+ // from a periodic tick so epochs still expire during idle/no-event periods.
520
+ this.expiryTicker = new RunningPromise(
521
+ () => this.checkEpochExpiry(),
522
+ this.log,
523
+ this.config.proverNodePollingIntervalMs,
291
524
  );
525
+ this.expiryTicker.start();
292
526
 
293
- // Set deadline for this job to run. It will abort if it takes too long.
294
- const deadlineTs = getProofSubmissionDeadlineTimestamp(epochNumber, await this.getL1Constants());
295
- const deadline = new Date(Number(deadlineTs) * 1000);
296
- const job = this.doCreateEpochProvingJob(epochData, deadline, publicProcessorFactory, this.publisher, opts);
297
- this.jobs.set(job.getId(), job);
298
- return job;
527
+ await this.rewardsMetrics.start();
528
+ this.l1Metrics.start();
529
+ this.log.info(`Started Prover Node with prover id ${this.prover.getProverId().toString()}`, this.config);
299
530
  }
300
531
 
301
- @memoize
302
- private getL1Constants() {
303
- return this.l2BlockSource.getL1Constants();
532
+ async stop() {
533
+ this.log.info('Stopping ProverNode');
534
+ this.jobMetrics.stopObservingState();
535
+ await this.blockStream?.stop();
536
+ await this.expiryTicker?.stop();
537
+ if (this.sessionManager) {
538
+ await this.sessionManager.stop();
539
+ }
540
+ if (this.publishingService) {
541
+ // Bound the wait: the publishing service blocks until any in-flight L1 proof-submission tx
542
+ // settles, which can outlast a reasonable shutdown window. On timeout we log and move on —
543
+ // the tx may still mine, but shutdown must not hang on it.
544
+ const publishingService = this.publishingService;
545
+ await executeTimeout(
546
+ () => publishingService.stop(),
547
+ PUBLISHING_SERVICE_STOP_TIMEOUT_MS,
548
+ 'prover-node publishing-service stop',
549
+ ).catch(err => this.log.warn(`Timed out stopping proof publishing service`, err));
550
+ }
551
+ await this.checkpointStore.stop();
552
+ this.chonkCache.stop();
553
+ await this.prover.stop();
554
+ await tryStop(this.publisherFactory);
555
+ this.rewardsMetrics.stop();
556
+ this.l1Metrics.stop();
557
+ await this.telemetryClient.stop();
558
+ this.log.info('Stopped ProverNode');
304
559
  }
305
560
 
306
- @trackSpan('ProverNode.gatherEpochData', epochNumber => ({ [Attributes.EPOCH_NUMBER]: epochNumber }))
307
- private async gatherEpochData(epochNumber: EpochNumber): Promise<EpochProvingJobData> {
308
- const checkpoints = await this.gatherCheckpoints(epochNumber);
309
- const txArray = await this.gatherTxs(epochNumber, checkpoints);
310
- const txs = new Map<string, Tx>(txArray.map(tx => [tx.getTxHash().toString(), tx]));
311
- const l1ToL2Messages = await this.gatherMessages(epochNumber, checkpoints);
312
- const [firstBlock] = checkpoints[0].blocks;
313
- const previousBlockHeader = await this.gatherPreviousBlockHeader(epochNumber, firstBlock.number - 1);
314
- const [lastPublishedCheckpoint] = await this.l2BlockSource.getCheckpoints(checkpoints.at(-1)!.number, 1);
315
- const attestations = lastPublishedCheckpoint?.attestations ?? [];
316
-
317
- return { checkpoints, txs, l1ToL2Messages, epochNumber, previousBlockHeader, attestations };
561
+ /**
562
+ * Constructs the session manager. Extracted so subclasses (test harness) can swap
563
+ * the implementation. Wired to `tryUploadSessionFailure` so failed sessions get
564
+ * their proving data uploaded.
565
+ */
566
+ protected createSessionManager(publishingService: ProofPublishingService): SessionManager {
567
+ return new SessionManager({
568
+ checkpointStore: this.checkpointStore,
569
+ l2BlockSource: this.l2BlockSource,
570
+ proverFactory: this.prover,
571
+ proverId: this.prover.getProverId(),
572
+ publishingService,
573
+ metrics: this.jobMetrics,
574
+ dateProvider: this.dateProvider,
575
+ config: {
576
+ maxPendingJobs: this.config.proverNodeMaxPendingJobs,
577
+ tickIntervalMs: this.config.proverNodePollingIntervalMs,
578
+ finalizationDelayMs: this.config.proverNodeEpochProvingDelayMs,
579
+ },
580
+ onSessionFailed: async session => {
581
+ await this.tryUploadSessionFailure(session);
582
+ },
583
+ bindings: this.log.getBindings(),
584
+ });
318
585
  }
319
586
 
320
- private async gatherCheckpoints(epochNumber: EpochNumber) {
321
- const checkpoints = await this.l2BlockSource.getCheckpointsForEpoch(epochNumber);
322
- if (checkpoints.length === 0) {
323
- throw new EmptyEpochError(epochNumber);
587
+ /**
588
+ * Installs session hooks for the e2e harness to interpose around top-tree proving
589
+ * (gate, override, or observe it) without monkey-patching the orchestrator factory.
590
+ * Applies to every session constructed after this call.
591
+ */
592
+ public setSessionHooks(hooks: EpochSessionHooks): void {
593
+ if (!this.sessionManager) {
594
+ throw new Error('ProverNode not started; call start() before setting session hooks.');
324
595
  }
325
- return checkpoints;
596
+ this.sessionManager.setSessionHooks(hooks);
326
597
  }
327
598
 
328
- private async gatherTxs(epochNumber: EpochNumber, checkpoints: Checkpoint[]) {
329
- const deadline = new Date(this.dateProvider.now() + this.config.txGatheringTimeoutMs);
330
- const txProvider = this.p2pClient.getTxProvider();
331
- const blocks = checkpoints.flatMap(checkpoint => checkpoint.blocks);
332
- const txsByBlock = await Promise.all(blocks.map(block => txProvider.getTxsForBlock(block, { deadline })));
333
- const txs = txsByBlock.map(({ txs }) => txs).flat();
334
- const missingTxs = txsByBlock.map(({ missingTxs }) => missingTxs).flat();
335
-
336
- if (missingTxs.length === 0) {
337
- this.log.verbose(`Gathered all ${txs.length} txs for epoch ${epochNumber}`, { epochNumber });
338
- return txs;
599
+ /** Uploads failure snapshots when sessions exit with `failed`. Exposed as a method so tests can spy on it. */
600
+ public async tryUploadSessionFailure(session: EpochSession): Promise<string | undefined> {
601
+ if (!this.config.proverNodeFailedEpochStore) {
602
+ return undefined;
339
603
  }
604
+ const data = SessionManager.buildSessionProvingData(session);
605
+ return await uploadEpochProofFailure(
606
+ this.config.proverNodeFailedEpochStore,
607
+ session.getId(),
608
+ data,
609
+ this.l2BlockSource as Archiver,
610
+ this.worldState,
611
+ assertRequired(pick(this.config, 'l1ChainId', 'rollupVersion', 'dataDirectory')),
612
+ this.log,
613
+ );
614
+ }
615
+
616
+ // ---------------- helpers ----------------
340
617
 
341
- throw new Error(`Txs not found for epoch ${epochNumber}: ${missingTxs.map(hash => hash.toString()).join(', ')}`);
618
+ @memoize
619
+ private getL1Constants(): Promise<L1RollupConstants> {
620
+ return this.l2BlockSource.getL1Constants();
342
621
  }
343
622
 
344
- private async gatherMessages(epochNumber: EpochNumber, checkpoints: Checkpoint[]) {
345
- const messages = await Promise.all(checkpoints.map(c => this.l1ToL2MessageSource.getL1ToL2Messages(c.number)));
346
- const messageCount = sum(messages.map(m => m.length));
347
- this.log.verbose(`Gathered all ${messageCount} messages for epoch ${epochNumber}`, { epochNumber });
348
- const messagesByCheckpoint: Record<CheckpointNumber, Fr[]> = {};
349
- for (let i = 0; i < checkpoints.length; i++) {
350
- messagesByCheckpoint[checkpoints[i].number] = messages[i];
623
+ /**
624
+ * Returns true if every block in the given epoch is proven on L1. An epoch is only
625
+ * fully proven when its *last* block is proven. Protected for direct unit-test access.
626
+ */
627
+ protected async isEpochFullyProven(
628
+ epochNumber: EpochNumber,
629
+ l1Constants: Pick<L1RollupConstants, 'epochDuration'>,
630
+ ): Promise<boolean> {
631
+ const provenBlockNumber = await this.l2BlockSource.getBlockNumber({ tag: 'proven' });
632
+ if (!provenBlockNumber || provenBlockNumber <= 0) {
633
+ return false;
634
+ }
635
+ const provenHeader = (await this.l2BlockSource.getBlockData({ number: BlockNumber(provenBlockNumber) }))?.header;
636
+ if (!provenHeader) {
637
+ return false;
638
+ }
639
+ const provenEpoch = getEpochAtSlot(provenHeader.getSlot(), l1Constants);
640
+ if (epochNumber < provenEpoch) {
641
+ return true;
642
+ }
643
+ if (epochNumber > provenEpoch) {
644
+ return false;
351
645
  }
352
- return messagesByCheckpoint;
646
+ return this.isProvenBlockLastOfItsEpoch(BlockNumber(provenBlockNumber), provenEpoch, l1Constants);
353
647
  }
354
648
 
355
- private async gatherPreviousBlockHeader(epochNumber: EpochNumber, previousBlockNumber: number) {
356
- const header = await (previousBlockNumber === 0
357
- ? this.worldState.getCommitted().getInitialHeader()
358
- : this.l2BlockSource.getBlockHeader(BlockNumber(previousBlockNumber)));
359
-
360
- if (!header) {
361
- throw new Error(`Previous block header ${previousBlockNumber} not found for proving epoch ${epochNumber}`);
649
+ /** Protected for direct unit-test access. */
650
+ protected async isProvenBlockLastOfItsEpoch(
651
+ provenBlockNumber: BlockNumber,
652
+ provenEpoch: EpochNumber,
653
+ l1Constants: Pick<L1RollupConstants, 'epochDuration'>,
654
+ ): Promise<boolean> {
655
+ const nextHeader = (await this.l2BlockSource.getBlockData({ number: BlockNumber(provenBlockNumber + 1) }))?.header;
656
+ if (nextHeader) {
657
+ return getEpochAtSlot(nextHeader.getSlot(), l1Constants) > provenEpoch;
362
658
  }
659
+ return this.l2BlockSource.isEpochComplete(provenEpoch);
660
+ }
363
661
 
364
- this.log.verbose(`Gathered previous block header ${header.getBlockNumber()} for epoch ${epochNumber}`);
365
- return header;
662
+ /**
663
+ * Resolves the last fully-proven epoch from L1 proven state, used to seed the catch-up cursor (via
664
+ * `computeStartingCheckpoint`) and `lastExpiredEpoch`. The fully-proven epoch is `provenEpoch` when the
665
+ * proven tip is the last block of its epoch, otherwise `provenEpoch - 1`, or `undefined` if no block is
666
+ * proven yet (so a restart reprocesses the partially-proven epoch rather than trusting a stale tip).
667
+ */
668
+ protected async resolveLastFullyProvenEpoch(): Promise<{ lastFullyProvenEpoch: EpochNumber | undefined }> {
669
+ const provenBlockNumber = await this.l2BlockSource.getBlockNumber({ tag: 'proven' });
670
+ if (!provenBlockNumber || provenBlockNumber <= 0) {
671
+ return { lastFullyProvenEpoch: undefined };
672
+ }
673
+ const l1Constants = await this.getL1Constants();
674
+ const provenHeader = (await this.l2BlockSource.getBlockData({ number: BlockNumber(provenBlockNumber) }))?.header;
675
+ if (!provenHeader) {
676
+ return { lastFullyProvenEpoch: undefined };
677
+ }
678
+ const provenEpoch = getEpochAtSlot(provenHeader.getSlot(), l1Constants);
679
+ if (await this.isProvenBlockLastOfItsEpoch(BlockNumber(provenBlockNumber), provenEpoch, l1Constants)) {
680
+ return { lastFullyProvenEpoch: provenEpoch };
681
+ }
682
+ const lastFullyProvenEpoch = provenEpoch > 0 ? EpochNumber(provenEpoch - 1) : undefined;
683
+ return { lastFullyProvenEpoch };
366
684
  }
367
685
 
368
- /** Extracted for testing purposes. */
369
- protected doCreateEpochProvingJob(
370
- data: EpochProvingJobData,
371
- deadline: Date | undefined,
372
- publicProcessorFactory: PublicProcessorFactory,
373
- publisher: ProverNodePublisher,
374
- opts: { skipEpochCheck?: boolean } = {},
375
- ) {
376
- const { proverNodeMaxParallelBlocksPerEpoch: parallelBlockLimit, proverNodeDisableProofPublish } = this.config;
377
- return new EpochProvingJob(
378
- data,
379
- this.worldState,
380
- this.prover.createEpochProver(),
381
- publicProcessorFactory,
382
- publisher,
383
- this.l2BlockSource,
384
- this.jobMetrics,
385
- deadline,
386
- { parallelBlockLimit, skipSubmitProof: proverNodeDisableProofPublish, ...opts },
387
- );
686
+ /**
687
+ * Resolves the catch-up cursor seed: the last checkpoint of the last fully-proven epoch, or 0 if none. Seeding
688
+ * from a checkpoint (rather than a checkpointed tip) guarantees a restart reprocesses every checkpoint of the
689
+ * partially-proven epoch, since the checkpointed tip can sit ahead of the last fully-proven checkpoint.
690
+ */
691
+ protected async computeStartingCheckpoint(lastFullyProvenEpoch: EpochNumber | undefined): Promise<CheckpointNumber> {
692
+ if (lastFullyProvenEpoch === undefined) {
693
+ return CheckpointNumber.ZERO;
694
+ }
695
+ const checkpoints = await this.l2BlockSource.getCheckpointsData({ epoch: lastFullyProvenEpoch });
696
+ return checkpoints.at(-1)?.checkpointNumber ?? CheckpointNumber.ZERO;
388
697
  }
389
698
 
390
- /** Extracted for testing purposes. */
391
- protected async triggerMonitors() {
392
- await this.epochsMonitor.work();
699
+ private async gatherPreviousBlockHeader(previousBlockNumber: number) {
700
+ const data = await this.l2BlockSource.getBlockData({ number: BlockNumber(previousBlockNumber) });
701
+ if (!data?.header) {
702
+ throw new Error(`Previous block header ${previousBlockNumber} not found`);
703
+ }
704
+ return data.header;
393
705
  }
394
706
 
395
707
  private validateConfig() {
@@ -408,9 +720,5 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
408
720
  }
409
721
  }
410
722
 
411
- class EmptyEpochError extends Error {
412
- constructor(epochNumber: EpochNumber) {
413
- super(`No blocks found for epoch ${epochNumber}`);
414
- this.name = 'EmptyEpochError';
415
- }
416
- }
723
+ // Re-export so handlers can compare states externally.
724
+ export { EpochProvingJobTerminalState };