@aztec/prover-client 0.0.1-commit.e3c1de76 → 0.0.1-commit.e588bc7e5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dest/config.d.ts +1 -1
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +12 -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 +41 -18
  7. package/dest/mocks/test_context.d.ts +1 -1
  8. package/dest/mocks/test_context.d.ts.map +1 -1
  9. package/dest/mocks/test_context.js +10 -5
  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 +3 -3
  17. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -1
  18. package/dest/orchestrator/checkpoint-proving-state.js +3 -3
  19. package/dest/orchestrator/epoch-proving-state.d.ts +3 -3
  20. package/dest/orchestrator/epoch-proving-state.d.ts.map +1 -1
  21. package/dest/orchestrator/epoch-proving-state.js +5 -3
  22. package/dest/orchestrator/orchestrator.d.ts +5 -3
  23. package/dest/orchestrator/orchestrator.d.ts.map +1 -1
  24. package/dest/orchestrator/orchestrator.js +64 -57
  25. package/dest/prover-client/prover-client.d.ts +4 -4
  26. package/dest/prover-client/prover-client.d.ts.map +1 -1
  27. package/dest/prover-client/prover-client.js +9 -7
  28. package/dest/proving_broker/broker_prover_facade.d.ts +1 -1
  29. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -1
  30. package/dest/proving_broker/broker_prover_facade.js +13 -19
  31. package/dest/proving_broker/config.d.ts +10 -2
  32. package/dest/proving_broker/config.d.ts.map +1 -1
  33. package/dest/proving_broker/config.js +14 -3
  34. package/dest/proving_broker/proof_store/factory.d.ts +2 -5
  35. package/dest/proving_broker/proof_store/factory.d.ts.map +1 -1
  36. package/dest/proving_broker/proof_store/factory.js +7 -30
  37. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts +18 -0
  38. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts.map +1 -0
  39. package/dest/proving_broker/proof_store/file_store_proof_store.js +60 -0
  40. package/dest/proving_broker/proof_store/index.d.ts +2 -2
  41. package/dest/proving_broker/proof_store/index.d.ts.map +1 -1
  42. package/dest/proving_broker/proof_store/index.js +1 -1
  43. package/dest/proving_broker/proving_broker.d.ts +7 -4
  44. package/dest/proving_broker/proving_broker.d.ts.map +1 -1
  45. package/dest/proving_broker/proving_broker.js +36 -4
  46. package/dest/proving_broker/proving_broker_instrumentation.d.ts +3 -1
  47. package/dest/proving_broker/proving_broker_instrumentation.d.ts.map +1 -1
  48. package/dest/proving_broker/proving_broker_instrumentation.js +7 -0
  49. package/dest/proving_broker/rpc.d.ts +6 -2
  50. package/dest/proving_broker/rpc.d.ts.map +1 -1
  51. package/dest/proving_broker/rpc.js +24 -15
  52. package/dest/test/mock_prover.d.ts +4 -4
  53. package/package.json +17 -18
  54. package/src/config.ts +13 -2
  55. package/src/light/lightweight_checkpoint_builder.ts +42 -19
  56. package/src/mocks/test_context.ts +6 -4
  57. package/src/orchestrator/block-building-helpers.ts +2 -2
  58. package/src/orchestrator/block-proving-state.ts +9 -0
  59. package/src/orchestrator/checkpoint-proving-state.ts +4 -4
  60. package/src/orchestrator/epoch-proving-state.ts +6 -4
  61. package/src/orchestrator/orchestrator.ts +72 -63
  62. package/src/prover-client/prover-client.ts +8 -9
  63. package/src/proving_broker/broker_prover_facade.ts +17 -20
  64. package/src/proving_broker/config.ts +14 -1
  65. package/src/proving_broker/proof_store/factory.ts +10 -32
  66. package/src/proving_broker/proof_store/file_store_proof_store.ts +78 -0
  67. package/src/proving_broker/proof_store/index.ts +1 -1
  68. package/src/proving_broker/proving_broker.ts +37 -3
  69. package/src/proving_broker/proving_broker_instrumentation.ts +9 -0
  70. package/src/proving_broker/rpc.ts +26 -3
  71. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts +0 -14
  72. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts.map +0 -1
  73. package/dest/proving_broker/proof_store/gcs_proof_store.js +0 -52
  74. package/src/proving_broker/proof_store/gcs_proof_store.ts +0 -76
