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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dest/config.d.ts +1 -1
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +16 -2
  4. package/dest/light/lightweight_checkpoint_builder.d.ts +2 -1
  5. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -1
  6. package/dest/light/lightweight_checkpoint_builder.js +22 -5
  7. package/dest/mocks/test_context.d.ts +11 -11
  8. package/dest/mocks/test_context.d.ts.map +1 -1
  9. package/dest/mocks/test_context.js +25 -28
  10. package/dest/orchestrator/block-building-helpers.d.ts +1 -1
  11. package/dest/orchestrator/checkpoint-proving-state.d.ts +20 -36
  12. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -1
  13. package/dest/orchestrator/checkpoint-proving-state.js +22 -120
  14. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts +161 -0
  15. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts.map +1 -0
  16. package/dest/orchestrator/{orchestrator.js → checkpoint-sub-tree-orchestrator.js} +267 -435
  17. package/dest/orchestrator/chonk-cache.d.ts +39 -0
  18. package/dest/orchestrator/chonk-cache.d.ts.map +1 -0
  19. package/dest/orchestrator/chonk-cache.js +80 -0
  20. package/dest/orchestrator/index.d.ts +4 -2
  21. package/dest/orchestrator/index.d.ts.map +1 -1
  22. package/dest/orchestrator/index.js +3 -1
  23. package/dest/orchestrator/proving-scheduler.d.ts +81 -0
  24. package/dest/orchestrator/proving-scheduler.d.ts.map +1 -0
  25. package/dest/orchestrator/proving-scheduler.js +120 -0
  26. package/dest/orchestrator/top-tree-orchestrator.d.ts +88 -0
  27. package/dest/orchestrator/top-tree-orchestrator.d.ts.map +1 -0
  28. package/dest/orchestrator/top-tree-orchestrator.js +232 -0
  29. package/dest/orchestrator/top-tree-proving-state.d.ts +61 -0
  30. package/dest/orchestrator/top-tree-proving-state.d.ts.map +1 -0
  31. package/dest/orchestrator/top-tree-proving-state.js +185 -0
  32. package/dest/orchestrator/tx-proving-state.d.ts +3 -3
  33. package/dest/orchestrator/tx-proving-state.d.ts.map +1 -1
  34. package/dest/prover-client/prover-client.d.ts +62 -5
  35. package/dest/prover-client/prover-client.d.ts.map +1 -1
  36. package/dest/prover-client/prover-client.js +54 -7
  37. package/dest/proving_broker/broker_prover_facade.d.ts +3 -3
  38. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -1
  39. package/dest/proving_broker/broker_prover_facade.js +26 -20
  40. package/dest/proving_broker/config.d.ts +9 -73
  41. package/dest/proving_broker/config.d.ts.map +1 -1
  42. package/dest/proving_broker/config.js +3 -3
  43. package/dest/proving_broker/index.d.ts +2 -1
  44. package/dest/proving_broker/index.d.ts.map +1 -1
  45. package/dest/proving_broker/index.js +1 -0
  46. package/dest/proving_broker/proving_broker.d.ts +3 -2
  47. package/dest/proving_broker/proving_broker.d.ts.map +1 -1
  48. package/dest/proving_broker/proving_broker.js +219 -76
  49. package/dest/proving_broker/proving_broker_database/memory.d.ts +5 -2
  50. package/dest/proving_broker/proving_broker_database/memory.d.ts.map +1 -1
  51. package/dest/proving_broker/proving_broker_database/memory.js +14 -1
  52. package/dest/proving_broker/proving_broker_database/persisted.d.ts +15 -2
  53. package/dest/proving_broker/proving_broker_database/persisted.d.ts.map +1 -1
  54. package/dest/proving_broker/proving_broker_database/persisted.js +57 -6
  55. package/dest/proving_broker/proving_broker_database.d.ts +27 -1
  56. package/dest/proving_broker/proving_broker_database.d.ts.map +1 -1
  57. package/dest/proving_broker/rpc.d.ts +3 -1
  58. package/dest/proving_broker/rpc.d.ts.map +1 -1
  59. package/dest/proving_broker/rpc.js +80 -24
  60. package/dest/test/epoch_settlement.d.ts +36 -0
  61. package/dest/test/epoch_settlement.d.ts.map +1 -0
  62. package/dest/test/epoch_settlement.js +52 -0
  63. package/dest/test/index.d.ts +2 -0
  64. package/dest/test/index.d.ts.map +1 -0
  65. package/dest/test/index.js +1 -0
  66. package/dest/test/mock_prover.d.ts +4 -4
  67. package/dest/test/mock_prover.js +2 -2
  68. package/package.json +19 -18
  69. package/src/config.ts +18 -2
  70. package/src/light/lightweight_checkpoint_builder.ts +27 -6
  71. package/src/mocks/test_context.ts +24 -41
  72. package/src/orchestrator/checkpoint-proving-state.ts +21 -162
  73. package/src/orchestrator/{orchestrator.ts → checkpoint-sub-tree-orchestrator.ts} +415 -646
  74. package/src/orchestrator/chonk-cache.ts +99 -0
  75. package/src/orchestrator/index.ts +8 -1
  76. package/src/orchestrator/proving-scheduler.ts +160 -0
  77. package/src/orchestrator/top-tree-orchestrator.ts +384 -0
  78. package/src/orchestrator/top-tree-proving-state.ts +219 -0
  79. package/src/orchestrator/tx-proving-state.ts +3 -3
  80. package/src/prover-client/prover-client.ts +129 -18
  81. package/src/proving_broker/broker_prover_facade.ts +29 -23
  82. package/src/proving_broker/config.ts +3 -2
  83. package/src/proving_broker/index.ts +1 -0
  84. package/src/proving_broker/proving_broker.ts +209 -78
  85. package/src/proving_broker/proving_broker_database/memory.ts +16 -2
  86. package/src/proving_broker/proving_broker_database/persisted.ts +71 -8
  87. package/src/proving_broker/proving_broker_database.ts +30 -0
  88. package/src/proving_broker/rpc.ts +36 -24
  89. package/src/test/epoch_settlement.ts +82 -0
  90. package/src/test/index.ts +1 -0
  91. package/src/test/mock_prover.ts +2 -2
  92. package/dest/orchestrator/epoch-proving-state.d.ts +0 -75
  93. package/dest/orchestrator/epoch-proving-state.d.ts.map +0 -1
  94. package/dest/orchestrator/epoch-proving-state.js +0 -269
  95. package/dest/orchestrator/orchestrator.d.ts +0 -128
  96. package/dest/orchestrator/orchestrator.d.ts.map +0 -1
  97. package/dest/prover-client/server-epoch-prover.d.ts +0 -32
  98. package/dest/prover-client/server-epoch-prover.d.ts.map +0 -1
  99. package/dest/prover-client/server-epoch-prover.js +0 -40
  100. package/src/orchestrator/epoch-proving-state.ts +0 -380
  101. package/src/prover-client/server-epoch-prover.ts +0 -69
@@ -370,49 +370,48 @@ function applyDecs2203RFactory() {
370
370
  function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
371
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
372
  }
373
- var _dec, _dec1, _dec2, _dec3, _dec4, _initProto;
374
- import { L1_TO_L2_MSG_SUBTREE_HEIGHT, L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH, NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, NUM_BASE_PARITY_PER_ROOT_PARITY } from '@aztec/constants';
373
+ var _dec, _dec1, _dec2, _dec3, _initProto;
374
+ import { L1_TO_L2_MSG_SUBTREE_HEIGHT, L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH, NUM_BASE_PARITY_PER_ROOT_PARITY } from '@aztec/constants';
375
375
  import { BlockNumber } from '@aztec/foundation/branded-types';
376
- import { padArrayEnd } from '@aztec/foundation/collection';
377
- import { Fr } from '@aztec/foundation/curves/bn254';
378
376
  import { AbortError } from '@aztec/foundation/error';
379
- import { createLogger } from '@aztec/foundation/log';
380
377
  import { promiseWithResolvers } from '@aztec/foundation/promise';
381
378
  import { assertLength } from '@aztec/foundation/serialize';
