@aztec/prover-client 0.0.1-commit.b655e406 → 0.0.1-commit.b8a057fa

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 (178) hide show
  1. package/dest/config.d.ts +2 -2
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +17 -3
  4. package/dest/index.d.ts +1 -1
  5. package/dest/light/index.d.ts +2 -0
  6. package/dest/light/index.d.ts.map +1 -0
  7. package/dest/light/index.js +1 -0
  8. package/dest/light/lightweight_checkpoint_builder.d.ts +52 -0
  9. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -0
  10. package/dest/light/lightweight_checkpoint_builder.js +233 -0
  11. package/dest/mocks/fixtures.d.ts +1 -4
  12. package/dest/mocks/fixtures.d.ts.map +1 -1
  13. package/dest/mocks/fixtures.js +9 -18
  14. package/dest/mocks/test_context.d.ts +38 -55
  15. package/dest/mocks/test_context.d.ts.map +1 -1
  16. package/dest/mocks/test_context.js +143 -142
  17. package/dest/orchestrator/block-building-helpers.d.ts +18 -20
  18. package/dest/orchestrator/block-building-helpers.d.ts.map +1 -1
  19. package/dest/orchestrator/block-building-helpers.js +90 -115
  20. package/dest/orchestrator/block-proving-state.d.ts +20 -11
  21. package/dest/orchestrator/block-proving-state.d.ts.map +1 -1
  22. package/dest/orchestrator/block-proving-state.js +87 -19
  23. package/dest/orchestrator/checkpoint-proving-state.d.ts +24 -27
  24. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -1
  25. package/dest/orchestrator/checkpoint-proving-state.js +28 -94
  26. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts +161 -0
  27. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts.map +1 -0
  28. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.js +1066 -0
  29. package/dest/orchestrator/chonk-cache.d.ts +39 -0
  30. package/dest/orchestrator/chonk-cache.d.ts.map +1 -0
  31. package/dest/orchestrator/chonk-cache.js +80 -0
  32. package/dest/orchestrator/index.d.ts +4 -2
  33. package/dest/orchestrator/index.d.ts.map +1 -1
  34. package/dest/orchestrator/index.js +3 -1
  35. package/dest/orchestrator/orchestrator_metrics.d.ts +1 -3
  36. package/dest/orchestrator/orchestrator_metrics.d.ts.map +1 -1
  37. package/dest/orchestrator/orchestrator_metrics.js +2 -15
  38. package/dest/orchestrator/proving-scheduler.d.ts +81 -0
  39. package/dest/orchestrator/proving-scheduler.d.ts.map +1 -0
  40. package/dest/orchestrator/proving-scheduler.js +120 -0
  41. package/dest/orchestrator/top-tree-orchestrator.d.ts +88 -0
  42. package/dest/orchestrator/top-tree-orchestrator.d.ts.map +1 -0
  43. package/dest/orchestrator/top-tree-orchestrator.js +232 -0
  44. package/dest/orchestrator/top-tree-proving-state.d.ts +61 -0
  45. package/dest/orchestrator/top-tree-proving-state.d.ts.map +1 -0
  46. package/dest/orchestrator/top-tree-proving-state.js +185 -0
  47. package/dest/orchestrator/tx-proving-state.d.ts +7 -6
  48. package/dest/orchestrator/tx-proving-state.d.ts.map +1 -1
  49. package/dest/orchestrator/tx-proving-state.js +7 -16
  50. package/dest/prover-client/factory.d.ts +3 -3
  51. package/dest/prover-client/factory.d.ts.map +1 -1
  52. package/dest/prover-client/index.d.ts +1 -1
  53. package/dest/prover-client/prover-client.d.ts +65 -8
  54. package/dest/prover-client/prover-client.d.ts.map +1 -1
  55. package/dest/prover-client/prover-client.js +66 -14
  56. package/dest/proving_broker/broker_prover_facade.d.ts +26 -24
  57. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -1
  58. package/dest/proving_broker/broker_prover_facade.js +21 -33
  59. package/dest/proving_broker/config.d.ts +14 -62
  60. package/dest/proving_broker/config.d.ts.map +1 -1
  61. package/dest/proving_broker/config.js +29 -6
  62. package/dest/proving_broker/factory.d.ts +1 -1
  63. package/dest/proving_broker/fixtures.d.ts +3 -2
  64. package/dest/proving_broker/fixtures.d.ts.map +1 -1
  65. package/dest/proving_broker/fixtures.js +3 -2
  66. package/dest/proving_broker/index.d.ts +2 -1
  67. package/dest/proving_broker/index.d.ts.map +1 -1
  68. package/dest/proving_broker/index.js +1 -0
  69. package/dest/proving_broker/proof_store/factory.d.ts +2 -5
  70. package/dest/proving_broker/proof_store/factory.d.ts.map +1 -1
  71. package/dest/proving_broker/proof_store/factory.js +7 -30
  72. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts +18 -0
  73. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts.map +1 -0
  74. package/dest/proving_broker/proof_store/file_store_proof_store.js +60 -0
  75. package/dest/proving_broker/proof_store/index.d.ts +2 -2
  76. package/dest/proving_broker/proof_store/index.d.ts.map +1 -1
  77. package/dest/proving_broker/proof_store/index.js +1 -1
  78. package/dest/proving_broker/proof_store/inline_proof_store.d.ts +1 -1
  79. package/dest/proving_broker/proof_store/inline_proof_store.d.ts.map +1 -1
  80. package/dest/proving_broker/proof_store/proof_store.d.ts +1 -1
  81. package/dest/proving_broker/proving_agent.d.ts +5 -9
  82. package/dest/proving_broker/proving_agent.d.ts.map +1 -1
  83. package/dest/proving_broker/proving_agent.js +4 -19
  84. package/dest/proving_broker/proving_broker.d.ts +8 -5
  85. package/dest/proving_broker/proving_broker.d.ts.map +1 -1
  86. package/dest/proving_broker/proving_broker.js +74 -22
  87. package/dest/proving_broker/proving_broker_database/memory.d.ts +3 -2
  88. package/dest/proving_broker/proving_broker_database/memory.d.ts.map +1 -1
  89. package/dest/proving_broker/proving_broker_database/persisted.d.ts +5 -3
  90. package/dest/proving_broker/proving_broker_database/persisted.d.ts.map +1 -1
  91. package/dest/proving_broker/proving_broker_database/persisted.js +394 -5
  92. package/dest/proving_broker/proving_broker_database.d.ts +3 -2
  93. package/dest/proving_broker/proving_broker_database.d.ts.map +1 -1
  94. package/dest/proving_broker/proving_broker_instrumentation.d.ts +3 -1
  95. package/dest/proving_broker/proving_broker_instrumentation.d.ts.map +1 -1
  96. package/dest/proving_broker/proving_broker_instrumentation.js +22 -35
  97. package/dest/proving_broker/proving_job_controller.d.ts +5 -3
  98. package/dest/proving_broker/proving_job_controller.d.ts.map +1 -1
  99. package/dest/proving_broker/proving_job_controller.js +8 -6
  100. package/dest/proving_broker/rpc.d.ts +9 -5
  101. package/dest/proving_broker/rpc.d.ts.map +1 -1
  102. package/dest/proving_broker/rpc.js +87 -23
  103. package/dest/test/epoch_settlement.d.ts +36 -0
  104. package/dest/test/epoch_settlement.d.ts.map +1 -0
  105. package/dest/test/epoch_settlement.js +52 -0
  106. package/dest/test/index.d.ts +2 -0
  107. package/dest/test/index.d.ts.map +1 -0
  108. package/dest/test/index.js +1 -0
  109. package/dest/test/mock_proof_store.d.ts +1 -1
  110. package/dest/test/mock_proof_store.d.ts.map +1 -1
  111. package/dest/test/mock_prover.d.ts +5 -6
  112. package/dest/test/mock_prover.d.ts.map +1 -1
  113. package/dest/test/mock_prover.js +4 -4
  114. package/package.json +25 -23
  115. package/src/config.ts +19 -3
  116. package/src/light/index.ts +1 -0
  117. package/src/light/lightweight_checkpoint_builder.ts +322 -0
  118. package/src/mocks/fixtures.ts +9 -31
  119. package/src/mocks/test_context.ts +182 -217
  120. package/src/orchestrator/block-building-helpers.ts +129 -209
  121. package/src/orchestrator/block-proving-state.ts +109 -22
  122. package/src/orchestrator/checkpoint-proving-state.ts +32 -123
  123. package/src/orchestrator/checkpoint-sub-tree-orchestrator.ts +1044 -0
  124. package/src/orchestrator/chonk-cache.ts +99 -0
  125. package/src/orchestrator/index.ts +8 -1
  126. package/src/orchestrator/orchestrator_metrics.ts +2 -25
  127. package/src/orchestrator/proving-scheduler.ts +160 -0
  128. package/src/orchestrator/top-tree-orchestrator.ts +384 -0
  129. package/src/orchestrator/top-tree-proving-state.ts +219 -0
  130. package/src/orchestrator/tx-proving-state.ts +10 -27
  131. package/src/prover-client/factory.ts +6 -2
  132. package/src/prover-client/prover-client.ts +148 -29
  133. package/src/proving_broker/broker_prover_facade.ts +47 -56
  134. package/src/proving_broker/config.ts +33 -3
  135. package/src/proving_broker/fixtures.ts +8 -3
  136. package/src/proving_broker/index.ts +1 -0
  137. package/src/proving_broker/proof_store/factory.ts +10 -32
  138. package/src/proving_broker/proof_store/file_store_proof_store.ts +78 -0
  139. package/src/proving_broker/proof_store/index.ts +1 -1
  140. package/src/proving_broker/proving_agent.ts +6 -19
  141. package/src/proving_broker/proving_broker.ts +70 -17
  142. package/src/proving_broker/proving_broker_database/memory.ts +2 -1
  143. package/src/proving_broker/proving_broker_database/persisted.ts +22 -7
  144. package/src/proving_broker/proving_broker_database.ts +2 -1
  145. package/src/proving_broker/proving_broker_instrumentation.ts +23 -35
  146. package/src/proving_broker/proving_job_controller.ts +13 -7
  147. package/src/proving_broker/rpc.ts +46 -20
  148. package/src/test/epoch_settlement.ts +82 -0
  149. package/src/test/index.ts +1 -0
  150. package/src/test/mock_prover.ts +3 -15
  151. package/dest/block-factory/index.d.ts +0 -2
  152. package/dest/block-factory/index.d.ts.map +0 -1
  153. package/dest/block-factory/index.js +0 -1
  154. package/dest/block-factory/light.d.ts +0 -38
  155. package/dest/block-factory/light.d.ts.map +0 -1
  156. package/dest/block-factory/light.js +0 -94
  157. package/dest/orchestrator/epoch-proving-state.d.ts +0 -73
  158. package/dest/orchestrator/epoch-proving-state.d.ts.map +0 -1
  159. package/dest/orchestrator/epoch-proving-state.js +0 -233
  160. package/dest/orchestrator/orchestrator.d.ts +0 -113
  161. package/dest/orchestrator/orchestrator.d.ts.map +0 -1
  162. package/dest/orchestrator/orchestrator.js +0 -848
  163. package/dest/prover-client/server-epoch-prover.d.ts +0 -31
  164. package/dest/prover-client/server-epoch-prover.d.ts.map +0 -1
  165. package/dest/prover-client/server-epoch-prover.js +0 -40
  166. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts +0 -14
  167. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts.map +0 -1
  168. package/dest/proving_broker/proof_store/gcs_proof_store.js +0 -52
  169. package/dest/proving_broker/proving_agent_instrumentation.d.ts +0 -8
  170. package/dest/proving_broker/proving_agent_instrumentation.d.ts.map +0 -1
  171. package/dest/proving_broker/proving_agent_instrumentation.js +0 -16
  172. package/src/block-factory/index.ts +0 -1
  173. package/src/block-factory/light.ts +0 -140
  174. package/src/orchestrator/epoch-proving-state.ts +0 -328
  175. package/src/orchestrator/orchestrator.ts +0 -1272
  176. package/src/prover-client/server-epoch-prover.ts +0 -70
  177. package/src/proving_broker/proof_store/gcs_proof_store.ts +0 -76
  178. package/src/proving_broker/proving_agent_instrumentation.ts +0 -21
