@aztec-labs/prover-client 6.0.0-nightly.20260829

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