382
- import { pushTestData } from '@aztec/foundation/testing';
383
- import { elapsed } from '@aztec/foundation/timer';
384
- import { BlockRootEmptyTxFirstRollupPrivateInputs, BlockRootFirstRollupPrivateInputs, BlockRootSingleTxFirstRollupPrivateInputs, BlockRootSingleTxRollupPrivateInputs, CheckpointRootSingleBlockRollupPrivateInputs, PrivateTxBaseRollupPrivateInputs } from '@aztec/stdlib/rollup';
379
+ import { appendL1ToL2MessagesToTree } from '@aztec/stdlib/messaging';
380
+ import { BlockRootEmptyTxFirstRollupPrivateInputs, BlockRootFirstRollupPrivateInputs, BlockRootSingleTxFirstRollupPrivateInputs, BlockRootSingleTxRollupPrivateInputs, PrivateTxBaseRollupPrivateInputs } from '@aztec/stdlib/rollup';
385
381
  import { MerkleTreeId } from '@aztec/stdlib/trees';
386
382
  import { Attributes, getTelemetryClient, trackSpan, wrapCallbackInSpan } from '@aztec/telemetry-client';
387
383
  import { inspect } from 'util';
388
384
  import { buildHeaderFromCircuitOutputs, getLastSiblingPath, getPublicChonkVerifierPrivateInputsFromTx, getRootTreeSiblingPath, getSubtreeSiblingPath, getTreeSnapshot, insertSideEffectsAndBuildBaseRollupHints, validatePartialState, validateTx } from './block-building-helpers.js';
389
- import { EpochProvingState } from './epoch-proving-state.js';
385
+ import { CheckpointProvingState } from './checkpoint-proving-state.js';
390
386
  import { ProvingOrchestratorMetrics } from './orchestrator_metrics.js';
387
+ import { ProvingScheduler } from './proving-scheduler.js';
391
388
  import { TxProvingState } from './tx-proving-state.js';
392
- _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
389
+ _dec = trackSpan('CheckpointSubTreeOrchestrator.startNewBlock', (blockNumber)=>({
393
390
  [Attributes.BLOCK_NUMBER]: blockNumber
394
- })), _dec1 = trackSpan('ProvingOrchestrator.addTxs', (txs)=>({
391
+ })), _dec1 = trackSpan('CheckpointSubTreeOrchestrator.addTxs', (txs)=>({
395
392
  [Attributes.BLOCK_TXS_COUNT]: txs.length
396
- })), _dec2 = trackSpan('ProvingOrchestrator.startChonkVerifierCircuits'), _dec3 = trackSpan('ProvingOrchestrator.setBlockCompleted', (blockNumber)=>({
393
+ })), _dec2 = trackSpan('CheckpointSubTreeOrchestrator.setBlockCompleted', (blockNumber)=>({
397
394
  [Attributes.BLOCK_NUMBER]: blockNumber
398
- })), _dec4 = trackSpan('ProvingOrchestrator.prepareBaseRollupInputs', (tx)=>({
395
+ })), _dec3 = trackSpan('CheckpointSubTreeOrchestrator.prepareBaseRollupInputs', (tx)=>({
399
396
  [Attributes.TX_HASH]: tx.hash.toString()
400
397
  }));
401
398
  /**
402
- * Implements an event driven proving scheduler to build the recursive proof tree. The idea being:
403
- * 1. Transactions are provided to the scheduler post simulation.
404
- * 2. Tree insertions are performed as required to generate transaction specific proofs
405
- * 3. Those transaction specific proofs are generated in the necessary order accounting for dependencies
406
- * 4. Once a transaction is proven, it will be incorporated into a merge proof
407
- * 5. Merge proofs are produced at each level of the tree until the root proof is produced
399
+ * Orchestrates block-level proving for a single checkpoint, stopping at the boundary
400
+ * where checkpoint root rollup would otherwise begin. Used by the per-checkpoint
401
+ * `CheckpointProver` in production; the top-tree orchestrator then composes the
402
+ * sub-tree's block proofs into the epoch proof.
408
403
  *
409
- * The proving implementation is determined by the provided prover. This could be for example a local prover or a remote prover pool.
410
- */ /**
411
- * The orchestrator, managing the flow of recursive proving operations required to build the rollup proof tree.
412
- */ export class ProvingOrchestrator {
404
+ * Wiring: a single-checkpoint mini-proving session is owned by the constructor. The
405
+ * canonical way to obtain a fully-started sub-tree is the `start` static factory,
406
+ * which also drives the single internal `startCheckpoint` call. The sub-tree never
407
+ * escalates past the checkpoint root boundary; `getSubTreeResult()` resolves once
408
+ * every block-level proof in the checkpoint's tree is ready.
409
+ */ export class CheckpointSubTreeOrchestrator extends ProvingScheduler {
413
410
  dbProvider;
414
411
  prover;
415
412
  proverId;
413
+ chonkCache;
414
+ epochNumber;
416
415
  cancelJobsOnStop;
417
416
  static{
418
417
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
@@ -429,39 +428,33 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
429
428
  [
430
429
  _dec2,
431
430
  2,
432
- "startChonkVerifierCircuits"
433
- ],
434
- [
435
- _dec3,
436
- 2,
437
431
  "setBlockCompleted"
438
432
  ],
439
433
  [
440
- _dec4,
434
+ _dec3,
441
435
  2,
442
436
  "prepareBaseRollupInputs"
443
437
  ]
444
438
  ], []));
445
439
  }
446
- provingState;
447
- pendingProvingJobs;
448
- provingPromise;
440
+ /** The single checkpoint proving state this sub-tree owns. Allocated in the `start` factory. */ provingState;
441
+ subTreeResult;
449
442
  metrics;
450
- // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
451
443
  dbs;
