@aztec/prover-client 0.0.1-commit.f146247c → 0.0.1-commit.f224bb98b

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 (68) hide show
  1. package/dest/light/lightweight_checkpoint_builder.d.ts +10 -5
  2. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -1
  3. package/dest/light/lightweight_checkpoint_builder.js +37 -18
  4. package/dest/mocks/test_context.js +6 -3
  5. package/dest/orchestrator/block-building-helpers.d.ts +4 -4
  6. package/dest/orchestrator/block-building-helpers.d.ts.map +1 -1
  7. package/dest/orchestrator/block-building-helpers.js +2 -2
  8. package/dest/orchestrator/block-proving-state.d.ts +4 -1
  9. package/dest/orchestrator/block-proving-state.d.ts.map +1 -1
  10. package/dest/orchestrator/block-proving-state.js +7 -0
  11. package/dest/orchestrator/checkpoint-proving-state.d.ts +3 -3
  12. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -1
  13. package/dest/orchestrator/checkpoint-proving-state.js +3 -3
  14. package/dest/orchestrator/epoch-proving-state.d.ts +3 -3
  15. package/dest/orchestrator/epoch-proving-state.d.ts.map +1 -1
  16. package/dest/orchestrator/epoch-proving-state.js +5 -3
  17. package/dest/orchestrator/orchestrator.d.ts +5 -3
  18. package/dest/orchestrator/orchestrator.d.ts.map +1 -1
  19. package/dest/orchestrator/orchestrator.js +61 -57
  20. package/dest/prover-client/prover-client.d.ts +4 -4
  21. package/dest/prover-client/prover-client.d.ts.map +1 -1
  22. package/dest/prover-client/prover-client.js +9 -7
  23. package/dest/proving_broker/broker_prover_facade.d.ts +1 -1
  24. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -1
  25. package/dest/proving_broker/broker_prover_facade.js +3 -3
  26. package/dest/proving_broker/config.d.ts +10 -2
  27. package/dest/proving_broker/config.d.ts.map +1 -1
  28. package/dest/proving_broker/config.js +14 -3
  29. package/dest/proving_broker/proof_store/factory.d.ts +2 -5
  30. package/dest/proving_broker/proof_store/factory.d.ts.map +1 -1
  31. package/dest/proving_broker/proof_store/factory.js +7 -30
  32. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts +18 -0
  33. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts.map +1 -0
  34. package/dest/proving_broker/proof_store/file_store_proof_store.js +60 -0
  35. package/dest/proving_broker/proof_store/index.d.ts +2 -2
  36. package/dest/proving_broker/proof_store/index.d.ts.map +1 -1
  37. package/dest/proving_broker/proof_store/index.js +1 -1
  38. package/dest/proving_broker/proving_broker.d.ts +7 -4
  39. package/dest/proving_broker/proving_broker.d.ts.map +1 -1
  40. package/dest/proving_broker/proving_broker.js +36 -4
  41. package/dest/proving_broker/proving_broker_instrumentation.d.ts +3 -1
  42. package/dest/proving_broker/proving_broker_instrumentation.d.ts.map +1 -1
  43. package/dest/proving_broker/proving_broker_instrumentation.js +7 -0
  44. package/dest/proving_broker/rpc.d.ts +4 -2
  45. package/dest/proving_broker/rpc.d.ts.map +1 -1
  46. package/dest/proving_broker/rpc.js +8 -0
  47. package/dest/test/mock_prover.d.ts +4 -4
  48. package/package.json +17 -18
  49. package/src/light/lightweight_checkpoint_builder.ts +35 -19
  50. package/src/mocks/test_context.ts +3 -3
  51. package/src/orchestrator/block-building-helpers.ts +2 -2
  52. package/src/orchestrator/block-proving-state.ts +9 -0
  53. package/src/orchestrator/checkpoint-proving-state.ts +4 -4
  54. package/src/orchestrator/epoch-proving-state.ts +6 -4
  55. package/src/orchestrator/orchestrator.ts +69 -63
  56. package/src/prover-client/prover-client.ts +8 -9
  57. package/src/proving_broker/broker_prover_facade.ts +9 -4
  58. package/src/proving_broker/config.ts +14 -1
  59. package/src/proving_broker/proof_store/factory.ts +10 -32
  60. package/src/proving_broker/proof_store/file_store_proof_store.ts +78 -0
  61. package/src/proving_broker/proof_store/index.ts +1 -1
  62. package/src/proving_broker/proving_broker.ts +37 -3
  63. package/src/proving_broker/proving_broker_instrumentation.ts +9 -0
  64. package/src/proving_broker/rpc.ts +14 -0
  65. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts +0 -14
  66. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts.map +0 -1
  67. package/dest/proving_broker/proof_store/gcs_proof_store.js +0 -52
  68. package/src/proving_broker/proof_store/gcs_proof_store.ts +0 -76
@@ -4,6 +4,7 @@ import { type CheckpointNumber, IndexWithinCheckpoint } from '@aztec/foundation/
4
4
  import { padArrayEnd } from '@aztec/foundation/collection';
