@aztec/prover-node 0.0.1-commit.a89ec08 → 0.0.1-commit.aa0c64f

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 (74) 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 +245 -23
  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 +1 -3
  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 +4 -2
  13. package/dest/config.d.ts.map +1 -1
  14. package/dest/config.js +9 -2
  15. package/dest/factory.d.ts +4 -1
  16. package/dest/factory.d.ts.map +1 -1
  17. package/dest/factory.js +23 -8
  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 +154 -0
  22. package/dest/job/checkpoint-prover.d.ts.map +1 -0
  23. package/dest/job/checkpoint-prover.js +363 -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-session.js +744 -0
  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 +35 -8
  31. package/dest/metrics.d.ts.map +1 -1
  32. package/dest/metrics.js +86 -14
  33. package/dest/monitors/epoch-monitor.js +6 -2
  34. package/dest/proof-publishing-service.d.ts +161 -0
  35. package/dest/proof-publishing-service.d.ts.map +1 -0
  36. package/dest/proof-publishing-service.js +335 -0
  37. package/dest/prover-node-publisher.d.ts +25 -15
  38. package/dest/prover-node-publisher.d.ts.map +1 -1
  39. package/dest/prover-node-publisher.js +201 -62
  40. package/dest/prover-node.d.ts +134 -67
  41. package/dest/prover-node.d.ts.map +1 -1
  42. package/dest/prover-node.js +538 -219
  43. package/dest/prover-publisher-factory.d.ts +4 -2
  44. package/dest/prover-publisher-factory.d.ts.map +1 -1
  45. package/dest/prover-publisher-factory.js +4 -3
  46. package/dest/session-manager.d.ts +158 -0
  47. package/dest/session-manager.d.ts.map +1 -0
  48. package/dest/session-manager.js +486 -0
  49. package/dest/test/index.d.ts +7 -6
  50. package/dest/test/index.d.ts.map +1 -1
  51. package/package.json +24 -23
  52. package/src/actions/download-epoch-proving-job.ts +1 -1
  53. package/src/actions/rerun-epoch-proving-job.ts +190 -31
  54. package/src/actions/upload-epoch-proof-failure.ts +1 -1
  55. package/src/bin/run-failed-epoch.ts +1 -2
  56. package/src/checkpoint-store.ts +212 -0
  57. package/src/config.ts +13 -2
  58. package/src/factory.ts +23 -10
  59. package/src/index.ts +1 -0
  60. package/src/job/checkpoint-prover.ts +496 -0
  61. package/src/job/epoch-session.ts +462 -0
  62. package/src/job/top-tree-job.ts +227 -0
  63. package/src/metrics.ts +102 -23
  64. package/src/monitors/epoch-monitor.ts +2 -2
  65. package/src/proof-publishing-service.ts +427 -0
  66. package/src/prover-node-publisher.ts +236 -78
  67. package/src/prover-node.ts +621 -244
  68. package/src/prover-publisher-factory.ts +6 -3
  69. package/src/session-manager.ts +589 -0
  70. package/src/test/index.ts +6 -6
  71. package/dest/job/epoch-proving-job.d.ts +0 -63
  72. package/dest/job/epoch-proving-job.d.ts.map +0 -1
  73. package/dest/job/epoch-proving-job.js +0 -762
  74. package/src/job/epoch-proving-job.ts +0 -465