@@ -12,7 +12,9 @@ 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';
17
+ import { sleep } from '@aztec/foundation/sleep';
16
18
  import { pushTestData } from '@aztec/foundation/testing';
17
19
  import { elapsed } from '@aztec/foundation/timer';
18
20
  import type { TreeNodeLocation } from '@aztec/foundation/trees';
@@ -71,11 +73,6 @@ import { EpochProvingState, type ProvingResult, type TreeSnapshots } from './epo
71
73
  import { ProvingOrchestratorMetrics } from './orchestrator_metrics.js';
72
74
  import { TxProvingState } from './tx-proving-state.js';
73
75
 
74
- type WorldStateFork = {
75
- fork: MerkleTreeWriteOperations;
76
- cleanupPromise: Promise<void> | undefined;
77
- };
78
-
79
76
  /**
80
77
  * Implements an event driven proving scheduler to build the recursive proof tree. The idea being:
81
78
  * 1. Transactions are provided to the scheduler post simulation.
@@ -97,19 +94,22 @@ export class ProvingOrchestrator implements EpochProver {
97
94
  private provingPromise: Promise<ProvingResult> | undefined = undefined;
98
95
  private metrics: ProvingOrchestratorMetrics;
99
96
  // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
100
- private dbs: Map<BlockNumber, WorldStateFork> = new Map();
97
+ private dbs: Map<BlockNumber, MerkleTreeWriteOperations> = new Map();
101
98
  private logger: Logger;
99
+ private deferredJobQueue = new SerialQueue();
102
100
 
103
101
  constructor(
104
102
  private dbProvider: ReadonlyWorldStateAccess & ForkMerkleTreeOperations,
105
103
  private prover: ServerCircuitProver,
106
104
  private readonly proverId: EthAddress,
107
105
  private readonly cancelJobsOnStop: boolean = false,
106
+ private readonly enqueueConcurrency: number,
108
107
  telemetryClient: TelemetryClient = getTelemetryClient(),
109
108
  bindings?: LoggerBindings,
110
109
  ) {
111
110
  this.logger = createLogger('prover-client:orchestrator', bindings);
112
111
  this.metrics = new ProvingOrchestratorMetrics(telemetryClient, 'ProvingOrchestrator');
112
+ this.deferredJobQueue.start(this.enqueueConcurrency);
113
113
  }
114
114
 
115
115
  get tracer(): Tracer {
@@ -124,9 +124,11 @@ export class ProvingOrchestrator implements EpochProver {
124
124
  return this.dbs.size;
125
125
  }
126
126
 
127
- public stop(): Promise<void> {
127
+ public async stop(): Promise<void> {
128
+ // Grab the old queue before cancel() replaces it, so we can await its draining.
129
+ const oldQueue = this.deferredJobQueue;
128
130
  this.cancel();
129
- return Promise.resolve();
131
+ await oldQueue.cancel();
130
132
  }
131
133
 
132
134
  public startNewEpoch(
@@ -182,7 +184,7 @@ export class ProvingOrchestrator implements EpochProver {
182
184
  const db = await this.dbProvider.fork(lastBlockNumber);
183
185
 
184
186
  const firstBlockNumber = BlockNumber(lastBlockNumber + 1);
185
- this.dbs.set(firstBlockNumber, { fork: db, cleanupPromise: undefined });
187
+ this.dbs.set(firstBlockNumber, db);
186
188
 
187
189
  // Get archive sibling path before any block in this checkpoint lands.
188
190
  const lastArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, db);
@@ -240,9 +242,9 @@ export class ProvingOrchestrator implements EpochProver {
240
242
  if (!this.dbs.has(blockNumber)) {
241
243
  // Fork world state at the end of the immediately previous block
242
244
  const db = await this.dbProvider.fork(BlockNumber(blockNumber - 1));
243
- this.dbs.set(blockNumber, { fork: db, cleanupPromise: undefined });
245
+ this.dbs.set(blockNumber, db);
244
246
  }
245
- const db = this.dbs.get(blockNumber)!.fork;
247
+ const db = this.getDbForBlock(blockNumber);
246
248
 
247
249
  // Get archive snapshot and sibling path before any txs in this block lands.
248
250
  const lastArchiveTreeSnapshot = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
@@ -317,7 +319,7 @@ export class ProvingOrchestrator implements EpochProver {
317
319
 
318
320
  this.logger.info(`Adding ${txs.length} transactions to block ${blockNumber}`);
319
321
 
320
- const db = this.dbs.get(blockNumber)!.fork;
322
+ const db = this.getDbForBlock(blockNumber);
321
323
  const lastArchive = provingState.lastArchiveTreeSnapshot;
322
324
  const newL1ToL2MessageTreeSnapshot = provingState.newL1ToL2MessageTreeSnapshot;
323
325
  const spongeBlobState = provingState.getStartSpongeBlob().clone();
@@ -445,14 +447,20 @@ export class ProvingOrchestrator implements EpochProver {
445
447
  throw new Error('Block header mismatch');
446
448
  }
447
449
 
448
- // Get db for this block
449
- const db = this.dbs.get(provingState.blockNumber)!.fork;
450
+ // Get db for this block and remove from map — no other code should use it after this point.
451
+ const db = this.getDbForBlock(provingState.blockNumber);
452
+ this.dbs.delete(provingState.blockNumber);
450
453
 
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);
454
+ // Update the archive tree, capture the snapshot, and close the fork deterministically.
455
+ try {
456
+ this.logger.verbose(
457
+ `Updating archive tree with block ${provingState.blockNumber} header ${(await header.hash()).toString()}`,
458
+ );
459
+ await db.updateArchive(header);
460
+ provingState.setBuiltArchive(await getTreeSnapshot(MerkleTreeId.ARCHIVE, db));
461
+ } finally {
462
+ await db.close();
463
+ }
456
464
 
457
465
  await this.verifyBuiltBlockAgainstSyncedState(provingState);
458
466
 
@@ -472,6 +480,13 @@ export class ProvingOrchestrator implements EpochProver {
472
480
  this.logger.debug('Block root rollup proof not built yet, skipping header check.');
473
481
  return;
474
482
  }
483
+
484
+ const newArchive = provingState.getBuiltArchive();
485
+ if (!newArchive) {
486
+ this.logger.debug('Archive snapshot not yet captured, skipping header check.');
487
+ return;
488
+ }
489
+
475
490
  const header = await buildHeaderFromCircuitOutputs(output);
476
491
 
477
492
  if (!(await header.hash()).equals(await builtBlockHeader.hash())) {
@@ -480,11 +495,7 @@ export class ProvingOrchestrator implements EpochProver {
480
495
  return;
481
496
  }
482
497
 
483
- // Get db for this block
484
498
  const blockNumber = provingState.blockNumber;
485
- const db = this.dbs.get(blockNumber)!.fork;
486
-
487
- const newArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
488
499
  const syncedArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.dbProvider.getSnapshot(blockNumber));
489
500
  if (!syncedArchive.equals(newArchive)) {
490
501
  this.logger.error(
@@ -502,12 +513,6 @@ export class ProvingOrchestrator implements EpochProver {
502
513
  provingState.reject(`New archive mismatch.`);
503
514
  return;
504
515
  }
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
516
  }
512
517
 
513
518
  /**
@@ -516,6 +521,11 @@ export class ProvingOrchestrator implements EpochProver {
516
521
  * If cancelJobsOnStop is false (default), jobs remain in the broker queue and can be reused on restart/reorg.
517
522
  */