5
5
  import { Fr } from '@aztec/foundation/curves/bn254';
6
6
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
7
+ import { elapsed } from '@aztec/foundation/timer';
7
8
  import { L2Block } from '@aztec/stdlib/block';
8
9
  import { Checkpoint } from '@aztec/stdlib/checkpoint';
9
10
  import type { MerkleTreeWriteOperations } from '@aztec/stdlib/interfaces/server';
@@ -44,6 +45,7 @@ export class LightweightCheckpointBuilder {
44
45
  constructor(
45
46
  public readonly checkpointNumber: CheckpointNumber,
46
47
  public readonly constants: CheckpointGlobalVariables,
48
+ public feeAssetPriceModifier: bigint,
47
49
  public readonly l1ToL2Messages: Fr[],
48
50
  private readonly previousCheckpointOutHashes: Fr[],
49
51
  public readonly db: MerkleTreeWriteOperations,
@@ -54,7 +56,7 @@ export class LightweightCheckpointBuilder {
54
56
  instanceId: `checkpoint-${checkpointNumber}`,
55
57
  });
56
58
  this.spongeBlob = SpongeBlob.init();
57
- this.logger.debug('Starting new checkpoint', { constants, l1ToL2Messages });
59
+ this.logger.debug('Starting new checkpoint', { constants, l1ToL2Messages, feeAssetPriceModifier });
58
60
  }
59
61
 
