@aztec/prover-client 0.0.1-commit.f2ce05ee → 0.0.1-commit.f5a9928

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 (113) hide show
  1. package/dest/config.d.ts +1 -1
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +16 -2
  4. package/dest/light/lightweight_checkpoint_builder.d.ts +10 -5
  5. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -1
  6. package/dest/light/lightweight_checkpoint_builder.js +56 -23
  7. package/dest/mocks/test_context.d.ts +11 -11
  8. package/dest/mocks/test_context.d.ts.map +1 -1
  9. package/dest/mocks/test_context.js +30 -30
  10. package/dest/orchestrator/block-building-helpers.d.ts +4 -4
  11. package/dest/orchestrator/block-building-helpers.d.ts.map +1 -1
  12. package/dest/orchestrator/block-building-helpers.js +2 -2
  13. package/dest/orchestrator/block-proving-state.d.ts +4 -1
  14. package/dest/orchestrator/block-proving-state.d.ts.map +1 -1
  15. package/dest/orchestrator/block-proving-state.js +7 -0
  16. package/dest/orchestrator/checkpoint-proving-state.d.ts +20 -36
  17. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -1
  18. package/dest/orchestrator/checkpoint-proving-state.js +22 -120
  19. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts +161 -0
  20. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts.map +1 -0
  21. package/dest/orchestrator/{orchestrator.js → checkpoint-sub-tree-orchestrator.js} +285 -462
  22. package/dest/orchestrator/chonk-cache.d.ts +39 -0
  23. package/dest/orchestrator/chonk-cache.d.ts.map +1 -0
  24. package/dest/orchestrator/chonk-cache.js +80 -0
  25. package/dest/orchestrator/index.d.ts +4 -2
  26. package/dest/orchestrator/index.d.ts.map +1 -1
  27. package/dest/orchestrator/index.js +3 -1
  28. package/dest/orchestrator/proving-scheduler.d.ts +81 -0
  29. package/dest/orchestrator/proving-scheduler.d.ts.map +1 -0
  30. package/dest/orchestrator/proving-scheduler.js +120 -0
  31. package/dest/orchestrator/top-tree-orchestrator.d.ts +88 -0
  32. package/dest/orchestrator/top-tree-orchestrator.d.ts.map +1 -0
  33. package/dest/orchestrator/top-tree-orchestrator.js +232 -0
  34. package/dest/orchestrator/top-tree-proving-state.d.ts +61 -0
  35. package/dest/orchestrator/top-tree-proving-state.d.ts.map +1 -0
  36. package/dest/orchestrator/top-tree-proving-state.js +185 -0
  37. package/dest/orchestrator/tx-proving-state.d.ts +3 -3
  38. package/dest/orchestrator/tx-proving-state.d.ts.map +1 -1
  39. package/dest/prover-client/prover-client.d.ts +62 -5
  40. package/dest/prover-client/prover-client.d.ts.map +1 -1
  41. package/dest/prover-client/prover-client.js +54 -7
  42. package/dest/proving_broker/broker_prover_facade.d.ts +3 -3
  43. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -1
  44. package/dest/proving_broker/broker_prover_facade.js +26 -20
  45. package/dest/proving_broker/config.d.ts +9 -73
  46. package/dest/proving_broker/config.d.ts.map +1 -1
  47. package/dest/proving_broker/config.js +3 -3
  48. package/dest/proving_broker/index.d.ts +2 -1
  49. package/dest/proving_broker/index.d.ts.map +1 -1
  50. package/dest/proving_broker/index.js +1 -0
  51. package/dest/proving_broker/proving_broker.d.ts +3 -2
  52. package/dest/proving_broker/proving_broker.d.ts.map +1 -1
  53. package/dest/proving_broker/proving_broker.js +217 -70
  54. package/dest/proving_broker/proving_broker_database/memory.d.ts +5 -2
  55. package/dest/proving_broker/proving_broker_database/memory.d.ts.map +1 -1
  56. package/dest/proving_broker/proving_broker_database/memory.js +14 -1
  57. package/dest/proving_broker/proving_broker_database/persisted.d.ts +15 -2
  58. package/dest/proving_broker/proving_broker_database/persisted.d.ts.map +1 -1
  59. package/dest/proving_broker/proving_broker_database/persisted.js +57 -6
  60. package/dest/proving_broker/proving_broker_database.d.ts +27 -1
  61. package/dest/proving_broker/proving_broker_database.d.ts.map +1 -1
  62. package/dest/proving_broker/proving_broker_instrumentation.d.ts +3 -1
  63. package/dest/proving_broker/proving_broker_instrumentation.d.ts.map +1 -1
  64. package/dest/proving_broker/proving_broker_instrumentation.js +7 -0
  65. package/dest/proving_broker/rpc.d.ts +3 -1
  66. package/dest/proving_broker/rpc.d.ts.map +1 -1
  67. package/dest/proving_broker/rpc.js +80 -24
  68. package/dest/test/epoch_settlement.d.ts +36 -0
  69. package/dest/test/epoch_settlement.d.ts.map +1 -0
  70. package/dest/test/epoch_settlement.js +52 -0
  71. package/dest/test/index.d.ts +2 -0
  72. package/dest/test/index.d.ts.map +1 -0
  73. package/dest/test/index.js +1 -0
  74. package/dest/test/mock_prover.d.ts +4 -4
  75. package/dest/test/mock_prover.js +2 -2
  76. package/package.json +20 -20
  77. package/src/config.ts +18 -2
  78. package/src/light/lightweight_checkpoint_builder.ts +58 -25
  79. package/src/mocks/test_context.ts +26 -43
  80. package/src/orchestrator/block-building-helpers.ts +2 -2
  81. package/src/orchestrator/block-proving-state.ts +9 -0
  82. package/src/orchestrator/checkpoint-proving-state.ts +21 -162
  83. package/src/orchestrator/checkpoint-sub-tree-orchestrator.ts +1044 -0
  84. package/src/orchestrator/chonk-cache.ts +99 -0
  85. package/src/orchestrator/index.ts +8 -1
  86. package/src/orchestrator/proving-scheduler.ts +160 -0
  87. package/src/orchestrator/top-tree-orchestrator.ts +384 -0
  88. package/src/orchestrator/top-tree-proving-state.ts +219 -0
  89. package/src/orchestrator/tx-proving-state.ts +3 -3
  90. package/src/prover-client/prover-client.ts +129 -18
  91. package/src/proving_broker/broker_prover_facade.ts +29 -23
  92. package/src/proving_broker/config.ts +3 -2
  93. package/src/proving_broker/index.ts +1 -0
  94. package/src/proving_broker/proving_broker.ts +208 -72
  95. package/src/proving_broker/proving_broker_database/memory.ts +16 -2
  96. package/src/proving_broker/proving_broker_database/persisted.ts +71 -8
  97. package/src/proving_broker/proving_broker_database.ts +30 -0
  98. package/src/proving_broker/proving_broker_instrumentation.ts +9 -0
  99. package/src/proving_broker/rpc.ts +36 -24
  100. package/src/test/epoch_settlement.ts +82 -0
  101. package/src/test/index.ts +1 -0
  102. package/src/test/mock_prover.ts +2 -2
  103. package/dest/orchestrator/epoch-proving-state.d.ts +0 -75
  104. package/dest/orchestrator/epoch-proving-state.d.ts.map +0 -1
  105. package/dest/orchestrator/epoch-proving-state.js +0 -267
  106. package/dest/orchestrator/orchestrator.d.ts +0 -128
  107. package/dest/orchestrator/orchestrator.d.ts.map +0 -1
  108. package/dest/prover-client/server-epoch-prover.d.ts +0 -32
  109. package/dest/prover-client/server-epoch-prover.d.ts.map +0 -1
  110. package/dest/prover-client/server-epoch-prover.js +0 -40
  111. package/src/orchestrator/epoch-proving-state.ts +0 -378
  112. package/src/orchestrator/orchestrator.ts +0 -1281
  113. package/src/prover-client/server-epoch-prover.ts +0 -69