518
523
  public cancel() {
524
+ void this.deferredJobQueue.cancel();
525
+ // Recreate the queue so it can accept jobs for subsequent epochs.
526
+ this.deferredJobQueue = new SerialQueue();
527
+ this.deferredJobQueue.start(this.enqueueConcurrency);
528
+
519
529
  if (this.cancelJobsOnStop) {
520
530
  for (const controller of this.pendingProvingJobs) {
521
531
  controller.abort();
@@ -523,6 +533,19 @@ export class ProvingOrchestrator implements EpochProver {
523
533
  }
524
534
 
525
535
  this.provingState?.cancel();
536
+
537
+ for (const [blockNumber, db] of this.dbs.entries()) {
538
+ void db.close().catch(err => this.logger.error(`Error closing db for block ${blockNumber}`, err));
539
+ }
540
+ this.dbs.clear();
541
+ }
542
+
543
+ private getDbForBlock(blockNumber: BlockNumber): MerkleTreeWriteOperations {
544
+ const db = this.dbs.get(blockNumber);
545
+ if (!db) {
546
+ throw new Error(`World state fork for block ${blockNumber} not found.`);
547
+ }
548
+ return db;
526
549
  }
527
550
 
528
551
  /**
@@ -554,24 +577,6 @@ export class ProvingOrchestrator implements EpochProver {
554
577
  return epochProofResult;
555
578
  }
556
579
 
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
580
  /**
576
581
  * Enqueue a job to be scheduled
577
582
  * @param provingState - The proving state object being operated on
@@ -630,8 +635,11 @@ export class ProvingOrchestrator implements EpochProver {
630
635
  }
631
636
  };
632
637
 
633
- // let the callstack unwind before adding the job to the queue
634
- setImmediate(() => void safeJob());
638
+ void this.deferredJobQueue.put(async () => {
639
+ void safeJob();
640
+ // we yield here to the macro task queue such to give Nodejs a chance to run other operatoins in between enqueues
641
+ await sleep(0);
642
+ });
635
643
  }
636
644
 
637
645
  private async updateL1ToL2MessageTree(l1ToL2Messages: Fr[], db: MerkleTreeWriteOperations) {
@@ -894,17 +902,15 @@ export class ProvingOrchestrator implements EpochProver {
894
902
  const leafLocation = provingState.setBlockRootRollupProof(result);
895
903
  const checkpointProvingState = provingState.parentCheckpoint;
896
904
 
897
- // If the proofs were slower than the block header building, then we need to try validating the block header hashes here.
905
+ // Verification is called from both here and setBlockCompleted. Whichever runs last
906
+ // will be the first to see all three pieces (header, proof output, archive) and run the checks.
898
907
  await this.verifyBuiltBlockAgainstSyncedState(provingState);
899
908
 
900
909
  if (checkpointProvingState.totalNumBlocks === 1) {
901
- this.checkAndEnqueueCheckpointRootRollup(checkpointProvingState);
910
+ await this.checkAndEnqueueCheckpointRootRollup(checkpointProvingState);
902
911
  } else {
903
- this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
912
+ await this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
904
913
  }
905
-
906
- // We are finished with the block at this point, ensure the fork is cleaned up
907
- void this.cleanupDBFork(provingState.blockNumber);
908
914
  },
909
915
  );
910
916
  }
@@ -1009,14 +1015,14 @@ export class ProvingOrchestrator implements EpochProver {
1009
1015
  },
1010
1016
  signal => this.prover.getBlockMergeRollupProof(inputs, signal, provingState.epochNumber),
1011
1017
  ),
1012
- result => {
1018
+ async result => {
1013
1019
  provingState.setBlockMergeRollupProof(location, result);
1014
- this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
1020
+ await this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
1015
1021
  },
1016
1022
  );
1017
1023
  }
1018
1024
 
1019
- private enqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1025
+ private async enqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1020
1026
  if (!provingState.verifyState()) {
1021
1027
  this.logger.debug('Not running checkpoint root rollup. State no longer valid.');
1022
1028
  return;
@@ -1031,7 +1037,7 @@ export class ProvingOrchestrator implements EpochProver {
1031
1037
 
1032
1038
  this.logger.debug(`Enqueuing ${rollupType} for checkpoint ${provingState.index}.`);
1033
1039
 
1034
- const inputs = provingState.getCheckpointRootRollupInputs();
1040
+ const inputs = await provingState.getCheckpointRootRollupInputs();
1035
1041
 
1036
1042
  this.deferredProving(
1037
1043
  provingState,
@@ -1191,25 +1197,28 @@ export class ProvingOrchestrator implements EpochProver {
1191
1197
  this.enqueueBlockRootRollup(provingState);
1192
1198
  }
1193
1199
 
1194
- private checkAndEnqueueNextBlockMergeRollup(provingState: CheckpointProvingState, currentLocation: TreeNodeLocation) {
1200
+ private async checkAndEnqueueNextBlockMergeRollup(
1201
+ provingState: CheckpointProvingState,
1202
+ currentLocation: TreeNodeLocation,
1203
+ ) {
1195
1204
  if (!provingState.isReadyForBlockMerge(currentLocation)) {
1196
1205
  return;
1197
1206
  }
1198
1207
 
1199
1208
  const parentLocation = provingState.getParentLocation(currentLocation);
1200
1209
  if (parentLocation.level === 0) {
1201
- this.checkAndEnqueueCheckpointRootRollup(provingState);
1210
+ await this.checkAndEnqueueCheckpointRootRollup(provingState);
1202
1211
  } else {
1203
1212
  this.enqueueBlockMergeRollup(provingState, parentLocation);
1204
1213
  }
1205
1214
  }
1206
1215
 
1207
- private checkAndEnqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1216
+ private async checkAndEnqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1208
1217
  if (!provingState.isReadyForCheckpointRoot()) {
1209
1218
  return;
1210
1219
  }
1211
1220
 
1212
- this.enqueueCheckpointRootRollup(provingState);
1221
+ await this.enqueueCheckpointRootRollup(provingState);
1213
1222
  }
1214
1223
 
1215
1224
  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) {
@@ -4,8 +4,9 @@ import type {
4
4
  NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
5
5
  RECURSIVE_PROOF_LENGTH,
6
6
  } from '@aztec/constants';
7
+ import { asyncPool } from '@aztec/foundation/async-pool';
7
8
  import { EpochNumber } from '@aztec/foundation/branded-types';
8
- import { sha256 } from '@aztec/foundation/crypto/sha256';
9
+ import { chunk } from '@aztec/foundation/collection';
9
10
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
10
11
  import { type PromiseWithResolvers, RunningPromise, promiseWithResolvers } from '@aztec/foundation/promise';
11
12
  import { truncate } from '@aztec/foundation/string';
@@ -46,6 +47,8 @@ import type {
46
47
  TxRollupPublicInputs,
47
48
  } from '@aztec/stdlib/rollup';
48
49
 
50
+ import { createHash } from 'node:crypto';
51
+
49
52
  import { InlineProofStore, type ProofStore } from './proof_store/index.js';
50
53
 
51
54
  // Perform a snapshot sync every 30 seconds
@@ -225,17 +228,11 @@ export class BrokerCircuitProverFacade implements ServerCircuitProver {
225
228
  // We collect all returned notifications and return them
226
229
  const allCompleted = new Set<ProvingJobId>();
227
230
  try {
228
- let numRequests = 0;
229
- while (ids.length > 0) {
230
- const slice = ids.splice(0, SNAPSHOT_SYNC_CHECK_MAX_REQUEST_SIZE);
231
- const completed = await this.broker.getCompletedJobs(slice);
231
+ const batches = ids.length > 0 ? chunk(ids, SNAPSHOT_SYNC_CHECK_MAX_REQUEST_SIZE) : [[]];
232
+ await asyncPool(1, batches, async batch => {
233
+ const completed = await this.broker.getCompletedJobs(batch);
232
234
  completed.forEach(id => allCompleted.add(id));
233
- ++numRequests;
234
- }
235
- if (numRequests === 0) {
236
- const final = await this.broker.getCompletedJobs([]);
237
- final.forEach(id => allCompleted.add(id));
238
- }
235
+ });
239
236
  } catch (err) {
240
237
  this.log.error(`Error thrown when requesting completed job notifications from the broker`, err);
241
238
  }
@@ -351,12 +348,8 @@ export class BrokerCircuitProverFacade implements ServerCircuitProver {
351
348
  .map(id => this.jobs.get(id)!)
352
349
  .filter(x => x !== undefined);
353
350
  const totalJobsToRetrieve = toBeRetrieved.length;
354
- let totalJobsRetrieved = 0;
355
- while (toBeRetrieved.length > 0) {
356
- const slice = toBeRetrieved.splice(0, MAX_CONCURRENT_JOB_SETTLED_REQUESTS);
357
- const results = await Promise.all(slice.map(job => processJob(job!)));
358
- totalJobsRetrieved += results.filter(x => x).length;
359
- }
351
+ const results = await asyncPool(MAX_CONCURRENT_JOB_SETTLED_REQUESTS, toBeRetrieved, job => processJob(job));
352
+ const totalJobsRetrieved = results.filter(x => x).length;
360
353
  if (totalJobsToRetrieve > 0) {
361
354
  this.log.verbose(
362
355
  `Successfully retrieved ${totalJobsRetrieved} of ${totalJobsToRetrieve} jobs that should be ready, total ready jobs is now: ${this.jobsToRetrieve.size}`,
@@ -659,8 +652,12 @@ export class BrokerCircuitProverFacade implements ServerCircuitProver {
659
652
  );
660
653
  }
661
654
 
662
- private generateId(type: ProvingRequestType, inputs: { toBuffer(): Buffer }, epochNumber = EpochNumber.ZERO) {
663
- const inputsHash = sha256(inputs.toBuffer());
664
- return makeProvingJobId(epochNumber, type, inputsHash.toString('hex'));
655
+ private generateId(
656
+ type: ProvingRequestType,
657
+ inputs: { toBuffer(): Buffer },
658
+ epochNumber = EpochNumber.ZERO,
659
+ ): ProvingJobId {
660
+ const inputsHash = createHash('sha256').update(inputs.toBuffer()).digest('hex');
661
+ return makeProvingJobId(epochNumber, type, inputsHash);
665
662
  }
666
663
  }
@@ -6,8 +6,8 @@ import {
6
6
  numberConfigHelper,
7
7
  } from '@aztec/foundation/config';
8
8
  import { pickConfigMappings } from '@aztec/foundation/config';
9
- import { type DataStoreConfig, dataConfigMappings } from '@aztec/kv-store/config';
10
9
  import { type ChainConfig, chainConfigMappings } from '@aztec/stdlib/config';
10
+ import { type DataStoreConfig, dataConfigMappings } from '@aztec/stdlib/kv-store';
11
11
  import { ProvingRequestType } from '@aztec/stdlib/proofs';
12
12
 
13
13
  import { z } from 'zod';
@@ -31,6 +31,8 @@ export const ProverBrokerConfig = z.object({
31
31
  proverBrokerBatchIntervalMs: z.number().int().nonnegative(),
32
32
  /** The maximum number of epochs to keep results for */
33
33
  proverBrokerMaxEpochsToKeepResultsFor: z.number().int().nonnegative(),
34
+ /** Enable debug replay mode for replaying proving jobs from stored inputs */
35
+ proverBrokerDebugReplayEnabled: z.boolean(),
34
36
  });