@@ -0,0 +1,496 @@
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 } 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
+ /** Per-prover tx map — populated by the internal gather. Empty until then. */
103
+ readonly txs: Map<string, Tx> = new Map();
104
+
105
+ /** Resolved by the sub-tree on success, rejected on cancel/failure. */
106
+ private readonly blockProofs: PromiseWithResolvers<SubTreeResult['blockProofOutputs']> = promiseWithResolvers();
107
+
108
+ // Three independent lifecycle facts — deliberately not collapsed into one status enum, because several
109
+ // combinations are legal and relied on: a prover can be `completed` and then `cancelled` (routine
110
+ // teardown of an already-proven checkpoint), or `completed` and then `failed` (block proving was
111
+ // enqueued, but the sub-tree subsequently faulted). Only `failed` + `cancelled` is excluded — a cancel
112
+ // is not a failure (enforced in `failBlockProofs`).
113
+ /** Block-level proving was fully *enqueued* (a progress marker; the sub-tree may still be proving). */
114
+ private completed = false;
115
+ /** Block proofs rejected for a genuine (non-cancel) reason — a sub-tree or prune-induced fork fault. */
116
+ private failed = false;
117
+ /** The prover was torn down (prune / reap / shutdown). */
118
+ private cancelled = false;
119
+ private subTree?: CheckpointSubTreeOrchestrator;
120
+ private readonly abortController = new AbortController();
121
+
122
+ /** Tracks the eager gather+execute task so `cancel()` and `whenDone()` can await its unwind. */
123
+ private readonly runPromise: Promise<void>;
124
+ /** Tracks the cancel-driven teardown so `whenDone()` can await it. */
125
+ private cancelPromise?: Promise<void>;
126
+
127
+ constructor(
128
+ args: CheckpointProverArgs,
129
+ private readonly deps: CheckpointProverDeps,
130
+ ) {
131
+ this.checkpoint = args.checkpoint;
132
+ this.epochNumber = args.epochNumber;
133
+ this.slotNumber = args.checkpoint.header.slotNumber;
134
+ this.attestations = args.attestations;
135
+ this.previousBlockHeader = args.previousBlockHeader;
136
+ this.l1ToL2Messages = args.l1ToL2Messages;
137
+ this.previousArchiveSiblingPath = args.previousArchiveSiblingPath;
138
+ this.id = CheckpointProver.idFor(args.checkpoint);
139
+ // Mark blockProofs as observed so a cancel that lands before any consumer awaits
140
+ // does not surface as an unhandled rejection.
141
+ this.blockProofs.promise.catch(() => {});
142
+ deps.log.info(`Created CheckpointProver ${this.id}`, {
143
+ checkpointNumber: this.checkpoint.number,
144
+ epochNumber: this.epochNumber,
145
+ slotNumber: this.slotNumber,
146
+ blockCount: this.checkpoint.blocks.length,
147
+ l1ToL2MessageCount: this.l1ToL2Messages.length,
148
+ archiveRoot: this.checkpoint.archive.root.toString(),
149
+ });
150
+ // Kick off the eager gather + sub-tree pipeline.
151
+ this.runPromise = this.gatherAndExecute();
152
+ }
153
+
154
+ /**
155
+ * Stable content-addressed identifier: `${checkpoint number}:${slot}:${archive root}`.
156
+ * The archive root is the checkpoint's post-state, so it distinguishes any two
157
+ * checkpoints that differ in history or content while collapsing identical re-adds.
158
+ */
159
+ public static idFor(checkpoint: Checkpoint): string {
160
+ return `${checkpoint.number}:${checkpoint.header.slotNumber}:${checkpoint.archive.root.toString()}`;
161
+ }
162
+
163
+ public isCancelled(): boolean {
164
+ return this.cancelled;
165
+ }
166
+
167
+ /**
168
+ * True once this prover's block proofs have rejected for a genuine (non-cancel) reason — a sub-tree
169
+ * proving fault or a prune-induced world-state fork fault. A failed prover cannot produce its block
170
+ * proofs, so the reconciler must not build (or rebuild) an EpochSession over it; it is cleared only by
171
+ * a prune/re-add replacing it with a fresh prover, or by expiry reaping it.
172
+ */
173
+ public isFailed(): boolean {
174
+ return this.failed;
175
+ }
176
+
177
+ /** AbortSignal that fires on cancel — for callers that want to wire their own tasks. */
178
+ public getAbortSignal(): AbortSignal {
179
+ return this.abortController.signal;
180
+ }
181
+
182
+ /** Promise that resolves with the block-rollup proofs for this checkpoint (or rejects on cancel/failure). */
183
+ public whenBlockProofsReady(): Promise<SubTreeResult['blockProofOutputs']> {
184
+ return this.blockProofs.promise;
185
+ }
186
+
187
+ /** Resolves when all in-flight work for this prover has fully unwound. */
188
+ public async whenDone(): Promise<void> {
189
+ await this.runPromise.catch(() => {});
190
+ if (this.cancelPromise) {
191
+ await this.cancelPromise;
192
+ }
193
+ }
194
+
195
+ private async gatherAndExecute(): Promise<void> {
196
+ try {
197
+ const txs = await this.gatherTxs();
198
+ if (this.cancelled) {
199
+ return;
200
+ }
201
+ await this.executeCheckpoint(txs);
202
+ } catch (err) {
203
+ if (this.cancelled) {
204
+ this.deps.log.debug(`CheckpointProver ${this.id} cancelled during gather/execute`, {
205
+ checkpointNumber: this.checkpoint.number,
206
+ });
207
+ return;
208
+ }
209
+ this.deps.log.error(`Error in CheckpointProver ${this.id}`, err, {
210
+ checkpointNumber: this.checkpoint.number,
211
+ });
212
+ this.failBlockProofs(err instanceof Error ? err : new Error(String(err)));
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Rejects the block-proof promise and, unless this is a cancellation, records the prover as failed so
218
+ * the reconciler won't build an EpochSession over it. First rejection wins, so a later duplicate reject
219
+ * (e.g. the executeCheckpoint `finally`) is a harmless no-op.
220
+ */
221
+ private failBlockProofs(err: Error): void {
222
+ if (!this.cancelled && !this.failed) {
223
+ this.failed = true;
224
+ // Notify the owner so it can upload a post-mortem for this checkpoint. Fire-and-forget: the
225
+ // callback must not block the prover's teardown, and a throw in it must not mask the rejection.
226
+ try {
227
+ this.deps.onFailed?.(this);
228
+ } catch (err) {
229
+ this.deps.log.error(`Error in CheckpointProver onFailed callback for ${this.id}`, err);
230
+ }
231
+ }
232
+ this.blockProofs.reject(err);
233
+ }
234
+
235
+ private async gatherTxs(): Promise<Map<string, Tx>> {
236
+ const deadline = new Date(this.deps.dateProvider.now() + this.deps.txGatheringTimeoutMs);
237
+ const txsByBlock = await Promise.all(
238
+ this.checkpoint.blocks.map(block => this.deps.txProvider.getTxsForBlock(block, { deadline })),
239
+ );
240
+ const txs = txsByBlock.map(({ txs }) => txs).flat();
241
+ const missingTxs = txsByBlock.map(({ missingTxs }) => missingTxs).flat();
242
+
243
+ if (missingTxs.length > 0) {
244
+ throw new Error(
245
+ `Txs not found for checkpoint ${this.checkpoint.number}: ${missingTxs.map(hash => hash.toString()).join(', ')}`,
246
+ );
247
+ }
248
+ return new Map<string, Tx>(txs.map(tx => [tx.getTxHash().toString(), tx]));
249
+ }
250
+
251
+ private async executeCheckpoint(txs: Map<string, Tx>): Promise<void> {
252
+ const signal = this.abortController.signal;
253
+ const checkpointTimer = new Timer();
254
+ let subTreeStarted = false;
255
+
256
+ try {
257
+ // Test hook: force a sub-tree failure to exercise the checkpoint failure/upload path.
258
+ if (this.deps.checkpointProveOverride) {
259
+ await this.deps.checkpointProveOverride();
260
+ }
261
+
262
+ for (const [hash, tx] of txs) {
263
+ this.txs.set(hash, tx);
264
+ }
265
+
266
+ const { chainId, version } = this.checkpoint.blocks[0].header.globalVariables;
267
+ const checkpointConstants = CheckpointConstantData.from({
268
+ chainId,
269
+ version,
270
+ vkTreeRoot: getVKTreeRoot(),
271
+ protocolContractsHash: protocolContractsHash,
272
+ proverId: this.deps.proverId.toField(),
273
+ slotNumber: this.checkpoint.header.slotNumber,
274
+ coinbase: this.checkpoint.header.coinbase,
275
+ feeRecipient: this.checkpoint.header.feeRecipient,
276
+ gasFees: this.checkpoint.header.gasFees,
277
+ });
278
+
279
+ this.deps.log.info(`Starting processing checkpoint ${this.checkpoint.number}`, {
280
+ checkpointNumber: this.checkpoint.number,
281
+ checkpointHash: this.checkpoint.hash().toString(),
282
+ blockCount: this.checkpoint.blocks.length,
283
+ });
284
+
285
+ this.subTree = await this.deps.proverFactory.createCheckpointSubTreeOrchestrator(
286
+ this.deps.chonkCache,
287
+ this.epochNumber,
288
+ checkpointConstants,
289
+ this.l1ToL2Messages,
290
+ this.checkpoint.blocks.length,
291
+ this.previousBlockHeader,
292
+ );
293
+ subTreeStarted = true;
294
+ // Bridge the sub-tree's result onto blockProofs.
295
+ void this.subTree.getSubTreeResult().then(
296
+ result => {
297
+ this.deps.log.info(`Sub-tree block proofs ready for checkpoint ${this.checkpoint.number}`, {
298
+ checkpointNumber: this.checkpoint.number,
299
+ blockProofCount: result.blockProofOutputs.length,
300
+ });
301
+ // Spans processing + proving (from executeCheckpoint start, after tx gathering) to proofs ready.
302
+ this.deps.metrics.recordCheckpointProving(checkpointTimer.ms());
303
+ this.blockProofs.resolve(result.blockProofOutputs);
304
+ },
305
+ err => this.failBlockProofs(err instanceof Error ? err : new Error(String(err))),
306
+ );
307
+ if (signal.aborted) {
308
+ return;
309
+ }
310
+
311
+ const allTxs = this.checkpoint.blocks.flatMap(block =>
312
+ block.body.txEffects.map(txEffect => txs.get(txEffect.txHash.toString())!),
313
+ );
314
+ const publicTxs = allTxs.filter(tx => tx?.data.forPublic);
315
+ if (publicTxs.length > 0) {
316
+ await this.subTree.startChonkVerifierCircuits(publicTxs);
317
+ if (signal.aborted) {
318
+ return;
319
+ }
320
+ }
321
+
322
+ for (let blockIndex = 0; blockIndex < this.checkpoint.blocks.length; blockIndex++) {
323
+ const blockTimer = new Timer();
324
+ const block = this.checkpoint.blocks[blockIndex];
325
+ const globalVariables = block.header.globalVariables;
326
+ const blockTxs = this.getTxsForBlock(block, txs);
327
+
328
+ await this.subTree.startNewBlock(block.number, globalVariables.timestamp, blockTxs.length);
329
+ if (signal.aborted) {
330
+ return;
331
+ }
332
+
333
+ const db = await this.createFork(
334
+ BlockNumber(block.number - 1),
335
+ blockIndex === 0 ? this.l1ToL2Messages : undefined,
336
+ );
337
+ try {
338
+ if (signal.aborted) {
339
+ return;
340
+ }
341
+ const config = PublicSimulatorConfig.from({
342
+ proverId: this.deps.proverId.toField(),
343
+ skipFeeEnforcement: false,
344
+ collectDebugLogs: false,
345
+ collectHints: true,
346
+ collectPublicInputs: true,
347
+ collectStatistics: false,
348
+ });
349
+ const publicProcessor = this.deps.publicProcessorFactory.create(db, globalVariables, config);
350
+ const processed = await this.processTxs(publicProcessor, blockTxs);
351
+ if (signal.aborted) {
352
+ return;
353
+ }
354
+ await this.subTree.addTxs(processed);
355
+ } finally {
356
+ await db.close();
357
+ }
358
+ if (signal.aborted) {
359
+ return;
360
+ }
361
+
362
+ await this.subTree.setBlockCompleted(block.number, block.header);
363
+ this.deps.metrics.recordBlockProcessing(blockTimer.ms());
364
+ if (signal.aborted) {
365
+ return;
366
+ }
367
+ }
368
+
369
+ this.completed = true;
370
+ const numTxs = this.checkpoint.blocks.reduce((acc, block) => acc + block.body.txEffects.length, 0);
371
+ this.deps.metrics.recordCheckpointProcessing(checkpointTimer.ms(), this.checkpoint.blocks.length, numTxs);
372
+ this.deps.log.info(
373
+ `Finished enqueueing block-level proving for checkpoint ${this.checkpoint.number} in ${checkpointTimer.ms()}ms`,
374
+ {
375
+ checkpointNumber: this.checkpoint.number,
376
+ blockCount: this.checkpoint.blocks.length,
377
+ durationMs: checkpointTimer.ms(),
378
+ },
379
+ );
380
+ } finally {
381
+ if (!this.completed) {
382
+ if (subTreeStarted) {
383
+ await this.teardownSubTree();
384
+ }
385
+ this.failBlockProofs(new Error(`Checkpoint ${this.id} did not complete block processing`));
386
+ }
387
+ }
388
+ }
389
+
390
+ /**
391
+ * Mark cancelled. Idempotent. Aborts in-flight work, rejects the block-proof promise,
392
+ * and kicks off a background teardown of the sub-tree. The teardown promise is exposed
393
+ * via `whenDone()`.
394
+ *
395
+ * `routine` distinguishes a post-finalize teardown (sub-tree already proven, fires
396
+ * once at prover exit) from a real abort (reorg, prune, deadline). Behaviour is
397
+ * identical either way; the flag only adjusts log verbosity.
398
+ */
399
+ public cancel({ routine = false }: { routine?: boolean } = {}): void {
400
+ if (this.cancelled) {
401
+ return;
402
+ }
403
+ this.cancelled = true;
404
+ // A teardown of a completed prover is routine regardless of the caller's flag —
405
+ // we logged the work as done already, so don't relabel it as a mid-flight cancel.
406
+ if (routine || this.completed) {
407
+ this.deps.log.verbose(`Tearing down CheckpointProver ${this.id}`, {
408
+ checkpointNumber: this.checkpoint.number,
409
+ wasCompleted: this.completed,
410
+ });
411
+ } else {
412
+ this.deps.log.info(`Cancelling in-flight CheckpointProver ${this.id}`, {
413
+ checkpointNumber: this.checkpoint.number,
414
+ wasCompleted: this.completed,
415
+ });
416
+ }
417
+ this.abortController.abort();
418
+ this.blockProofs.reject(new Error(`Checkpoint ${this.id} cancelled`));
419
+ this.cancelPromise = this.runCancel().catch(() => {});
420
+ }
421
+
422
+ private async runCancel(): Promise<void> {
423
+ if (this.subTree) {
424
+ try {
425
+ this.subTree.cancel();
426
+ } catch (err) {
427
+ this.deps.log.error('Error cancelling sub-tree', err);
428
+ }
429
+ }
430
+ await this.runPromise.catch(() => {});
431
+ if (this.subTree) {
432
+ await this.teardownSubTree();
433
+ }
434
+ }
435
+
436
+ private async teardownSubTree(): Promise<void> {
437
+ const { subTree } = this;
438
+ this.subTree = undefined;
439
+ if (subTree) {
440
+ this.deps.log.debug(`Tearing down sub-tree for checkpoint ${this.checkpoint.number}`, {
441
+ checkpointNumber: this.checkpoint.number,
442
+ });
443
+ try {
444
+ await subTree.stop();
445
+ } catch (err) {
446
+ this.deps.log.error('Error stopping sub-tree', err);
447
+ }
448
+ }
449
+ }
450
+
451
+ private getTxsForBlock(block: L2Block, txs: Map<string, Tx>): Tx[] {
452
+ return block.body.txEffects.map(txEffect => txs.get(txEffect.txHash.toString())!);
453
+ }
454
+
455
+ private async processTxs(publicProcessor: PublicProcessor, txs: Tx[]): Promise<ProcessedTx[]> {
456
+ // Pass the abort signal so a prune-driven cancel stops the current block's public execution
457
+ // immediately, rather than running it to completion before the next `signal.aborted` check.
458
+ // On abort `process` returns a partial result, the length check below throws, and
459
+ // `gatherAndExecute` swallows it via its `cancelled` guard.
460
+ const [processedTxs, failedTxs] = await publicProcessor.process(txs, {
461
+ deadline: this.deps.deadline,
462
+ signal: this.abortController.signal,
463
+ });
464
+
465
+ if (failedTxs.length) {
466
+ const failedTxHashes = await Promise.all(failedTxs.map(({ tx }) => tx.getTxHash()));
467
+ throw new Error(
468
+ `Txs failed processing: ${failedTxs
469
+ .map(({ error }, index) => `${failedTxHashes[index]} (${error})`)
470
+ .join(', ')}`,
471
+ );
472
+ }
473
+
474
+ if (processedTxs.length !== txs.length) {
475
+ throw new Error(`Failed to process all txs: processed ${processedTxs.length} out of ${txs.length}`);
476
+ }
477
+
478
+ return processedTxs;
479
+ }
480
+
481
+ private async createFork(blockNumber: BlockNumber, l1ToL2Messages: Fr[] | undefined) {
482
+ const db = await this.deps.dbProvider.fork(blockNumber);
483
+
484
+ if (l1ToL2Messages !== undefined) {
485
+ const l1ToL2MessagesPadded = padArrayEnd<Fr, number>(
486
+ l1ToL2Messages,
487
+ Fr.ZERO,
488
+ NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
489
+ 'Too many L1 to L2 messages',
490
+ );
491
+ await db.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
492
+ }
493
+
494
+ return db;
495
+ }
496
+ }