@@ -1,848 +0,0 @@
1
- function _ts_decorate(decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- }
7
- 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';
8
- import { padArrayEnd } from '@aztec/foundation/collection';
9
- import { AbortError } from '@aztec/foundation/error';
10
- import { Fr } from '@aztec/foundation/fields';
11
- import { createLogger } from '@aztec/foundation/log';
12
- import { promiseWithResolvers } from '@aztec/foundation/promise';
13
- import { assertLength } from '@aztec/foundation/serialize';
14
- import { pushTestData } from '@aztec/foundation/testing';
15
- import { elapsed } from '@aztec/foundation/timer';
16
- import { readAvmMinimalPublicTxInputsFromFile } from '@aztec/simulator/public/fixtures';
17
- import { createBlockEndMarker } from '@aztec/stdlib/block';
18
- import { BlockRootEmptyTxFirstRollupPrivateInputs, BlockRootFirstRollupPrivateInputs, BlockRootSingleTxFirstRollupPrivateInputs, BlockRootSingleTxRollupPrivateInputs, CheckpointRootSingleBlockRollupPrivateInputs, PrivateTxBaseRollupPrivateInputs } from '@aztec/stdlib/rollup';
19
- import { MerkleTreeId } from '@aztec/stdlib/trees';
20
- import { Attributes, getTelemetryClient, trackSpan, wrapCallbackInSpan } from '@aztec/telemetry-client';
21
- import { inspect } from 'util';
22
- import { buildBlockHeaderFromTxs, buildHeaderFromCircuitOutputs, getLastSiblingPath, getPublicChonkVerifierPrivateInputsFromTx, getRootTreeSiblingPath, getSubtreeSiblingPath, getTreeSnapshot, insertSideEffectsAndBuildBaseRollupHints, validatePartialState, validateTx } from './block-building-helpers.js';
23
- import { EpochProvingState } from './epoch-proving-state.js';
24
- import { ProvingOrchestratorMetrics } from './orchestrator_metrics.js';
25
- import { TxProvingState } from './tx-proving-state.js';
26
- const logger = createLogger('prover-client:orchestrator');
27
- /**
28
- * Implements an event driven proving scheduler to build the recursive proof tree. The idea being:
29
- * 1. Transactions are provided to the scheduler post simulation.
30
- * 2. Tree insertions are performed as required to generate transaction specific proofs
31
- * 3. Those transaction specific proofs are generated in the necessary order accounting for dependencies
32
- * 4. Once a transaction is proven, it will be incorporated into a merge proof
33
- * 5. Merge proofs are produced at each level of the tree until the root proof is produced
34
- *
35
- * The proving implementation is determined by the provided prover. This could be for example a local prover or a remote prover pool.
36
- */ /**
37
- * The orchestrator, managing the flow of recursive proving operations required to build the rollup proof tree.
38
- */ export class ProvingOrchestrator {
39
- dbProvider;
40
- prover;
41
- proverId;
42
- provingState;
43
- pendingProvingJobs;
44
- provingPromise;
45
- metrics;
46
- dbs;
47
- constructor(dbProvider, prover, proverId, telemetryClient = getTelemetryClient()){
48
- this.dbProvider = dbProvider;
49
- this.prover = prover;
50
- this.proverId = proverId;
51
- this.provingState = undefined;
52
- this.pendingProvingJobs = [];
53
- this.provingPromise = undefined;
54
- this.dbs = new Map();
55
- this.metrics = new ProvingOrchestratorMetrics(telemetryClient, 'ProvingOrchestrator');
56
- }
57
- get tracer() {
58
- return this.metrics.tracer;
59
- }
60
- getProverId() {
61
- return this.proverId;
62
- }
63
- stop() {
64
- this.cancel();
65
- return Promise.resolve();
66
- }
67
- startNewEpoch(epochNumber, totalNumCheckpoints, finalBlobBatchingChallenges) {
68
- if (this.provingState?.verifyState()) {
69
- throw new Error(`Cannot start epoch ${epochNumber} when epoch ${this.provingState.epochNumber} is still being processed.`);
70
- }
71
- const { promise: _promise, resolve, reject } = promiseWithResolvers();
72
- const promise = _promise.catch((reason)=>({
73
- status: 'failure',
74
- reason
75
- }));
76
- logger.info(`Starting epoch ${epochNumber} with ${totalNumCheckpoints} checkpoints.`);
77
- this.provingState = new EpochProvingState(epochNumber, totalNumCheckpoints, finalBlobBatchingChallenges, (provingState)=>this.checkAndEnqueueCheckpointRootRollup(provingState), resolve, reject);
78
- this.provingPromise = promise;
79
- }
80
- async startNewCheckpoint(checkpointIndex, constants, l1ToL2Messages, totalNumBlocks, totalNumBlobFields, headerOfLastBlockInPreviousCheckpoint) {
81
- if (!this.provingState) {
82
- throw new Error('Empty epoch proving state. Call startNewEpoch before starting a checkpoint.');
83
- }
84
- if (!this.provingState.isAcceptingCheckpoints()) {
85
- throw new Error(`Epoch not accepting further checkpoints.`);
86
- }
87
- // Fork world state at the end of the immediately previous block.
88
- const lastBlockNumber = headerOfLastBlockInPreviousCheckpoint.globalVariables.blockNumber;
89
- const db = await this.dbProvider.fork(lastBlockNumber);
90
- const firstBlockNumber = lastBlockNumber + 1;
91
- this.dbs.set(firstBlockNumber, db);
92
- // Get archive sibling path before any block in this checkpoint lands.
93
- const lastArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, db);
94
- // Insert all the l1 to l2 messages into the db. And get the states before and after the insertion.
95
- const { lastL1ToL2MessageTreeSnapshot, lastL1ToL2MessageSubtreeRootSiblingPath, newL1ToL2MessageTreeSnapshot, newL1ToL2MessageSubtreeRootSiblingPath } = await this.updateL1ToL2MessageTree(l1ToL2Messages, db);
96
- this.provingState.startNewCheckpoint(checkpointIndex, constants, totalNumBlocks, totalNumBlobFields, headerOfLastBlockInPreviousCheckpoint, lastArchiveSiblingPath, l1ToL2Messages, lastL1ToL2MessageTreeSnapshot, lastL1ToL2MessageSubtreeRootSiblingPath, newL1ToL2MessageTreeSnapshot, newL1ToL2MessageSubtreeRootSiblingPath);
97
- }
98
- /**
99
- * Starts off a new block
100
- * @param blockNumber - The block number
101
- * @param timestamp - The timestamp of the block. This is only required for constructing the private inputs for the
102
- * block that doesn't have any txs.
103
- * @param totalNumTxs - The total number of txs in the block
104
- */ async startNewBlock(blockNumber, timestamp, totalNumTxs) {
105
- if (!this.provingState) {
106
- throw new Error('Empty epoch proving state. Call startNewEpoch before starting a block.');
107
- }
108
- const checkpointProvingState = this.provingState.getCheckpointProvingStateByBlockNumber(blockNumber);
109
- if (!checkpointProvingState) {
110
- throw new Error(`Checkpoint not started. Call startNewCheckpoint first.`);
111
- }
112
- if (!checkpointProvingState.isAcceptingBlocks()) {
113
- throw new Error(`Checkpoint not accepting further blocks.`);
114
- }
115
- const constants = checkpointProvingState.constants;
116
- logger.info(`Starting block ${blockNumber} for slot ${constants.slotNumber.toNumber()}.`);
117
- // Fork the db only when it's not already set. The db for the first block is set in `startNewCheckpoint`.
118
- if (!this.dbs.has(blockNumber)) {
119
- // Fork world state at the end of the immediately previous block
120
- const db = await this.dbProvider.fork(blockNumber - 1);
121
- this.dbs.set(blockNumber, db);
122
- }
123
- const db = this.dbs.get(blockNumber);
124
- // Get archive snapshot and sibling path before any txs in this block lands.
125
- const lastArchiveTreeSnapshot = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
126
- const lastArchiveSiblingPath = await getRootTreeSiblingPath(MerkleTreeId.ARCHIVE, db);
127
- const blockProvingState = await checkpointProvingState.startNewBlock(blockNumber, timestamp, totalNumTxs, lastArchiveTreeSnapshot, lastArchiveSiblingPath);
128
- // Enqueue base parity circuits for the first block in the checkpoint.
129
- if (blockProvingState.index === 0) {
130
- for(let i = 0; i < NUM_BASE_PARITY_PER_ROOT_PARITY; i++){
131
- this.enqueueBaseParityCircuit(checkpointProvingState, blockProvingState, i);
132
- }
133
- }
134
- // Because `addTxs` won't be called for a block without txs, and that's where the sponge blob state is computed.
135
- // We need to set its end sponge blob here, which will become the start sponge blob for the next block.
136
- if (totalNumTxs === 0) {
137
- const endSpongeBlob = blockProvingState.getStartSpongeBlob().clone();
138
- await endSpongeBlob.absorb([
139
- createBlockEndMarker(0)
140
- ]);
141
- blockProvingState.setEndSpongeBlob(endSpongeBlob);
142
- // And also try to accumulate the blobs as far as we can:
143
- await this.provingState.setBlobAccumulators();
144
- }
145
- }
146
- /**
147
- * The interface to add simulated transactions to the scheduler. This can only be called once per block.
148
- * @param txs - The transactions to be proven
149
- */ async addTxs(txs) {
150
- if (!this.provingState) {
151
- throw new Error(`Empty epoch proving state. Call startNewEpoch before adding txs.`);
152
- }
153
- if (!txs.length) {
154
- // To avoid an ugly throw below. If we require an empty block, we can just call setBlockCompleted
155
- // on a block with no txs. We cannot do that here because we cannot find the blockNumber without any txs.
156
- logger.warn(`Provided no txs to orchestrator addTxs.`);
157
- return;
158
- }
159
- const blockNumber = txs[0].globalVariables.blockNumber;
160
- const provingState = this.provingState.getBlockProvingStateByBlockNumber(blockNumber);
161
- if (!provingState) {
162
- throw new Error(`Proving state for block ${blockNumber} not found. Call startNewBlock first.`);
163
- }
164
- if (provingState.totalNumTxs !== txs.length) {
165
- throw new Error(`Block ${blockNumber} should be filled with ${provingState.totalNumTxs} txs. Received ${txs.length} txs.`);
166
- }
167
- if (!provingState.isAcceptingTxs()) {
168
- throw new Error(`Block ${blockNumber} has been initialized with transactions.`);
169
- }
170
- logger.info(`Adding ${txs.length} transactions to block ${blockNumber}`);
171
- const db = this.dbs.get(blockNumber);
172
- const lastArchive = provingState.lastArchiveTreeSnapshot;
173
- const newL1ToL2MessageTreeSnapshot = provingState.newL1ToL2MessageTreeSnapshot;
174
- const spongeBlobState = provingState.getStartSpongeBlob().clone();
175
- for (const tx of txs){
176
- try {
177
- if (!provingState.verifyState()) {
178
- throw new Error(`Invalid proving state when adding a tx`);
179
- }
180
- validateTx(tx);
181
- logger.info(`Received transaction: ${tx.hash}`);
182
- const startSpongeBlob = spongeBlobState.clone();
183
- const [hints, treeSnapshots] = await this.prepareBaseRollupInputs(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, db);
184
- if (!provingState.verifyState()) {
185
- throw new Error(`Unable to add transaction, preparing base inputs failed`);
186
- }
187
- await spongeBlobState.absorb(tx.txEffect.toBlobFields());
188
- const txProvingState = new TxProvingState(tx, hints, treeSnapshots, this.proverId.toField());
189
- const txIndex = provingState.addNewTx(txProvingState);
190
- if (txProvingState.requireAvmProof) {
191
- this.getOrEnqueueChonkVerifier(provingState, txIndex);
192
- logger.debug(`Enqueueing public VM for tx ${txIndex}`);
193
- this.enqueueVM(provingState, txIndex);
194
- } else {
195
- logger.debug(`Enqueueing base rollup for private-only tx ${txIndex}`);
196
- this.enqueueBaseRollup(provingState, txIndex);
197
- }
198
- } catch (err) {
199
- throw new Error(`Error adding transaction ${tx.hash.toString()} to block ${blockNumber}: ${err.message}`, {
200
- cause: err
201
- });
202
- }
203
- }
204
- await spongeBlobState.absorb([
205
- createBlockEndMarker(txs.length)
206
- ]);
207
- provingState.setEndSpongeBlob(spongeBlobState);
208
- // Txs have been added to the block. Now try to accumulate the blobs as far as we can:
209
- await this.provingState.setBlobAccumulators();
210
- }
211
- /**
212
- * Kickstarts chonk verifier circuits for the specified txs. These will be used during epoch proving.
213
- * Note that if the chonk verifier circuits are not started this way, they will be started nontheless after processing.
214
- */ startChonkVerifierCircuits(txs) {
215
- if (!this.provingState?.verifyState()) {
216
- throw new Error(`Empty epoch proving state. call startNewEpoch before starting chonk verifier circuits.`);
217
- }
218
- const publicTxs = txs.filter((tx)=>tx.data.forPublic);
219
- for (const tx of publicTxs){
220
- const txHash = tx.getTxHash().toString();
221
- const privateInputs = getPublicChonkVerifierPrivateInputsFromTx(tx, this.proverId.toField());
222
- const tubeProof = promiseWithResolvers();
223
- logger.debug(`Starting chonk verifier circuit for tx ${txHash}`);
224
- this.doEnqueueChonkVerifier(txHash, privateInputs, (proof)=>{
225
- tubeProof.resolve(proof);
226
- });
227
- this.provingState.cachedChonkVerifierProofs.set(txHash, tubeProof.promise);
228
- }
229
- return Promise.resolve();
230
- }
231
- /**
232
- * Marks the block as completed.
233
- * Computes the block header and updates the archive tree.
234
- */ async setBlockCompleted(blockNumber, expectedHeader) {
235
- const provingState = this.provingState?.getBlockProvingStateByBlockNumber(blockNumber);
236
- if (!provingState) {
237
- throw new Error(`Block proving state for ${blockNumber} not found`);
238
- }
239
- // Abort with specific error for the block if there's one.
240
- const error = provingState.getError();
241
- if (error) {
242
- throw new Error(`Block proving failed: ${error}`);
243
- }
244
- // Abort if the proving state is not valid due to errors occurred elsewhere.
245
- if (!provingState.verifyState()) {
246
- throw new Error(`Invalid proving state when completing block ${blockNumber}.`);
247
- }
248
- if (provingState.isAcceptingTxs()) {
249
- throw new Error(`Block ${blockNumber} is still accepting txs. Call setBlockCompleted after all txs have been added.`);
250
- }
251
- // And build the block header
252
- logger.verbose(`Block ${blockNumber} completed. Assembling header.`);
253
- const header = await this.buildL2BlockHeader(provingState, expectedHeader);
254
- await this.verifyBuiltBlockAgainstSyncedState(provingState);
255
- return header;
256
- }
257
- async buildL2BlockHeader(provingState, expectedHeader) {
258
- // Collect all txs in this block to build the header. The function calling this has made sure that all txs have been added.
259
- const txs = provingState.getProcessedTxs();
260
- const startSpongeBlob = provingState.getStartSpongeBlob();
261
- // Get db for this block
262
- const db = this.dbs.get(provingState.blockNumber);
263
- // Given we've applied every change from this block, now assemble the block header
264
- // and update the archive tree, so we're ready to start processing the next block
265
- const header = await buildBlockHeaderFromTxs(txs, provingState.getGlobalVariables(), startSpongeBlob, db);
266
- if (expectedHeader && !header.equals(expectedHeader)) {
267
- logger.error(`Block header mismatch: header=${header} expectedHeader=${expectedHeader}`);
268
- throw new Error('Block header mismatch');
269
- }
270
- logger.verbose(`Updating archive tree with block ${provingState.blockNumber} header ${(await header.hash()).toString()}`);
271
- await db.updateArchive(header);
272
- provingState.setBuiltBlockHeader(header);
273
- return header;
274
- }
275
- // Flagged as protected to disable in certain unit tests
276
- async verifyBuiltBlockAgainstSyncedState(provingState) {
277
- const builtBlockHeader = provingState.getBuiltBlockHeader();
278
- if (!builtBlockHeader) {
279
- logger.debug('Block header not built yet, skipping header check.');
280
- return;
281
- }
282
- const output = provingState.getBlockRootRollupOutput();
283
- if (!output) {
284
- logger.debug('Block root rollup proof not built yet, skipping header check.');
285
- return;
286
- }
287
- const header = await buildHeaderFromCircuitOutputs(output);
288
- if (!(await header.hash()).equals(await builtBlockHeader.hash())) {
289
- logger.error(`Block header mismatch.\nCircuit: ${inspect(header)}\nComputed: ${inspect(builtBlockHeader)}`);
290
- provingState.reject(`Block header hash mismatch.`);
291
- return;
292
- }
293
- // Get db for this block
294
- const blockNumber = provingState.blockNumber;
295
- const db = this.dbs.get(blockNumber);
296
- const newArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
297
- const syncedArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.dbProvider.getSnapshot(blockNumber));
298
- if (!syncedArchive.equals(newArchive)) {
299
- logger.error(`Archive tree mismatch for block ${blockNumber}: world state synced to ${inspect(syncedArchive)} but built ${inspect(newArchive)}`);
300
- provingState.reject(`Archive tree mismatch.`);
301
- return;
302
- }
303
- const circuitArchive = output.newArchive;
304
- if (!newArchive.equals(circuitArchive)) {
305
- logger.error(`New archive mismatch.\nCircuit: ${output.newArchive}\nComputed: ${newArchive}`);
306
- provingState.reject(`New archive mismatch.`);
307
- return;
308
- }
309
- // TODO(palla/prover): This closes the fork only on the happy path. If this epoch orchestrator
310
- // is aborted and never reaches this point, it will leak the fork. We need to add a global cleanup,
311
- // but have to make sure it only runs once all operations are completed, otherwise some function here
312
- // will attempt to access the fork after it was closed.
313
- logger.debug(`Cleaning up world state fork for ${blockNumber}`);
314
- void this.dbs.get(blockNumber)?.close().then(()=>this.dbs.delete(blockNumber)).catch((err)=>logger.error(`Error closing db for block ${blockNumber}`, err));
315
- }
316
- /**
317
- * Cancel any further proving
318
- */ cancel() {
319
- for (const controller of this.pendingProvingJobs){
320
- controller.abort();
321
- }
322
- this.provingState?.cancel();
323
- }
324
- /**
325
- * Returns the proof for the current epoch.
326
- */ async finalizeEpoch() {
327
- if (!this.provingState || !this.provingPromise) {
328
- throw new Error(`Invalid proving state, an epoch must be proven before it can be finalized`);
329
- }
330
- const result = await this.provingPromise;
331
- if (result.status === 'failure') {
332
- throw new Error(`Epoch proving failed: ${result.reason}`);
333
- }
334
- await this.provingState.finalizeBatchedBlob();
335
- const epochProofResult = this.provingState.getEpochProofResult();
336
- pushTestData('epochProofResult', {
337
- proof: epochProofResult.proof.toString(),
338
- publicInputs: epochProofResult.publicInputs.toString()
339
- });
340
- return epochProofResult;
341
- }
342
- /**
343
- * Enqueue a job to be scheduled
344
- * @param provingState - The proving state object being operated on
345
- * @param jobType - The type of job to be queued
346
- * @param job - The actual job, returns a promise notifying of the job's completion
347
- */ deferredProving(provingState, request, callback) {
348
- if (!provingState.verifyState()) {
349
- logger.debug(`Not enqueuing job, state no longer valid`);
350
- return;
351
- }
352
- const controller = new AbortController();
353
- this.pendingProvingJobs.push(controller);
354
- // We use a 'safeJob'. We don't want promise rejections in the proving pool, we want to capture the error here
355
- // and reject the proving job whilst keeping the event loop free of rejections
356
- const safeJob = async ()=>{
357
- try {
358
- // there's a delay between enqueueing this job and it actually running
359
- if (controller.signal.aborted) {
360
- return;
361
- }
362
- const result = await request(controller.signal);
363
- if (!provingState.verifyState()) {
364
- logger.debug(`State no longer valid, discarding result`);
365
- return;
366
- }
367
- // we could have been cancelled whilst waiting for the result
368
- // and the prover ignored the signal. Drop the result in that case
369
- if (controller.signal.aborted) {
370
- return;
371
- }
372
- await callback(result);
373
- } catch (err) {
374
- if (err instanceof AbortError) {
375
- // operation was cancelled, probably because the block was cancelled
376
- // drop this result
377
- return;
378
- }
379
- logger.error(`Error thrown when proving job`, err);
380
- provingState.reject(`${err}`);
381
- } finally{
382
- const index = this.pendingProvingJobs.indexOf(controller);
383
- if (index > -1) {
384
- this.pendingProvingJobs.splice(index, 1);
385
- }
386
- }
387
- };
388
- // let the callstack unwind before adding the job to the queue
389
- setImmediate(()=>void safeJob());
390
- }
391
- async updateL1ToL2MessageTree(l1ToL2Messages, db) {
392
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, 'Too many L1 to L2 messages');
393
- const lastL1ToL2MessageTreeSnapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
394
- 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);
395
- // Update the local trees to include the new l1 to l2 messages
396
- await db.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
397
- const newL1ToL2MessageTreeSnapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
398
- 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);
399
- return {
400
- lastL1ToL2MessageTreeSnapshot,
401
- lastL1ToL2MessageSubtreeRootSiblingPath,
402
- newL1ToL2MessageTreeSnapshot,
403
- newL1ToL2MessageSubtreeRootSiblingPath
404
- };
405
- }
406
- // Updates the merkle trees for a transaction. The first enqueued job for a transaction
407
- async prepareBaseRollupInputs(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, db) {
408
- // We build the base rollup inputs using a mock proof and verification key.
409
- // These will be overwritten later once we have proven the chonk verifier circuit and any public kernels
410
- const [ms, hints] = await elapsed(insertSideEffectsAndBuildBaseRollupHints(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, this.proverId.toField(), db));
411
- this.metrics.recordBaseRollupInputs(ms);
412
- const promises = [
413
- MerkleTreeId.NOTE_HASH_TREE,
414
- MerkleTreeId.NULLIFIER_TREE,
415
- MerkleTreeId.PUBLIC_DATA_TREE
416
- ].map(async (id)=>{
417
- return {
418
- key: id,
419
- value: await getTreeSnapshot(id, db)
420
- };
421
- });
422
- const treeSnapshots = new Map((await Promise.all(promises)).map((obj)=>[
423
- obj.key,
424
- obj.value
425
- ]));
426
- return [
427
- hints,
428
- treeSnapshots
429
- ];
430
- }
431
- // Executes the base rollup circuit and stored the output as intermediate state for the parent merge/root circuit
432
- // Executes the next level of merge if all inputs are available
433
- enqueueBaseRollup(provingState, txIndex) {
434
- if (!provingState.verifyState()) {
435
- logger.debug('Not running base rollup, state invalid');
436
- return;
437
- }
438
- if (!provingState.tryStartProvingBase(txIndex)) {
439
- logger.debug(`Base rollup for tx ${txIndex} already started.`);
440
- return;
441
- }
442
- const txProvingState = provingState.getTxProvingState(txIndex);
443
- const { processedTx } = txProvingState;
444
- const { rollupType, inputs } = txProvingState.getBaseRollupTypeAndInputs();
445
- logger.debug(`Enqueuing deferred proving base rollup for ${processedTx.hash.toString()}`);
446
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, `ProvingOrchestrator.prover.${inputs instanceof PrivateTxBaseRollupPrivateInputs ? 'getPrivateTxBaseRollupProof' : 'getPublicTxBaseRollupProof'}`, {
447
- [Attributes.TX_HASH]: processedTx.hash.toString(),
448
- [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
449
- }, (signal)=>{
450
- if (inputs instanceof PrivateTxBaseRollupPrivateInputs) {
451
- return this.prover.getPrivateTxBaseRollupProof(inputs, signal, provingState.epochNumber);
452
- } else {
453
- return this.prover.getPublicTxBaseRollupProof(inputs, signal, provingState.epochNumber);
454
- }
455
- }), (result)=>{
456
- logger.debug(`Completed proof for ${rollupType} for tx ${processedTx.hash.toString()}`);
457
- validatePartialState(result.inputs.endTreeSnapshots, txProvingState.treeSnapshots);
458
- const leafLocation = provingState.setBaseRollupProof(txIndex, result);
459
- if (provingState.totalNumTxs === 1) {
460
- this.checkAndEnqueueBlockRootRollup(provingState);
461
- } else {
462
- this.checkAndEnqueueNextMergeRollup(provingState, leafLocation);
463
- }
464
- });
465
- }
466
- // Enqueues the public chonk verifier circuit for a given transaction index, or reuses the one already enqueued.
467
- // Once completed, will enqueue the the public tx base rollup.
468
- getOrEnqueueChonkVerifier(provingState, txIndex) {
469
- if (!provingState.verifyState()) {
470
- logger.debug('Not running chonk verifier circuit, state invalid');
471
- return;
472
- }
473
- const txProvingState = provingState.getTxProvingState(txIndex);
474
- const txHash = txProvingState.processedTx.hash.toString();
475
- NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH;
476
- const handleResult = (result)=>{
477
- logger.debug(`Got chonk verifier proof for tx index: ${txIndex}`, {
478
- txHash
479
- });
480
- txProvingState.setPublicChonkVerifierProof(result);
481
- this.provingState?.cachedChonkVerifierProofs.delete(txHash);
482
- this.checkAndEnqueueBaseRollup(provingState, txIndex);
483
- };
484
- if (this.provingState?.cachedChonkVerifierProofs.has(txHash)) {
485
- logger.debug(`Chonk verifier proof already enqueued for tx index: ${txIndex}`, {
486
- txHash
487
- });
488
- void this.provingState.cachedChonkVerifierProofs.get(txHash).then(handleResult);
489
- return;
490
- }
491
- logger.debug(`Enqueuing chonk verifier circuit for tx index: ${txIndex}`);
492
- this.doEnqueueChonkVerifier(txHash, txProvingState.getPublicChonkVerifierPrivateInputs(), handleResult);
493
- }
494
- doEnqueueChonkVerifier(txHash, inputs, handler, provingState = this.provingState) {
495
- if (!provingState.verifyState()) {
496
- logger.debug('Not running chonk verifier circuit, state invalid');
497
- return;
498
- }
499
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getPublicChonkVerifierProof', {
500
- [Attributes.TX_HASH]: txHash,
501
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'chonk-verifier-public'
502
- }, (signal)=>this.prover.getPublicChonkVerifierProof(inputs, signal, provingState.epochNumber)), handler);
503
- }
504
- // Executes the merge rollup circuit and stored the output as intermediate state for the parent merge/block root circuit
505
- // Enqueues the next level of merge if all inputs are available
506
- enqueueMergeRollup(provingState, location) {
507
- if (!provingState.verifyState()) {
508
- logger.debug('Not running merge rollup. State no longer valid.');
509
- return;
510
- }
511
- if (!provingState.tryStartProvingMerge(location)) {
512
- logger.debug('Merge rollup already started.');
513
- return;
514
- }
515
- const inputs = provingState.getMergeRollupInputs(location);
516
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getTxMergeRollupProof', {
517
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-tx-merge'
518
- }, (signal)=>this.prover.getTxMergeRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
519
- provingState.setMergeRollupProof(location, result);
520
- this.checkAndEnqueueNextMergeRollup(provingState, location);
521
- });
522
- }
523
- // Executes the block root rollup circuit
524
- enqueueBlockRootRollup(provingState) {
525
- if (!provingState.verifyState()) {
526
- logger.debug('Not running block root rollup, state no longer valid');
527
- return;
528
- }
529
- if (!provingState.tryStartProvingBlockRoot()) {
530
- logger.debug('Block root rollup already started.');
531
- return;
532
- }
533
- const { rollupType, inputs } = provingState.getBlockRootRollupTypeAndInputs();
534
- logger.debug(`Enqueuing ${rollupType} for block ${provingState.blockNumber}.`);
535
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getBlockRootRollupProof', {
536
- [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
537
- }, (signal)=>{
538
- if (inputs instanceof BlockRootFirstRollupPrivateInputs) {
539
- return this.prover.getBlockRootFirstRollupProof(inputs, signal, provingState.epochNumber);
540
- } else if (inputs instanceof BlockRootSingleTxFirstRollupPrivateInputs) {
541
- return this.prover.getBlockRootSingleTxFirstRollupProof(inputs, signal, provingState.epochNumber);
542
- } else if (inputs instanceof BlockRootEmptyTxFirstRollupPrivateInputs) {
543
- return this.prover.getBlockRootEmptyTxFirstRollupProof(inputs, signal, provingState.epochNumber);
544
- } else if (inputs instanceof BlockRootSingleTxRollupPrivateInputs) {
545
- return this.prover.getBlockRootSingleTxRollupProof(inputs, signal, provingState.epochNumber);
546
- } else {
547
- return this.prover.getBlockRootRollupProof(inputs, signal, provingState.epochNumber);
548
- }
549
- }), async (result)=>{
550
- // If the proofs were slower than the block header building, then we need to try validating the block header hashes here.
551
- await this.verifyBuiltBlockAgainstSyncedState(provingState);
552
- logger.debug(`Completed ${rollupType} proof for block ${provingState.blockNumber}`);
553
- const leafLocation = provingState.setBlockRootRollupProof(result);
554
- const checkpointProvingState = provingState.parentCheckpoint;
555
- if (checkpointProvingState.totalNumBlocks === 1) {
556
- this.checkAndEnqueueCheckpointRootRollup(checkpointProvingState);
557
- } else {
558
- this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
559
- }
560
- });
561
- }
562
- // Executes the base parity circuit and stores the intermediate state for the root parity circuit
563
- // Enqueues the root parity circuit if all inputs are available
564
- enqueueBaseParityCircuit(checkpointProvingState, provingState, baseParityIndex) {
565
- if (!provingState.verifyState()) {
566
- logger.debug('Not running base parity. State no longer valid.');
567
- return;
568
- }
569
- if (!provingState.tryStartProvingBaseParity(baseParityIndex)) {
570
- logger.warn(`Base parity ${baseParityIndex} already started.`);
571
- return;
572
- }
573
- const inputs = checkpointProvingState.getBaseParityInputs(baseParityIndex);
574
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getBaseParityProof', {
575
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-base'
576
- }, (signal)=>this.prover.getBaseParityProof(inputs, signal, provingState.epochNumber)), (provingOutput)=>{
577
- provingState.setBaseParityProof(baseParityIndex, provingOutput);
578
- this.checkAndEnqueueRootParityCircuit(provingState);
579
- });
580
- }
581
- checkAndEnqueueRootParityCircuit(provingState) {
582
- if (!provingState.isReadyForRootParity()) {
583
- return;
584
- }
585
- this.enqueueRootParityCircuit(provingState);
586
- }
587
- // Runs the root parity circuit ans stored the outputs
588
- // Enqueues the root rollup proof if all inputs are available
589
- enqueueRootParityCircuit(provingState) {
590
- if (!provingState.verifyState()) {
591
- logger.debug('Not running root parity. State no longer valid.');
592
- return;
593
- }
594
- if (!provingState.tryStartProvingRootParity()) {
595
- logger.debug('Root parity already started.');
596
- return;
597
- }
598
- const inputs = provingState.getParityRootInputs();
599
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getRootParityProof', {
600
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-root'
601
- }, (signal)=>this.prover.getRootParityProof(inputs, signal, provingState.epochNumber)), (result)=>{
602
- provingState.setRootParityProof(result);
603
- this.checkAndEnqueueBlockRootRollup(provingState);
604
- });
605
- }
606
- // Executes the block merge rollup circuit and stored the output as intermediate state for the parent merge/block root circuit
607
- // Enqueues the next level of merge if all inputs are available
608
- enqueueBlockMergeRollup(provingState, location) {
609
- if (!provingState.verifyState()) {
610
- logger.debug('Not running block merge rollup. State no longer valid.');
611
- return;
612
- }
613
- if (!provingState.tryStartProvingBlockMerge(location)) {
614
- logger.debug('Block merge rollup already started.');
615
- return;
616
- }
617
- const inputs = provingState.getBlockMergeRollupInputs(location);
618
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getBlockMergeRollupProof', {
619
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-block-merge'
620
- }, (signal)=>this.prover.getBlockMergeRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
621
- provingState.setBlockMergeRollupProof(location, result);
622
- this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
623
- });
624
- }
625
- enqueueCheckpointRootRollup(provingState) {
626
- if (!provingState.verifyState()) {
627
- logger.debug('Not running checkpoint root rollup. State no longer valid.');
628
- return;
629
- }
630
- if (!provingState.tryStartProvingCheckpointRoot()) {
631
- logger.debug('Checkpoint root rollup already started.');
632
- return;
633
- }
634
- const rollupType = provingState.getCheckpointRootRollupType();
635
- logger.debug(`Enqueuing ${rollupType} for checkpoint ${provingState.index}.`);
636
- const inputs = provingState.getCheckpointRootRollupInputs();
637
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getCheckpointRootRollupProof', {
638
- [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
639
- }, (signal)=>{
640
- if (inputs instanceof CheckpointRootSingleBlockRollupPrivateInputs) {
641
- return this.prover.getCheckpointRootSingleBlockRollupProof(inputs, signal, provingState.epochNumber);
642
- } else {
643
- return this.prover.getCheckpointRootRollupProof(inputs, signal, provingState.epochNumber);
644
- }
645
- }), (result)=>{
646
- const computedEndBlobAccumulatorState = provingState.getEndBlobAccumulator().toBlobAccumulator();
647
- const circuitEndBlobAccumulatorState = result.inputs.endBlobAccumulator;
648
- if (!circuitEndBlobAccumulatorState.equals(computedEndBlobAccumulatorState)) {
649
- logger.error(`Blob accumulator state mismatch.\nCircuit: ${inspect(circuitEndBlobAccumulatorState)}\nComputed: ${inspect(computedEndBlobAccumulatorState)}`);
650
- provingState.reject(`Blob accumulator state mismatch.`);
651
- return;
652
- }
653
- logger.debug(`Completed ${rollupType} proof for checkpoint ${provingState.index}.`);
654
- const leafLocation = provingState.setCheckpointRootRollupProof(result);
655
- const epochProvingState = provingState.parentEpoch;
656
- if (epochProvingState.totalNumCheckpoints === 1) {
657
- this.enqueueEpochPadding(epochProvingState);
658
- } else {
659
- this.checkAndEnqueueNextCheckpointMergeRollup(epochProvingState, leafLocation);
660
- }
661
- });
662
- }
663
- enqueueCheckpointMergeRollup(provingState, location) {
664
- if (!provingState.verifyState()) {
665
- logger.debug('Not running checkpoint merge rollup. State no longer valid.');
666
- return;
667
- }
668
- if (!provingState.tryStartProvingCheckpointMerge(location)) {
669
- logger.debug('Checkpoint merge rollup already started.');
670
- return;
671
- }
672
- const inputs = provingState.getCheckpointMergeRollupInputs(location);
673
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getCheckpointMergeRollupProof', {
674
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-checkpoint-merge'
675
- }, (signal)=>this.prover.getCheckpointMergeRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
676
- logger.debug('Completed proof for checkpoint merge rollup.');
677
- provingState.setCheckpointMergeRollupProof(location, result);
678
- this.checkAndEnqueueNextCheckpointMergeRollup(provingState, location);
679
- });
680
- }
681
- enqueueEpochPadding(provingState) {
682
- if (!provingState.verifyState()) {
683
- logger.debug('Not running epoch padding. State no longer valid.');
684
- return;
685
- }
686
- if (!provingState.tryStartProvingPaddingCheckpoint()) {
687
- logger.debug('Padding checkpoint already started.');
688
- return;
689
- }
690
- logger.debug('Padding epoch proof with a padding block root proof.');
691
- const inputs = provingState.getPaddingCheckpointInputs();
692
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getCheckpointPaddingRollupProof', {
693
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-checkpoint-padding'
694
- }, (signal)=>this.prover.getCheckpointPaddingRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
695
- logger.debug('Completed proof for padding checkpoint.');
696
- provingState.setCheckpointPaddingProof(result);
697
- this.checkAndEnqueueRootRollup(provingState);
698
- });
699
- }
700
- // Executes the root rollup circuit
701
- enqueueRootRollup(provingState) {
702
- if (!provingState.verifyState()) {
703
- logger.debug('Not running root rollup, state no longer valid');
704
- return;
705
- }
706
- logger.debug(`Preparing root rollup`);
707
- const inputs = provingState.getRootRollupInputs();
708
- this.deferredProving(provingState, wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getRootRollupProof', {
709
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-root'
710
- }, (signal)=>this.prover.getRootRollupProof(inputs, signal, provingState.epochNumber)), (result)=>{
711
- logger.verbose(`Orchestrator completed root rollup for epoch ${provingState.epochNumber}`);
712
- provingState.setRootRollupProof(result);
713
- provingState.resolve({
714
- status: 'success'
715
- });
716
- });
717
- }
718
- checkAndEnqueueNextMergeRollup(provingState, currentLocation) {
719
- if (!provingState.isReadyForMergeRollup(currentLocation)) {
720
- return;
721
- }
722
- const parentLocation = provingState.getParentLocation(currentLocation);
723
- if (parentLocation.level === 0) {
724
- this.checkAndEnqueueBlockRootRollup(provingState);
725
- } else {
726
- this.enqueueMergeRollup(provingState, parentLocation);
727
- }
728
- }
729
- checkAndEnqueueBlockRootRollup(provingState) {
730
- if (!provingState.isReadyForBlockRootRollup()) {
731
- logger.debug('Not ready for block root rollup');
732
- return;
733
- }
734
- this.enqueueBlockRootRollup(provingState);
735
- }
736
- checkAndEnqueueNextBlockMergeRollup(provingState, currentLocation) {
737
- if (!provingState.isReadyForBlockMerge(currentLocation)) {
738
- return;
739
- }
740
- const parentLocation = provingState.getParentLocation(currentLocation);
741
- if (parentLocation.level === 0) {
742
- this.checkAndEnqueueCheckpointRootRollup(provingState);
743
- } else {
744
- this.enqueueBlockMergeRollup(provingState, parentLocation);
745
- }
746
- }
747
- checkAndEnqueueCheckpointRootRollup(provingState) {
748
- if (!provingState.isReadyForCheckpointRoot()) {
749
- return;
750
- }
751
- this.enqueueCheckpointRootRollup(provingState);
752
- }
753
- checkAndEnqueueNextCheckpointMergeRollup(provingState, currentLocation) {
754
- if (!provingState.isReadyForCheckpointMerge(currentLocation)) {
755
- return;
756
- }
757
- const parentLocation = provingState.getParentLocation(currentLocation);
758
- if (parentLocation.level === 0) {
759
- this.checkAndEnqueueRootRollup(provingState);
760
- } else {
761
- this.enqueueCheckpointMergeRollup(provingState, parentLocation);
762
- }
763
- }
764
- checkAndEnqueueRootRollup(provingState) {
765
- if (!provingState.isReadyForRootRollup()) {
766
- logger.debug('Not ready for root rollup');
767
- return;
768
- }
769
- this.enqueueRootRollup(provingState);
770
- }
771
- /**
772
- * Executes the VM circuit for a public function, will enqueue the corresponding kernel if the
773
- * previous kernel is ready
774
- * @param provingState - The proving state being operated on
775
- * @param txIndex - The index of the transaction being proven
776
- */ enqueueVM(provingState, txIndex) {
777
- if (!provingState.verifyState()) {
778
- logger.debug(`Not running VM circuit as state is no longer valid`);
779
- return;
780
- }
781
- const txProvingState = provingState.getTxProvingState(txIndex);
782
- // This function tries to do AVM proving. If there is a failure, it fakes the proof unless AVM_PROVING_STRICT is defined.
783
- // Nothing downstream depends on the AVM proof yet. So having this mode lets us incrementally build the AVM circuit.
784
- const doAvmProving = wrapCallbackInSpan(this.tracer, 'ProvingOrchestrator.prover.getAvmProof', {
785
- [Attributes.TX_HASH]: txProvingState.processedTx.hash.toString()
786
- }, async (signal)=>{
787
- const inputs = txProvingState.getAvmInputs();
788
- try {
789
- // TODO(#14234)[Unconditional PIs validation]: Remove the whole try-catch logic and
790
- // just keep the next line but removing the second argument (false).
791
- return await this.prover.getAvmProof(inputs, false, signal, provingState.epochNumber);
792
- } catch (err) {
793
- if (process.env.AVM_PROVING_STRICT) {
794
- logger.error(`Error thrown when proving AVM circuit with AVM_PROVING_STRICT on`, err);
795
- throw err;
796
- } else {
797
- logger.warn(`Error thrown when proving AVM circuit but AVM_PROVING_STRICT is off. Use snapshotted
798
- AVM inputs and carrying on. ${inspect(err)}.`);
799
- try {
800
- this.metrics.incAvmFallback();
801
- const snapshotAvmPrivateInputs = readAvmMinimalPublicTxInputsFromFile();
802
- return await this.prover.getAvmProof(snapshotAvmPrivateInputs, true, signal, provingState.epochNumber);
803
- } catch (err) {
804
- logger.error(`Error thrown when proving snapshotted AVM inputs.`, err);
805
- throw err;
806
- }
807
- }
808
- }
809
- });
810
- this.deferredProving(provingState, doAvmProving, (proofAndVk)=>{
811
- logger.debug(`Proven VM for tx index: ${txIndex}`);
812
- txProvingState.setAvmProof(proofAndVk);
813
- this.checkAndEnqueueBaseRollup(provingState, txIndex);
814
- });
815
- }
816
- checkAndEnqueueBaseRollup(provingState, txIndex) {
817
- const txProvingState = provingState.getTxProvingState(txIndex);
818
- if (!txProvingState.ready()) {
819
- return;
820
- }
821
- // We must have completed all proving (chonk verifier proof and (if required) vm proof are generated), we now move to the base rollup.
822
- logger.debug(`Public functions completed for tx ${txIndex} enqueueing base rollup`);
823
- this.enqueueBaseRollup(provingState, txIndex);
824
- }
825
- }
826
- _ts_decorate([
827
- trackSpan('ProvingOrchestrator.startNewBlock', (blockNumber)=>({
828
- [Attributes.BLOCK_NUMBER]: blockNumber
829
- }))
830
- ], ProvingOrchestrator.prototype, "startNewBlock", null);
831
- _ts_decorate([
832
- trackSpan('ProvingOrchestrator.addTxs', (txs)=>({
833
- [Attributes.BLOCK_TXS_COUNT]: txs.length
834
- }))
835
- ], ProvingOrchestrator.prototype, "addTxs", null);
836
- _ts_decorate([
837
- trackSpan('ProvingOrchestrator.startChonkVerifierCircuits')
838
- ], ProvingOrchestrator.prototype, "startChonkVerifierCircuits", null);
839
- _ts_decorate([
840
- trackSpan('ProvingOrchestrator.setBlockCompleted', (blockNumber)=>({
841
- [Attributes.BLOCK_NUMBER]: blockNumber
842
- }))
843
- ], ProvingOrchestrator.prototype, "setBlockCompleted", null);
844
- _ts_decorate([
845
- trackSpan('ProvingOrchestrator.prepareBaseRollupInputs', (tx)=>({
846
- [Attributes.TX_HASH]: tx.hash.toString()
847
- }))
848
- ], ProvingOrchestrator.prototype, "prepareBaseRollupInputs", null);