@aztec/prover-node 0.0.1-commit.c31f2472 → 0.0.1-commit.c52d6e7

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 +572 -0
  2. package/dest/actions/download-epoch-proving-job.js +1 -1
  3. package/dest/actions/rerun-epoch-proving-job.d.ts +14 -4
  4. package/dest/actions/rerun-epoch-proving-job.d.ts.map +1 -1
  5. package/dest/actions/rerun-epoch-proving-job.js +244 -24
  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 +95 -0
  10. package/dest/checkpoint-store.d.ts.map +1 -0
  11. package/dest/checkpoint-store.js +178 -0
  12. package/dest/config.d.ts +7 -8
  13. package/dest/config.d.ts.map +1 -1
  14. package/dest/config.js +24 -20
  15. package/dest/factory.d.ts +22 -13
  16. package/dest/factory.d.ts.map +1 -1
  17. package/dest/factory.js +41 -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 +165 -0
  22. package/dest/job/checkpoint-prover.d.ts.map +1 -0
  23. package/dest/job/checkpoint-prover.js +405 -0
  24. package/dest/job/epoch-session.d.ts +160 -0
  25. package/dest/job/epoch-session.d.ts.map +1 -0
  26. package/dest/job/{epoch-proving-job.js → epoch-session.js} +301 -298
  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 +101 -4
  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 -15
  40. package/dest/prover-node-publisher.d.ts.map +1 -1
  41. package/dest/prover-node-publisher.js +202 -63
  42. package/dest/prover-node.d.ts +146 -69
  43. package/dest/prover-node.d.ts.map +1 -1
  44. package/dest/prover-node.js +545 -221
  45. package/dest/prover-publisher-factory.d.ts +6 -4
  46. package/dest/prover-publisher-factory.d.ts.map +1 -1
  47. package/dest/prover-publisher-factory.js +4 -3
  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 +492 -0
  51. package/dest/test/index.d.ts +7 -6
  52. package/dest/test/index.d.ts.map +1 -1
  53. package/package.json +24 -22
  54. package/src/actions/download-epoch-proving-job.ts +1 -1
  55. package/src/actions/rerun-epoch-proving-job.ts +190 -31
  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 +212 -0
  59. package/src/config.ts +35 -32
  60. package/src/factory.ts +73 -111
  61. package/src/index.ts +1 -0
  62. package/src/job/checkpoint-prover.ts +538 -0
  63. package/src/job/epoch-session.ts +462 -0
  64. package/src/job/top-tree-job.ts +227 -0
  65. package/src/metrics.ts +123 -10
  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 +237 -79
  69. package/src/prover-node.ts +631 -248
  70. package/src/prover-publisher-factory.ts +8 -5
  71. package/src/session-manager.ts +592 -0
  72. package/src/test/index.ts +6 -6
  73. package/dest/job/epoch-proving-job.d.ts +0 -63
  74. package/dest/job/epoch-proving-job.d.ts.map +0 -1
  75. package/src/job/epoch-proving-job.ts +0 -435
