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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +1 -0
  2. package/dest/config.d.ts +17 -0
  3. package/dest/config.d.ts.map +1 -0
  4. package/dest/config.js +63 -0
  5. package/dest/index.d.ts +4 -0
  6. package/dest/index.d.ts.map +1 -0
  7. package/dest/index.js +2 -0
  8. package/dest/light/index.d.ts +2 -0
  9. package/dest/light/index.d.ts.map +1 -0
  10. package/dest/light/index.js +1 -0
  11. package/dest/light/lightweight_checkpoint_builder.d.ts +58 -0
  12. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -0
  13. package/dest/light/lightweight_checkpoint_builder.js +243 -0
  14. package/dest/mocks/fixtures.d.ts +20 -0
  15. package/dest/mocks/fixtures.d.ts.map +1 -0
  16. package/dest/mocks/fixtures.js +96 -0
  17. package/dest/mocks/test_context.d.ts +93 -0
  18. package/dest/mocks/test_context.d.ts.map +1 -0
  19. package/dest/mocks/test_context.js +354 -0
  20. package/dest/orchestrator/block-building-helpers.d.ts +67 -0
  21. package/dest/orchestrator/block-building-helpers.d.ts.map +1 -0
  22. package/dest/orchestrator/block-building-helpers.js +274 -0
  23. package/dest/orchestrator/block-proving-state.d.ts +107 -0
  24. package/dest/orchestrator/block-proving-state.d.ts.map +1 -0
  25. package/dest/orchestrator/block-proving-state.js +339 -0
  26. package/dest/orchestrator/checkpoint-proving-state.d.ts +67 -0
  27. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -0
  28. package/dest/orchestrator/checkpoint-proving-state.js +175 -0
  29. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts +169 -0
  30. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts.map +1 -0
  31. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.js +1047 -0
  32. package/dest/orchestrator/chonk-cache.d.ts +39 -0
  33. package/dest/orchestrator/chonk-cache.d.ts.map +1 -0
  34. package/dest/orchestrator/chonk-cache.js +80 -0
  35. package/dest/orchestrator/index.d.ts +4 -0
  36. package/dest/orchestrator/index.d.ts.map +1 -0
  37. package/dest/orchestrator/index.js +3 -0
  38. package/dest/orchestrator/orchestrator_metrics.d.ts +8 -0
  39. package/dest/orchestrator/orchestrator_metrics.d.ts.map +1 -0
  40. package/dest/orchestrator/orchestrator_metrics.js +13 -0
  41. package/dest/orchestrator/proving-scheduler.d.ts +81 -0
  42. package/dest/orchestrator/proving-scheduler.d.ts.map +1 -0
  43. package/dest/orchestrator/proving-scheduler.js +120 -0
  44. package/dest/orchestrator/top-tree-orchestrator.d.ts +89 -0
  45. package/dest/orchestrator/top-tree-orchestrator.d.ts.map +1 -0
  46. package/dest/orchestrator/top-tree-orchestrator.js +233 -0
  47. package/dest/orchestrator/top-tree-proving-state.d.ts +61 -0
  48. package/dest/orchestrator/top-tree-proving-state.d.ts.map +1 -0
  49. package/dest/orchestrator/top-tree-proving-state.js +185 -0
  50. package/dest/orchestrator/tx-proving-state.d.ts +37 -0
  51. package/dest/orchestrator/tx-proving-state.d.ts.map +1 -0
  52. package/dest/orchestrator/tx-proving-state.js +77 -0
  53. package/dest/prover-client/factory.d.ts +6 -0
  54. package/dest/prover-client/factory.d.ts.map +1 -0
  55. package/dest/prover-client/factory.js +5 -0
  56. package/dest/prover-client/index.d.ts +3 -0
  57. package/dest/prover-client/index.d.ts.map +1 -0
  58. package/dest/prover-client/index.js +2 -0
  59. package/dest/prover-client/prover-client.d.ts +99 -0
  60. package/dest/prover-client/prover-client.d.ts.map +1 -0
  61. package/dest/prover-client/prover-client.js +163 -0
  62. package/dest/proving_broker/broker_prover_facade.d.ts +52 -0
  63. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -0
  64. package/dest/proving_broker/broker_prover_facade.js +360 -0
  65. package/dest/proving_broker/config.d.ts +40 -0
  66. package/dest/proving_broker/config.d.ts.map +1 -0
  67. package/dest/proving_broker/config.js +138 -0
  68. package/dest/proving_broker/factory.d.ts +5 -0
  69. package/dest/proving_broker/factory.d.ts.map +1 -0
  70. package/dest/proving_broker/factory.js +13 -0
  71. package/dest/proving_broker/fixtures.d.ts +6 -0
  72. package/dest/proving_broker/fixtures.d.ts.map +1 -0
  73. package/dest/proving_broker/fixtures.js +13 -0
  74. package/dest/proving_broker/index.d.ts +11 -0
  75. package/dest/proving_broker/index.d.ts.map +1 -0
  76. package/dest/proving_broker/index.js +10 -0
  77. package/dest/proving_broker/proof_store/factory.d.ts +3 -0
  78. package/dest/proving_broker/proof_store/factory.d.ts.map +1 -0
  79. package/dest/proving_broker/proof_store/factory.js +13 -0
  80. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts +18 -0
  81. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts.map +1 -0
  82. package/dest/proving_broker/proof_store/file_store_proof_store.js +60 -0
  83. package/dest/proving_broker/proof_store/index.d.ts +5 -0
  84. package/dest/proving_broker/proof_store/index.d.ts.map +1 -0
  85. package/dest/proving_broker/proof_store/index.js +4 -0
  86. package/dest/proving_broker/proof_store/inline_proof_store.d.ts +15 -0
  87. package/dest/proving_broker/proof_store/inline_proof_store.d.ts.map +1 -0
  88. package/dest/proving_broker/proof_store/inline_proof_store.js +41 -0
  89. package/dest/proving_broker/proof_store/proof_store.d.ts +36 -0
  90. package/dest/proving_broker/proof_store/proof_store.d.ts.map +1 -0
  91. package/dest/proving_broker/proof_store/proof_store.js +3 -0
  92. package/dest/proving_broker/proving_agent.d.ts +42 -0
  93. package/dest/proving_broker/proving_agent.d.ts.map +1 -0
  94. package/dest/proving_broker/proving_agent.js +155 -0
  95. package/dest/proving_broker/proving_broker.d.ts +77 -0
  96. package/dest/proving_broker/proving_broker.d.ts.map +1 -0
  97. package/dest/proving_broker/proving_broker.js +780 -0
  98. package/dest/proving_broker/proving_broker_database/memory.d.ts +20 -0
  99. package/dest/proving_broker/proving_broker_database/memory.d.ts.map +1 -0
  100. package/dest/proving_broker/proving_broker_database/memory.js +67 -0
  101. package/dest/proving_broker/proving_broker_database/persisted.d.ts +40 -0
  102. package/dest/proving_broker/proving_broker_database/persisted.d.ts.map +1 -0
  103. package/dest/proving_broker/proving_broker_database/persisted.js +623 -0
  104. package/dest/proving_broker/proving_broker_database.d.ts +66 -0
  105. package/dest/proving_broker/proving_broker_database.d.ts.map +1 -0
  106. package/dest/proving_broker/proving_broker_database.js +3 -0
  107. package/dest/proving_broker/proving_broker_instrumentation.d.ts +31 -0
  108. package/dest/proving_broker/proving_broker_instrumentation.d.ts.map +1 -0
  109. package/dest/proving_broker/proving_broker_instrumentation.js +97 -0
  110. package/dest/proving_broker/proving_job_controller.d.ts +34 -0
  111. package/dest/proving_broker/proving_job_controller.d.ts.map +1 -0
  112. package/dest/proving_broker/proving_job_controller.js +184 -0
  113. package/dest/proving_broker/rpc.d.ts +38 -0
  114. package/dest/proving_broker/rpc.d.ts.map +1 -0
  115. package/dest/proving_broker/rpc.js +138 -0
  116. package/dest/test/epoch_settlement.d.ts +36 -0
  117. package/dest/test/epoch_settlement.d.ts.map +1 -0
  118. package/dest/test/epoch_settlement.js +52 -0
  119. package/dest/test/index.d.ts +2 -0
  120. package/dest/test/index.d.ts.map +1 -0
  121. package/dest/test/index.js +1 -0
  122. package/dest/test/mock_proof_store.d.ts +9 -0
  123. package/dest/test/mock_proof_store.d.ts.map +1 -0
  124. package/dest/test/mock_proof_store.js +10 -0
  125. package/dest/test/mock_prover.d.ts +38 -0
  126. package/dest/test/mock_prover.d.ts.map +1 -0
  127. package/dest/test/mock_prover.js +91 -0
  128. package/package.json +113 -0
  129. package/src/config.ts +87 -0
  130. package/src/index.ts +4 -0
  131. package/src/light/index.ts +1 -0
  132. package/src/light/lightweight_checkpoint_builder.ts +342 -0
  133. package/src/mocks/fixtures.ts +120 -0
  134. package/src/mocks/test_context.ts +477 -0
  135. package/src/orchestrator/block-building-helpers.ts +486 -0
  136. package/src/orchestrator/block-proving-state.ts +457 -0
  137. package/src/orchestrator/checkpoint-proving-state.ts +247 -0
  138. package/src/orchestrator/checkpoint-sub-tree-orchestrator.ts +1010 -0
  139. package/src/orchestrator/chonk-cache.ts +99 -0
  140. package/src/orchestrator/index.ts +12 -0
  141. package/src/orchestrator/orchestrator_metrics.ts +18 -0
  142. package/src/orchestrator/proving-scheduler.ts +160 -0
  143. package/src/orchestrator/top-tree-orchestrator.ts +394 -0
  144. package/src/orchestrator/top-tree-proving-state.ts +219 -0
  145. package/src/orchestrator/tx-proving-state.ts +121 -0
  146. package/src/prover-client/factory.ts +18 -0
  147. package/src/prover-client/index.ts +2 -0
  148. package/src/prover-client/prover-client.ts +286 -0
  149. package/src/proving_broker/broker_prover_facade.ts +626 -0
  150. package/src/proving_broker/config.ts +178 -0
  151. package/src/proving_broker/factory.ts +19 -0
  152. package/src/proving_broker/fixtures.ts +20 -0
  153. package/src/proving_broker/index.ts +10 -0
  154. package/src/proving_broker/proof_store/factory.ts +20 -0
  155. package/src/proving_broker/proof_store/file_store_proof_store.ts +78 -0
  156. package/src/proving_broker/proof_store/index.ts +4 -0
  157. package/src/proving_broker/proof_store/inline_proof_store.ts +63 -0
  158. package/src/proving_broker/proof_store/proof_store.ts +54 -0
  159. package/src/proving_broker/proving_agent.ts +210 -0
  160. package/src/proving_broker/proving_broker.ts +888 -0
  161. package/src/proving_broker/proving_broker_database/memory.ts +78 -0
  162. package/src/proving_broker/proving_broker_database/persisted.ts +296 -0
  163. package/src/proving_broker/proving_broker_database.ts +75 -0
  164. package/src/proving_broker/proving_broker_instrumentation.ts +133 -0
  165. package/src/proving_broker/proving_job_controller.ts +199 -0
  166. package/src/proving_broker/rpc.ts +131 -0
  167. package/src/test/epoch_settlement.ts +82 -0
  168. package/src/test/index.ts +1 -0
  169. package/src/test/mock_proof_store.ts +14 -0
  170. package/src/test/mock_prover.ts +304 -0