452
- logger;
453
- constructor(dbProvider, prover, proverId, cancelJobsOnStop = false, telemetryClient = getTelemetryClient(), bindings){
454
- this.dbProvider = dbProvider;
455
- this.prover = prover;
456
- this.proverId = proverId;
457
- this.cancelJobsOnStop = cancelJobsOnStop;
458
- this.provingState = (_initProto(this), undefined);
459
- this.pendingProvingJobs = [];
460
- this.provingPromise = undefined;
461
- this.dbs = new Map();
462
- this.logger = createLogger('prover-client:orchestrator', bindings);
463
- this.metrics = new ProvingOrchestratorMetrics(telemetryClient, 'ProvingOrchestrator');
444
+ constructor(dbProvider, prover, proverId, /**
445
+ * Shared chonk-verifier proof cache. Every chonk-verifier proof started by this
446
+ * sub-tree lives on the cache and survives the sub-tree's cancellation, so a tx
447
+ * whose original checkpoint is reorged out and re-appears in a replacement
448
+ * checkpoint reuses the cached proof.
449
+ */ chonkCache, /** The epoch this sub-tree proves into. */ epochNumber, cancelJobsOnStop = false, deferredJobQueue, telemetryClient = getTelemetryClient(), bindings){
450
+ super(deferredJobQueue, 'prover-client:checkpoint-sub-tree-orchestrator', bindings), this.dbProvider = dbProvider, this.prover = prover, this.proverId = proverId, this.chonkCache = chonkCache, this.epochNumber = epochNumber, this.cancelJobsOnStop = cancelJobsOnStop, this.provingState = (_initProto(this), undefined), this.dbs = new Map(), this.cancelled = false;
451
+ this.metrics = new ProvingOrchestratorMetrics(telemetryClient, 'CheckpointSubTreeOrchestrator');
452
+ this.subTreeResult = promiseWithResolvers();
453
+ // Mark the rejection branch as observed so a `cancel()` or proving failure does not
454
+ // surface an unhandled rejection when no consumer awaits getSubTreeResult().
455
+ this.subTreeResult.promise.catch(()=>{});
464
456
  }
457
+ /** Tracks whether `cancel()` has been called; flows into the checkpoint state's isAlive hook. */ cancelled;
465
458
  get tracer() {
466
459
  return this.metrics.tracer;
467
460
  }
@@ -471,70 +464,74 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
471
464
  getNumActiveForks() {
472
465
  return this.dbs.size;
473
466
  }
474
- stop() {
475
- this.cancel();
476
- return Promise.resolve();
477
- }
478
- startNewEpoch(epochNumber, totalNumCheckpoints, finalBlobBatchingChallenges) {
479
- if (this.provingState?.verifyState()) {
480
- throw new Error(`Cannot start epoch ${epochNumber} when epoch ${this.provingState.epochNumber} is still being processed.`);
481
- }
482
- const { promise: _promise, resolve, reject } = promiseWithResolvers();
483
- const promise = _promise.catch((reason)=>({
484
- status: 'failure',
485
- reason
486
- }));
487
- this.logger.info(`Starting epoch ${epochNumber} with ${totalNumCheckpoints} checkpoints.`);
488
- this.provingState = new EpochProvingState(epochNumber, totalNumCheckpoints, finalBlobBatchingChallenges, (provingState)=>this.checkAndEnqueueCheckpointRootRollup(provingState), resolve, reject);
489
- this.provingPromise = promise;
467
+ /** Returns a promise that resolves when block-level proving completes for the checkpoint. */ getSubTreeResult() {
468
+ return this.subTreeResult.promise;
490
469
  }
491
470
  /**
492
- * Starts a new checkpoint.
493
- * @param checkpointIndex - The index of the checkpoint in the epoch.
494
- * @param constants - The constants for this checkpoint.
495
- * @param l1ToL2Messages - The set of L1 to L2 messages to be inserted at the beginning of this checkpoint.
496
- * @param totalNumBlocks - The total number of blocks expected in the checkpoint (must be at least one).
497
- * @param headerOfLastBlockInPreviousCheckpoint - The header of the last block in the previous checkpoint.
498
- */ async startNewCheckpoint(checkpointIndex, constants, l1ToL2Messages, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint) {
471
+ * Returns the archive sibling path captured at the internal checkpoint start.
472
+ * Available synchronously once `start` has resolved, before block-level proving
473
+ * completes. The top-tree consumer uses this to assemble checkpoint root rollup hints
474
+ * up-front so checkpoint root proofs can pipeline against in-flight sub-tree proving.
475
+ */ getPreviousArchiveSiblingPath() {
499
476
  if (!this.provingState) {
500
- throw new Error('Empty epoch proving state. Call startNewEpoch before starting a checkpoint.');
477
+ throw new Error('Checkpoint not started; call CheckpointSubTreeOrchestrator.start first.');
501
478
  }
502
- if (!this.provingState.isAcceptingCheckpoints()) {
503
- throw new Error(`Epoch not accepting further checkpoints.`);
479
+ return this.provingState.getLastArchiveSiblingPath();
480
+ }
481
+ /**
482
+ * Constructs and starts a sub-tree for a single checkpoint. The returned sub-tree
483
+ * has had its single internal checkpoint state allocated; callers proceed directly
484
+ * to per-block `startNewBlock` / `addTxs` / `setBlockCompleted`.
485
+ *
486
+ * If the internal start rejects, the partially-constructed sub-tree is stopped
487
+ * before the error propagates, so no broker resources leak.
488
+ */ static async start(dbProvider, prover, proverId, chonkCache, epochNumber, cancelJobsOnStop, deferredJobQueue, checkpointConstants, l1ToL2Messages, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint, telemetryClient = getTelemetryClient(), bindings) {
489
+ const subTree = new CheckpointSubTreeOrchestrator(dbProvider, prover, proverId, chonkCache, epochNumber, cancelJobsOnStop, deferredJobQueue, telemetryClient, bindings);
490
+ try {
491
+ await subTree.startCheckpoint(checkpointConstants, l1ToL2Messages, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint);
492
+ return subTree;
493
+ } catch (err) {
494
+ await subTree.stop().catch(()=>{});
495
+ throw err;
504
496
  }
505
- // Fork world state at the end of the immediately previous block.
506
- const lastBlockNumber = headerOfLastBlockInPreviousCheckpoint.globalVariables.blockNumber;
507
- const db = await this.dbProvider.fork(lastBlockNumber);
508
- const firstBlockNumber = BlockNumber(lastBlockNumber + 1);
509
- this.dbs.set(firstBlockNumber, db);
510
- // Get archive sibling path before any block in this checkpoint lands.
511
- const lastArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, db);
512
- // Insert all the l1 to l2 messages into the db. And get the states before and after the insertion.
513
- const { lastL1ToL2MessageTreeSnapshot, lastL1ToL2MessageSubtreeRootSiblingPath, newL1ToL2MessageTreeSnapshot, newL1ToL2MessageSubtreeRootSiblingPath } = await this.updateL1ToL2MessageTree(l1ToL2Messages, db);
514
- this.provingState.startNewCheckpoint(checkpointIndex, constants, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint, lastArchiveSiblingPath, l1ToL2Messages, lastL1ToL2MessageTreeSnapshot, lastL1ToL2MessageSubtreeRootSiblingPath, newL1ToL2MessageTreeSnapshot, newL1ToL2MessageSubtreeRootSiblingPath);
515
497
  }
516
498
  /**
517
- * Starts off a new block
499
+ * Kickstart chonk-verifier circuits via the shared `ChonkCache`. The cache owns the
500
+ * broker job lifecycle, so the proof survives this sub-tree's `cancel()` — a tx that
501
+ * ends up in a replacement checkpoint after a reorg can pick the cached promise up
502
+ * and skip re-proving.
503
+ */ startChonkVerifierCircuits(txs) {
504
+ if (!this.provingState?.verifyState()) {
505
+ return Promise.reject(new Error('Sub-tree proving state is not active.'));
506
+ }
507
+ const publicTxs = txs.filter((tx)=>tx.data.forPublic);
508
+ for (const tx of publicTxs){
509
+ const txHash = tx.getTxHash().toString();
510
+ const inputs = getPublicChonkVerifierPrivateInputsFromTx(tx, this.getProverId().toField());
511
+ // Fire and forget — getOrEnqueueChonkVerifier later picks up the cached promise
512
+ // when the tx is processed inside its block.
513
+ void this.chonkCache.getOrCompute(txHash, (signal)=>this.prover.getPublicChonkVerifierProof(inputs, signal, this.epochNumber));
514
+ }
515
+ return Promise.resolve();
516
+ }
517
+ // ---------------- per-block driving (called by the per-checkpoint CheckpointProver) ----------------
518
+ /**
519
+ * Starts off a new block.
518
520
  * @param blockNumber - The block number
519
- * @param timestamp - The timestamp of the block. This is only required for constructing the private inputs for the
520
- * block that doesn't have any txs.
521
- * @param totalNumTxs - The total number of txs in the block
521
+ * @param timestamp - The timestamp of the block. Required for empty blocks to construct private inputs.
522
+ * @param totalNumTxs - The total number of txs in the block.
522
523
  */ async startNewBlock(blockNumber, timestamp, totalNumTxs) {
523
524
  if (!this.provingState) {
524
- throw new Error('Empty epoch proving state. Call startNewEpoch before starting a block.');
525
+ throw new Error('Empty proving state. The checkpoint sub-tree has not been started.');
525
526
  }
526
- const checkpointProvingState = this.provingState.getCheckpointProvingStateByBlockNumber(blockNumber);
527
- if (!checkpointProvingState) {
528
- throw new Error(`Checkpoint not started. Call startNewCheckpoint first.`);
529
- }
530
- if (!checkpointProvingState.isAcceptingBlocks()) {
527
+ if (!this.provingState.isAcceptingBlocks()) {
531
528
  throw new Error(`Checkpoint not accepting further blocks.`);
532
529
  }
533
- const constants = checkpointProvingState.constants;
530
+ const constants = this.provingState.constants;
534
531
  this.logger.info(`Starting block ${blockNumber} for slot ${constants.slotNumber}.`);
535
- // Fork the db only when it's not already set. The db for the first block is set in `startNewCheckpoint`.
532
+ // Fork the db only when it's not already set. The db for the first block is set in startCheckpoint.
536
533
  if (!this.dbs.has(blockNumber)) {
537
- // Fork world state at the end of the immediately previous block
534
+ // Fork world state at the end of the immediately previous block.
538
535
  const db = await this.dbProvider.fork(BlockNumber(blockNumber - 1));
539
536
  this.dbs.set(blockNumber, db);
540
537
  }
@@ -542,15 +539,15 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
542
539
  // Get archive snapshot and sibling path before any txs in this block lands.
543
540
  const lastArchiveTreeSnapshot = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
544
541
  const lastArchiveSiblingPath = await getRootTreeSiblingPath(MerkleTreeId.ARCHIVE, db);
545
- const blockProvingState = checkpointProvingState.startNewBlock(blockNumber, timestamp, totalNumTxs, lastArchiveTreeSnapshot, lastArchiveSiblingPath);
542
+ const blockProvingState = this.provingState.startNewBlock(blockNumber, timestamp, totalNumTxs, lastArchiveTreeSnapshot, lastArchiveSiblingPath);
546
543
  // Enqueue base parity circuits for the first block in the checkpoint.
547
544
  if (blockProvingState.index === 0) {
548
545
  for(let i = 0; i < NUM_BASE_PARITY_PER_ROOT_PARITY; i++){
549
- this.enqueueBaseParityCircuit(checkpointProvingState, blockProvingState, i);
546
+ this.enqueueBaseParityCircuit(this.provingState, blockProvingState, i);
550
547
  }
551
548
  }
552
- // Because `addTxs` won't be called for a block without txs, and that's where the sponge blob state is computed.
553
- // We need to set its end sponge blob here, which will become the start sponge blob for the next block.
549
+ // Because `addTxs` won't be called for a block without txs, and that's where the sponge blob state is computed,
550
+ // set its end sponge blob here. This becomes the start sponge blob for the next block.
554
551
  if (totalNumTxs === 0) {
555
552
  const endState = await db.getStateReference();
556
553
  blockProvingState.setEndState(endState);
@@ -558,22 +555,19 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
558
555
  const blockEndBlobFields = blockProvingState.getBlockEndBlobFields();
559
556
  await endSpongeBlob.absorb(blockEndBlobFields);
560
557
  blockProvingState.setEndSpongeBlob(endSpongeBlob);
561
- // Try to accumulate the out hashes and blobs as far as we can:
562
- await this.provingState.accumulateCheckpointOutHashes();
563
- await this.provingState.setBlobAccumulators();
564
558
  }
565
559
  }
566
560
  /**
567
- * The interface to add simulated transactions to the scheduler. This can only be called once per block.
561
+ * The interface to add simulated transactions to the scheduler. Called at most once per block.
568
562
  * @param txs - The transactions to be proven
569
563
  */ async addTxs(txs) {
570
564
  if (!this.provingState) {
571
- throw new Error(`Empty epoch proving state. Call startNewEpoch before adding txs.`);
565
+ throw new Error(`Empty proving state. The checkpoint sub-tree has not been started.`);
572
566
  }
573
567
  if (!txs.length) {
574
- // To avoid an ugly throw below. If we require an empty block, we can just call setBlockCompleted
575
- // on a block with no txs. We cannot do that here because we cannot find the blockNumber without any txs.
576
- this.logger.warn(`Provided no txs to orchestrator addTxs.`);
568
+ // Empty block: setBlockCompleted handles this without addTxs being called. Bail to
569
+ // avoid the throw below (we cannot find the blockNumber without any txs).
570
+ this.logger.verbose(`Provided no txs to addTxs.`);
577
571
  return;
578
572
  }
579
573
  const blockNumber = BlockNumber(txs[0].globalVariables.blockNumber);
@@ -626,29 +620,6 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
626
620
  const blockEndBlobFields = provingState.getBlockEndBlobFields();
627
621
  await spongeBlobState.absorb(blockEndBlobFields);
628
622
  provingState.setEndSpongeBlob(spongeBlobState);
629
- // Txs have been added to the block. Now try to accumulate the out hashes and blobs as far as we can:
630
- await this.provingState.accumulateCheckpointOutHashes();
631
- await this.provingState.setBlobAccumulators();
632
- }
633
- /**
634
- * Kickstarts chonk verifier circuits for the specified txs. These will be used during epoch proving.
635
- * Note that if the chonk verifier circuits are not started this way, they will be started nontheless after processing.
636
- */ startChonkVerifierCircuits(txs) {
637
- if (!this.provingState?.verifyState()) {
638
- throw new Error(`Empty epoch proving state. call startNewEpoch before starting chonk verifier circuits.`);
639
- }
640
- const publicTxs = txs.filter((tx)=>tx.data.forPublic);
641
- for (const tx of publicTxs){
642
- const txHash = tx.getTxHash().toString();
643
- const privateInputs = getPublicChonkVerifierPrivateInputsFromTx(tx, this.proverId.toField());
644
- const tubeProof = promiseWithResolvers();
645
- this.logger.debug(`Starting chonk verifier circuit for tx ${txHash}`);
646
- this.doEnqueueChonkVerifier(txHash, privateInputs, (proof)=>{
647
- tubeProof.resolve(proof);
648
- });
649
- this.provingState.cachedChonkVerifierProofs.set(txHash, tubeProof.promise);
650
- }
651
- return Promise.resolve();
652
623
  }
653
624
  /**
654
625
  * Marks the block as completed.
@@ -691,139 +662,50 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
691
662
  await this.verifyBuiltBlockAgainstSyncedState(provingState);
692
663
  return header;
693
664
  }
694
- // Flagged as protected to disable in certain unit tests
695
- async verifyBuiltBlockAgainstSyncedState(provingState) {
696
- const builtBlockHeader = provingState.getBuiltBlockHeader();
697
- if (!builtBlockHeader) {
698
- this.logger.debug('Block header not built yet, skipping header check.');
699
- return;
700
- }
701
- const output = provingState.getBlockRootRollupOutput();
702
- if (!output) {
703
- this.logger.debug('Block root rollup proof not built yet, skipping header check.');
704
- return;
705
- }
706
- const newArchive = provingState.getBuiltArchive();
707
- if (!newArchive) {
708
- this.logger.debug('Archive snapshot not yet captured, skipping header check.');
709
- return;
710
- }
711
- const header = await buildHeaderFromCircuitOutputs(output);
712
- if (!(await header.hash()).equals(await builtBlockHeader.hash())) {
713
- this.logger.error(`Block header mismatch.\nCircuit: ${inspect(header)}\nComputed: ${inspect(builtBlockHeader)}`);
714
- provingState.reject(`Block header hash mismatch.`);
715
- return;
716
- }
717
- const blockNumber = provingState.blockNumber;
718
- const syncedArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.dbProvider.getSnapshot(blockNumber));
719
- if (!syncedArchive.equals(newArchive)) {
720
- this.logger.error(`Archive tree mismatch for block ${blockNumber}: world state synced to ${inspect(syncedArchive)} but built ${inspect(newArchive)}`);
721
- provingState.reject(`Archive tree mismatch.`);
722
- return;
723
- }
724
- const circuitArchive = output.newArchive;
725
- if (!newArchive.equals(circuitArchive)) {
726
- this.logger.error(`New archive mismatch.\nCircuit: ${output.newArchive}\nComputed: ${newArchive}`);
727
- provingState.reject(`New archive mismatch.`);
728
- return;
729
- }
730
- }
665
+ // ---------------- lifecycle ----------------
731
666
  /**
732
- * Cancel any further proving.
733
- * If cancelJobsOnStop is true, aborts all pending jobs with the broker (which marks them as 'Aborted').
734
- * If cancelJobsOnStop is false (default), jobs remain in the broker queue and can be reused on restart/reorg.
667
+ * Cancels any further proving. If `cancelJobsOnStop` was set, aborts all pending broker jobs
668
+ * (used on reorg). Otherwise jobs remain in the broker queue and can be reused on restart.
735
669
  */ cancel() {
736
- if (this.cancelJobsOnStop) {
737
- for (const controller of this.pendingProvingJobs){
738
- controller.abort();
739
- }
740
- }
670
+ this.cancelled = true;
671
+ this.resetSchedulerState(this.cancelJobsOnStop);
672
+ // Reject the proving state (and hence subTreeResult) so anyone awaiting the sub-tree result
673
+ // is released rather than hanging — matching TopTreeOrchestrator.cancel().
741
674
  this.provingState?.cancel();
742
675
  for (const [blockNumber, db] of this.dbs.entries()){
743
676
  void db.close().catch((err)=>this.logger.error(`Error closing db for block ${blockNumber}`, err));
744
677
  }
745
678
  this.dbs.clear();
746
679
  }
747
- getDbForBlock(blockNumber) {
748
- const db = this.dbs.get(blockNumber);
749
- if (!db) {
750
- throw new Error(`World state fork for block ${blockNumber} not found.`);
751
- }
752
- return db;
753
- }
754
- /**
755
- * Returns the proof for the current epoch.
756
- */ async finalizeEpoch() {
757
- if (!this.provingState || !this.provingPromise) {
758
- throw new Error(`Invalid proving state, an epoch must be proven before it can be finalized`);
759
- }
760
- const result = await this.provingPromise;
761
- if (result.status === 'failure') {
762
- throw new Error(`Epoch proving failed: ${result.reason}`);
763
- }
764
- await this.provingState.finalizeBatchedBlob();
765
- const epochProofResult = this.provingState.getEpochProofResult();
766
- pushTestData('epochProofResult', {
767
- proof: epochProofResult.proof.toString(),
768
- publicInputs: epochProofResult.publicInputs.toString()
769
- });
770
- return epochProofResult;
680
+ cancelInternal() {
681
+ this.cancel();
771
682
  }
683
+ // ---------------- private: per-checkpoint init ----------------
772
684
  /**
773
- * Enqueue a job to be scheduled
774
- * @param provingState - The proving state object being operated on
775
- * @param jobType - The type of job to be queued
776
- * @param job - The actual job, returns a promise notifying of the job's completion
777
- */ deferredProving(provingState, request, callback) {
778
- if (!provingState.verifyState()) {
779
- this.logger.debug(`Not enqueuing job, state no longer valid`);
780
- return;
685
+ * Internal driver for the single-checkpoint init. Allocates the world-state fork,
686
+ * inserts L1-to-L2 messages, and creates the per-checkpoint proving state with this
687
+ * sub-tree as its parent. Only called once, from the `start` factory.
688
+ */ async startCheckpoint(constants, l1ToL2Messages, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint) {
689
+ if (this.provingState) {
690
+ throw new Error('Checkpoint sub-tree already started.');
781
691
  }
782
- const controller = new AbortController();
783
- this.pendingProvingJobs.push(controller);
784
- // We use a 'safeJob'. We don't want promise rejections in the proving pool, we want to capture the error here
785
- // and reject the proving job whilst keeping the event loop free of rejections
786
- const safeJob = async ()=>{
787
- try {
788
- // there's a delay between enqueueing this job and it actually running
789
- if (controller.signal.aborted) {
790
- return;
791
- }
792
- const result = await request(controller.signal);
793
- if (!provingState.verifyState()) {
794
- this.logger.debug(`State no longer valid, discarding result`);
795
- return;
796
- }
797
- // we could have been cancelled whilst waiting for the result
798
- // and the prover ignored the signal. Drop the result in that case
799
- if (controller.signal.aborted) {
800
- return;
801
- }
802
- await callback(result);
803
- } catch (err) {
804
- if (err instanceof AbortError) {
805
- // operation was cancelled, probably because the block was cancelled
806
- // drop this result
807
- return;
808
- }
809
- this.logger.error(`Error thrown when proving job`, err);
810
- provingState.reject(`${err}`);
811
- } finally{
812
- const index = this.pendingProvingJobs.indexOf(controller);
813
- if (index > -1) {
814
- this.pendingProvingJobs.splice(index, 1);
815
- }
816
- }
817
- };
818
- // let the callstack unwind before adding the job to the queue
819
- setImmediate(()=>void safeJob());
692
+ // Fork world state at the end of the immediately previous block.
693
+ const lastBlockNumber = headerOfLastBlockInPreviousCheckpoint.globalVariables.blockNumber;
694
+ const db = await this.dbProvider.fork(lastBlockNumber);
695
+ const firstBlockNumber = BlockNumber(lastBlockNumber + 1);
696
+ this.dbs.set(firstBlockNumber, db);
697
+ // Get archive sibling path before any block in this checkpoint lands.
698
+ const lastArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, db);
699
+ // Insert all the l1 to l2 messages into the db. Get the states before and after the insertion.
700
+ const { lastL1ToL2MessageTreeSnapshot, lastL1ToL2MessageSubtreeRootSiblingPath, newL1ToL2MessageTreeSnapshot, newL1ToL2MessageSubtreeRootSiblingPath } = await this.updateL1ToL2MessageTree(l1ToL2Messages, db);
701
+ this.provingState = new CheckpointProvingState(/* index */ 0, constants, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint, lastArchiveSiblingPath, l1ToL2Messages, lastL1ToL2MessageTreeSnapshot, lastL1ToL2MessageSubtreeRootSiblingPath, newL1ToL2MessageTreeSnapshot, newL1ToL2MessageSubtreeRootSiblingPath, Number(this.epochNumber), /* isAlive */ ()=>!this.cancelled, /* onReject */ (reason)=>this.subTreeResult.reject(new Error(reason)));
820
702
  }
703
+ // ---------------- private: per-block proof orchestration ----------------
821
704
  async updateL1ToL2MessageTree(l1ToL2Messages, db) {
822
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, 'Too many L1 to L2 messages');
823
705
  const lastL1ToL2MessageTreeSnapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
824
706
  const lastL1ToL2MessageSubtreeRootSiblingPath = assertLength(await getSubtreeSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, L1_TO_L2_MSG_SUBTREE_HEIGHT, db), L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH);
825
- // Update the local trees to include the new l1 to l2 messages
826
- await db.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
707
+ // Update the local trees to include the new l1 to l2 messages.
708
+ await appendL1ToL2MessagesToTree(db, l1ToL2Messages);
827
709
  const newL1ToL2MessageTreeSnapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
828
710
  const newL1ToL2MessageSubtreeRootSiblingPath = assertLength(await getSubtreeSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, L1_TO_L2_MSG_SUBTREE_HEIGHT, db), L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH);
829
711
  return {
@@ -833,12 +715,15 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
833
715
  newL1ToL2MessageSubtreeRootSiblingPath
834
716
  };
835
717
  }
836
- // Updates the merkle trees for a transaction. The first enqueued job for a transaction
718
+ // Updates the merkle trees for a transaction. The first enqueued job for a transaction.
837
719
  async prepareBaseRollupInputs(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, db) {
838
- // We build the base rollup inputs using a mock proof and verification key.
839
- // These will be overwritten later once we have proven the chonk verifier circuit and any public kernels
840
- const [ms, hints] = await elapsed(insertSideEffectsAndBuildBaseRollupHints(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, this.proverId.toField(), db));
841
- this.metrics.recordBaseRollupInputs(ms);
720
+ // These hints deliberately carry no recursive proof or verification key — see
721
+ // BaseRollupHintsWithoutProofAndVK. The tx's proof + VK are attached later in
722
+ // TxProvingState.getBaseRollupTypeAndInputs from the proven chonk-verifier / kernel / AVM
723
+ // proofs, which are required there and so cannot be silently omitted.
724
+ const start = performance.now();
725
+ const hints = await insertSideEffectsAndBuildBaseRollupHints(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, this.proverId.toField(), db);
726
+ this.metrics.recordBaseRollupInputs(performance.now() - start);
842
727
  const promises = [
843
728
  MerkleTreeId.NOTE_HASH_TREE,
844
729
  MerkleTreeId.NULLIFIER_TREE,
@@ -858,8 +743,8 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
858
743
  treeSnapshots
859
744
  ];
860
745
  }
861
- // Executes the base rollup circuit and stored the output as intermediate state for the parent merge/root circuit
862
- // Executes the next level of merge if all inputs are available
746
+ // Executes the base rollup circuit and stores the output as intermediate state for the parent merge/root circuit.
747
+ // Executes the next level of merge if all inputs are available.
863
748
  enqueueBaseRollup(provingState, txIndex) {
864
749
  if (!provingState.verifyState()) {
865
750
  this.logger.debug('Not running base rollup, state invalid');
@@ -873,15 +758,15 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
873
758
  const { processedTx } = txProvingState;
874
759
  const { rollupType, inputs } = txProvingState.getBaseRollupTypeAndInputs();
875
760
  this.logger.debug(`Enqueuing deferred proving base rollup for ${processedTx.hash.toString()}`);
876
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, `ProvingOrchestrator.prover.${inputs instanceof PrivateTxBaseRollupPrivateInputs ? 'getPrivateTxBaseRollupProof' : 'getPublicTxBaseRollupProof'}`, {
877
- [Attributes.TX_HASH]: processedTx.hash.toString(),
878
- [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
879
- }, (signal)=>{
761
+ this.deferredProving(provingState, this.wrapCircuitCall(inputs instanceof PrivateTxBaseRollupPrivateInputs ? 'getPrivateTxBaseRollupProof' : 'getPublicTxBaseRollupProof', (signal)=>{
880
762
  if (inputs instanceof PrivateTxBaseRollupPrivateInputs) {
881
763
  return this.prover.getPrivateTxBaseRollupProof(inputs, signal, provingState.epochNumber);
882
764
  } else {
883
765
  return this.prover.getPublicTxBaseRollupProof(inputs, signal, provingState.epochNumber);
884
766
  }
767
+ }, {
768
+ [Attributes.TX_HASH]: processedTx.hash.toString(),
769
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
885
770
  }), (result)=>{
886
771
  this.logger.debug(`Completed proof for ${rollupType} for tx ${processedTx.hash.toString()}`);
887
772
  validatePartialState(result.inputs.endTreeSnapshots, txProvingState.treeSnapshots);
@@ -893,46 +778,37 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
893
778
  }
894
779
  });
895
780
  }
896
- // Enqueues the public chonk verifier circuit for a given transaction index, or reuses the one already enqueued.
897
- // Once completed, will enqueue the the public tx base rollup.
898
- getOrEnqueueChonkVerifier(provingState, txIndex) {
781
+ /**
782
+ * Route the tx's chonk-verifier dependency through the per-epoch context: read the
783
+ * cached promise (or enqueue if missing), then `.then(handleResult)` to progress to
784
+ * the base rollup once the proof lands.
785
+ */ getOrEnqueueChonkVerifier(provingState, txIndex) {
899
786
  if (!provingState.verifyState()) {
900
- this.logger.debug('Not running chonk verifier circuit, state invalid');
901
787
  return;
902
788
  }
903
789
  const txProvingState = provingState.getTxProvingState(txIndex);
904
790
  const txHash = txProvingState.processedTx.hash.toString();
905
- NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH;
906
791
  const handleResult = (result)=>{
907
- this.logger.debug(`Got chonk verifier proof for tx index: ${txIndex}`, {
908
- txHash
909
- });
792
+ if (!provingState.verifyState()) {
793
+ return;
794
+ }
910
795
  txProvingState.setPublicChonkVerifierProof(result);
911
- this.provingState?.cachedChonkVerifierProofs.delete(txHash);
912
796
  this.checkAndEnqueueBaseRollup(provingState, txIndex);
913
797
  };
914
- if (this.provingState?.cachedChonkVerifierProofs.has(txHash)) {
915
- this.logger.debug(`Chonk verifier proof already enqueued for tx index: ${txIndex}`, {
916
- txHash
917
- });
918
- void this.provingState.cachedChonkVerifierProofs.get(txHash).then(handleResult);
919
- return;
920
- }
921
- this.logger.debug(`Enqueuing chonk verifier circuit for tx index: ${txIndex}`);
922
- this.doEnqueueChonkVerifier(txHash, txProvingState.getPublicChonkVerifierPrivateInputs(), handleResult);
923
- }
924
- doEnqueueChonkVerifier(txHash, inputs, handler, provingState = this.provingState) {
925
- if (!provingState.verifyState()) {
926
- this.logger.debug('Not running chonk verifier circuit, state invalid');
927
- return;
928
- }
929
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getPublicChonkVerifierProof', {
930
- [Attributes.TX_HASH]: txHash,
931
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'chonk-verifier-public'
932
- }, (signal)=>this.prover.getPublicChonkVerifierProof(inputs, signal, provingState.epochNumber)), handler);
798
+ const promise = this.chonkCache.getOrCompute(txHash, (signal)=>this.prover.getPublicChonkVerifierProof(txProvingState.getPublicChonkVerifierPrivateInputs(), signal, this.epochNumber));
799
+ void promise.then(handleResult).catch((err)=>{
800
+ // The cache self-cleans on rejection, so a replacement sub-tree for this tx will see the
801
+ // miss and re-enqueue. But if this proving state is still active, the failure must abort
802
+ // it: otherwise the base rollup for this tx is never enqueued and the checkpoint (and
803
+ // epoch) orchestrators hang forever waiting for a proof that will never arrive.
804
+ if (err instanceof AbortError || !provingState.verifyState()) {
805
+ return;
806
+ }
807
+ this.logger.error(`Chonk verifier proof failed for tx ${txHash}`, err);
808
+ provingState.reject(`Chonk verifier proof failed for tx ${txHash}: ${err}`);
809
+ });
933
810
  }
934
- // Executes the merge rollup circuit and stored the output as intermediate state for the parent merge/block root circuit
935
- // Enqueues the next level of merge if all inputs are available
811
+ // Executes the merge rollup circuit. Enqueues the next level of merge if all inputs are available.
936
812
  enqueueMergeRollup(provingState, location) {
937
813
  if (!provingState.verifyState()) {
938
814
  this.logger.debug('Not running merge rollup. State no longer valid.');
@@ -943,14 +819,14 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
943
819
  return;
944
820
  }
945
821
  const inputs = provingState.getMergeRollupInputs(location);
946
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getTxMergeRollupProof', {
822
+ this.deferredProving(provingState, this.wrapCircuitCall('getTxMergeRollupProof', (signal)=>this.prover.getTxMergeRollupProof(inputs, signal, provingState.epochNumber), {
947
823
  [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-tx-merge'
948
- }, (signal)=>this.prover.getTxMergeRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
824
+ }), (result)=>{
949
825
  provingState.setMergeRollupProof(location, result);
950
826
  this.checkAndEnqueueNextMergeRollup(provingState, location);
951
827
  });
952
828
  }
953
- // Executes the block root rollup circuit
829
+ // Executes the block root rollup circuit.
954
830
  enqueueBlockRootRollup(provingState) {
955
831
  if (!provingState.verifyState()) {
956
832
  this.logger.debug('Not running block root rollup, state no longer valid');
@@ -962,9 +838,7 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
962
838
  }
963
839
  const { rollupType, inputs } = provingState.getBlockRootRollupTypeAndInputs();
964
840
  this.logger.debug(`Enqueuing ${rollupType} for block ${provingState.blockNumber}.`);
965
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getBlockRootRollupProof', {
966
- [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
967
- }, (signal)=>{
841
+ this.deferredProving(provingState, this.wrapCircuitCall('getBlockRootRollupProof', (signal)=>{
968
842
  if (inputs instanceof BlockRootFirstRollupPrivateInputs) {
969
843
  return this.prover.getBlockRootFirstRollupProof(inputs, signal, provingState.epochNumber);
970
844
  } else if (inputs instanceof BlockRootSingleTxFirstRollupPrivateInputs) {
@@ -976,22 +850,27 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
976
850
  } else {
977
851
  return this.prover.getBlockRootRollupProof(inputs, signal, provingState.epochNumber);
978
852
  }
853
+ }, {
854
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
979
855
  }), async (result)=>{
980
- this.logger.debug(`Completed ${rollupType} proof for block ${provingState.blockNumber}`);
856
+ this.logger.debug(`Completed ${rollupType} proof for block ${provingState.blockNumber}`, {
857
+ blockNumber: provingState.blockNumber,
858
+ checkpointIndex: provingState.parentCheckpoint.index,
859
+ ...result.inputs.toInspect()
860
+ });
981
861
  const leafLocation = provingState.setBlockRootRollupProof(result);
982
862
  const checkpointProvingState = provingState.parentCheckpoint;
983
863
  // Verification is called from both here and setBlockCompleted. Whichever runs last
984
864
  // will be the first to see all three pieces (header, proof output, archive) and run the checks.
985
865
  await this.verifyBuiltBlockAgainstSyncedState(provingState);
986
866
  if (checkpointProvingState.totalNumBlocks === 1) {
987
- await this.checkAndEnqueueCheckpointRootRollup(checkpointProvingState);
867
+ this.checkAndEnqueueSubTreeResolution(checkpointProvingState);
988
868
  } else {
989
- await this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
869
+ this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
990
870
  }
991
871
  });
992
872
  }
993
- // Executes the base parity circuit and stores the intermediate state for the root parity circuit
994
- // Enqueues the root parity circuit if all inputs are available
873
+ // Executes the base parity circuit. Enqueues the root parity circuit if all inputs are available.
995
874
  enqueueBaseParityCircuit(checkpointProvingState, provingState, baseParityIndex) {
996
875
  if (!provingState.verifyState()) {
997
876
  this.logger.debug('Not running base parity. State no longer valid.');
@@ -1002,9 +881,9 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
1002
881
  return;
1003
882
  }
1004
883
  const inputs = checkpointProvingState.getBaseParityInputs(baseParityIndex);
1005
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getBaseParityProof', {
884
+ this.deferredProving(provingState, this.wrapCircuitCall('getBaseParityProof', (signal)=>this.prover.getBaseParityProof(inputs, signal, provingState.epochNumber), {
1006
885
  [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-base'
1007
- }, (signal)=>this.prover.getBaseParityProof(inputs, signal, provingState.epochNumber)), (provingOutput)=>{
886
+ }), (provingOutput)=>{
1008
887
  provingState.setBaseParityProof(baseParityIndex, provingOutput);
1009
888
  this.checkAndEnqueueRootParityCircuit(provingState);
1010
889
  });
@@ -1015,8 +894,8 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
1015
894
  }
1016
895
  this.enqueueRootParityCircuit(provingState);
1017
896
  }
1018
- // Runs the root parity circuit ans stored the outputs
1019
- // Enqueues the root rollup proof if all inputs are available
897
+ // Runs the root parity circuit and stores the outputs.
898
+ // Enqueues the block root rollup if all inputs are available.
1020
899
  enqueueRootParityCircuit(provingState) {
1021
900
  if (!provingState.verifyState()) {
1022
901
  this.logger.debug('Not running root parity. State no longer valid.');
@@ -1027,15 +906,14 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
1027
906
  return;
1028
907
  }
1029
908
  const inputs = provingState.getParityRootInputs();
1030
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getRootParityProof', {
909
+ this.deferredProving(provingState, this.wrapCircuitCall('getRootParityProof', (signal)=>this.prover.getRootParityProof(inputs, signal, provingState.epochNumber), {
1031
910
  [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-root'
1032
- }, (signal)=>this.prover.getRootParityProof(inputs, signal, provingState.epochNumber)), (result)=>{
911
+ }), (result)=>{
1033
912
  provingState.setRootParityProof(result);
1034
913
  this.checkAndEnqueueBlockRootRollup(provingState);
1035
914
  });
1036
915
  }
1037
- // Executes the block merge rollup circuit and stored the output as intermediate state for the parent merge/block root circuit
1038
- // Enqueues the next level of merge if all inputs are available
916
+ // Executes the block merge rollup circuit.
1039
917
  enqueueBlockMergeRollup(provingState, location) {
1040
918
  if (!provingState.verifyState()) {
1041
919
  this.logger.debug('Not running block merge rollup. State no longer valid.');
@@ -1046,104 +924,16 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
1046
924
  return;
1047
925
  }
1048
926
  const inputs = provingState.getBlockMergeRollupInputs(location);
1049
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getBlockMergeRollupProof', {
927
+ this.deferredProving(provingState, this.wrapCircuitCall('getBlockMergeRollupProof', (signal)=>this.prover.getBlockMergeRollupProof(inputs, signal, provingState.epochNumber), {
1050
928
  [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-block-merge'
1051
- }, (signal)=>this.prover.getBlockMergeRollupProof(inputs, signal, provingState.epochNumber)), async (result)=>{
1052
- provingState.setBlockMergeRollupProof(location, result);
1053
- await this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
1054
- });
1055
- }
1056
- async enqueueCheckpointRootRollup(provingState) {
1057
- if (!provingState.verifyState()) {
1058
- this.logger.debug('Not running checkpoint root rollup. State no longer valid.');
1059
- return;
1060
- }
1061
- if (!provingState.tryStartProvingCheckpointRoot()) {
1062
- this.logger.debug('Checkpoint root rollup already started.');
1063
- return;
1064
- }
1065
- const rollupType = provingState.getCheckpointRootRollupType();
1066
- this.logger.debug(`Enqueuing ${rollupType} for checkpoint ${provingState.index}.`);
1067
- const inputs = await provingState.getCheckpointRootRollupInputs();
1068
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getCheckpointRootRollupProof', {
1069
- [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
1070
- }, (signal)=>{
1071
- if (inputs instanceof CheckpointRootSingleBlockRollupPrivateInputs) {
1072
- return this.prover.getCheckpointRootSingleBlockRollupProof(inputs, signal, provingState.epochNumber);
1073
- } else {
1074
- return this.prover.getCheckpointRootRollupProof(inputs, signal, provingState.epochNumber);
1075
- }
1076
929
  }), (result)=>{
1077
- const computedEndBlobAccumulatorState = provingState.getEndBlobAccumulator().toBlobAccumulator();
1078
- const circuitEndBlobAccumulatorState = result.inputs.endBlobAccumulator;
1079
- if (!circuitEndBlobAccumulatorState.equals(computedEndBlobAccumulatorState)) {
1080
- this.logger.error(`Blob accumulator state mismatch.\nCircuit: ${inspect(circuitEndBlobAccumulatorState)}\nComputed: ${inspect(computedEndBlobAccumulatorState)}`);
1081
- provingState.reject(`Blob accumulator state mismatch.`);
1082
- return;
1083
- }
1084
- this.logger.debug(`Completed ${rollupType} proof for checkpoint ${provingState.index}.`);
1085
- const leafLocation = provingState.setCheckpointRootRollupProof(result);
1086
- const epochProvingState = provingState.parentEpoch;
1087
- if (epochProvingState.totalNumCheckpoints === 1) {
1088
- this.enqueueEpochPadding(epochProvingState);
1089
- } else {
1090
- this.checkAndEnqueueNextCheckpointMergeRollup(epochProvingState, leafLocation);
1091
- }
1092
- });
1093
- }
1094
- enqueueCheckpointMergeRollup(provingState, location) {
1095
- if (!provingState.verifyState()) {
1096
- this.logger.debug('Not running checkpoint merge rollup. State no longer valid.');
1097
- return;
1098
- }
1099
- if (!provingState.tryStartProvingCheckpointMerge(location)) {
1100
- this.logger.debug('Checkpoint merge rollup already started.');
1101
- return;
1102
- }
1103
- const inputs = provingState.getCheckpointMergeRollupInputs(location);
1104
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getCheckpointMergeRollupProof', {
1105
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-checkpoint-merge'
1106
- }, (signal)=>this.prover.getCheckpointMergeRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
1107
- this.logger.debug('Completed proof for checkpoint merge rollup.');
1108
- provingState.setCheckpointMergeRollupProof(location, result);
1109
- this.checkAndEnqueueNextCheckpointMergeRollup(provingState, location);
1110
- });
1111
- }
1112
- enqueueEpochPadding(provingState) {
1113
- if (!provingState.verifyState()) {
1114
- this.logger.debug('Not running epoch padding. State no longer valid.');
1115
- return;
1116
- }
1117
- if (!provingState.tryStartProvingPaddingCheckpoint()) {
1118
- this.logger.debug('Padding checkpoint already started.');
1119
- return;
1120
- }
1121
- this.logger.debug('Padding epoch proof with a padding block root proof.');
1122
- const inputs = provingState.getPaddingCheckpointInputs();
1123
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getCheckpointPaddingRollupProof', {
1124
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-checkpoint-padding'
1125
- }, (signal)=>this.prover.getCheckpointPaddingRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
1126
- this.logger.debug('Completed proof for padding checkpoint.');
1127
- provingState.setCheckpointPaddingProof(result);
1128
- this.checkAndEnqueueRootRollup(provingState);
1129
- });
1130
- }
1131
- // Executes the root rollup circuit
1132
- enqueueRootRollup(provingState) {
1133
- if (!provingState.verifyState()) {
1134
- this.logger.debug('Not running root rollup, state no longer valid');
1135
- return;
1136
- }
1137
- this.logger.debug(`Preparing root rollup`);
1138
- const inputs = provingState.getRootRollupInputs();
1139
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getRootRollupProof', {
1140
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-root'
1141
- }, (signal)=>this.prover.getRootRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
1142
- this.logger.verbose(`Orchestrator completed root rollup for epoch ${provingState.epochNumber}`);
1143
- provingState.setRootRollupProof(result);
1144
- provingState.resolve({
1145
- status: 'success'
930
+ this.logger.debug(`Completed block merge rollup proof for checkpoint ${provingState.index}`, {
931
+ checkpointIndex: provingState.index,
932
+ mergeLocation: location,
933
+ ...result.inputs.toInspect()
1146
934
  });
935
+ provingState.setBlockMergeRollupProof(location, result);
936
+ this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
1147
937
  });