@@ -0,0 +1,538 @@
1
+ import { type ARCHIVE_HEIGHT, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/constants';
2
+ import { BlockNumber, type EpochNumber, type SlotNumber } from '@aztec/foundation/branded-types';
3
+ import { padArrayEnd } from '@aztec/foundation/collection';
4
+ import { Fr } from '@aztec/foundation/curves/bn254';
5
+ import type { EthAddress } from '@aztec/foundation/eth-address';
6
+ import type { Logger } from '@aztec/foundation/log';
7
+ import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
8
+ import type { Tuple } from '@aztec/foundation/serialize';
9
+ import { type DateProvider, Timer } from '@aztec/foundation/timer';
10
+ import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
11
+ import { protocolContractsHash } from '@aztec/protocol-contracts';
12
+ import type { EpochProverFactory } from '@aztec/prover-client';
13
+ import type { CheckpointSubTreeOrchestrator, ChonkCache, SubTreeResult } from '@aztec/prover-client/orchestrator';
14
+ import type { PublicProcessor, PublicProcessorFactory } from '@aztec/simulator/server';
15
+ import { PublicSimulatorConfig } from '@aztec/stdlib/avm';
16
+ import type { CommitteeAttestation, L2Block } from '@aztec/stdlib/block';
17
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
18
+ import type { ForkMerkleTreeOperations, ITxProvider } from '@aztec/stdlib/interfaces/server';
19
+ import { CheckpointConstantData } from '@aztec/stdlib/rollup';
20
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
21
+ import type { BlockHeader, ProcessedTx, Tx, TxHash } from '@aztec/stdlib/tx';
22
+
23
+ import type { ProverNodeJobMetrics } from '../metrics.js';
24
+
25
+ /** Dependencies a `CheckpointProver` needs at construction. */
26
+ export type CheckpointProverDeps = {
27
+ proverFactory: EpochProverFactory;
28
+ /** Shared chonk-verifier cache. Survives across all sessions / epochs. */
29
+ chonkCache: ChonkCache;
30
+ publicProcessorFactory: PublicProcessorFactory;
31
+ dbProvider: Pick<ForkMerkleTreeOperations, 'fork'>;
32
+ txProvider: ITxProvider;
33
+ /** Clock the prover-node operates against — e2e fixtures inject a cheat-controlled one. */
34
+ dateProvider: DateProvider;
35
+ proverId: EthAddress;
36
+ metrics: ProverNodeJobMetrics;
37
+ /** Tx gathering deadline. */
38
+ txGatheringTimeoutMs: number;
39
+ /** Public processor deadline. */
40
+ deadline: Date | undefined;
41
+ /**
42
+ * Fired once when the prover's block proofs reject for a genuine (non-cancel) reason — a sub-tree
43
+ * fault or a prune-induced fork fault. Useful for performing post mortem on failures.
44
+ */
45
+ onFailed?: (prover: CheckpointProver) => void;
46
+ /**
47
+ * Test-only hook: if set, invoked at the start of checkpoint execution instead of proving. Lets e2e
48
+ * tests force a sub-tree failure (it should throw) to exercise the checkpoint failure/upload path.
49
+ */
50
+ checkpointProveOverride?: () => Promise<never>;
51
+ log: Logger;
52
+ };
53
+
54
+ /** Test-only hooks the store injects into every `CheckpointProver` it constructs. */
55
+ export type CheckpointProverTestHooks = {
56
+ /** If set, invoked at the start of checkpoint execution instead of proving; should throw to fail. */
57
+ checkpointProveOverride?: () => Promise<never>;
58
+ };
59
+
60
+ /** Inputs that fully describe a checkpoint at register time. */
61
+ export type CheckpointProverArgs = {
62
+ checkpoint: Checkpoint;
63
+ /** Epoch the checkpoint belongs to (derivable from slot + L1 constants; cached at register time). */
64
+ epochNumber: EpochNumber;
65
+ attestations: CommitteeAttestation[];
66
+ previousBlockHeader: BlockHeader;
67
+ l1ToL2Messages: Fr[];
68
+ previousArchiveSiblingPath: Tuple<Fr, typeof ARCHIVE_HEIGHT>;
69
+ };
70
+
71
+ /**
72
+ * Self-contained per-checkpoint prover, content-addressed by
73
+ * `(checkpoint number, slot number, checkpoint archive root)`.
74
+ *
75
+ * The store creates a CheckpointProver once per content-key. Keying on the checkpoint's
76
+ * own archive root (its post-state) means two checkpoints are "the same" iff they
77
+ * produce the same archive — so a reorg branch, or a replacement built on the same
78
+ * predecessor but with different content, keys to a distinct prover.
79
+ *
80
+ * The prover eagerly starts its own tx gather and sub-tree work in the constructor, so
81
+ * callers only need to call `whenBlockProofsReady()` to obtain the resulting block-rollup
82
+ * proofs.
83
+ *
84
+ * A CheckpointProver does not survive a prune: its sub-tree work forks world-state per
85
+ * block, and an L1 prune of a base block faults those reads. The store therefore cancels and
86
+ * discards a prover when its checkpoint is pruned, and a re-add (even of identical content)
87
+ * constructs a fresh prover.
88
+ *
89
+ * `cancel()` is idempotent. It aborts the gather + sub-tree, rejects the block-proof
90
+ * promise, and exposes a `whenDone()` that resolves once teardown has unwound.
91
+ */
92
+ export class CheckpointProver {
93
+ readonly id: string;
94
+ readonly checkpoint: Checkpoint;
95
+ readonly epochNumber: EpochNumber;
96
+ readonly slotNumber: SlotNumber;
97
+ readonly attestations: CommitteeAttestation[];
98
+ readonly previousBlockHeader: BlockHeader;
99
+ readonly l1ToL2Messages: Fr[];
100
+ readonly previousArchiveSiblingPath: Tuple<Fr, typeof ARCHIVE_HEIGHT>;
101
+
102
+ /** Resolved by the sub-tree on success, rejected on cancel/failure. */
103
+ private readonly blockProofs: PromiseWithResolvers<SubTreeResult['blockProofOutputs']> = promiseWithResolvers();
104
+
105
+ // Three independent lifecycle facts — deliberately not collapsed into one status enum, because several
106
+ // combinations are legal and relied on: a prover can be `completed` and then `cancelled` (routine
107
+ // teardown of an already-proven checkpoint), or `completed` and then `failed` (block proving was
108
+ // enqueued, but the sub-tree subsequently faulted). Only `failed` + `cancelled` is excluded — a cancel
109
+ // is not a failure (enforced in `failBlockProofs`).
110
+ /** Block-level proving was fully *enqueued* (a progress marker; the sub-tree may still be proving). */
111
+ private completed = false;
112
+ /** Block proofs rejected for a genuine (non-cancel) reason — a sub-tree or prune-induced fork fault. */
113
+ private failed = false;
114
+ /** The prover was torn down (prune / reap / shutdown). */
115
+ private cancelled = false;
116
+ private subTree?: CheckpointSubTreeOrchestrator;
117
+ private readonly abortController = new AbortController();
118
+
119
+ /** Tracks the eager gather+execute task so `cancel()` and `whenDone()` can await its unwind. */
120
+ private readonly runPromise: Promise<void>;
121
+ /** Tracks the cancel-driven teardown so `whenDone()` can await it. */
122
+ private cancelPromise?: Promise<void>;
123
+ /** Tracks the success-driven sub-tree teardown (once block proofs are captured) so `whenDone()` can await it. */
124
+ private teardownPromise?: Promise<void>;
125
+
126
+ constructor(
127
+ args: CheckpointProverArgs,
128
+ private readonly deps: CheckpointProverDeps,
129
+ ) {
130
+ this.checkpoint = args.checkpoint;
131
+ this.epochNumber = args.epochNumber;
132
+ this.slotNumber = args.checkpoint.header.slotNumber;
133
+ this.attestations = args.attestations;
134
+ this.previousBlockHeader = args.previousBlockHeader;
135
+ this.l1ToL2Messages = args.l1ToL2Messages;
136
+ this.previousArchiveSiblingPath = args.previousArchiveSiblingPath;
137
+ this.id = CheckpointProver.idFor(args.checkpoint);
138
+ // Mark blockProofs as observed so a cancel that lands before any consumer awaits
139
+ // does not surface as an unhandled rejection.
140
+ this.blockProofs.promise.catch(() => {});
141
+ deps.log.info(`Created CheckpointProver ${this.id}`, {
142
+ checkpointNumber: this.checkpoint.number,
143
+ epochNumber: this.epochNumber,
144
+ slotNumber: this.slotNumber,
145
+ blockCount: this.checkpoint.blocks.length,
146
+ l1ToL2MessageCount: this.l1ToL2Messages.length,
147
+ archiveRoot: this.checkpoint.archive.root.toString(),
148
+ });
149
+ // Kick off the eager gather + sub-tree pipeline.
150
+ this.runPromise = this.gatherAndExecute();
151
+ }
152
+
153
+ /**
154
+ * Stable content-addressed identifier: `${checkpoint number}:${slot}:${archive root}`.
155
+ * The archive root is the checkpoint's post-state, so it distinguishes any two
156
+ * checkpoints that differ in history or content while collapsing identical re-adds.
157
+ */
158
+ public static idFor(checkpoint: Checkpoint): string {
159
+ return `${checkpoint.number}:${checkpoint.header.slotNumber}:${checkpoint.archive.root.toString()}`;
160
+ }
161
+
162
+ public isCancelled(): boolean {
163
+ return this.cancelled;
164
+ }
165
+
166
+ /**
167
+ * True once this prover's block proofs have rejected for a genuine (non-cancel) reason — a sub-tree
168
+ * proving fault or a prune-induced world-state fork fault. A failed prover cannot produce its block
169
+ * proofs, so the reconciler must not build (or rebuild) an EpochSession over it; it is cleared only by
170
+ * a prune/re-add replacing it with a fresh prover, or by expiry reaping it.
171
+ */
172
+ public isFailed(): boolean {
173
+ return this.failed;
174
+ }
175
+
176
+ /** AbortSignal that fires on cancel — for callers that want to wire their own tasks. */
177
+ public getAbortSignal(): AbortSignal {
178
+ return this.abortController.signal;
179
+ }
180
+
181
+ /** Promise that resolves with the block-rollup proofs for this checkpoint (or rejects on cancel/failure). */
182
+ public whenBlockProofsReady(): Promise<SubTreeResult['blockProofOutputs']> {
183
+ return this.blockProofs.promise;
184
+ }
185
+
186
+ /** Resolves when all in-flight work for this prover has fully unwound. */
187
+ public async whenDone(): Promise<void> {
188
+ await this.runPromise.catch(() => {});
189
+ // `runPromise` resolves once block-level proving is *enqueued*, but the sub-tree's proofs (and the
190
+ // success-driven teardown they trigger) land later, on the `getSubTreeResult()` callback. Awaiting
191
+ // `blockProofs` here bridges that gap: on success the callback resolves `blockProofs` and then
192
+ // synchronously sets `teardownPromise` before this await resumes, so the teardown is observable
193
+ // below; on failure/cancel `blockProofs` rejects and teardown is driven by the `finally`/cancel
194
+ // paths already awaited via `runPromise`/`cancelPromise`.
195
+ await this.blockProofs.promise.catch(() => {});
196
+ if (this.cancelPromise) {
197
+ await this.cancelPromise;
198
+ }
199
+ if (this.teardownPromise) {
200
+ await this.teardownPromise;
201
+ }
202
+ }
203
+
204
+ private async gatherAndExecute(): Promise<void> {
205
+ try {
206
+ const txs = await this.gatherTxs();
207
+ if (this.cancelled) {
208
+ return;
209
+ }
210
+ await this.executeCheckpoint(txs);
211
+ } catch (err) {
212
+ if (this.cancelled) {
213
+ this.deps.log.debug(`CheckpointProver ${this.id} cancelled during gather/execute`, {
214
+ checkpointNumber: this.checkpoint.number,
215
+ });
216
+ return;
217
+ }
218
+ this.deps.log.error(`Error in CheckpointProver ${this.id}`, err, {
219
+ checkpointNumber: this.checkpoint.number,
220
+ });
221
+ this.failBlockProofs(err instanceof Error ? err : new Error(String(err)));
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Rejects the block-proof promise and, unless this is a cancellation, records the prover as failed so
227
+ * the reconciler won't build an EpochSession over it. First rejection wins, so a later duplicate reject
228
+ * (e.g. the executeCheckpoint `finally`) is a harmless no-op.
229
+ */
230
+ private failBlockProofs(err: Error): void {
231
+ if (!this.cancelled && !this.failed) {
232
+ this.failed = true;
233
+ // Notify the owner so it can upload a post-mortem for this checkpoint. Fire-and-forget: the
234
+ // callback must not block the prover's teardown, and a throw in it must not mask the rejection.
235
+ try {
236
+ this.deps.onFailed?.(this);
237
+ } catch (err) {
238
+ this.deps.log.error(`Error in CheckpointProver onFailed callback for ${this.id}`, err);
239
+ }
240
+ }
241
+ this.blockProofs.reject(err);
242
+ }
243
+
244
+ /** Fetches every tx in this checkpoint from the tx pool (by hash, via the block tx effects). */
245
+ private async fetchTxs(): Promise<{ txs: Map<string, Tx>; missingTxs: TxHash[] }> {
246
+ const deadline = new Date(this.deps.dateProvider.now() + this.deps.txGatheringTimeoutMs);
247
+ const txsByBlock = await Promise.all(
248
+ this.checkpoint.blocks.map(block => this.deps.txProvider.getTxsForBlock(block, { deadline })),
249
+ );
250
+ const txs = txsByBlock.flatMap(({ txs }) => txs);
251
+ const missingTxs = txsByBlock.flatMap(({ missingTxs }) => missingTxs);
252
+ return { txs: new Map<string, Tx>(txs.map(tx => [tx.getTxHash().toString(), tx])), missingTxs };
253
+ }
254
+
255
+ private async gatherTxs(): Promise<Map<string, Tx>> {
256
+ const { txs, missingTxs } = await this.fetchTxs();
257
+ if (missingTxs.length > 0) {
258
+ throw new Error(
259
+ `Txs not found for checkpoint ${this.checkpoint.number}: ${missingTxs.map(hash => hash.toString()).join(', ')}`,
260
+ );
261
+ }
262
+ return txs;
263
+ }
264
+
265
+ /**
266
+ * Re-fetches this checkpoint's txs from the tx pool for a post-mortem failure upload.
267
+ *
268
+ * The prover does not cache txs on the heap — they are consumed during proving and dropped — so the
269
+ * durable pool (which keeps a mined tx until L1 finality, with A-1274's retention margin covering a
270
+ * lagging prover) is the source of truth, read back by hash here. Best-effort: any tx the pool can
271
+ * no longer supply is logged and omitted rather than failing the upload, since a partial post-mortem
272
+ * snapshot is still useful for diagnosis.
273
+ */
274
+ public async getTxsForUpload(): Promise<Map<string, Tx>> {
275
+ const { txs, missingTxs } = await this.fetchTxs();
276
+ if (missingTxs.length > 0) {
277
+ this.deps.log.warn(
278
+ `Missing ${missingTxs.length} tx(s) re-fetching checkpoint ${this.checkpoint.number} for failure upload`,
279
+ { checkpointNumber: this.checkpoint.number, missingTxCount: missingTxs.length },
280
+ );
281
+ }
282
+ return txs;
283
+ }
284
+
285
+ private async executeCheckpoint(txs: Map<string, Tx>): Promise<void> {
286
+ const signal = this.abortController.signal;
287
+ const checkpointTimer = new Timer();
288
+ let subTreeStarted = false;
289
+
290
+ try {
291
+ // Test hook: force a sub-tree failure to exercise the checkpoint failure/upload path.
292
+ if (this.deps.checkpointProveOverride) {
293
+ await this.deps.checkpointProveOverride();
294
+ }
295
+
296
+ // The gathered txs are consumed locally below (public processing + sub-tree) and then dropped.
297
+ // They are deliberately not retained on the instance: the tx pool is the durable source and
298
+ // `getTxsForUpload` re-fetches them by hash if a post-mortem upload needs them.
299
+
300
+ const { chainId, version } = this.checkpoint.blocks[0].header.globalVariables;
301
+ const checkpointConstants = CheckpointConstantData.from({
302
+ chainId,
303
+ version,
304
+ vkTreeRoot: getVKTreeRoot(),
305
+ protocolContractsHash: protocolContractsHash,
306
+ proverId: this.deps.proverId.toField(),
307
+ slotNumber: this.checkpoint.header.slotNumber,
308
+ coinbase: this.checkpoint.header.coinbase,
309
+ feeRecipient: this.checkpoint.header.feeRecipient,
310
+ gasFees: this.checkpoint.header.gasFees,
311
+ });
312
+
313
+ this.deps.log.info(`Starting processing checkpoint ${this.checkpoint.number}`, {
314
+ checkpointNumber: this.checkpoint.number,
315
+ checkpointHash: this.checkpoint.hash().toString(),
316
+ blockCount: this.checkpoint.blocks.length,
317
+ });
318
+
319
+ this.subTree = await this.deps.proverFactory.createCheckpointSubTreeOrchestrator(
320
+ this.deps.chonkCache,
321
+ this.epochNumber,
322
+ checkpointConstants,
323
+ this.l1ToL2Messages,
324
+ this.checkpoint.blocks.length,
325
+ this.previousBlockHeader,
326
+ );
327
+ subTreeStarted = true;
328
+ // Bridge the sub-tree's result onto blockProofs.
329
+ void this.subTree.getSubTreeResult().then(
330
+ result => {
331
+ this.deps.log.info(`Sub-tree block proofs ready for checkpoint ${this.checkpoint.number}`, {
332
+ checkpointNumber: this.checkpoint.number,
333
+ blockProofCount: result.blockProofOutputs.length,
334
+ });
335
+ // Spans processing + proving (from executeCheckpoint start, after tx gathering) to proofs ready.
336
+ this.deps.metrics.recordCheckpointProving(checkpointTimer.ms());
337
+ this.blockProofs.resolve(result.blockProofOutputs);
338
+ // Release the sub-tree orchestrator now that its output is captured. The block-proof outputs
339
+ // survive via the resolved promise; everything else the sub-tree held — per-tx AVM inputs, and
340
+ // the base/merge/parity proof trees — is dead once proving completes, yet the prover is retained
341
+ // for the whole proof-submission window. Dropping it here is what stops that retention from
342
+ // accumulating across every proven checkpoint. Post-completion consumers (the top-tree job, a
343
+ // rebuilt EpochSession, failure upload) read only `whenBlockProofsReady()` and this prover's own
344
+ // fields (`checkpoint`, `txs`, headers, sibling paths), never the sub-tree.
345
+ this.teardownPromise = this.teardownSubTree();
346
+ },
347
+ err => this.failBlockProofs(err instanceof Error ? err : new Error(String(err))),
348
+ );
349
+ if (signal.aborted) {
350
+ return;
351
+ }
352
+
353
+ const allTxs = this.checkpoint.blocks.flatMap(block =>
354
+ block.body.txEffects.map(txEffect => txs.get(txEffect.txHash.toString())!),
355
+ );
356
+ const publicTxs = allTxs.filter(tx => tx?.data.forPublic);
357
+ if (publicTxs.length > 0) {
358
+ await this.subTree.startChonkVerifierCircuits(publicTxs);
359
+ if (signal.aborted) {
360
+ return;
361
+ }
362
+ }
363
+
364
+ for (let blockIndex = 0; blockIndex < this.checkpoint.blocks.length; blockIndex++) {
365
+ const blockTimer = new Timer();
366
+ const block = this.checkpoint.blocks[blockIndex];
367
+ const globalVariables = block.header.globalVariables;
368
+ const blockTxs = this.getTxsForBlock(block, txs);
369
+
370
+ await this.subTree.startNewBlock(block.number, globalVariables.timestamp, blockTxs.length);
371
+ if (signal.aborted) {
372
+ return;
373
+ }
374
+
375
+ const db = await this.createFork(
376
+ BlockNumber(block.number - 1),
377
+ blockIndex === 0 ? this.l1ToL2Messages : undefined,
378
+ );
379
+ try {
380
+ if (signal.aborted) {
381
+ return;
382
+ }
383
+ const config = PublicSimulatorConfig.from({
384
+ proverId: this.deps.proverId.toField(),
385
+ skipFeeEnforcement: false,
386
+ collectDebugLogs: false,
387
+ collectHints: true,
388
+ collectPublicInputs: true,
389
+ collectStatistics: false,
390
+ });
391
+ const publicProcessor = this.deps.publicProcessorFactory.create(db, globalVariables, config);
392
+ const processed = await this.processTxs(publicProcessor, blockTxs);
393
+ if (signal.aborted) {
394
+ return;
395
+ }
396
+ await this.subTree.addTxs(processed);
397
+ } finally {
398
+ await db.close();
399
+ }
400
+ if (signal.aborted) {
401
+ return;
402
+ }
403
+
404
+ await this.subTree.setBlockCompleted(block.number, block.header);
405
+ this.deps.metrics.recordBlockProcessing(blockTimer.ms());
406
+ if (signal.aborted) {
407
+ return;
408
+ }
409
+ }
410
+
411
+ this.completed = true;
412
+ const numTxs = this.checkpoint.blocks.reduce((acc, block) => acc + block.body.txEffects.length, 0);
413
+ this.deps.metrics.recordCheckpointProcessing(checkpointTimer.ms(), this.checkpoint.blocks.length, numTxs);
414
+ this.deps.log.info(
415
+ `Finished enqueueing block-level proving for checkpoint ${this.checkpoint.number} in ${checkpointTimer.ms()}ms`,
416
+ {
417
+ checkpointNumber: this.checkpoint.number,
418
+ blockCount: this.checkpoint.blocks.length,
419
+ durationMs: checkpointTimer.ms(),
420
+ },
421
+ );
422
+ } finally {
423
+ if (!this.completed) {
424
+ if (subTreeStarted) {
425
+ await this.teardownSubTree();
426
+ }
427
+ this.failBlockProofs(new Error(`Checkpoint ${this.id} did not complete block processing`));
428
+ }
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Mark cancelled. Idempotent. Aborts in-flight work, rejects the block-proof promise,
434
+ * and kicks off a background teardown of the sub-tree. The teardown promise is exposed
435
+ * via `whenDone()`.
436
+ *
437
+ * `routine` distinguishes a post-finalize teardown (sub-tree already proven, fires
438
+ * once at prover exit) from a real abort (reorg, prune, deadline). Behaviour is
439
+ * identical either way; the flag only adjusts log verbosity.
440
+ */
441
+ public cancel({ routine = false }: { routine?: boolean } = {}): void {
442
+ if (this.cancelled) {
443
+ return;
444
+ }
445
+ this.cancelled = true;
446
+ // A teardown of a completed prover is routine regardless of the caller's flag —
447
+ // we logged the work as done already, so don't relabel it as a mid-flight cancel.
448
+ if (routine || this.completed) {
449
+ this.deps.log.verbose(`Tearing down CheckpointProver ${this.id}`, {
450
+ checkpointNumber: this.checkpoint.number,
451
+ wasCompleted: this.completed,
452
+ });
453
+ } else {
454
+ this.deps.log.info(`Cancelling in-flight CheckpointProver ${this.id}`, {
455
+ checkpointNumber: this.checkpoint.number,
456
+ wasCompleted: this.completed,
457
+ });
458
+ }
459
+ this.abortController.abort();
460
+ this.blockProofs.reject(new Error(`Checkpoint ${this.id} cancelled`));
461
+ this.cancelPromise = this.runCancel().catch(() => {});
462
+ }
463
+
464
+ private async runCancel(): Promise<void> {
465
+ if (this.subTree) {
466
+ try {
467
+ this.subTree.cancel();
468
+ } catch (err) {
469
+ this.deps.log.error('Error cancelling sub-tree', err);
470
+ }
471
+ }
472
+ await this.runPromise.catch(() => {});
473
+ if (this.subTree) {
474
+ await this.teardownSubTree();
475
+ }
476
+ }
477
+
478
+ private async teardownSubTree(): Promise<void> {
479
+ const { subTree } = this;
480
+ this.subTree = undefined;
481
+ if (subTree) {
482
+ this.deps.log.debug(`Tearing down sub-tree for checkpoint ${this.checkpoint.number}`, {
483
+ checkpointNumber: this.checkpoint.number,
484
+ });
485
+ try {
486
+ await subTree.stop();
487
+ } catch (err) {
488
+ this.deps.log.error('Error stopping sub-tree', err);
489
+ }
490
+ }
491
+ }
492
+
493
+ private getTxsForBlock(block: L2Block, txs: Map<string, Tx>): Tx[] {
494
+ return block.body.txEffects.map(txEffect => txs.get(txEffect.txHash.toString())!);
495
+ }
496
+
497
+ private async processTxs(publicProcessor: PublicProcessor, txs: Tx[]): Promise<ProcessedTx[]> {
498
+ // Pass the abort signal so a prune-driven cancel stops the current block's public execution
499
+ // immediately, rather than running it to completion before the next `signal.aborted` check.
500
+ // On abort `process` returns a partial result, the length check below throws, and
501
+ // `gatherAndExecute` swallows it via its `cancelled` guard.
502
+ const [processedTxs, failedTxs] = await publicProcessor.process(txs, {
503
+ deadline: this.deps.deadline,
504
+ signal: this.abortController.signal,
505
+ });
506
+
507
+ if (failedTxs.length) {
508
+ const failedTxHashes = await Promise.all(failedTxs.map(({ tx }) => tx.getTxHash()));
509
+ throw new Error(
510
+ `Txs failed processing: ${failedTxs
511
+ .map(({ error }, index) => `${failedTxHashes[index]} (${error})`)
512
+ .join(', ')}`,
513
+ );
514
+ }
515
+
516
+ if (processedTxs.length !== txs.length) {
517
+ throw new Error(`Failed to process all txs: processed ${processedTxs.length} out of ${txs.length}`);
518
+ }
519
+
520
+ return processedTxs;
521
+ }
522
+
523
+ private async createFork(blockNumber: BlockNumber, l1ToL2Messages: Fr[] | undefined) {
524
+ const db = await this.deps.dbProvider.fork(blockNumber);
525
+
526
+ if (l1ToL2Messages !== undefined) {
527
+ const l1ToL2MessagesPadded = padArrayEnd<Fr, number>(
528
+ l1ToL2Messages,
529
+ Fr.ZERO,
530
+ NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
531
+ 'Too many L1 to L2 messages',
532
+ );
533
+ await db.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
534
+ }
535
+
536
+ return db;
537
+ }
538
+ }