35
37
 
36
38
  export type ProverBrokerConfig = z.infer<typeof ProverBrokerConfig> &
@@ -74,6 +76,11 @@ export const proverBrokerConfigMappings: ConfigMappingsType<ProverBrokerConfig>
74
76
  parseEnv: (val: string | undefined) => (val ? +val : undefined),
75
77
  description: "The size of the prover broker's database. Will override the dataStoreMapSizeKb if set.",
76
78
  },
79
+ proverBrokerDebugReplayEnabled: {
80
+ env: 'PROVER_BROKER_DEBUG_REPLAY_ENABLED',
81
+ description: 'Enable debug replay mode for replaying proving jobs from stored inputs',
82
+ ...booleanConfigHelper(false),
83
+ },
77
84
  ...dataConfigMappings,
78
85
  ...l1ReaderConfigMappings,
79
86
  ...pickConfigMappings(chainConfigMappings, ['rollupVersion']),
@@ -102,6 +109,8 @@ export const ProverAgentConfig = z.object({
102
109
  proverTestVerificationDelayMs: z.number().optional(),
103
110
  /** Whether to abort pending proving jobs when the orchestrator is cancelled */
104
111
  cancelJobsOnStop: z.boolean(),
112
+ /** Where to store proving results. Must be accessible to both prover node and agents. If not set will inline-encode the parameters */
113
+ proofStore: z.string().optional(),
105
114
  });