@@ -0,0 +1,1044 @@
1
+ import type { SpongeBlob } from '@aztec/blob-lib/types';
2
+ import {
3
+ type ARCHIVE_HEIGHT,
4
+ L1_TO_L2_MSG_SUBTREE_HEIGHT,
5
+ L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH,
6
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
7
+ NUM_BASE_PARITY_PER_ROOT_PARITY,
8
+ } from '@aztec/constants';
9
+ import { BlockNumber, type EpochNumber } from '@aztec/foundation/branded-types';
10
+ import { Fr } from '@aztec/foundation/curves/bn254';
11
+ import { AbortError } from '@aztec/foundation/error';
12
+ import type { LoggerBindings } from '@aztec/foundation/log';
13
+ import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
14
+ import type { SerialQueue } from '@aztec/foundation/queue';
15
+ import { type Tuple, assertLength } from '@aztec/foundation/serialize';
16
+ import type { TreeNodeLocation } from '@aztec/foundation/trees';
17
+ import { EthAddress } from '@aztec/stdlib/block';
18
+ import type {
19
+ ForkMerkleTreeOperations,
20
+ MerkleTreeWriteOperations,
21
+ PublicInputsAndRecursiveProof,
22
+ ReadonlyWorldStateAccess,
23
+ ServerCircuitProver,
24
+ } from '@aztec/stdlib/interfaces/server';
25
+ import { appendL1ToL2MessagesToTree } from '@aztec/stdlib/messaging';
26
+ import {
27
+ type BaseRollupHints,
28
+ type BlockRollupPublicInputs,
29
+ BlockRootEmptyTxFirstRollupPrivateInputs,
30
+ BlockRootFirstRollupPrivateInputs,
31
+ BlockRootSingleTxFirstRollupPrivateInputs,
32
+ BlockRootSingleTxRollupPrivateInputs,
33
+ CheckpointConstantData,
34
+ PrivateTxBaseRollupPrivateInputs,
35
+ type PublicChonkVerifierPublicInputs,
36
+ } from '@aztec/stdlib/rollup';
37
+ import type { CircuitName } from '@aztec/stdlib/stats';
38
+ import { type AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
39
+ import type { BlockHeader, ProcessedTx, Tx } from '@aztec/stdlib/tx';
40
+ import type { UInt64 } from '@aztec/stdlib/types';
41
+ import {
42
+ Attributes,
43
+ type TelemetryClient,
44
+ type Tracer,
45
+ getTelemetryClient,
46
+ trackSpan,
47
+ wrapCallbackInSpan,
48
+ } from '@aztec/telemetry-client';
49
+
50
+ import { inspect } from 'util';
51
+
52
+ import {
53
+ buildHeaderFromCircuitOutputs,
54
+ getLastSiblingPath,
55
+ getPublicChonkVerifierPrivateInputsFromTx,
56
+ getRootTreeSiblingPath,
57
+ getSubtreeSiblingPath,
58
+ getTreeSnapshot,
59
+ insertSideEffectsAndBuildBaseRollupHints,
60
+ validatePartialState,
61
+ validateTx,
62
+ } from './block-building-helpers.js';
63
+ import type { BlockProvingState } from './block-proving-state.js';
64
+ import { CheckpointProvingState } from './checkpoint-proving-state.js';
65
+ import type { ChonkCache } from './chonk-cache.js';
66
+ import { ProvingOrchestratorMetrics } from './orchestrator_metrics.js';
67
+ import { ProvingScheduler } from './proving-scheduler.js';
68
+ import { TxProvingState } from './tx-proving-state.js';
69
+
70
+ /**
71
+ * Result of proving a single checkpoint's block-level sub-tree.
72
+ *
73
+ * Contains the final block-rollup proof outputs that feed the checkpoint root rollup,
74
+ * plus the archive sibling path captured before any block in the checkpoint landed
75
+ * (the top-tree needs this to assemble the checkpoint root rollup hints).
76
+ */
77
+ export type SubTreeResult = {
78
+ blockProofOutputs: PublicInputsAndRecursiveProof<
79
+ BlockRollupPublicInputs,
80
+ typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH
81
+ >[];
82
+ previousArchiveSiblingPath: Tuple<Fr, typeof ARCHIVE_HEIGHT>;
83
+ };
84
+
85
+ type TreeSnapshots = Map<MerkleTreeId, AppendOnlyTreeSnapshot>;
86
+
87
+ /**
88
+ * Base rollup hints as produced before proving: `PrivateBaseRollupHints` / `PublicBaseRollupHints`
89
+ * deliberately carry no recursive proof or verification key. The proof + VK are supplied later, when
90
+ * `TxProvingState.getBaseRollupTypeAndInputs` wraps these hints into the "with proof + VK" types —
91
+ * `PrivateTxBaseRollupPrivateInputs` (a `ChonkProofData`) or `PublicTxBaseRollupPrivateInputs` (a
92
+ * chonk-verifier proof + AVM proof). Those proofs are *required constructor arguments* of the wrapper
93
+ * types, so the only way to obtain a provable input is to populate them — they cannot be silently
94
+ * omitted. Naming the proof-less hints type here makes that boundary explicit at `prepareBaseRollupInputs`.
95
+ */
96
+ type BaseRollupHintsWithoutProofAndVK = BaseRollupHints;
97
+
98
+ /**
99
+ * Orchestrates block-level proving for a single checkpoint, stopping at the boundary
100
+ * where checkpoint root rollup would otherwise begin. Used by the per-checkpoint
101
+ * `CheckpointProver` in production; the top-tree orchestrator then composes the
102
+ * sub-tree's block proofs into the epoch proof.
103
+ *
104
+ * Wiring: a single-checkpoint mini-proving session is owned by the constructor. The
105
+ * canonical way to obtain a fully-started sub-tree is the `start` static factory,
106
+ * which also drives the single internal `startCheckpoint` call. The sub-tree never
107
+ * escalates past the checkpoint root boundary; `getSubTreeResult()` resolves once
108
+ * every block-level proof in the checkpoint's tree is ready.
109
+ */
110
+ export class CheckpointSubTreeOrchestrator extends ProvingScheduler {
111
+ /** The single checkpoint proving state this sub-tree owns. Allocated in the `start` factory. */
112
+ protected provingState: CheckpointProvingState | undefined = undefined;
113
+ private readonly subTreeResult: PromiseWithResolvers<SubTreeResult>;
114
+ private readonly metrics: ProvingOrchestratorMetrics;
115
+ private dbs: Map<BlockNumber, MerkleTreeWriteOperations> = new Map();
116
+
117
+ constructor(
118
+ private readonly dbProvider: ReadonlyWorldStateAccess & ForkMerkleTreeOperations,
119
+ protected readonly prover: ServerCircuitProver,
120
+ private readonly proverId: EthAddress,
121
+ /**
122
+ * Shared chonk-verifier proof cache. Every chonk-verifier proof started by this
123
+ * sub-tree lives on the cache and survives the sub-tree's cancellation, so a tx
124
+ * whose original checkpoint is reorged out and re-appears in a replacement
125
+ * checkpoint reuses the cached proof.
126
+ */
127
+ private readonly chonkCache: ChonkCache,
128
+ /** The epoch this sub-tree proves into. */
129
+ private readonly epochNumber: EpochNumber,
130
+ private readonly cancelJobsOnStop: boolean = false,
131
+ deferredJobQueue: SerialQueue,
132
+ telemetryClient: TelemetryClient = getTelemetryClient(),
133
+ bindings?: LoggerBindings,
134
+ ) {
135
+ super(deferredJobQueue, 'prover-client:checkpoint-sub-tree-orchestrator', bindings);
136
+ this.metrics = new ProvingOrchestratorMetrics(telemetryClient, 'CheckpointSubTreeOrchestrator');
137
+
138
+ this.subTreeResult = promiseWithResolvers<SubTreeResult>();
139
+ // Mark the rejection branch as observed so a `cancel()` or proving failure does not
140
+ // surface an unhandled rejection when no consumer awaits getSubTreeResult().
141
+ this.subTreeResult.promise.catch(() => {});
142
+ }
143
+
144
+ /** Tracks whether `cancel()` has been called; flows into the checkpoint state's isAlive hook. */
145
+ private cancelled = false;
146
+
147
+ public get tracer(): Tracer {
148
+ return this.metrics.tracer;
149
+ }
150
+
151
+ public getProverId(): EthAddress {
152
+ return this.proverId;
153
+ }
154
+
155
+ public getNumActiveForks(): number {
156
+ return this.dbs.size;
157
+ }
158
+
159
+ /** Returns a promise that resolves when block-level proving completes for the checkpoint. */
160
+ public getSubTreeResult(): Promise<SubTreeResult> {
161
+ return this.subTreeResult.promise;
162
+ }
163
+
164
+ /**
165
+ * Returns the archive sibling path captured at the internal checkpoint start.
166
+ * Available synchronously once `start` has resolved, before block-level proving
167
+ * completes. The top-tree consumer uses this to assemble checkpoint root rollup hints
168
+ * up-front so checkpoint root proofs can pipeline against in-flight sub-tree proving.
169
+ */
170
+ public getPreviousArchiveSiblingPath(): Tuple<Fr, typeof ARCHIVE_HEIGHT> {
171
+ if (!this.provingState) {
172
+ throw new Error('Checkpoint not started; call CheckpointSubTreeOrchestrator.start first.');
173
+ }
174
+ return this.provingState.getLastArchiveSiblingPath();
175
+ }
176
+
177
+ /**
178
+ * Constructs and starts a sub-tree for a single checkpoint. The returned sub-tree
179
+ * has had its single internal checkpoint state allocated; callers proceed directly
180
+ * to per-block `startNewBlock` / `addTxs` / `setBlockCompleted`.
181
+ *
182
+ * If the internal start rejects, the partially-constructed sub-tree is stopped
183
+ * before the error propagates, so no broker resources leak.
184
+ */
185
+ public static async start(
186
+ dbProvider: ReadonlyWorldStateAccess & ForkMerkleTreeOperations,
187
+ prover: ServerCircuitProver,
188
+ proverId: EthAddress,
189
+ chonkCache: ChonkCache,
190
+ epochNumber: EpochNumber,
191
+ cancelJobsOnStop: boolean,
192
+ deferredJobQueue: SerialQueue,
193
+ checkpointConstants: CheckpointConstantData,
194
+ l1ToL2Messages: Fr[],
195
+ totalNumBlocks: number,
196
+ headerOfLastBlockInPreviousCheckpoint: BlockHeader,
197
+ telemetryClient: TelemetryClient = getTelemetryClient(),
198
+ bindings?: LoggerBindings,
199
+ ): Promise<CheckpointSubTreeOrchestrator> {
200
+ const subTree = new CheckpointSubTreeOrchestrator(
201
+ dbProvider,
202
+ prover,
203
+ proverId,
204
+ chonkCache,
205
+ epochNumber,
206
+ cancelJobsOnStop,
207
+ deferredJobQueue,
208
+ telemetryClient,
209
+ bindings,
210
+ );
211
+ try {
212
+ await subTree.startCheckpoint(
213
+ checkpointConstants,
214
+ l1ToL2Messages,
215
+ totalNumBlocks,
216
+ headerOfLastBlockInPreviousCheckpoint,
217
+ );
218
+ return subTree;
219
+ } catch (err) {
220
+ await subTree.stop().catch(() => {});
221
+ throw err;
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Kickstart chonk-verifier circuits via the shared `ChonkCache`. The cache owns the
227
+ * broker job lifecycle, so the proof survives this sub-tree's `cancel()` — a tx that
228
+ * ends up in a replacement checkpoint after a reorg can pick the cached promise up
229
+ * and skip re-proving.
230
+ */
231
+ public startChonkVerifierCircuits(txs: Tx[]): Promise<void> {
232
+ if (!this.provingState?.verifyState()) {
233
+ return Promise.reject(new Error('Sub-tree proving state is not active.'));
234
+ }
235
+ const publicTxs = txs.filter(tx => tx.data.forPublic);
236
+ for (const tx of publicTxs) {
237
+ const txHash = tx.getTxHash().toString();
238
+ const inputs = getPublicChonkVerifierPrivateInputsFromTx(tx, this.getProverId().toField());
239
+ // Fire and forget — getOrEnqueueChonkVerifier later picks up the cached promise
240
+ // when the tx is processed inside its block.
241
+ void this.chonkCache.getOrCompute(txHash, signal =>
242
+ this.prover.getPublicChonkVerifierProof(inputs, signal, this.epochNumber),
243
+ );
244
+ }
245
+ return Promise.resolve();
246
+ }
247
+
248
+ // ---------------- per-block driving (called by the per-checkpoint CheckpointProver) ----------------
249
+
250
+ /**
251
+ * Starts off a new block.
252
+ * @param blockNumber - The block number
253
+ * @param timestamp - The timestamp of the block. Required for empty blocks to construct private inputs.
254
+ * @param totalNumTxs - The total number of txs in the block.
255
+ */
256
+ @trackSpan('CheckpointSubTreeOrchestrator.startNewBlock', blockNumber => ({
257
+ [Attributes.BLOCK_NUMBER]: blockNumber,
258
+ }))
259
+ public async startNewBlock(blockNumber: BlockNumber, timestamp: UInt64, totalNumTxs: number) {
260
+ if (!this.provingState) {
261
+ throw new Error('Empty proving state. The checkpoint sub-tree has not been started.');
262
+ }
263
+
264
+ if (!this.provingState.isAcceptingBlocks()) {
265
+ throw new Error(`Checkpoint not accepting further blocks.`);
266
+ }
267
+
268
+ const constants = this.provingState.constants;
269
+ this.logger.info(`Starting block ${blockNumber} for slot ${constants.slotNumber}.`);
270
+
271
+ // Fork the db only when it's not already set. The db for the first block is set in startCheckpoint.
272
+ if (!this.dbs.has(blockNumber)) {
273
+ // Fork world state at the end of the immediately previous block.
274
+ const db = await this.dbProvider.fork(BlockNumber(blockNumber - 1));
275
+ this.dbs.set(blockNumber, db);
276
+ }
277
+ const db = this.getDbForBlock(blockNumber);
278
+
279
+ // Get archive snapshot and sibling path before any txs in this block lands.
280
+ const lastArchiveTreeSnapshot = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
281
+ const lastArchiveSiblingPath = await getRootTreeSiblingPath(MerkleTreeId.ARCHIVE, db);
282
+
283
+ const blockProvingState = this.provingState.startNewBlock(
284
+ blockNumber,
285
+ timestamp,
286
+ totalNumTxs,
287
+ lastArchiveTreeSnapshot,
288
+ lastArchiveSiblingPath,
289
+ );
290
+
291
+ // Enqueue base parity circuits for the first block in the checkpoint.
292
+ if (blockProvingState.index === 0) {
293
+ for (let i = 0; i < NUM_BASE_PARITY_PER_ROOT_PARITY; i++) {
294
+ this.enqueueBaseParityCircuit(this.provingState, blockProvingState, i);
295
+ }
296
+ }
297
+
298
+ // Because `addTxs` won't be called for a block without txs, and that's where the sponge blob state is computed,
299
+ // set its end sponge blob here. This becomes the start sponge blob for the next block.
300
+ if (totalNumTxs === 0) {
301
+ const endState = await db.getStateReference();
302
+ blockProvingState.setEndState(endState);
303
+
304
+ const endSpongeBlob = blockProvingState.getStartSpongeBlob().clone();
305
+ const blockEndBlobFields = blockProvingState.getBlockEndBlobFields();
306
+ await endSpongeBlob.absorb(blockEndBlobFields);
307
+ blockProvingState.setEndSpongeBlob(endSpongeBlob);
308
+ }
309
+ }
310
+
311
+ /**
312
+ * The interface to add simulated transactions to the scheduler. Called at most once per block.
313
+ * @param txs - The transactions to be proven
314
+ */
315
+ @trackSpan('CheckpointSubTreeOrchestrator.addTxs', txs => ({
316
+ [Attributes.BLOCK_TXS_COUNT]: txs.length,
317
+ }))
318
+ public async addTxs(txs: ProcessedTx[]): Promise<void> {
319
+ if (!this.provingState) {
320
+ throw new Error(`Empty proving state. The checkpoint sub-tree has not been started.`);
321
+ }
322
+
323
+ if (!txs.length) {
324
+ // Empty block: setBlockCompleted handles this without addTxs being called. Bail to
325
+ // avoid the throw below (we cannot find the blockNumber without any txs).
326
+ this.logger.verbose(`Provided no txs to addTxs.`);
327
+ return;
328
+ }
329
+
330
+ const blockNumber = BlockNumber(txs[0].globalVariables.blockNumber);
331
+ const provingState = this.provingState.getBlockProvingStateByBlockNumber(blockNumber!);
332
+ if (!provingState) {
333
+ throw new Error(`Proving state for block ${blockNumber} not found. Call startNewBlock first.`);
334
+ }
335
+
336
+ if (provingState.totalNumTxs !== txs.length) {
337
+ throw new Error(
338
+ `Block ${blockNumber} should be filled with ${provingState.totalNumTxs} txs. Received ${txs.length} txs.`,
339
+ );
340
+ }
341
+
342
+ if (!provingState.isAcceptingTxs()) {
343
+ throw new Error(`Block ${blockNumber} has been initialized with transactions.`);
344
+ }
345
+
346
+ this.logger.info(`Adding ${txs.length} transactions to block ${blockNumber}`);
347
+
348
+ const db = this.getDbForBlock(blockNumber);
349
+ const lastArchive = provingState.lastArchiveTreeSnapshot;
350
+ const newL1ToL2MessageTreeSnapshot = provingState.newL1ToL2MessageTreeSnapshot;
351
+ const spongeBlobState = provingState.getStartSpongeBlob().clone();
352
+
353
+ for (const tx of txs) {
354
+ try {
355
+ if (!provingState.verifyState()) {
356
+ throw new Error(`Invalid proving state when adding a tx`);
357
+ }
358
+
359
+ validateTx(tx);
360
+
361
+ this.logger.debug(`Received transaction: ${tx.hash}`);
362
+
363
+ const startSpongeBlob = spongeBlobState.clone();
364
+ const [hints, treeSnapshots] = await this.prepareBaseRollupInputs(
365
+ tx,
366
+ lastArchive,
367
+ newL1ToL2MessageTreeSnapshot,
368
+ startSpongeBlob,
369
+ db,
370
+ );
371
+
372
+ if (!provingState.verifyState()) {
373
+ throw new Error(`Unable to add transaction, preparing base inputs failed`);
374
+ }
375
+
376
+ await spongeBlobState.absorb(tx.txEffect.toBlobFields());
377
+
378
+ const txProvingState = new TxProvingState(tx, hints, treeSnapshots, this.proverId.toField());
379
+ const txIndex = provingState.addNewTx(txProvingState);
380
+ if (txProvingState.requireAvmProof) {
381
+ this.getOrEnqueueChonkVerifier(provingState, txIndex);
382
+ this.logger.debug(`Enqueueing public VM for tx ${txIndex}`);
383
+ this.enqueueVM(provingState, txIndex);
384
+ } else {
385
+ this.logger.debug(`Enqueueing base rollup for private-only tx ${txIndex}`);
386
+ this.enqueueBaseRollup(provingState, txIndex);
387
+ }
388
+ } catch (err: any) {
389
+ throw new Error(`Error adding transaction ${tx.hash.toString()} to block ${blockNumber}: ${err.message}`, {
390
+ cause: err,
391
+ });
392
+ }
393
+ }
394
+
395
+ const endState = await db.getStateReference();
396
+ provingState.setEndState(endState);
397
+
398
+ const blockEndBlobFields = provingState.getBlockEndBlobFields();
399
+ await spongeBlobState.absorb(blockEndBlobFields);
400
+
401
+ provingState.setEndSpongeBlob(spongeBlobState);
402
+ }
403
+
404
+ /**
405
+ * Marks the block as completed.
406
+ * Computes the block header and updates the archive tree.
407
+ */
408
+ @trackSpan('CheckpointSubTreeOrchestrator.setBlockCompleted', (blockNumber: BlockNumber) => ({
409
+ [Attributes.BLOCK_NUMBER]: blockNumber,
410
+ }))
411
+ public async setBlockCompleted(blockNumber: BlockNumber, expectedHeader?: BlockHeader): Promise<BlockHeader> {
412
+ const provingState = this.provingState?.getBlockProvingStateByBlockNumber(blockNumber);
413
+ if (!provingState) {
414
+ throw new Error(`Block proving state for ${blockNumber} not found`);
415
+ }
416
+
417
+ // Abort with specific error for the block if there's one.
418
+ const error = provingState.getError();
419
+ if (error) {
420
+ throw new Error(`Block proving failed: ${error}`);
421
+ }
422
+
423
+ // Abort if the proving state is not valid due to errors occurred elsewhere.
424
+ if (!provingState.verifyState()) {
425
+ throw new Error(`Invalid proving state when completing block ${blockNumber}.`);
426
+ }
427
+
428
+ if (provingState.isAcceptingTxs()) {
429
+ throw new Error(
430
+ `Block ${blockNumber} is still accepting txs. Call setBlockCompleted after all txs have been added.`,
431
+ );
432
+ }
433
+
434
+ // Given we've applied every change from this block, now assemble the block header:
435
+ this.logger.verbose(`Block ${blockNumber} completed. Assembling header.`);
436
+ const header = await provingState.buildBlockHeader();
437
+
438
+ if (expectedHeader && !header.equals(expectedHeader)) {
439
+ this.logger.error(`Block header mismatch: header=${header} expectedHeader=${expectedHeader}`);
440
+ throw new Error('Block header mismatch');
441
+ }
442
+
443
+ // Get db for this block and remove from map — no other code should use it after this point.
444
+ const db = this.getDbForBlock(provingState.blockNumber);
445
+ this.dbs.delete(provingState.blockNumber);
446
+
447
+ // Update the archive tree, capture the snapshot, and close the fork deterministically.
448
+ try {
449
+ this.logger.verbose(
450
+ `Updating archive tree with block ${provingState.blockNumber} header ${(await header.hash()).toString()}`,
451
+ );
452
+ await db.updateArchive(header);
453
+ provingState.setBuiltArchive(await getTreeSnapshot(MerkleTreeId.ARCHIVE, db));
454
+ } finally {
455
+ await db.close();
456
+ }
457
+
458
+ await this.verifyBuiltBlockAgainstSyncedState(provingState);
459
+
460
+ return header;
461
+ }
462
+
463
+ // ---------------- lifecycle ----------------
464
+
465
+ /**
466
+ * Cancels any further proving. If `cancelJobsOnStop` was set, aborts all pending broker jobs
467
+ * (used on reorg). Otherwise jobs remain in the broker queue and can be reused on restart.
468
+ */
469
+ public cancel() {
470
+ this.cancelled = true;
471
+ this.resetSchedulerState(this.cancelJobsOnStop);
472
+ // Reject the proving state (and hence subTreeResult) so anyone awaiting the sub-tree result
473
+ // is released rather than hanging — matching TopTreeOrchestrator.cancel().
474
+ this.provingState?.cancel();
475
+
476
+ for (const [blockNumber, db] of this.dbs.entries()) {
477
+ void db.close().catch(err => this.logger.error(`Error closing db for block ${blockNumber}`, err));
478
+ }
479
+ this.dbs.clear();
480
+ }
481
+
482
+ protected override cancelInternal(): void {
483
+ this.cancel();
484
+ }
485
+
486
+ // ---------------- private: per-checkpoint init ----------------
487
+
488
+ /**
489
+ * Internal driver for the single-checkpoint init. Allocates the world-state fork,
490
+ * inserts L1-to-L2 messages, and creates the per-checkpoint proving state with this
491
+ * sub-tree as its parent. Only called once, from the `start` factory.
492
+ */
493
+ private async startCheckpoint(
494
+ constants: CheckpointConstantData,
495
+ l1ToL2Messages: Fr[],
496
+ totalNumBlocks: number,
497
+ headerOfLastBlockInPreviousCheckpoint: BlockHeader,
498
+ ): Promise<void> {
499
+ if (this.provingState) {
500
+ throw new Error('Checkpoint sub-tree already started.');
501
+ }
502
+
503
+ // Fork world state at the end of the immediately previous block.
504
+ const lastBlockNumber = headerOfLastBlockInPreviousCheckpoint.globalVariables.blockNumber;
505
+ const db = await this.dbProvider.fork(lastBlockNumber);
506
+
507
+ const firstBlockNumber = BlockNumber(lastBlockNumber + 1);
508
+ this.dbs.set(firstBlockNumber, db);
509
+
510
+ // Get archive sibling path before any block in this checkpoint lands.
511
+ const lastArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, db);
512
+
513
+ // Insert all the l1 to l2 messages into the db. Get the states before and after the insertion.
514
+ const {
515
+ lastL1ToL2MessageTreeSnapshot,
516
+ lastL1ToL2MessageSubtreeRootSiblingPath,
517
+ newL1ToL2MessageTreeSnapshot,
518
+ newL1ToL2MessageSubtreeRootSiblingPath,
519
+ } = await this.updateL1ToL2MessageTree(l1ToL2Messages, db);
520
+
521
+ this.provingState = new CheckpointProvingState(
522
+ /* index */ 0,
523
+ constants,
524
+ totalNumBlocks,
525
+ headerOfLastBlockInPreviousCheckpoint,
526
+ lastArchiveSiblingPath,
527
+ l1ToL2Messages,
528
+ lastL1ToL2MessageTreeSnapshot,
529
+ lastL1ToL2MessageSubtreeRootSiblingPath,
530
+ newL1ToL2MessageTreeSnapshot,
531
+ newL1ToL2MessageSubtreeRootSiblingPath,
532
+ Number(this.epochNumber),
533
+ /* isAlive */ () => !this.cancelled,
534
+ /* onReject */ reason => this.subTreeResult.reject(new Error(reason)),
535
+ );
536
+ }
537
+
538
+ // ---------------- private: per-block proof orchestration ----------------
539
+
540
+ private async updateL1ToL2MessageTree(l1ToL2Messages: Fr[], db: MerkleTreeWriteOperations) {
541
+ const lastL1ToL2MessageTreeSnapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
542
+ const lastL1ToL2MessageSubtreeRootSiblingPath = assertLength(
543
+ await getSubtreeSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, L1_TO_L2_MSG_SUBTREE_HEIGHT, db),
544
+ L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH,
545
+ );
546
+
547
+ // Update the local trees to include the new l1 to l2 messages.
548
+ await appendL1ToL2MessagesToTree(db, l1ToL2Messages);
549
+
550
+ const newL1ToL2MessageTreeSnapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
551
+ const newL1ToL2MessageSubtreeRootSiblingPath = assertLength(
552
+ await getSubtreeSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, L1_TO_L2_MSG_SUBTREE_HEIGHT, db),
553
+ L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH,
554
+ );
555
+
556
+ return {
557
+ lastL1ToL2MessageTreeSnapshot,
558
+ lastL1ToL2MessageSubtreeRootSiblingPath,
559
+ newL1ToL2MessageTreeSnapshot,
560
+ newL1ToL2MessageSubtreeRootSiblingPath,
561
+ };
562
+ }
563
+
564
+ // Updates the merkle trees for a transaction. The first enqueued job for a transaction.
565
+ @trackSpan('CheckpointSubTreeOrchestrator.prepareBaseRollupInputs', tx => ({
566
+ [Attributes.TX_HASH]: tx.hash.toString(),
567
+ }))
568
+ private async prepareBaseRollupInputs(
569
+ tx: ProcessedTx,
570
+ lastArchive: AppendOnlyTreeSnapshot,
571
+ newL1ToL2MessageTreeSnapshot: AppendOnlyTreeSnapshot,
572
+ startSpongeBlob: SpongeBlob,
573
+ db: MerkleTreeWriteOperations,
574
+ ): Promise<[BaseRollupHintsWithoutProofAndVK, TreeSnapshots]> {
575
+ // These hints deliberately carry no recursive proof or verification key — see
576
+ // BaseRollupHintsWithoutProofAndVK. The tx's proof + VK are attached later in
577
+ // TxProvingState.getBaseRollupTypeAndInputs from the proven chonk-verifier / kernel / AVM
578
+ // proofs, which are required there and so cannot be silently omitted.
579
+ const start = performance.now();
580
+ const hints = await insertSideEffectsAndBuildBaseRollupHints(
581
+ tx,
582
+ lastArchive,
583
+ newL1ToL2MessageTreeSnapshot,
584
+ startSpongeBlob,
585
+ this.proverId.toField(),
586
+ db,
587
+ );
588
+ this.metrics.recordBaseRollupInputs(performance.now() - start);
589
+
590
+ const promises = [MerkleTreeId.NOTE_HASH_TREE, MerkleTreeId.NULLIFIER_TREE, MerkleTreeId.PUBLIC_DATA_TREE].map(
591
+ async (id: MerkleTreeId) => {
592
+ return { key: id, value: await getTreeSnapshot(id, db) };
593
+ },
594
+ );
595
+ const treeSnapshots: TreeSnapshots = new Map((await Promise.all(promises)).map(obj => [obj.key, obj.value]));
596
+
597
+ return [hints, treeSnapshots];
598
+ }
599
+
600
+ // Executes the base rollup circuit and stores the output as intermediate state for the parent merge/root circuit.
601
+ // Executes the next level of merge if all inputs are available.
602
+ private enqueueBaseRollup(provingState: BlockProvingState, txIndex: number) {
603
+ if (!provingState.verifyState()) {
604
+ this.logger.debug('Not running base rollup, state invalid');
605
+ return;
606
+ }
607
+
608
+ if (!provingState.tryStartProvingBase(txIndex)) {
609
+ this.logger.debug(`Base rollup for tx ${txIndex} already started.`);
610
+ return;
611
+ }
612
+
613
+ const txProvingState = provingState.getTxProvingState(txIndex);
614
+ const { processedTx } = txProvingState;
615
+ const { rollupType, inputs } = txProvingState.getBaseRollupTypeAndInputs();
616
+
617
+ this.logger.debug(`Enqueuing deferred proving base rollup for ${processedTx.hash.toString()}`);
618
+
619
+ this.deferredProving(
620
+ provingState,
621
+ this.wrapCircuitCall(
622
+ inputs instanceof PrivateTxBaseRollupPrivateInputs
623
+ ? 'getPrivateTxBaseRollupProof'
624
+ : 'getPublicTxBaseRollupProof',
625
+ signal => {
626
+ if (inputs instanceof PrivateTxBaseRollupPrivateInputs) {
627
+ return this.prover.getPrivateTxBaseRollupProof(inputs, signal, provingState.epochNumber);
628
+ } else {
629
+ return this.prover.getPublicTxBaseRollupProof(inputs, signal, provingState.epochNumber);
630
+ }
631
+ },
632
+ { [Attributes.TX_HASH]: processedTx.hash.toString(), [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType },
633
+ ),
634
+ result => {
635
+ this.logger.debug(`Completed proof for ${rollupType} for tx ${processedTx.hash.toString()}`);
636
+ validatePartialState(result.inputs.endTreeSnapshots, txProvingState.treeSnapshots);
637
+ const leafLocation = provingState.setBaseRollupProof(txIndex, result);
638
+ if (provingState.totalNumTxs === 1) {
639
+ this.checkAndEnqueueBlockRootRollup(provingState);
640
+ } else {
641
+ this.checkAndEnqueueNextMergeRollup(provingState, leafLocation);
642
+ }
643
+ },
644
+ );
645
+ }
646
+
647
+ /**
648
+ * Route the tx's chonk-verifier dependency through the per-epoch context: read the
649
+ * cached promise (or enqueue if missing), then `.then(handleResult)` to progress to
650
+ * the base rollup once the proof lands.
651
+ */
652
+ private getOrEnqueueChonkVerifier(provingState: BlockProvingState, txIndex: number) {
653
+ if (!provingState.verifyState()) {
654
+ return;
655
+ }
656
+
657
+ const txProvingState = provingState.getTxProvingState(txIndex);
658
+ const txHash = txProvingState.processedTx.hash.toString();
659
+
660
+ const handleResult = (
661
+ result: PublicInputsAndRecursiveProof<
662
+ PublicChonkVerifierPublicInputs,
663
+ typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH
664
+ >,
665
+ ) => {
666
+ if (!provingState.verifyState()) {
667
+ return;
668
+ }
669
+ txProvingState.setPublicChonkVerifierProof(result);
670
+ this.checkAndEnqueueBaseRollup(provingState, txIndex);
671
+ };
672
+
673
+ const promise = this.chonkCache.getOrCompute(txHash, signal =>
674
+ this.prover.getPublicChonkVerifierProof(
675
+ txProvingState.getPublicChonkVerifierPrivateInputs(),
676
+ signal,
677
+ this.epochNumber,
678
+ ),
679
+ );
680
+ void promise.then(handleResult).catch(err => {
681
+ // The cache self-cleans on rejection, so a replacement sub-tree for this tx will see the
682
+ // miss and re-enqueue. But if this proving state is still active, the failure must abort
683
+ // it: otherwise the base rollup for this tx is never enqueued and the checkpoint (and
684
+ // epoch) orchestrators hang forever waiting for a proof that will never arrive.
685
+ if (err instanceof AbortError || !provingState.verifyState()) {
686
+ return;
687
+ }
688
+ this.logger.error(`Chonk verifier proof failed for tx ${txHash}`, err);
689
+ provingState.reject(`Chonk verifier proof failed for tx ${txHash}: ${err}`);
690
+ });
691
+ }
692
+
693
+ // Executes the merge rollup circuit. Enqueues the next level of merge if all inputs are available.
694
+ private enqueueMergeRollup(provingState: BlockProvingState, location: TreeNodeLocation) {
695
+ if (!provingState.verifyState()) {
696
+ this.logger.debug('Not running merge rollup. State no longer valid.');
697
+ return;
698
+ }
699
+
700
+ if (!provingState.tryStartProvingMerge(location)) {
701
+ this.logger.debug('Merge rollup already started.');
702
+ return;
703
+ }
704
+
705
+ const inputs = provingState.getMergeRollupInputs(location);
706
+
707
+ this.deferredProving(
708
+ provingState,
709
+ this.wrapCircuitCall(
710
+ 'getTxMergeRollupProof',
711
+ signal => this.prover.getTxMergeRollupProof(inputs, signal, provingState.epochNumber),
712
+ { [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-tx-merge' satisfies CircuitName },
713
+ ),
714
+ result => {
715
+ provingState.setMergeRollupProof(location, result);
716
+ this.checkAndEnqueueNextMergeRollup(provingState, location);
717
+ },
718
+ );
719
+ }
720
+
721
+ // Executes the block root rollup circuit.
722
+ private enqueueBlockRootRollup(provingState: BlockProvingState) {
723
+ if (!provingState.verifyState()) {
724
+ this.logger.debug('Not running block root rollup, state no longer valid');
725
+ return;
726
+ }
727
+
728
+ if (!provingState.tryStartProvingBlockRoot()) {
729
+ this.logger.debug('Block root rollup already started.');
730
+ return;
731
+ }
732
+
733
+ const { rollupType, inputs } = provingState.getBlockRootRollupTypeAndInputs();
734
+
735
+ this.logger.debug(`Enqueuing ${rollupType} for block ${provingState.blockNumber}.`);
736
+
737
+ this.deferredProving(
738
+ provingState,
739
+ this.wrapCircuitCall(
740
+ 'getBlockRootRollupProof',
741
+ signal => {
742
+ if (inputs instanceof BlockRootFirstRollupPrivateInputs) {
743
+ return this.prover.getBlockRootFirstRollupProof(inputs, signal, provingState.epochNumber);
744
+ } else if (inputs instanceof BlockRootSingleTxFirstRollupPrivateInputs) {
745
+ return this.prover.getBlockRootSingleTxFirstRollupProof(inputs, signal, provingState.epochNumber);
746
+ } else if (inputs instanceof BlockRootEmptyTxFirstRollupPrivateInputs) {
747
+ return this.prover.getBlockRootEmptyTxFirstRollupProof(inputs, signal, provingState.epochNumber);
748
+ } else if (inputs instanceof BlockRootSingleTxRollupPrivateInputs) {
749
+ return this.prover.getBlockRootSingleTxRollupProof(inputs, signal, provingState.epochNumber);
750
+ } else {
751
+ return this.prover.getBlockRootRollupProof(inputs, signal, provingState.epochNumber);
752
+ }
753
+ },
754
+ { [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType },
755
+ ),
756
+ async result => {
757
+ this.logger.debug(`Completed ${rollupType} proof for block ${provingState.blockNumber}`, {
758
+ blockNumber: provingState.blockNumber,
759
+ checkpointIndex: provingState.parentCheckpoint.index,
760
+ ...result.inputs.toInspect(),
761
+ });
762
+
763
+ const leafLocation = provingState.setBlockRootRollupProof(result);
764
+ const checkpointProvingState = provingState.parentCheckpoint;
765
+
766
+ // Verification is called from both here and setBlockCompleted. Whichever runs last
767
+ // will be the first to see all three pieces (header, proof output, archive) and run the checks.
768
+ await this.verifyBuiltBlockAgainstSyncedState(provingState);
769
+
770
+ if (checkpointProvingState.totalNumBlocks === 1) {
771
+ this.checkAndEnqueueSubTreeResolution(checkpointProvingState);
772
+ } else {
773
+ this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
774
+ }
775
+ },
776
+ );
777
+ }
778
+
779
+ // Executes the base parity circuit. Enqueues the root parity circuit if all inputs are available.
780
+ private enqueueBaseParityCircuit(
781
+ checkpointProvingState: CheckpointProvingState,
782
+ provingState: BlockProvingState,
783
+ baseParityIndex: number,
784
+ ) {
785
+ if (!provingState.verifyState()) {
786
+ this.logger.debug('Not running base parity. State no longer valid.');
787
+ return;
788
+ }
789
+
790
+ if (!provingState.tryStartProvingBaseParity(baseParityIndex)) {
791
+ this.logger.warn(`Base parity ${baseParityIndex} already started.`);
792
+ return;
793
+ }
794
+
795
+ const inputs = checkpointProvingState.getBaseParityInputs(baseParityIndex);
796
+
797
+ this.deferredProving(
798
+ provingState,
799
+ this.wrapCircuitCall(
800
+ 'getBaseParityProof',
801
+ signal => this.prover.getBaseParityProof(inputs, signal, provingState.epochNumber),
802
+ { [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-base' satisfies CircuitName },
803
+ ),
804
+ provingOutput => {
805
+ provingState.setBaseParityProof(baseParityIndex, provingOutput);
806
+ this.checkAndEnqueueRootParityCircuit(provingState);
807
+ },
808
+ );
809
+ }
810
+
811
+ private checkAndEnqueueRootParityCircuit(provingState: BlockProvingState) {
812
+ if (!provingState.isReadyForRootParity()) {
813
+ return;
814
+ }
815
+ this.enqueueRootParityCircuit(provingState);
816
+ }
817
+
818
+ // Runs the root parity circuit and stores the outputs.
819
+ // Enqueues the block root rollup if all inputs are available.
820
+ private enqueueRootParityCircuit(provingState: BlockProvingState) {
821
+ if (!provingState.verifyState()) {
822
+ this.logger.debug('Not running root parity. State no longer valid.');
823
+ return;
824
+ }
825
+
826
+ if (!provingState.tryStartProvingRootParity()) {
827
+ this.logger.debug('Root parity already started.');
828
+ return;
829
+ }
830
+
831
+ const inputs = provingState.getParityRootInputs();
832
+
833
+ this.deferredProving(
834
+ provingState,
835
+ this.wrapCircuitCall(
836
+ 'getRootParityProof',
837
+ signal => this.prover.getRootParityProof(inputs, signal, provingState.epochNumber),
838
+ { [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-root' satisfies CircuitName },
839
+ ),
840
+ result => {
841
+ provingState.setRootParityProof(result);
842
+ this.checkAndEnqueueBlockRootRollup(provingState);
843
+ },
844
+ );
845
+ }
846
+
847
+ // Executes the block merge rollup circuit.
848
+ private enqueueBlockMergeRollup(provingState: CheckpointProvingState, location: TreeNodeLocation) {
849
+ if (!provingState.verifyState()) {
850
+ this.logger.debug('Not running block merge rollup. State no longer valid.');
851
+ return;
852
+ }
853
+
854
+ if (!provingState.tryStartProvingBlockMerge(location)) {
855
+ this.logger.debug('Block merge rollup already started.');
856
+ return;
857
+ }
858
+
859
+ const inputs = provingState.getBlockMergeRollupInputs(location);
860
+ this.deferredProving(
861
+ provingState,
862
+ this.wrapCircuitCall(
863
+ 'getBlockMergeRollupProof',
864
+ signal => this.prover.getBlockMergeRollupProof(inputs, signal, provingState.epochNumber),
865
+ { [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-block-merge' satisfies CircuitName },
866
+ ),
867
+ result => {
868
+ this.logger.debug(`Completed block merge rollup proof for checkpoint ${provingState.index}`, {
869
+ checkpointIndex: provingState.index,
870
+ mergeLocation: location,
871
+ ...result.inputs.toInspect(),
872
+ });
873
+ provingState.setBlockMergeRollupProof(location, result);
874
+ this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
875
+ },
876
+ );
877
+ }
878
+
879
+ private checkAndEnqueueNextMergeRollup(provingState: BlockProvingState, currentLocation: TreeNodeLocation) {
880
+ if (!provingState.isReadyForMergeRollup(currentLocation)) {
881
+ return;
882
+ }
883
+ const parentLocation = provingState.getParentLocation(currentLocation);
884
+ if (parentLocation.level === 0) {
885
+ this.checkAndEnqueueBlockRootRollup(provingState);
886
+ } else {
887
+ this.enqueueMergeRollup(provingState, parentLocation);
888
+ }
889
+ }
890
+
891
+ private checkAndEnqueueBlockRootRollup(provingState: BlockProvingState) {
892
+ if (!provingState.isReadyForBlockRootRollup()) {
893
+ this.logger.debug('Not ready for block root rollup');
894
+ return;
895
+ }
896
+ this.enqueueBlockRootRollup(provingState);
897
+ }
898
+
899
+ private checkAndEnqueueNextBlockMergeRollup(
900
+ provingState: CheckpointProvingState,
901
+ currentLocation: TreeNodeLocation,
902
+ ): void {
903
+ if (!provingState.isReadyForBlockMerge(currentLocation)) {
904
+ return;
905
+ }
906
+ const parentLocation = provingState.getParentLocation(currentLocation);
907
+ if (parentLocation.level === 0) {
908
+ this.checkAndEnqueueSubTreeResolution(provingState);
909
+ } else {
910
+ this.enqueueBlockMergeRollup(provingState, parentLocation);
911
+ }
912
+ }
913
+
914
+ /**
915
+ * Sub-tree analogue of the orchestrator's `checkAndEnqueueCheckpointRootRollup`:
916
+ * resolves the sub-tree promise with the block-level proof outputs once they're all ready,
917
+ * instead of escalating to the checkpoint root rollup.
918
+ */
919
+ private checkAndEnqueueSubTreeResolution(provingState: CheckpointProvingState): void {
920
+ const proofs = provingState.getSubTreeOutputProofs();
921
+ const nonEmpty = proofs.filter((p): p is NonNullable<typeof p> => !!p);
922
+ if (proofs.length !== nonEmpty.length) {
923
+ // Block merge tree not fully resolved yet — retried as more block proofs land.
924
+ return;
925
+ }
926
+ this.subTreeResult.resolve({
927
+ blockProofOutputs: nonEmpty,
928
+ previousArchiveSiblingPath: provingState.getLastArchiveSiblingPath(),
929
+ });
930
+ }
931
+
932
+ /**
933
+ * Executes the VM circuit for a public function. Enqueues the base rollup once the
934
+ * tx's chonk-verifier + VM proofs are both ready.
935
+ */
936
+ private enqueueVM(provingState: BlockProvingState, txIndex: number) {
937
+ if (!provingState.verifyState()) {
938
+ this.logger.debug(`Not running VM circuit as state is no longer valid`);
939
+ return;
940
+ }
941
+
942
+ const txProvingState = provingState.getTxProvingState(txIndex);
943
+
944
+ this.deferredProving(
945
+ provingState,
946
+ this.wrapCircuitCall(
947
+ 'getAvmProof',
948
+ async (signal: AbortSignal) => {
949
+ const inputs = txProvingState.getAvmInputs();
950
+ return await this.prover.getAvmProof(inputs, signal, provingState.epochNumber);
951
+ },
952
+ { [Attributes.TX_HASH]: txProvingState.processedTx.hash.toString() },
953
+ ),
954
+ proof => {
955
+ this.logger.debug(`Proven VM for tx index: ${txIndex}`);
956
+ txProvingState.setAvmProof(proof);
957
+ this.checkAndEnqueueBaseRollup(provingState, txIndex);
958
+ },
959
+ );
960
+ }
961
+
962
+ private checkAndEnqueueBaseRollup(provingState: BlockProvingState, txIndex: number) {
963
+ const txProvingState = provingState.getTxProvingState(txIndex);
964
+ if (!txProvingState.ready()) {
965
+ return;
966
+ }
967
+ // All upstream proofs (chonk verifier and, if required, vm) are ready — proceed to the base rollup.
968
+ this.logger.debug(`Public functions completed for tx ${txIndex} enqueueing base rollup`);
969
+ this.enqueueBaseRollup(provingState, txIndex);
970
+ }
971
+
972
+ // Flagged as protected so unit tests can override.
973
+ protected async verifyBuiltBlockAgainstSyncedState(provingState: BlockProvingState) {
974
+ const builtBlockHeader = provingState.getBuiltBlockHeader();
975
+ if (!builtBlockHeader) {
976
+ this.logger.debug('Block header not built yet, skipping header check.');
977
+ return;
978
+ }
979
+
980
+ const output = provingState.getBlockRootRollupOutput();
981
+ if (!output) {
982
+ this.logger.debug('Block root rollup proof not built yet, skipping header check.');
983
+ return;
984
+ }
985
+
986
+ const newArchive = provingState.getBuiltArchive();
987
+ if (!newArchive) {
988
+ this.logger.debug('Archive snapshot not yet captured, skipping header check.');
989
+ return;
990
+ }
991
+
992
+ const header = await buildHeaderFromCircuitOutputs(output);
993
+
994
+ if (!(await header.hash()).equals(await builtBlockHeader.hash())) {
995
+ this.logger.error(`Block header mismatch.\nCircuit: ${inspect(header)}\nComputed: ${inspect(builtBlockHeader)}`);
996
+ provingState.reject(`Block header hash mismatch.`);
997
+ return;
998
+ }
999
+
1000
+ const blockNumber = provingState.blockNumber;
1001
+ const syncedArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.dbProvider.getSnapshot(blockNumber));
1002
+ if (!syncedArchive.equals(newArchive)) {
1003
+ this.logger.error(
1004
+ `Archive tree mismatch for block ${blockNumber}: world state synced to ${inspect(
1005
+ syncedArchive,
1006
+ )} but built ${inspect(newArchive)}`,
1007
+ );
1008
+ provingState.reject(`Archive tree mismatch.`);
1009
+ return;
1010
+ }
1011
+
1012
+ const circuitArchive = output.newArchive;
1013
+ if (!newArchive.equals(circuitArchive)) {
1014
+ this.logger.error(`New archive mismatch.\nCircuit: ${output.newArchive}\nComputed: ${newArchive}`);
1015
+ provingState.reject(`New archive mismatch.`);
1016
+ return;
1017
+ }
1018
+ }
1019
+
1020
+ private getDbForBlock(blockNumber: BlockNumber): MerkleTreeWriteOperations {
1021
+ const db = this.dbs.get(blockNumber);
1022
+ if (!db) {
1023
+ throw new Error(`World state fork for block ${blockNumber} not found.`);
1024
+ }
1025
+ return db;
1026
+ }
1027
+
1028
+ /**
1029
+ * Wraps a circuit call with a tracer span and circuit attributes. Replaces the
1030
+ * `ProvingScheduler.wrapCircuitCall` indirection that used to live on the abstract base.
1031
+ */
1032
+ private wrapCircuitCall<T>(
1033
+ circuitName: string,
1034
+ fn: (signal: AbortSignal) => Promise<T>,
1035
+ attributes: Record<string, unknown> = {},
1036
+ ): (signal: AbortSignal) => Promise<T> {
1037
+ return wrapCallbackInSpan(
1038
+ this.tracer,
1039
+ `CheckpointSubTreeOrchestrator.prover.${circuitName}`,
1040
+ { [Attributes.PROTOCOL_CIRCUIT_NAME]: circuitName as CircuitName, ...attributes },
1041
+ fn,
1042
+ );
1043
+ }
1044
+ }