60
62
  static async startNewCheckpoint(
@@ -64,6 +66,7 @@ export class LightweightCheckpointBuilder {
64
66
  previousCheckpointOutHashes: Fr[],
65
67
  db: MerkleTreeWriteOperations,
66
68
  bindings?: LoggerBindings,
69
+ feeAssetPriceModifier: bigint = 0n,
67
70
  ): Promise<LightweightCheckpointBuilder> {
68
71
  // Insert l1-to-l2 messages into the tree.
69
72
  await db.appendLeaves(
@@ -74,6 +77,7 @@ export class LightweightCheckpointBuilder {
74
77
  return new LightweightCheckpointBuilder(
75
78
  checkpointNumber,
76
79
  constants,
80
+ feeAssetPriceModifier,
77
81
  l1ToL2Messages,
78
82
  previousCheckpointOutHashes,
79
83
  db,
@@ -90,6 +94,7 @@ export class LightweightCheckpointBuilder {
90
94
  static async resumeCheckpoint(
91
95
  checkpointNumber: CheckpointNumber,
92
96
  constants: CheckpointGlobalVariables,
97
+ feeAssetPriceModifier: bigint,
93
98
  l1ToL2Messages: Fr[],
94
99
  previousCheckpointOutHashes: Fr[],
95
100
  db: MerkleTreeWriteOperations,
@@ -99,6 +104,7 @@ export class LightweightCheckpointBuilder {
99
104
  const builder = new LightweightCheckpointBuilder(
100
105
  checkpointNumber,
101
106
  constants,
107
+ feeAssetPriceModifier,
102
108
  l1ToL2Messages,
103
109
  previousCheckpointOutHashes,
104
110
  db,
@@ -148,6 +154,10 @@ export class LightweightCheckpointBuilder {
148
154
  return this.blocks.length;
149
155
  }
150
156
 
157
+ public getBlocks() {
158
+ return this.blocks;
159
+ }
160
+
151
161
  /**
152
162
  * Adds a new block to the checkpoint. The tx effects must have already been inserted into the db if
153
163
  * this is called after tx processing, if that's not the case, then set `insertTxsEffects` to true.
@@ -156,7 +166,8 @@ export class LightweightCheckpointBuilder {
156
166
  globalVariables: GlobalVariables,
157
167
  txs: ProcessedTx[],
158
168
  opts: { insertTxsEffects?: boolean; expectedEndState?: StateReference } = {},
159
- ): Promise<L2Block> {
169
+ ): Promise<{ block: L2Block; timings: Record<string, number> }> {
170
+ const timings: Record<string, number> = {};
160
171
  const isFirstBlock = this.blocks.length === 0;
161
172
 
162
173
  // Empty blocks are only allowed as the first block in a checkpoint
@@ -165,7 +176,9 @@ export class LightweightCheckpointBuilder {
165
176
  }
166
177
 
167
178
  if (isFirstBlock) {
168
- this.lastArchives.push(await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.db));
179
+ const [msGetInitialArchive, initialArchive] = await elapsed(() => getTreeSnapshot(MerkleTreeId.ARCHIVE, this.db));
180
+ this.lastArchives.push(initialArchive);
181
+ timings.getInitialArchive = msGetInitialArchive;
169
182
  }
170
183
 
171
184
  const lastArchive = this.lastArchives.at(-1)!;
@@ -175,12 +188,17 @@ export class LightweightCheckpointBuilder {
175
188
  `Inserting side effects for ${txs.length} txs for block ${globalVariables.blockNumber} into db`,
176
189
  { txs: txs.map(tx => tx.hash.toString()) },
177
190
  );
191
+ let msInsertSideEffects = 0;
178
192
  for (const tx of txs) {
179
- await insertSideEffects(tx, this.db);
193
+ const [ms] = await elapsed(() => insertSideEffects(tx, this.db));
194
+ msInsertSideEffects += ms;
180
195
  }
196
+ timings.insertSideEffects = msInsertSideEffects;
181
197
  }
182
198
 
183
- const endState = await this.db.getStateReference();
199
+ const [msGetEndState, endState] = await elapsed(() => this.db.getStateReference());
200
+ timings.getEndState = msGetEndState;
201
+
184
202
  if (opts.expectedEndState && !endState.equals(opts.expectedEndState)) {
185
203
  this.logger.error('End state after processing txs does not match expected end state', {
186
204
  globalVariables: globalVariables.toInspect(),
@@ -190,26 +208,24 @@ export class LightweightCheckpointBuilder {
190
208
  throw new Error(`End state does not match expected end state when building block ${globalVariables.blockNumber}`);
191
209
  }
192
210
 
193
- const { header, body, blockBlobFields } = await buildHeaderAndBodyFromTxs(
194
- txs,
195
- lastArchive,
196
- endState,
197
- globalVariables,
198
- this.spongeBlob,
199
- isFirstBlock,
211
+ const [msBuildHeaderAndBody, { header, body, blockBlobFields }] = await elapsed(() =>
212
+ buildHeaderAndBodyFromTxs(txs, lastArchive, endState, globalVariables, this.spongeBlob, isFirstBlock),
200
213
  );
214
+ timings.buildHeaderAndBody = msBuildHeaderAndBody;
201
215
 
202
216
  header.state.validate();
203
217
 
204
218
  await this.db.updateArchive(header);
205
- const newArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.db);
219
+ const [msUpdateArchive, newArchive] = await elapsed(() => getTreeSnapshot(MerkleTreeId.ARCHIVE, this.db));
220
+ timings.updateArchive = msUpdateArchive;
206
221
  this.lastArchives.push(newArchive);
207
222
 
208
223
  const indexWithinCheckpoint = IndexWithinCheckpoint(this.blocks.length);
209
224
  const block = new L2Block(newArchive, header, body, this.checkpointNumber, indexWithinCheckpoint);
210
225
  this.blocks.push(block);
211
226
 
212
- await this.spongeBlob.absorb(blockBlobFields);
227
+ const [msSpongeAbsorb] = await elapsed(() => this.spongeBlob.absorb(blockBlobFields));
228
+ timings.spongeAbsorb = msSpongeAbsorb;
213
229
  this.blobFields.push(...blockBlobFields);
214
230
 
215
231
  this.logger.debug(`Built block ${header.getBlockNumber()}`, {
@@ -220,7 +236,7 @@ export class LightweightCheckpointBuilder {
220
236
  txs: block.body.txEffects.map(tx => tx.txHash.toString()),
221
237
  });
222
238
 
223
- return block;
239
+ return { block, timings };
224
240
  }
225
241
 
226
242
  async completeCheckpoint(): Promise<Checkpoint> {
@@ -237,7 +253,7 @@ export class LightweightCheckpointBuilder {
237
253
 
238
254
  const newArchive = this.lastArchives[this.lastArchives.length - 1];
239
255
 
240
- const blobs = getBlobsPerL1Block(this.blobFields);
256
+ const blobs = await getBlobsPerL1Block(this.blobFields);
241
257
  const blobsHash = computeBlobsHashFromBlobs(blobs);
242
258
 
243
259
  const inHash = computeInHashFromL1ToL2Messages(this.l1ToL2Messages);
@@ -248,8 +264,7 @@ export class LightweightCheckpointBuilder {
248
264
  );
249
265
  const epochOutHash = accumulateCheckpointOutHashes([...this.previousCheckpointOutHashes, checkpointOutHash]);
250
266
 
251
- // TODO(palla/mbps): Should we source this from the constants instead?
252
- // timestamp of a checkpoint is the timestamp of the last block in the checkpoint.
267
+ // All blocks in the checkpoint have the same timestamp
253
268
  const timestamp = blocks[blocks.length - 1].timestamp;
254
269
 
255
270
  const totalManaUsed = blocks.reduce((acc, block) => acc.add(block.header.totalManaUsed), Fr.ZERO);
@@ -268,13 +283,14 @@ export class LightweightCheckpointBuilder {
268
283
  totalManaUsed,
269
284
  });
270
285
 
271
- return new Checkpoint(newArchive, header, blocks, this.checkpointNumber);
286
+ return new Checkpoint(newArchive, header, blocks, this.checkpointNumber, this.feeAssetPriceModifier);
272
287
  }
273
288
 
274
289
  clone() {
275
290
  const clone = new LightweightCheckpointBuilder(
276
291
  this.checkpointNumber,
277
292
  this.constants,
293
+ this.feeAssetPriceModifier,
278
294
  [...this.l1ToL2Messages],
279
295
  [...this.previousCheckpointOutHashes],
280
296
  this.db,
@@ -116,7 +116,7 @@ export class TestContext {
116
116
 
117
117
  const broker = new TestBroker(proverCount, localProver);
118
118
  const facade = new BrokerCircuitProverFacade(broker);
119
- const orchestrator = new TestProvingOrchestrator(ws, facade, EthAddress.ZERO);
119
+ const orchestrator = new TestProvingOrchestrator(ws, facade, EthAddress.ZERO, false, 10);
120
120
 
121
121
  await broker.start();
122
122
  facade.start();
@@ -250,7 +250,7 @@ export class TestContext {
250
250
  const previousCheckpointOutHashes = this.checkpointOutHashes;
251
251
  const builder = await LightweightCheckpointBuilder.startNewCheckpoint(
252
252
  checkpointNumber,
253
- constants,
253
+ { ...constants, timestamp },
254
254
  l1ToL2Messages,
255
255
  previousCheckpointOutHashes,
256
256
  cleanFork,
@@ -262,7 +262,7 @@ export class TestContext {
262
262
  const txs = blockTxs[i];
263
263
  const state = blockEndStates[i];
264
264
 
265
- const block = await builder.addBlock(blockGlobalVariables[i], txs, {
265
+ const { block } = await builder.addBlock(blockGlobalVariables[i], txs, {
266
266
  expectedEndState: state,
267
267
  insertTxsEffects: true,
268
268
  });
@@ -253,8 +253,8 @@ export function getPublicChonkVerifierPrivateInputsFromTx(tx: Tx | ProcessedTx,
253
253
  // Build "hints" as the private inputs for the checkpoint root rollup circuit.
254
254
  // The `blobCommitments` will be accumulated and checked in the root rollup against the `finalBlobChallenges`.
255
255
  // The `blobsHash` will be validated on L1 against the submitted blob data.
256
- export const buildBlobHints = (blobFields: Fr[]) => {
257
- const blobs = getBlobsPerL1Block(blobFields);
256
+ export const buildBlobHints = async (blobFields: Fr[]) => {
257
+ const blobs = await getBlobsPerL1Block(blobFields);
258
258
  const blobCommitments = getBlobCommitmentsFromBlobs(blobs);
259
259
  const blobsHash = computeBlobsHashFromBlobs(blobs);
260
260
  return { blobCommitments, blobs, blobsHash };
@@ -55,6 +55,7 @@ export class BlockProvingState {
55
55
  | ProofState<BlockRollupPublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
56
56
  | undefined;
57
57
  private builtBlockHeader: BlockHeader | undefined;
58
+ private builtArchive: AppendOnlyTreeSnapshot | undefined;
58
59
  private endState: StateReference | undefined;
59
60
  private endSpongeBlob: SpongeBlob | undefined;
60
61
  private txs: TxProvingState[] = [];
@@ -232,6 +233,14 @@ export class BlockProvingState {
232
233
  return this.builtBlockHeader;
233
234
  }
234
235
 
236
+ public setBuiltArchive(archive: AppendOnlyTreeSnapshot) {
237
+ this.builtArchive = archive;
238
+ }
239
+
240
+ public getBuiltArchive() {
241
+ return this.builtArchive;
242
+ }
243
+
235
244
  public getStartSpongeBlob() {
236
245
  return this.startSpongeBlob;
237
246
  }
@@ -85,7 +85,7 @@ export class CheckpointProvingState {
85
85
  typeof L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH
86
86
  >,
87
87
  public parentEpoch: EpochProvingState,
88
- private onBlobAccumulatorSet: (checkpoint: CheckpointProvingState) => void,
88
+ private onBlobAccumulatorSet: (checkpoint: CheckpointProvingState) => Promise<void>,
89
89
  ) {
90
90
  this.blockProofs = new UnbalancedTreeStore(totalNumBlocks);
91
91
  this.firstBlockNumber = BlockNumber(headerOfLastBlockInPreviousCheckpoint.globalVariables.blockNumber + 1);
@@ -245,7 +245,7 @@ export class CheckpointProvingState {
245
245
  this.endBlobAccumulator = await accumulateBlobs(this.blobFields!, startBlobAccumulator);
246
246
  this.startBlobAccumulator = startBlobAccumulator;
247
247
 
248
- this.onBlobAccumulatorSet(this);
248
+ await this.onBlobAccumulatorSet(this);
249
249
 
250
250
  return this.endBlobAccumulator;
251
251
  }
@@ -271,7 +271,7 @@ export class CheckpointProvingState {
271
271
  return this.totalNumBlocks === 1 ? 'rollup-checkpoint-root-single-block' : 'rollup-checkpoint-root';
272
272
  }
273
273
 
274
- public getCheckpointRootRollupInputs() {
274
+ public async getCheckpointRootRollupInputs() {
275
275
  const proofs = this.#getChildProofsForRoot();
276
276
  const nonEmptyProofs = proofs.filter(p => !!p);
277
277
  if (proofs.length !== nonEmptyProofs.length) {
@@ -287,7 +287,7 @@ export class CheckpointProvingState {
287
287
  // `blobFields` must've been set if `startBlobAccumulator` is set (in `accumulateBlobs`).
288
288
  const blobFields = this.blobFields!;
289
289
 
290
- const { blobCommitments, blobsHash } = buildBlobHints(blobFields);
290
+ const { blobCommitments, blobsHash } = await buildBlobHints(blobFields);
291
291
 
292
292
  const hints = CheckpointRootRollupHints.from({
293
293
  previousBlockHeader: this.headerOfLastBlockInPreviousCheckpoint,
@@ -76,7 +76,7 @@ export class EpochProvingState {
76
76
  public readonly epochNumber: EpochNumber,
77
77
  public readonly totalNumCheckpoints: number,
78
78
  private readonly finalBlobBatchingChallenges: FinalBlobBatchingChallenges,
79
- private onCheckpointBlobAccumulatorSet: (checkpoint: CheckpointProvingState) => void,
79
+ private onCheckpointBlobAccumulatorSet: (checkpoint: CheckpointProvingState) => Promise<void>,
80
80
  private completionCallback: (result: ProvingResult) => void,
81
81
  private rejectionCallback: (reason: string) => void,
82
82
  ) {
@@ -254,9 +254,11 @@ export class EpochProvingState {
254
254
  }
255
255
  outHashes.push(outHash);
256
256
 
257
- // Get or create hints for the next checkpoint.
258
- hint = checkpoint.getOutHashHintForNextCheckpoint() ?? (await computeOutHashHint(outHashes));
259
- checkpoint.setOutHashHintForNextCheckpoint(hint);
257
+ // If this is NOT the last checkpoint, get or create the hint for the next checkpoint.
258
+ if (i !== this.totalNumCheckpoints - 1) {
259
+ hint = checkpoint.getOutHashHintForNextCheckpoint() ?? (await computeOutHashHint(outHashes));
260
+ checkpoint.setOutHashHintForNextCheckpoint(hint);
261
+ }
260
262
  }
261
263
  }
262
264
 
@@ -12,6 +12,7 @@ import { Fr } from '@aztec/foundation/curves/bn254';
12
12
  import { AbortError } from '@aztec/foundation/error';
13
13
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
14
14
  import { promiseWithResolvers } from '@aztec/foundation/promise';
15
+ import { SerialQueue } from '@aztec/foundation/queue';
15
16
  import { assertLength } from '@aztec/foundation/serialize';
16
17
  import { pushTestData } from '@aztec/foundation/testing';
17
18
  import { elapsed } from '@aztec/foundation/timer';
@@ -71,11 +72,6 @@ import { EpochProvingState, type ProvingResult, type TreeSnapshots } from './epo
71
72
  import { ProvingOrchestratorMetrics } from './orchestrator_metrics.js';
72
73
  import { TxProvingState } from './tx-proving-state.js';
73
74
 
74
- type WorldStateFork = {
75
- fork: MerkleTreeWriteOperations;
76
- cleanupPromise: Promise<void> | undefined;
77
- };
78
-
79
75
  /**
80
76
  * Implements an event driven proving scheduler to build the recursive proof tree. The idea being:
81
77
  * 1. Transactions are provided to the scheduler post simulation.
@@ -97,19 +93,22 @@ export class ProvingOrchestrator implements EpochProver {
97
93
  private provingPromise: Promise<ProvingResult> | undefined = undefined;
98
94
  private metrics: ProvingOrchestratorMetrics;
99
95
  // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
100
- private dbs: Map<BlockNumber, WorldStateFork> = new Map();
96
+ private dbs: Map<BlockNumber, MerkleTreeWriteOperations> = new Map();
101
97
  private logger: Logger;
98
+ private deferredJobQueue = new SerialQueue();
102
99
 
103
100
  constructor(
104
101
  private dbProvider: ReadonlyWorldStateAccess & ForkMerkleTreeOperations,
105
102
  private prover: ServerCircuitProver,
106
103
  private readonly proverId: EthAddress,
107
104
  private readonly cancelJobsOnStop: boolean = false,
105
+ private readonly enqueueConcurrency: number,
108
106
  telemetryClient: TelemetryClient = getTelemetryClient(),
109
107
  bindings?: LoggerBindings,
110
108
  ) {
111
109
  this.logger = createLogger('prover-client:orchestrator', bindings);
112
110
  this.metrics = new ProvingOrchestratorMetrics(telemetryClient, 'ProvingOrchestrator');
111
+ this.deferredJobQueue.start(this.enqueueConcurrency);
113
112
  }
114
113
 
115
114
  get tracer(): Tracer {
@@ -124,9 +123,11 @@ export class ProvingOrchestrator implements EpochProver {
124
123
  return this.dbs.size;
125
124
  }
126
125
 
127
- public stop(): Promise<void> {
126
+ public async stop(): Promise<void> {
127
+ // Grab the old queue before cancel() replaces it, so we can await its draining.
128
+ const oldQueue = this.deferredJobQueue;
128
129
  this.cancel();
129
- return Promise.resolve();
130
+ await oldQueue.cancel();
130
131
  }
131
132
 
132
133
  public startNewEpoch(
@@ -182,7 +183,7 @@ export class ProvingOrchestrator implements EpochProver {
182
183
  const db = await this.dbProvider.fork(lastBlockNumber);
183
184
 
184
185
  const firstBlockNumber = BlockNumber(lastBlockNumber + 1);
185
- this.dbs.set(firstBlockNumber, { fork: db, cleanupPromise: undefined });
186
+ this.dbs.set(firstBlockNumber, db);
186
187
 
187
188
  // Get archive sibling path before any block in this checkpoint lands.
188
189
  const lastArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, db);
@@ -240,9 +241,9 @@ export class ProvingOrchestrator implements EpochProver {
240
241
  if (!this.dbs.has(blockNumber)) {
241
242
  // Fork world state at the end of the immediately previous block
242
243
  const db = await this.dbProvider.fork(BlockNumber(blockNumber - 1));
243
- this.dbs.set(blockNumber, { fork: db, cleanupPromise: undefined });
244
+ this.dbs.set(blockNumber, db);
244
245
  }
245
- const db = this.dbs.get(blockNumber)!.fork;
246
+ const db = this.getDbForBlock(blockNumber);
246
247
 
247
248
  // Get archive snapshot and sibling path before any txs in this block lands.
248
249
  const lastArchiveTreeSnapshot = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
@@ -317,7 +318,7 @@ export class ProvingOrchestrator implements EpochProver {
317
318
 
318
319
  this.logger.info(`Adding ${txs.length} transactions to block ${blockNumber}`);
319
320
 
320
- const db = this.dbs.get(blockNumber)!.fork;
321
+ const db = this.getDbForBlock(blockNumber);
321
322
  const lastArchive = provingState.lastArchiveTreeSnapshot;
322
323
  const newL1ToL2MessageTreeSnapshot = provingState.newL1ToL2MessageTreeSnapshot;
323
324
  const spongeBlobState = provingState.getStartSpongeBlob().clone();
@@ -445,14 +446,20 @@ export class ProvingOrchestrator implements EpochProver {
445
446
  throw new Error('Block header mismatch');
446
447
  }
447
448
 
448
- // Get db for this block
449
- const db = this.dbs.get(provingState.blockNumber)!.fork;
449
+ // Get db for this block and remove from map — no other code should use it after this point.
450
+ const db = this.getDbForBlock(provingState.blockNumber);
451
+ this.dbs.delete(provingState.blockNumber);
450
452
 
451
- // Update the archive tree, so we're ready to start processing the next block:
452
- this.logger.verbose(
453
- `Updating archive tree with block ${provingState.blockNumber} header ${(await header.hash()).toString()}`,
454
- );
455
- await db.updateArchive(header);
453
+ // Update the archive tree, capture the snapshot, and close the fork deterministically.
454
+ try {
455
+ this.logger.verbose(
456
+ `Updating archive tree with block ${provingState.blockNumber} header ${(await header.hash()).toString()}`,
457
+ );
458
+ await db.updateArchive(header);
459
+ provingState.setBuiltArchive(await getTreeSnapshot(MerkleTreeId.ARCHIVE, db));
460
+ } finally {
461
+ await db.close();
462
+ }
456
463
 
457
464
  await this.verifyBuiltBlockAgainstSyncedState(provingState);
458
465
 
@@ -472,6 +479,13 @@ export class ProvingOrchestrator implements EpochProver {
472
479
  this.logger.debug('Block root rollup proof not built yet, skipping header check.');
473
480
  return;
474
481
  }
482
+
483
+ const newArchive = provingState.getBuiltArchive();
484
+ if (!newArchive) {
485
+ this.logger.debug('Archive snapshot not yet captured, skipping header check.');
486
+ return;
487
+ }
488
+
475
489
  const header = await buildHeaderFromCircuitOutputs(output);
476
490
 
477
491
  if (!(await header.hash()).equals(await builtBlockHeader.hash())) {
@@ -480,11 +494,7 @@ export class ProvingOrchestrator implements EpochProver {
480
494
  return;
481
495
  }
482
496
 
483
- // Get db for this block
484
497
  const blockNumber = provingState.blockNumber;
485
- const db = this.dbs.get(blockNumber)!.fork;
486
-
487
- const newArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
488
498
  const syncedArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.dbProvider.getSnapshot(blockNumber));
489
499
  if (!syncedArchive.equals(newArchive)) {
490
500
  this.logger.error(
@@ -502,12 +512,6 @@ export class ProvingOrchestrator implements EpochProver {
502
512
  provingState.reject(`New archive mismatch.`);
503
513
  return;
504
514
  }
505
-
506
- // TODO(palla/prover): This closes the fork only on the happy path. If this epoch orchestrator
507
- // is aborted and never reaches this point, it will leak the fork. We need to add a global cleanup,
508
- // but have to make sure it only runs once all operations are completed, otherwise some function here
509
- // will attempt to access the fork after it was closed.
510
- void this.cleanupDBFork(blockNumber);
511
515
  }
512
516
 
513
517
  /**
@@ -516,6 +520,11 @@ export class ProvingOrchestrator implements EpochProver {
516
520
  * If cancelJobsOnStop is false (default), jobs remain in the broker queue and can be reused on restart/reorg.
517
521
  */
518
522
  public cancel() {
523
+ void this.deferredJobQueue.cancel();
524
+ // Recreate the queue so it can accept jobs for subsequent epochs.
525
+ this.deferredJobQueue = new SerialQueue();
526
+ this.deferredJobQueue.start(this.enqueueConcurrency);
527
+
519
528
  if (this.cancelJobsOnStop) {
520
529
  for (const controller of this.pendingProvingJobs) {
521
530
  controller.abort();
@@ -523,6 +532,19 @@ export class ProvingOrchestrator implements EpochProver {
523
532
  }
524
533
 
525
534
  this.provingState?.cancel();
535
+
536
+ for (const [blockNumber, db] of this.dbs.entries()) {
537
+ void db.close().catch(err => this.logger.error(`Error closing db for block ${blockNumber}`, err));
538
+ }
539
+ this.dbs.clear();
540
+ }
541
+
542
+ private getDbForBlock(blockNumber: BlockNumber): MerkleTreeWriteOperations {
543
+ const db = this.dbs.get(blockNumber);
544
+ if (!db) {
545
+ throw new Error(`World state fork for block ${blockNumber} not found.`);
546
+ }
547
+ return db;
526
548
  }
527
549
 
528
550
  /**
@@ -554,24 +576,6 @@ export class ProvingOrchestrator implements EpochProver {
554
576
  return epochProofResult;
555
577
  }
556
578
 
557
- private async cleanupDBFork(blockNumber: BlockNumber): Promise<void> {
558
- this.logger.debug(`Cleaning up world state fork for ${blockNumber}`);
559
- const fork = this.dbs.get(blockNumber);
560
- if (!fork) {
561
- return;
562
- }
563
-
564
- try {
565
- if (!fork.cleanupPromise) {
566
- fork.cleanupPromise = fork.fork.close();
567
- }
568
- await fork.cleanupPromise;
569
- this.dbs.delete(blockNumber);
570
- } catch (err) {
571
- this.logger.error(`Error closing db for block ${blockNumber}`, err);
572
- }
573
- }
574
-
575
579
  /**
576
580
  * Enqueue a job to be scheduled
577
581
  * @param provingState - The proving state object being operated on
@@ -630,8 +634,9 @@ export class ProvingOrchestrator implements EpochProver {
630
634
  }
631
635
  };
632
636
 
633
- // let the callstack unwind before adding the job to the queue
634
- setImmediate(() => void safeJob());
637
+ // Enqueue onto the serial queue with limited workers to avoid starving the event loop.
638
+ // Workers yield between jobs via await, allowing I/O callbacks to process.
639
+ void this.deferredJobQueue.put(() => safeJob());
635
640
  }
636
641
 
637
642
  private async updateL1ToL2MessageTree(l1ToL2Messages: Fr[], db: MerkleTreeWriteOperations) {
@@ -894,17 +899,15 @@ export class ProvingOrchestrator implements EpochProver {
894
899
  const leafLocation = provingState.setBlockRootRollupProof(result);
895
900
  const checkpointProvingState = provingState.parentCheckpoint;
896
901
 
897
- // If the proofs were slower than the block header building, then we need to try validating the block header hashes here.
902
+ // Verification is called from both here and setBlockCompleted. Whichever runs last
903
+ // will be the first to see all three pieces (header, proof output, archive) and run the checks.
898
904
  await this.verifyBuiltBlockAgainstSyncedState(provingState);
899
905
 
900
906
  if (checkpointProvingState.totalNumBlocks === 1) {
901
- this.checkAndEnqueueCheckpointRootRollup(checkpointProvingState);
907
+ await this.checkAndEnqueueCheckpointRootRollup(checkpointProvingState);
902
908
  } else {
903
- this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
909
+ await this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
904
910
  }
905
-
906
- // We are finished with the block at this point, ensure the fork is cleaned up
907
- void this.cleanupDBFork(provingState.blockNumber);
908
911
  },
909
912
  );
910
913
  }
@@ -1009,14 +1012,14 @@ export class ProvingOrchestrator implements EpochProver {
1009
1012
  },
1010
1013
  signal => this.prover.getBlockMergeRollupProof(inputs, signal, provingState.epochNumber),
1011
1014
  ),
1012
- result => {
1015
+ async result => {
1013
1016
  provingState.setBlockMergeRollupProof(location, result);
1014
- this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
1017
+ await this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
1015
1018
  },
1016
1019
  );
1017
1020
  }
1018
1021
 
1019
- private enqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1022
+ private async enqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1020
1023
  if (!provingState.verifyState()) {
1021
1024
  this.logger.debug('Not running checkpoint root rollup. State no longer valid.');
1022
1025
  return;
@@ -1031,7 +1034,7 @@ export class ProvingOrchestrator implements EpochProver {
1031
1034
 
1032
1035
  this.logger.debug(`Enqueuing ${rollupType} for checkpoint ${provingState.index}.`);
1033
1036
 
1034
- const inputs = provingState.getCheckpointRootRollupInputs();
1037
+ const inputs = await provingState.getCheckpointRootRollupInputs();
1035
1038
 
1036
1039
  this.deferredProving(
1037
1040
  provingState,
@@ -1191,25 +1194,28 @@ export class ProvingOrchestrator implements EpochProver {
1191
1194
  this.enqueueBlockRootRollup(provingState);
1192
1195
  }
1193
1196
 
1194
- private checkAndEnqueueNextBlockMergeRollup(provingState: CheckpointProvingState, currentLocation: TreeNodeLocation) {
1197
+ private async checkAndEnqueueNextBlockMergeRollup(
1198
+ provingState: CheckpointProvingState,
1199
+ currentLocation: TreeNodeLocation,
1200
+ ) {
1195
1201
  if (!provingState.isReadyForBlockMerge(currentLocation)) {
1196
1202
  return;
1197
1203
  }
1198
1204
 
1199
1205
  const parentLocation = provingState.getParentLocation(currentLocation);
1200
1206
  if (parentLocation.level === 0) {
1201
- this.checkAndEnqueueCheckpointRootRollup(provingState);
1207
+ await this.checkAndEnqueueCheckpointRootRollup(provingState);
1202
1208
  } else {
1203
1209
  this.enqueueBlockMergeRollup(provingState, parentLocation);
1204
1210
  }
1205
1211
  }
1206
1212
 
1207
- private checkAndEnqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1213
+ private async checkAndEnqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1208
1214
  if (!provingState.isReadyForCheckpointRoot()) {
1209
1215
  return;
1210
1216
  }
1211
1217
 
1212
- this.enqueueCheckpointRootRollup(provingState);
1218
+ await this.enqueueCheckpointRootRollup(provingState);
1213
1219
  }
1214
1220
 
1215
1221
  private checkAndEnqueueNextCheckpointMergeRollup(provingState: EpochProvingState, currentLocation: TreeNodeLocation) {
@@ -29,20 +29,16 @@ export class ProverClient implements EpochProverManager {
29
29
  private running = false;
30
30
  private agents: ProvingAgent[] = [];
31
31
 
32
- private proofStore: ProofStore;
33
- private failedProofStore: ProofStore | undefined;
34
-
35
32
  private constructor(
36
33
  private config: ProverClientConfig,
37
34
  private worldState: ForkMerkleTreeOperations & ReadonlyWorldStateAccess,
38
35
  private orchestratorClient: ProvingJobProducer,
36
+ private proofStore: ProofStore,
37
+ private failedProofStore: ProofStore | undefined,
39
38
  private agentClient?: ProvingJobConsumer,
40
39
  private telemetry: TelemetryClient = getTelemetryClient(),
41
40
  private log: Logger = createLogger('prover-client:tx-prover'),
42
- ) {
43
- this.proofStore = new InlineProofStore();
44
- this.failedProofStore = this.config.failedProofStore ? createProofStore(this.config.failedProofStore) : undefined;
45
- }
41
+ ) {}
46
42
 
47
43
  public createEpochProver(): EpochProver {
48
44
  const bindings = this.log.getBindings();
@@ -58,6 +54,7 @@ export class ProverClient implements EpochProverManager {
58
54
  facade,
59
55
  this.config.proverId,
60
56
  this.config.cancelJobsOnStop,
57
+ this.config.enqueueConcurrency,
61
58
  this.telemetry,
62
59
  bindings,
63
60
  );
@@ -118,7 +115,9 @@ export class ProverClient implements EpochProverManager {
118
115
  broker: ProvingJobBroker,
119
116
  telemetry: TelemetryClient = getTelemetryClient(),
120
117
  ) {
121
- const prover = new ProverClient(config, worldState, broker, broker, telemetry);
118
+ const proofStore = await createProofStore(config.proofStore);
119
+ const failedProofStore = config.failedProofStore ? await createProofStore(config.failedProofStore) : undefined;
120
+ const prover = new ProverClient(config, worldState, broker, proofStore, failedProofStore, broker, telemetry);
122
121
  await prover.start();
123
122
  return prover;
124
123
  }
@@ -158,7 +157,7 @@ export class ProverClient implements EpochProverManager {
158
157
  }
159
158
 
160
159
  export function buildServerCircuitProver(
161
- config: ActualProverConfig & ACVMConfig & BBConfig,
160
+ config: Omit<ActualProverConfig, 'enqueueConcurrency'> & ACVMConfig & BBConfig,
162
161
  telemetry: TelemetryClient,
163
162
  ): Promise<ServerCircuitProver> {
164
163
  if (config.realProofs) {