106
115
 
107
116
  export type ProverAgentConfig = z.infer<typeof ProverAgentConfig>;
@@ -162,4 +171,8 @@ export const proverAgentConfigMappings: ConfigMappingsType<ProverAgentConfig> =
162
171
  'When false (default), jobs remain in the broker queue and can be reused on restart/reorg.',
163
172
  ...booleanConfigHelper(false),
164
173
  },
174
+ proofStore: {
175
+ env: 'PROVER_PROOF_STORE',
176
+ description: 'Optional proof input store for the prover',
177
+ },
165
178
  };
@@ -1,42 +1,20 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
+ import { createFileStore } from '@aztec/stdlib/file-store';
2
3
 
3
- import { GoogleCloudStorageProofStore } from './gcs_proof_store.js';
4
+ import { FileStoreProofStore } from './file_store_proof_store.js';
4
5
  import { InlineProofStore } from './inline_proof_store.js';
5
6
  import type { ProofStore } from './proof_store.js';
6
7
 
7
- export function createProofStore(config: string | undefined, logger = createLogger('prover-client:proof-store')) {
8
- if (config === undefined) {
8
+ export async function createProofStore(
9
+ config: string | undefined,
10
+ logger = createLogger('prover-client:proof-store'),
11
+ ): Promise<ProofStore> {
12
+ if (!config) {
9
13
  logger.info('Creating inline proof store');
10
14
  return new InlineProofStore();
11
- } else if (config.startsWith('gs://')) {
12
- try {
13
- const url = new URL(config);
14
- const bucket = url.host;
15
- const path = url.pathname.replace(/^\/+/, '');
16
- logger.info(`Creating google cloud proof store at ${bucket}`, { bucket, path });
17
- return new GoogleCloudStorageProofStore(bucket, path);
18
- } catch {
19
- throw new Error(
20
- `Invalid google cloud proof store definition: '${config}'. Supported values are 'gs://bucket-name/path/to/store'.`,
21
- );
22
- }
23
- } else {
24
- throw new Error(`Unknown proof store config: '${config}'. Supported values are 'gs://bucket-name/path/to/store'.`);
25
15
  }
26
- }
27
16
 
28
- export function createProofStoreForUri(
29
- uri: string,
30
- logger = createLogger('prover-client:proof-store'),
31
- ): Pick<ProofStore, 'getProofInput' | 'getProofOutput'> {
32
- if (uri.startsWith('data://')) {
33
- return createProofStore(undefined, logger);
34
- } else if (uri.startsWith('gs://')) {
35
- const url = new URL(uri);
36
- const basePath = url.pathname.replace(/^\/+/, '').split('/').slice(0, -3);
37
- url.pathname = basePath.join('/');
38
- return createProofStore(uri, logger);
39
- } else {
40
- throw new Error(`Unknown proof store config: '${uri}'. Supported protocols are 'data://' and 'gs://'.`);
41
- }
17
+ const fileStore = await createFileStore(config, logger);
18
+ logger.info(`Creating file store proof store at ${config}`);
19
+ return new FileStoreProofStore(fileStore);
42
20
  }
@@ -0,0 +1,78 @@
1
+ import { jsonParseWithSchema, jsonStringify } from '@aztec/foundation/json-rpc';
2
+ import type { FileStore } from '@aztec/stdlib/file-store';
3
+ import {
4
+ type ProofUri,
5
+ type ProvingJobId,
6
+ type ProvingJobInputs,
7
+ type ProvingJobInputsMap,
8
+ ProvingJobResult,
9
+ type ProvingJobResultsMap,
10
+ getProvingJobInputClassFor,
11
+ } from '@aztec/stdlib/interfaces/server';
12
+ import { ProvingRequestType } from '@aztec/stdlib/proofs';
13
+
14
+ import type { ProofStore } from './proof_store.js';
15
+
16
+ const INPUTS_PATH = 'inputs';
17
+ const OUTPUTS_PATH = 'outputs';
18
+
19
+ /**
20
+ * A proof store implementation backed by a generic FileStore.
21
+ * Supports any storage backend (GCS, S3, local filesystem) via the FileStore abstraction.
22
+ */
23
+ export class FileStoreProofStore implements ProofStore {
24
+ constructor(private readonly fileStore: FileStore) {}
25
+
26
+ async saveProofInput<T extends ProvingRequestType>(
27
+ id: ProvingJobId,
28
+ type: T,
29
+ inputs: ProvingJobInputsMap[T],
30
+ ): Promise<ProofUri> {
31
+ const path = `${INPUTS_PATH}/${ProvingRequestType[type]}/${id}`;
32
+ const uri = await this.fileStore.save(path, inputs.toBuffer());
33
+ return uri as ProofUri;
34
+ }
35
+
36
+ async saveProofOutput<T extends ProvingRequestType>(
37
+ id: ProvingJobId,
38
+ type: T,
39
+ result: ProvingJobResultsMap[T],
40
+ ): Promise<ProofUri> {
41
+ const jobResult = { type, result } as ProvingJobResult;
42
+ const json = jsonStringify(jobResult);
43
+ const path = `${OUTPUTS_PATH}/${ProvingRequestType[type]}/${id}.json`;
44
+ const uri = await this.fileStore.save(path, Buffer.from(json, 'utf-8'));
45
+ return uri as ProofUri;
46
+ }
47
+
48
+ async getProofInput(uri: ProofUri): Promise<ProvingJobInputs> {
49
+ try {
50
+ const buffer = await this.fileStore.read(uri);
51
+ const type = this.extractTypeFromUri(uri);
52
+ const inputs = getProvingJobInputClassFor(type).fromBuffer(buffer);
53
+ return { inputs, type } as ProvingJobInputs;
54
+ } catch (err) {
55
+ throw new Error(`Error getting proof input at ${uri}: ${err}`);
56
+ }
57
+ }
58
+
59
+ async getProofOutput(uri: ProofUri): Promise<ProvingJobResult> {
60
+ try {
61
+ const buffer = await this.fileStore.read(uri);
62
+ return jsonParseWithSchema(buffer.toString('utf-8'), ProvingJobResult);
63
+ } catch (err) {
64
+ throw new Error(`Error getting proof output at ${uri}: ${err}`);
65
+ }
66
+ }
67
+
68
+ private extractTypeFromUri(uri: string): ProvingRequestType {
69
+ const url = new URL(uri);
70
+ const pathParts = url.pathname.split('/').filter(Boolean);
71
+ const typeString = pathParts.at(-2);
72
+ const type = typeString ? ProvingRequestType[typeString as keyof typeof ProvingRequestType] : undefined;
73
+ if (type === undefined) {
74
+ throw new Error(`Unrecognized proof type ${typeString} in URI ${uri}`);
75
+ }
76
+ return type;
77
+ }
78
+ }
@@ -1,4 +1,4 @@
1
1
  export * from './proof_store.js';
2
2
  export * from './inline_proof_store.js';
3
3
  export * from './factory.js';
4
- export * from './gcs_proof_store.js';
4
+ export * from './file_store_proof_store.js';