1148
938
  }
1149
939
  checkAndEnqueueNextMergeRollup(provingState, currentLocation) {
@@ -1164,59 +954,48 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
1164
954
  }
1165
955
  this.enqueueBlockRootRollup(provingState);
1166
956
  }
1167
- async checkAndEnqueueNextBlockMergeRollup(provingState, currentLocation) {
957
+ checkAndEnqueueNextBlockMergeRollup(provingState, currentLocation) {
1168
958
  if (!provingState.isReadyForBlockMerge(currentLocation)) {
1169
959
  return;
1170
960
  }
1171
961
  const parentLocation = provingState.getParentLocation(currentLocation);
1172
962
  if (parentLocation.level === 0) {
1173
- await this.checkAndEnqueueCheckpointRootRollup(provingState);
963
+ this.checkAndEnqueueSubTreeResolution(provingState);
1174
964
  } else {
1175
965
  this.enqueueBlockMergeRollup(provingState, parentLocation);
1176
966
  }
1177
967
  }
1178
- async checkAndEnqueueCheckpointRootRollup(provingState) {
1179
- if (!provingState.isReadyForCheckpointRoot()) {
1180
- return;
1181
- }
1182
- await this.enqueueCheckpointRootRollup(provingState);
1183
- }
1184
- checkAndEnqueueNextCheckpointMergeRollup(provingState, currentLocation) {
1185
- if (!provingState.isReadyForCheckpointMerge(currentLocation)) {
1186
- return;
1187
- }
1188
- const parentLocation = provingState.getParentLocation(currentLocation);
1189
- if (parentLocation.level === 0) {
1190
- this.checkAndEnqueueRootRollup(provingState);
1191
- } else {
1192
- this.enqueueCheckpointMergeRollup(provingState, parentLocation);
1193
- }
1194
- }
1195
- checkAndEnqueueRootRollup(provingState) {
1196
- if (!provingState.isReadyForRootRollup()) {
1197
- this.logger.debug('Not ready for root rollup');
968
+ /**
969
+ * Sub-tree analogue of the orchestrator's `checkAndEnqueueCheckpointRootRollup`:
970
+ * resolves the sub-tree promise with the block-level proof outputs once they're all ready,
971
+ * instead of escalating to the checkpoint root rollup.
972
+ */ checkAndEnqueueSubTreeResolution(provingState) {
973
+ const proofs = provingState.getSubTreeOutputProofs();
974
+ const nonEmpty = proofs.filter((p)=>!!p);
975
+ if (proofs.length !== nonEmpty.length) {
976
+ // Block merge tree not fully resolved yet — retried as more block proofs land.
1198
977
  return;
1199
978
  }
1200
- this.enqueueRootRollup(provingState);
979
+ this.subTreeResult.resolve({
980
+ blockProofOutputs: nonEmpty,
981
+ previousArchiveSiblingPath: provingState.getLastArchiveSiblingPath()
982
+ });
1201
983
  }
1202
984
  /**
1203
- * Executes the VM circuit for a public function, will enqueue the corresponding kernel if the
1204
- * previous kernel is ready
1205
- * @param provingState - The proving state being operated on
1206
- * @param txIndex - The index of the transaction being proven
985
+ * Executes the VM circuit for a public function. Enqueues the base rollup once the
986
+ * tx's chonk-verifier + VM proofs are both ready.
1207
987
  */ enqueueVM(provingState, txIndex) {
1208
988
  if (!provingState.verifyState()) {
1209
989
  this.logger.debug(`Not running VM circuit as state is no longer valid`);
1210
990
  return;
1211
991
  }
1212
992
  const txProvingState = provingState.getTxProvingState(txIndex);
1213
- const doAvmProving = wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getAvmProof', {
1214
- [Attributes.TX_HASH]: txProvingState.processedTx.hash.toString()
1215
- }, async (signal)=>{
993
+ this.deferredProving(provingState, this.wrapCircuitCall('getAvmProof', async (signal)=>{
1216
994
  const inputs = txProvingState.getAvmInputs();
1217
995
  return await this.prover.getAvmProof(inputs, signal, provingState.epochNumber);
1218
- });
1219
- this.deferredProving(provingState, doAvmProving, (proof)=>{
996
+ }, {
997
+ [Attributes.TX_HASH]: txProvingState.processedTx.hash.toString()
998
+ }), (proof)=>{
1220
999
  this.logger.debug(`Proven VM for tx index: ${txIndex}`);
1221
1000
  txProvingState.setAvmProof(proof);
1222
1001
  this.checkAndEnqueueBaseRollup(provingState, txIndex);
@@ -1227,8 +1006,61 @@ _dec = trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
1227
1006
  if (!txProvingState.ready()) {
1228
1007
  return;
1229
1008
  }
1230
- // We must have completed all proving (chonk verifier proof and (if required) vm proof are generated), we now move to the base rollup.
1009
+ // All upstream proofs (chonk verifier and, if required, vm) are ready proceed to the base rollup.
1231
1010
  this.logger.debug(`Public functions completed for tx ${txIndex} enqueueing base rollup`);
1232
1011
  this.enqueueBaseRollup(provingState, txIndex);
1233
1012
  }
1013
+ // Flagged as protected so unit tests can override.
1014
+ async verifyBuiltBlockAgainstSyncedState(provingState) {
1015
+ const builtBlockHeader = provingState.getBuiltBlockHeader();
1016
+ if (!builtBlockHeader) {
1017
+ this.logger.debug('Block header not built yet, skipping header check.');
1018
+ return;
1019
+ }
1020
+ const output = provingState.getBlockRootRollupOutput();
1021
+ if (!output) {
1022
+ this.logger.debug('Block root rollup proof not built yet, skipping header check.');
1023
+ return;
1024
+ }
1025
+ const newArchive = provingState.getBuiltArchive();
1026
+ if (!newArchive) {
1027
+ this.logger.debug('Archive snapshot not yet captured, skipping header check.');
1028
+ return;
1029
+ }
1030
+ const header = await buildHeaderFromCircuitOutputs(output);
1031
+ if (!(await header.hash()).equals(await builtBlockHeader.hash())) {
1032
+ this.logger.error(`Block header mismatch.\nCircuit: ${inspect(header)}\nComputed: ${inspect(builtBlockHeader)}`);
1033
+ provingState.reject(`Block header hash mismatch.`);
1034
+ return;
1035
+ }
1036
+ const blockNumber = provingState.blockNumber;
1037
+ const syncedArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.dbProvider.getSnapshot(blockNumber));
1038
+ if (!syncedArchive.equals(newArchive)) {
1039
+ this.logger.error(`Archive tree mismatch for block ${blockNumber}: world state synced to ${inspect(syncedArchive)} but built ${inspect(newArchive)}`);
1040
+ provingState.reject(`Archive tree mismatch.`);
1041
+ return;
1042
+ }
1043
+ const circuitArchive = output.newArchive;
1044
+ if (!newArchive.equals(circuitArchive)) {
1045
+ this.logger.error(`New archive mismatch.\nCircuit: ${output.newArchive}\nComputed: ${newArchive}`);
1046
+ provingState.reject(`New archive mismatch.`);
1047
+ return;
1048
+ }
1049
+ }
1050
+ getDbForBlock(blockNumber) {
1051
+ const db = this.dbs.get(blockNumber);
1052
+ if (!db) {
1053
+ throw new Error(`World state fork for block ${blockNumber} not found.`);
1054
+ }
1055
+ return db;
1056
+ }
1057
+ /**
1058
+ * Wraps a circuit call with a tracer span and circuit attributes. Replaces the
1059
+ * `ProvingScheduler.wrapCircuitCall` indirection that used to live on the abstract base.
1060
+ */ wrapCircuitCall(circuitName, fn, attributes = {}) {
1061
+ return wrapCallbackInSpan(this.tracer, `CheckpointSubTreeOrchestrator.prover.${circuitName}`, {
1062
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: circuitName,
1063
+ ...attributes
1064
+ }, fn);
1065
+ }
1234
1066
  }