@@ -0,0 +1,342 @@
1
+ import {
2
+ SpongeBlob,
3
+ computeBlobsHashFromBlobs,
4
+ encodeCheckpointEndMarker,
5
+ getBlobsPerL1Block,
6
+ } from '@aztec-labs/blob-lib';
7
+ import { type CheckpointNumber, IndexWithinCheckpoint } from '@aztec-labs/foundation/branded-types';
8
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
9
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec-labs/foundation/log';
10
+ import { elapsed } from '@aztec-labs/foundation/timer';
11
+ import { L2Block } from '@aztec-labs/stdlib/block';
12
+ import { Checkpoint } from '@aztec-labs/stdlib/checkpoint';
13
+ import type { MerkleTreeWriteOperations } from '@aztec-labs/stdlib/interfaces/server';
14
+ import {
15
+ accumulateCheckpointOutHashes,
16
+ accumulateInboxRollingHash,
17
+ appendL1ToL2MessagesToTree,
18
+ computeCheckpointOutHash,
19
+ } from '@aztec-labs/stdlib/messaging';
20
+ import { CheckpointHeader, computeBlockHeadersHash } from '@aztec-labs/stdlib/rollup';
21
+ import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec-labs/stdlib/trees';
22
+ import {
23
+ type CheckpointGlobalVariables,
24
+ type GlobalVariables,
25
+ type ProcessedTx,
26
+ StateReference,
27
+ } from '@aztec-labs/stdlib/tx';
28
+
29
+ import {
30
+ buildHeaderAndBodyFromTxs,
31
+ getTreeSnapshot,
32
+ insertSideEffects,
33
+ } from '../orchestrator/block-building-helpers.js';
34
+
35
+ /**
36
+ * Builds a checkpoint and its header and the blocks in it from a set of processed tx without running any circuits.
37
+ *
38
+ * Each added block inserts its own L1-to-L2 message bundle into the message tree and then updates the archive tree.
39
+ * Finally completes the checkpoint by computing its header.
40
+ */
41
+ export class LightweightCheckpointBuilder {
42
+ private readonly logger: Logger;
43
+
44
+ private lastArchives: AppendOnlyTreeSnapshot[] = [];
45
+ private spongeBlob: SpongeBlob;
46
+ private blocks: L2Block[] = [];
47
+ private blobFields: Fr[] = [];
48
+
49
+ constructor(
50
+ public readonly checkpointNumber: CheckpointNumber,
51
+ public readonly constants: CheckpointGlobalVariables,
52
+ public feeAssetPriceModifier: bigint,
53
+ public readonly l1ToL2Messages: Fr[],
54
+ private readonly previousCheckpointOutHashes: Fr[],
55
+ // Inbox rolling hash of the previous checkpoint (this checkpoint's chain start); genesis is zero.
56
+ private readonly previousInboxRollingHash: Fr,
57
+ public readonly db: MerkleTreeWriteOperations,
58
+ bindings?: LoggerBindings,
59
+ ) {
60
+ this.logger = createLogger('checkpoint-builder', {
61
+ ...bindings,
62
+ instanceId: `checkpoint-${checkpointNumber}`,
63
+ });
64
+ this.spongeBlob = SpongeBlob.init();
65
+ this.logger.debug('Starting new checkpoint', { constants, l1ToL2Messages, feeAssetPriceModifier });
66
+ }
67
+
68
+ /**
69
+ * Starts a fresh checkpoint. The checkpoint's L1-to-L2 messages are not supplied here: every block brings its own
70
+ * bundle to {@link addBlock}, which inserts it into the tree and accumulates it into the checkpoint's message list.
71
+ */
72
+ static startNewCheckpoint(
73
+ checkpointNumber: CheckpointNumber,
74
+ constants: CheckpointGlobalVariables,
75
+ previousCheckpointOutHashes: Fr[],
76
+ previousInboxRollingHash: Fr,
77
+ db: MerkleTreeWriteOperations,
78
+ bindings?: LoggerBindings,
79
+ feeAssetPriceModifier: bigint = 0n,
80
+ ): LightweightCheckpointBuilder {
81
+ return new LightweightCheckpointBuilder(
82
+ checkpointNumber,
83
+ constants,
84
+ feeAssetPriceModifier,
85
+ [],
86
+ previousCheckpointOutHashes,
87
+ previousInboxRollingHash,
88
+ db,
89
+ bindings,
90
+ );
91
+ }
92
+
93
+ /**
94
+ * Resumes building a checkpoint from existing blocks. This is used for validator re-execution
95
+ * where blocks have already been built and their effects are already in the database.
96
+ * `l1ToL2Messages` is the whole checkpoint's message list as consumed by the existing blocks: it seeds the
97
+ * checkpoint's rolling hash and is not inserted into the tree, since the blocks already inserted it.
98
+ */
99
+ static async resumeCheckpoint(
100
+ checkpointNumber: CheckpointNumber,
101
+ constants: CheckpointGlobalVariables,
102
+ feeAssetPriceModifier: bigint,
103
+ l1ToL2Messages: Fr[],
104
+ previousCheckpointOutHashes: Fr[],
105
+ previousInboxRollingHash: Fr,
106
+ db: MerkleTreeWriteOperations,
107
+ existingBlocks: L2Block[],
108
+ bindings?: LoggerBindings,
109
+ ): Promise<LightweightCheckpointBuilder> {
110
+ const builder = new LightweightCheckpointBuilder(
111
+ checkpointNumber,
112
+ constants,
113
+ feeAssetPriceModifier,
114
+ l1ToL2Messages,
115
+ previousCheckpointOutHashes,
116
+ previousInboxRollingHash,
117
+ db,
118
+ bindings,
119
+ );
120
+
121
+ builder.logger.debug('Resuming checkpoint from existing blocks', {
122
+ checkpointNumber,
123
+ numExistingBlocks: existingBlocks.length,
124
+ blockNumbers: existingBlocks.map(b => b.header.getBlockNumber()),
125
+ });
126
+
127
+ if (existingBlocks.length === 0) {
128
+ throw new Error(`Cannot resume checkpoint ${checkpointNumber} with no existing blocks`);
129
+ }
130
+
131
+ // Validate block order and consistency
132
+ for (let i = 1; i < existingBlocks.length; i++) {
133
+ const prev = existingBlocks[i - 1];
134
+ const curr = existingBlocks[i];
135
+ if (curr.number !== prev.number + 1) {
136
+ throw new Error(`Non-sequential block numbers in resumeCheckpoint: ${prev.number} -> ${curr.number}`);
137
+ }
138
+ if (!prev.archive.root.equals(curr.header.lastArchive.root)) {
139
+ throw new Error(`Archive root mismatch between blocks ${prev.number} and ${curr.number}`);
140
+ }
141
+ }
142
+
143
+ for (let i = 0; i < existingBlocks.length; i++) {
144
+ const block = existingBlocks[i];
145
+ const isFirstBlock = i === 0;
146
+
147
+ if (isFirstBlock) {
148
+ builder.lastArchives.push(block.header.lastArchive);
149
+ }
150
+
151
+ builder.lastArchives.push(block.archive);
152
+
153
+ const blockBlobFields = block.toBlobFields();
154
+ await builder.spongeBlob.absorb(blockBlobFields);
155
+ builder.blobFields.push(...blockBlobFields);
156
+
157
+ builder.blocks.push(block);
158
+ }
159
+
160
+ return builder;
161
+ }
162
+
163
+ /** Returns how many blocks have been added to this checkpoint so far */
164
+ public getBlockCount() {
165
+ return this.blocks.length;
166
+ }
167
+
168
+ public getBlocks() {
169
+ return this.blocks;
170
+ }
171
+
172
+ /**
173
+ * Adds a new block to the checkpoint. The tx effects must have already been inserted into the db if
174
+ * this is called after tx processing, if that's not the case, then set `insertTxsEffects` to true.
175
+ * @param l1ToL2Messages - The message leaves this block consumes from the Inbox, in insertion order.
176
+ */
177
+ public async addBlock(
178
+ globalVariables: GlobalVariables,
179
+ txs: ProcessedTx[],
180
+ l1ToL2Messages: Fr[],
181
+ opts: { insertTxsEffects?: boolean; expectedEndState?: StateReference } = {},
182
+ ): Promise<{ block: L2Block; timings: Record<string, number> }> {
183
+ const timings: Record<string, number> = {};
184
+ const isFirstBlock = this.blocks.length === 0;
185
+
186
+ if (isFirstBlock) {
187
+ const [msGetInitialArchive, initialArchive] = await elapsed(() => getTreeSnapshot(MerkleTreeId.ARCHIVE, this.db));
188
+ this.lastArchives.push(initialArchive);
189
+ timings.getInitialArchive = msGetInitialArchive;
190
+ }
191
+
192
+ const lastArchive = this.lastArchives.at(-1)!;
193
+
194
+ if (opts.insertTxsEffects) {
195
+ this.logger.debug(
196
+ `Inserting side effects for ${txs.length} txs for block ${globalVariables.blockNumber} into db`,
197
+ { txs: txs.map(tx => tx.hash.toString()) },
198
+ );
199
+ let msInsertSideEffects = 0;
200
+ for (const tx of txs) {
201
+ const [ms] = await elapsed(() => insertSideEffects(tx, this.db));
202
+ msInsertSideEffects += ms;
203
+ }
204
+ timings.insertSideEffects = msInsertSideEffects;
205
+ }
206
+
207
+ // Streaming Inbox: insert this block's L1-to-L2 message bundle before reading the end state,
208
+ // so the block header's L1-to-L2 tree snapshot reflects it. Bundles are appended compactly (unpadded, at the
209
+ // tree's current next-available index). The logical messages are accumulated only once the block is fully built
210
+ // (below), so a mid-build failure does not pollute the checkpoint's rolling hash; the rolling hash is recomputed
211
+ // over them at checkpoint completion.
212
+ await appendL1ToL2MessagesToTree(this.db, l1ToL2Messages);
213
+
214
+ const [msGetEndState, endState] = await elapsed(() => this.db.getStateReference());
215
+ timings.getEndState = msGetEndState;
216
+
217
+ if (opts.expectedEndState && !endState.equals(opts.expectedEndState)) {
218
+ this.logger.error('End state after processing txs does not match expected end state', {
219
+ globalVariables: globalVariables.toInspect(),
220
+ expectedEndState: opts.expectedEndState.toInspect(),
221
+ actualEndState: endState.toInspect(),
222
+ });
223
+ throw new Error(`End state does not match expected end state when building block ${globalVariables.blockNumber}`);
224
+ }
225
+
226
+ const [msBuildHeaderAndBody, { header, body, blockBlobFields }] = await elapsed(() =>
227
+ buildHeaderAndBodyFromTxs(txs, lastArchive, endState, globalVariables, this.spongeBlob),
228
+ );
229
+ timings.buildHeaderAndBody = msBuildHeaderAndBody;
230
+
231
+ header.state.validate();
232
+
233
+ await this.db.updateArchive(header);
234
+ const [msUpdateArchive, newArchive] = await elapsed(() => getTreeSnapshot(MerkleTreeId.ARCHIVE, this.db));
235
+ timings.updateArchive = msUpdateArchive;
236
+ this.lastArchives.push(newArchive);
237
+
238
+ const expectedNextLeafIndex = Number(globalVariables.blockNumber) + 1;
239
+ if (newArchive.nextAvailableLeafIndex !== expectedNextLeafIndex) {
240
+ throw new Error(
241
+ `Archive tree next leaf index mismatch after building block ${globalVariables.blockNumber} (expected ${expectedNextLeafIndex} but got ${newArchive.nextAvailableLeafIndex})`,
242
+ );
243
+ }
244
+
245
+ const indexWithinCheckpoint = IndexWithinCheckpoint(this.blocks.length);
246
+ const block = new L2Block(newArchive, header, body, this.checkpointNumber, indexWithinCheckpoint);
247
+ this.blocks.push(block);
248
+
249
+ // Accumulate the streaming bundle now that the block is fully built, so a mid-build throw above leaves the
250
+ // checkpoint's message list (and thus its rolling hash) consistent with the blocks actually built.
251
+ this.l1ToL2Messages.push(...l1ToL2Messages);
252
+
253
+ const [msSpongeAbsorb] = await elapsed(() => this.spongeBlob.absorb(blockBlobFields));
254
+ timings.spongeAbsorb = msSpongeAbsorb;
255
+ this.blobFields.push(...blockBlobFields);
256
+
257
+ this.logger.debug(`Built block ${header.getBlockNumber()}`, {
258
+ globalVariables: globalVariables.toInspect(),
259
+ archiveRoot: newArchive.root.toString(),
260
+ stateReference: header.state.toInspect(),
261
+ blockHash: (await block.hash()).toString(),
262
+ txs: block.body.txEffects.map(tx => tx.txHash.toString()),
263
+ });
264
+
265
+ return { block, timings };
266
+ }
267
+
268
+ async completeCheckpoint(): Promise<Checkpoint> {
269
+ if (!this.blocks.length) {
270
+ throw new Error('Cannot complete a checkpoint with no blocks');
271
+ }
272
+
273
+ const numBlobFields = this.blobFields.length + 1; // +1 for the checkpoint end marker.
274
+ const checkpointEndMarker = encodeCheckpointEndMarker({ numBlobFields });
275
+ this.blobFields.push(checkpointEndMarker);
276
+
277
+ const blocks = this.blocks;
278
+ const blockHeadersHash = await computeBlockHeadersHash(blocks.map(block => block.header));
279
+
280
+ const newArchive = this.lastArchives[this.lastArchives.length - 1];
281
+
282
+ const blobs = await getBlobsPerL1Block(this.blobFields);
283
+ const blobsHash = computeBlobsHashFromBlobs(blobs);
284
+
285
+ const inboxRollingHash = accumulateInboxRollingHash(this.previousInboxRollingHash, this.l1ToL2Messages);
286
+
287
+ const { slotNumber, coinbase, feeRecipient, gasFees } = this.constants;
288
+ const checkpointOutHash = computeCheckpointOutHash(
289
+ blocks.map(block => block.body.txEffects.map(tx => tx.l2ToL1Msgs)),
290
+ );
291
+ const epochOutHash = accumulateCheckpointOutHashes([...this.previousCheckpointOutHashes, checkpointOutHash]);
292
+
293
+ // All blocks in the checkpoint have the same timestamp
294
+ const timestamp = blocks[blocks.length - 1].timestamp;
295
+
296
+ const totalManaUsed = blocks.reduce((acc, block) => acc.add(block.header.totalManaUsed), Fr.ZERO);
297
+ const accumulatedFees = blocks.reduce((acc, block) => acc.add(block.header.totalFees), Fr.ZERO);
298
+
299
+ const header = CheckpointHeader.from({
300
+ lastArchiveRoot: this.lastArchives[0].root,
301
+ blobsHash,
302
+ inboxRollingHash,
303
+ epochOutHash,
304
+ blockHeadersHash,
305
+ slotNumber,
306
+ timestamp,
307
+ coinbase,
308
+ feeRecipient,
309
+ gasFees,
310
+ totalManaUsed,
311
+ accumulatedFees,
312
+ });
313
+
314
+ this.logger.debug(`Completed checkpoint ${this.checkpointNumber}`, {
315
+ checkpointNumber: this.checkpointNumber,
316
+ headerHash: header.hash().toString(),
317
+ checkpointOutHash: checkpointOutHash.toString(),
318
+ numPreviousCheckpointOutHashes: this.previousCheckpointOutHashes.length,
319
+ ...header.toInspect(),
320
+ });
321
+
322
+ return new Checkpoint(newArchive, header, blocks, this.checkpointNumber, this.feeAssetPriceModifier);
323
+ }
324
+
325
+ clone() {
326
+ const clone = new LightweightCheckpointBuilder(
327
+ this.checkpointNumber,
328
+ this.constants,
329
+ this.feeAssetPriceModifier,
330
+ [...this.l1ToL2Messages],
331
+ [...this.previousCheckpointOutHashes],
332
+ this.previousInboxRollingHash,
333
+ this.db,
334
+ this.logger.getBindings(),
335
+ );
336
+ clone.lastArchives = [...this.lastArchives];
337
+ clone.spongeBlob = this.spongeBlob.clone();
338
+ clone.blocks = [...this.blocks];
339
+ clone.blobFields = [...this.blobFields];
340
+ return clone;
341
+ }
342
+ }
@@ -0,0 +1,120 @@
1
+ import { BlockNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
2
+ import { randomBytes } from '@aztec-labs/foundation/crypto/random';
3
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
4
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
5
+ import type { Logger } from '@aztec-labs/foundation/log';
6
+ import type { FieldsOf } from '@aztec-labs/foundation/types';
7
+ import { fileURLToPath } from '@aztec-labs/foundation/url';
8
+ import { getVKTreeRoot } from '@aztec-labs/noir-protocol-circuits-types/vk-tree';
9
+ import { protocolContractsHash } from '@aztec-labs/protocol-contracts';
10
+ import { type CircuitSimulator, NativeACVMSimulator, WASMSimulatorWithBlobs } from '@aztec-labs/simulator/server';
11
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
12
+ import { GasFees } from '@aztec-labs/stdlib/gas';
13
+ import { CheckpointConstantData } from '@aztec-labs/stdlib/rollup';
14
+ import { GlobalVariables } from '@aztec-labs/stdlib/tx';
15
+ import { promises as fs } from 'fs';
16
+ import path from 'path';
17
+
18
+ const {
19
+ TEMP_DIR = '/tmp',
20
+ BB_BINARY_PATH = '',
21
+ BB_WORKING_DIRECTORY = '',
22
+ BB_SKIP_CLEANUP = '',
23
+ ACVM_BINARY_PATH = '',
24
+ ACVM_WORKING_DIRECTORY = '',
25
+ } = process.env;
26
+
27
+ // Determines if we have access to the bb binary and a tmp folder for temp files
28
+ export const getEnvironmentConfig = async (logger: Logger) => {
29
+ try {
30
+ const expectedBBPath = BB_BINARY_PATH
31
+ ? BB_BINARY_PATH
32
+ : `${path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../labs-aztec-toolchain/bin')}/bb-avm`;
33
+ await fs.access(expectedBBPath, fs.constants.R_OK);
34
+ const tempWorkingDirectory = `${TEMP_DIR}/${randomBytes(4).toString('hex')}`;
35
+ const bbWorkingDirectory = BB_WORKING_DIRECTORY ? BB_WORKING_DIRECTORY : `${tempWorkingDirectory}/bb`;
36
+ await fs.mkdir(bbWorkingDirectory, { recursive: true });
37
+ logger.info(`Found native BB binary at ${expectedBBPath} with working directory ${bbWorkingDirectory}`);
38
+
39
+ const expectedAcvmPath = ACVM_BINARY_PATH
40
+ ? ACVM_BINARY_PATH
41
+ : `${path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../labs-aztec-toolchain/bin')}/acvm`;
42
+ await fs.access(expectedAcvmPath, fs.constants.R_OK);
43
+ const acvmWorkingDirectory = ACVM_WORKING_DIRECTORY ? ACVM_WORKING_DIRECTORY : `${tempWorkingDirectory}/acvm`;
44
+ await fs.mkdir(acvmWorkingDirectory, { recursive: true });
45
+ logger.info(`Found native ACVM binary at ${expectedAcvmPath} with working directory ${acvmWorkingDirectory}`);
46
+
47
+ const bbSkipCleanup = ['1', 'true'].includes(BB_SKIP_CLEANUP);
48
+ bbSkipCleanup && logger.verbose(`Not going to clean up BB working directory ${bbWorkingDirectory} after run`);
49
+
50
+ return {
51
+ acvmWorkingDirectory,
52
+ bbWorkingDirectory,
53
+ expectedAcvmPath,
54
+ expectedBBPath,
55
+ directoryToCleanup: ACVM_WORKING_DIRECTORY && BB_WORKING_DIRECTORY ? undefined : tempWorkingDirectory,
56
+ bbSkipCleanup,
57
+ };
58
+ } catch (err) {
59
+ logger.info(`Native BB not available: ${err}`);
60
+ return undefined;
61
+ }
62
+ };
63
+
64
+ export async function getSimulator(
65
+ config: { acvmWorkingDirectory: string | undefined; acvmBinaryPath: string | undefined },
66
+ logger?: Logger,
67
+ ): Promise<CircuitSimulator> {
68
+ if (config.acvmBinaryPath && config.acvmWorkingDirectory) {
69
+ try {
70
+ await fs.access(config.acvmBinaryPath, fs.constants.R_OK);
71
+ await fs.mkdir(config.acvmWorkingDirectory, { recursive: true });
72
+ logger?.info(
73
+ `Using native ACVM at ${config.acvmBinaryPath} and working directory ${config.acvmWorkingDirectory}`,
74
+ );
75
+ const acvmLogger = logger?.createChild('acvm-native');
76
+ return new NativeACVMSimulator(config.acvmWorkingDirectory, config.acvmBinaryPath, undefined, acvmLogger);
77
+ } catch {
78
+ logger?.warn(`Failed to access ACVM at ${config.acvmBinaryPath}, falling back to WASM`);
79
+ }
80
+ }
81
+ logger?.info('Using WASM ACVM simulation');
82
+ return new WASMSimulatorWithBlobs();
83
+ }
84
+
85
+ export const makeGlobals = (
86
+ blockNumber: number,
87
+ slotNumber = blockNumber,
88
+ overrides: Partial<FieldsOf<GlobalVariables> & FieldsOf<CheckpointConstantData>> = {},
89
+ ) => {
90
+ const checkpointConstants = makeCheckpointConstants(slotNumber, overrides);
91
+ return GlobalVariables.from({
92
+ chainId: checkpointConstants.chainId,
93
+ version: checkpointConstants.version,
94
+ blockNumber: BlockNumber(blockNumber) /** block number */,
95
+ slotNumber: SlotNumber(slotNumber) /** slot number */,
96
+ timestamp: BigInt(blockNumber * 123) /** block number * 123 as pseudo-timestamp for testing */,
97
+ coinbase: checkpointConstants.coinbase,
98
+ feeRecipient: checkpointConstants.feeRecipient,
99
+ gasFees: checkpointConstants.gasFees,
100
+ ...overrides,
101
+ });
102
+ };
103
+
104
+ export const makeCheckpointConstants = (
105
+ slotNumber: number,
106
+ overrides: Partial<FieldsOf<CheckpointConstantData>> = {},
107
+ ) => {
108
+ return CheckpointConstantData.from({
109
+ chainId: Fr.ZERO,
110
+ version: Fr.ZERO,
111
+ vkTreeRoot: getVKTreeRoot(),
112
+ protocolContractsHash,
113
+ proverId: Fr.ZERO,
114
+ slotNumber: SlotNumber(slotNumber),
115
+ coinbase: EthAddress.ZERO,
116
+ feeRecipient: AztecAddress.ZERO,
117
+ gasFees: GasFees.empty(),
118
+ ...overrides,
119
+ });
120
+ };