@aztec/bb-prover 0.0.0-test.0

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 (97) hide show
  1. package/dest/avm_proving_tests/avm_proving_tester.d.ts +25 -0
  2. package/dest/avm_proving_tests/avm_proving_tester.d.ts.map +1 -0
  3. package/dest/avm_proving_tests/avm_proving_tester.js +105 -0
  4. package/dest/bb/cli.d.ts +12 -0
  5. package/dest/bb/cli.d.ts.map +1 -0
  6. package/dest/bb/cli.js +19 -0
  7. package/dest/bb/execute.d.ts +140 -0
  8. package/dest/bb/execute.d.ts.map +1 -0
  9. package/dest/bb/execute.js +780 -0
  10. package/dest/bb/index.d.ts +3 -0
  11. package/dest/bb/index.d.ts.map +1 -0
  12. package/dest/bb/index.js +16 -0
  13. package/dest/config.d.ts +13 -0
  14. package/dest/config.d.ts.map +1 -0
  15. package/dest/config.js +1 -0
  16. package/dest/honk.d.ts +13 -0
  17. package/dest/honk.d.ts.map +1 -0
  18. package/dest/honk.js +18 -0
  19. package/dest/index.d.ts +8 -0
  20. package/dest/index.d.ts.map +1 -0
  21. package/dest/index.js +6 -0
  22. package/dest/instrumentation.d.ts +47 -0
  23. package/dest/instrumentation.d.ts.map +1 -0
  24. package/dest/instrumentation.js +100 -0
  25. package/dest/prover/bb_native_private_kernel_prover.d.ts +25 -0
  26. package/dest/prover/bb_native_private_kernel_prover.d.ts.map +1 -0
  27. package/dest/prover/bb_native_private_kernel_prover.js +69 -0
  28. package/dest/prover/bb_private_kernel_prover.d.ts +32 -0
  29. package/dest/prover/bb_private_kernel_prover.d.ts.map +1 -0
  30. package/dest/prover/bb_private_kernel_prover.js +109 -0
  31. package/dest/prover/bb_prover.d.ts +120 -0
  32. package/dest/prover/bb_prover.d.ts.map +1 -0
  33. package/dest/prover/bb_prover.js +423 -0
  34. package/dest/prover/client_ivc_proof_utils.d.ts +25 -0
  35. package/dest/prover/client_ivc_proof_utils.d.ts.map +1 -0
  36. package/dest/prover/client_ivc_proof_utils.js +43 -0
  37. package/dest/prover/index.d.ts +4 -0
  38. package/dest/prover/index.d.ts.map +1 -0
  39. package/dest/prover/index.js +3 -0
  40. package/dest/stats.d.ts +5 -0
  41. package/dest/stats.d.ts.map +1 -0
  42. package/dest/stats.js +62 -0
  43. package/dest/test/delay_values.d.ts +4 -0
  44. package/dest/test/delay_values.d.ts.map +1 -0
  45. package/dest/test/delay_values.js +29 -0
  46. package/dest/test/index.d.ts +3 -0
  47. package/dest/test/index.d.ts.map +1 -0
  48. package/dest/test/index.js +2 -0
  49. package/dest/test/test_circuit_prover.d.ts +81 -0
  50. package/dest/test/test_circuit_prover.d.ts.map +1 -0
  51. package/dest/test/test_circuit_prover.js +175 -0
  52. package/dest/test/test_verifier.d.ts +6 -0
  53. package/dest/test/test_verifier.d.ts.map +1 -0
  54. package/dest/test/test_verifier.js +5 -0
  55. package/dest/verification_key/verification_key_data.d.ts +9 -0
  56. package/dest/verification_key/verification_key_data.d.ts.map +1 -0
  57. package/dest/verification_key/verification_key_data.js +44 -0
  58. package/dest/verifier/bb_verifier.d.ts +17 -0
  59. package/dest/verifier/bb_verifier.d.ts.map +1 -0
  60. package/dest/verifier/bb_verifier.js +86 -0
  61. package/dest/verifier/index.d.ts +2 -0
  62. package/dest/verifier/index.d.ts.map +1 -0
  63. package/dest/verifier/index.js +1 -0
  64. package/dest/wasm/bb_wasm_private_kernel_prover.d.ts +17 -0
  65. package/dest/wasm/bb_wasm_private_kernel_prover.d.ts.map +1 -0
  66. package/dest/wasm/bb_wasm_private_kernel_prover.js +46 -0
  67. package/dest/wasm/bundle.d.ts +6 -0
  68. package/dest/wasm/bundle.d.ts.map +1 -0
  69. package/dest/wasm/bundle.js +8 -0
  70. package/dest/wasm/lazy.d.ts +6 -0
  71. package/dest/wasm/lazy.d.ts.map +1 -0
  72. package/dest/wasm/lazy.js +8 -0
  73. package/package.json +111 -0
  74. package/src/avm_proving_tests/avm_proving_tester.ts +170 -0
  75. package/src/bb/cli.ts +32 -0
  76. package/src/bb/execute.ts +853 -0
  77. package/src/bb/index.ts +23 -0
  78. package/src/config.ts +13 -0
  79. package/src/honk.ts +30 -0
  80. package/src/index.ts +8 -0
  81. package/src/instrumentation.ts +144 -0
  82. package/src/prover/bb_native_private_kernel_prover.ts +119 -0
  83. package/src/prover/bb_private_kernel_prover.ts +249 -0
  84. package/src/prover/bb_prover.ts +781 -0
  85. package/src/prover/client_ivc_proof_utils.ts +42 -0
  86. package/src/prover/index.ts +3 -0
  87. package/src/stats.ts +64 -0
  88. package/src/test/delay_values.ts +31 -0
  89. package/src/test/index.ts +2 -0
  90. package/src/test/test_circuit_prover.ts +368 -0
  91. package/src/test/test_verifier.ts +8 -0
  92. package/src/verification_key/verification_key_data.ts +45 -0
  93. package/src/verifier/bb_verifier.ts +114 -0
  94. package/src/verifier/index.ts +1 -0
  95. package/src/wasm/bb_wasm_private_kernel_prover.ts +55 -0
  96. package/src/wasm/bundle.ts +11 -0
  97. package/src/wasm/lazy.ts +11 -0
@@ -0,0 +1,781 @@
1
+ /* eslint-disable require-await */
2
+ import {
3
+ AGGREGATION_OBJECT_LENGTH,
4
+ AVM_PROOF_LENGTH_IN_FIELDS,
5
+ IPA_CLAIM_LENGTH,
6
+ NESTED_RECURSIVE_PROOF_LENGTH,
7
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
8
+ RECURSIVE_PROOF_LENGTH,
9
+ TUBE_PROOF_LENGTH,
10
+ } from '@aztec/constants';
11
+ import { Fr } from '@aztec/foundation/fields';
12
+ import { runInDirectory } from '@aztec/foundation/fs';
13
+ import { createLogger } from '@aztec/foundation/log';
14
+ import { BufferReader } from '@aztec/foundation/serialize';
15
+ import { Timer } from '@aztec/foundation/timer';
16
+ import {
17
+ ServerCircuitArtifacts,
18
+ type ServerProtocolArtifact,
19
+ convertBaseParityInputsToWitnessMap,
20
+ convertBaseParityOutputsFromWitnessMap,
21
+ convertBlockMergeRollupInputsToWitnessMap,
22
+ convertBlockMergeRollupOutputsFromWitnessMap,
23
+ convertBlockRootRollupInputsToWitnessMap,
24
+ convertBlockRootRollupOutputsFromWitnessMap,
25
+ convertEmptyBlockRootRollupInputsToWitnessMap,
26
+ convertEmptyBlockRootRollupOutputsFromWitnessMap,
27
+ convertMergeRollupInputsToWitnessMap,
28
+ convertMergeRollupOutputsFromWitnessMap,
29
+ convertPrivateBaseRollupInputsToWitnessMap,
30
+ convertPrivateBaseRollupOutputsFromWitnessMap,
31
+ convertPublicBaseRollupInputsToWitnessMap,
32
+ convertPublicBaseRollupOutputsFromWitnessMap,
33
+ convertRootParityInputsToWitnessMap,
34
+ convertRootParityOutputsFromWitnessMap,
35
+ convertRootRollupInputsToWitnessMap,
36
+ convertRootRollupOutputsFromWitnessMap,
37
+ convertSingleTxBlockRootRollupInputsToWitnessMap,
38
+ convertSingleTxBlockRootRollupOutputsFromWitnessMap,
39
+ } from '@aztec/noir-protocol-circuits-types/server';
40
+ import { ServerCircuitVks } from '@aztec/noir-protocol-circuits-types/server/vks';
41
+ import { NativeACVMSimulator } from '@aztec/simulator/server';
42
+ import type { AvmCircuitInputs } from '@aztec/stdlib/avm';
43
+ import { ProvingError } from '@aztec/stdlib/errors';
44
+ import {
45
+ type ProofAndVerificationKey,
46
+ type PublicInputsAndRecursiveProof,
47
+ type ServerCircuitProver,
48
+ makeProofAndVerificationKey,
49
+ makePublicInputsAndRecursiveProof,
50
+ } from '@aztec/stdlib/interfaces/server';
51
+ import type { BaseParityInputs, ParityPublicInputs, RootParityInputs } from '@aztec/stdlib/parity';
52
+ import { Proof, RecursiveProof, makeRecursiveProofFromBinary } from '@aztec/stdlib/proofs';
53
+ import type {
54
+ BaseOrMergeRollupPublicInputs,
55
+ BlockMergeRollupInputs,
56
+ BlockRootOrBlockMergePublicInputs,
57
+ BlockRootRollupInputs,
58
+ EmptyBlockRootRollupInputs,
59
+ MergeRollupInputs,
60
+ PrivateBaseRollupInputs,
61
+ PublicBaseRollupInputs,
62
+ RootRollupInputs,
63
+ RootRollupPublicInputs,
64
+ SingleTxBlockRootRollupInputs,
65
+ TubeInputs,
66
+ } from '@aztec/stdlib/rollup';
67
+ import type { CircuitProvingStats, CircuitWitnessGenerationStats } from '@aztec/stdlib/stats';
68
+ import type { VerificationKeyData } from '@aztec/stdlib/vks';
69
+ import { Attributes, type TelemetryClient, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
70
+
71
+ import type { WitnessMap } from '@noir-lang/types';
72
+ import { assert } from 'console';
73
+ import crypto from 'crypto';
74
+ import { promises as fs } from 'fs';
75
+ import * as path from 'path';
76
+
77
+ import {
78
+ type BBFailure,
79
+ type BBSuccess,
80
+ BB_RESULT,
81
+ PROOF_FIELDS_FILENAME,
82
+ PROOF_FILENAME,
83
+ VK_FILENAME,
84
+ generateAvmProof,
85
+ generateProof,
86
+ generateTubeProof,
87
+ verifyAvmProof,
88
+ verifyProof,
89
+ } from '../bb/execute.js';
90
+ import type { ACVMConfig, BBConfig } from '../config.js';
91
+ import { type UltraHonkFlavor, getUltraHonkFlavorForCircuit } from '../honk.js';
92
+ import { ProverInstrumentation } from '../instrumentation.js';
93
+ import { mapProtocolArtifactNameToCircuitName } from '../stats.js';
94
+ import { extractAvmVkData, extractVkData } from '../verification_key/verification_key_data.js';
95
+ import { writeToOutputDirectory } from './client_ivc_proof_utils.js';
96
+
97
+ const logger = createLogger('bb-prover');
98
+
99
+ // All `ServerCircuitArtifact` are recursive.
100
+ const SERVER_CIRCUIT_RECURSIVE = true;
101
+
102
+ export interface BBProverConfig extends BBConfig, ACVMConfig {
103
+ // list of circuits supported by this prover. defaults to all circuits if empty
104
+ circuitFilter?: ServerProtocolArtifact[];
105
+ }
106
+
107
+ /**
108
+ * Prover implementation that uses barretenberg native proving
109
+ */
110
+ export class BBNativeRollupProver implements ServerCircuitProver {
111
+ private instrumentation: ProverInstrumentation;
112
+
113
+ constructor(private config: BBProverConfig, telemetry: TelemetryClient) {
114
+ this.instrumentation = new ProverInstrumentation(telemetry, 'BBNativeRollupProver');
115
+ }
116
+
117
+ get tracer() {
118
+ return this.instrumentation.tracer;
119
+ }
120
+
121
+ static async new(config: BBProverConfig, telemetry: TelemetryClient = getTelemetryClient()) {
122
+ await fs.access(config.acvmBinaryPath, fs.constants.R_OK);
123
+ await fs.mkdir(config.acvmWorkingDirectory, { recursive: true });
124
+ await fs.access(config.bbBinaryPath, fs.constants.R_OK);
125
+ await fs.mkdir(config.bbWorkingDirectory, { recursive: true });
126
+ logger.info(`Using native BB at ${config.bbBinaryPath} and working directory ${config.bbWorkingDirectory}`);
127
+ logger.info(`Using native ACVM at ${config.acvmBinaryPath} and working directory ${config.acvmWorkingDirectory}`);
128
+
129
+ return new BBNativeRollupProver(config, telemetry);
130
+ }
131
+
132
+ /**
133
+ * Simulates the base parity circuit from its inputs.
134
+ * @param inputs - Inputs to the circuit.
135
+ * @returns The public inputs of the parity circuit.
136
+ */
137
+ @trackSpan('BBNativeRollupProver.getBaseParityProof', { [Attributes.PROTOCOL_CIRCUIT_NAME]: 'base-parity' })
138
+ public async getBaseParityProof(
139
+ inputs: BaseParityInputs,
140
+ ): Promise<PublicInputsAndRecursiveProof<ParityPublicInputs, typeof RECURSIVE_PROOF_LENGTH>> {
141
+ const { circuitOutput, proof } = await this.createRecursiveProof(
142
+ inputs,
143
+ 'BaseParityArtifact',
144
+ RECURSIVE_PROOF_LENGTH,
145
+ convertBaseParityInputsToWitnessMap,
146
+ convertBaseParityOutputsFromWitnessMap,
147
+ );
148
+
149
+ const verificationKey = this.getVerificationKeyDataForCircuit('BaseParityArtifact');
150
+ await this.verifyProof('BaseParityArtifact', proof.binaryProof);
151
+
152
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
153
+ }
154
+
155
+ /**
156
+ * Simulates the root parity circuit from its inputs.
157
+ * @param inputs - Inputs to the circuit.
158
+ * @returns The public inputs of the parity circuit.
159
+ */
160
+ @trackSpan('BBNativeRollupProver.getRootParityProof', { [Attributes.PROTOCOL_CIRCUIT_NAME]: 'root-parity' })
161
+ public async getRootParityProof(
162
+ inputs: RootParityInputs,
163
+ ): Promise<PublicInputsAndRecursiveProof<ParityPublicInputs, typeof NESTED_RECURSIVE_PROOF_LENGTH>> {
164
+ const { circuitOutput, proof } = await this.createRecursiveProof(
165
+ inputs,
166
+ 'RootParityArtifact',
167
+ NESTED_RECURSIVE_PROOF_LENGTH,
168
+ convertRootParityInputsToWitnessMap,
169
+ convertRootParityOutputsFromWitnessMap,
170
+ );
171
+
172
+ const verificationKey = this.getVerificationKeyDataForCircuit('RootParityArtifact');
173
+ await this.verifyProof('RootParityArtifact', proof.binaryProof);
174
+
175
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
176
+ }
177
+
178
+ /**
179
+ * Creates an AVM proof and verifies it.
180
+ * @param inputs - The inputs to the AVM circuit.
181
+ * @returns The proof.
182
+ */
183
+ @trackSpan('BBNativeRollupProver.getAvmProof', inputs => ({
184
+ [Attributes.APP_CIRCUIT_NAME]: inputs.functionName,
185
+ }))
186
+ public async getAvmProof(
187
+ inputs: AvmCircuitInputs,
188
+ ): Promise<ProofAndVerificationKey<typeof AVM_PROOF_LENGTH_IN_FIELDS>> {
189
+ const proofAndVk = await this.createAvmProof(inputs);
190
+ await this.verifyAvmProof(proofAndVk.proof.binaryProof, proofAndVk.verificationKey);
191
+ return proofAndVk;
192
+ }
193
+
194
+ /**
195
+ * Simulates the base rollup circuit from its inputs.
196
+ * @param inputs - Inputs to the circuit.
197
+ * @returns The public inputs as outputs of the simulation.
198
+ */
199
+ public async getPrivateBaseRollupProof(
200
+ inputs: PrivateBaseRollupInputs,
201
+ ): Promise<
202
+ PublicInputsAndRecursiveProof<BaseOrMergeRollupPublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
203
+ > {
204
+ const artifactName = 'PrivateBaseRollupArtifact';
205
+
206
+ const { circuitOutput, proof } = await this.createRecursiveProof(
207
+ inputs,
208
+ artifactName,
209
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
210
+ convertPrivateBaseRollupInputsToWitnessMap,
211
+ convertPrivateBaseRollupOutputsFromWitnessMap,
212
+ );
213
+
214
+ const verificationKey = this.getVerificationKeyDataForCircuit(artifactName);
215
+
216
+ await this.verifyProof(artifactName, proof.binaryProof);
217
+
218
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
219
+ }
220
+
221
+ /**
222
+ * Requests that the public kernel tail circuit be executed and the proof generated
223
+ * @param kernelRequest - The object encapsulating the request for a proof
224
+ * @returns The requested circuit's public inputs and proof
225
+ */
226
+ public async getPublicBaseRollupProof(
227
+ inputs: PublicBaseRollupInputs,
228
+ ): Promise<
229
+ PublicInputsAndRecursiveProof<BaseOrMergeRollupPublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
230
+ > {
231
+ const artifactName = 'PublicBaseRollupArtifact';
232
+
233
+ const { circuitOutput, proof } = await this.createRecursiveProof(
234
+ inputs,
235
+ artifactName,
236
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
237
+ convertPublicBaseRollupInputsToWitnessMap,
238
+ convertPublicBaseRollupOutputsFromWitnessMap,
239
+ );
240
+
241
+ const verificationKey = this.getVerificationKeyDataForCircuit(artifactName);
242
+
243
+ await this.verifyProof(artifactName, proof.binaryProof);
244
+
245
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
246
+ }
247
+
248
+ /**
249
+ * Simulates the merge rollup circuit from its inputs.
250
+ * @param input - Inputs to the circuit.
251
+ * @returns The public inputs as outputs of the simulation.
252
+ */
253
+ public async getMergeRollupProof(
254
+ input: MergeRollupInputs,
255
+ ): Promise<
256
+ PublicInputsAndRecursiveProof<BaseOrMergeRollupPublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
257
+ > {
258
+ const { circuitOutput, proof } = await this.createRecursiveProof(
259
+ input,
260
+ 'MergeRollupArtifact',
261
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
262
+ convertMergeRollupInputsToWitnessMap,
263
+ convertMergeRollupOutputsFromWitnessMap,
264
+ );
265
+
266
+ const verificationKey = this.getVerificationKeyDataForCircuit('MergeRollupArtifact');
267
+
268
+ await this.verifyProof('MergeRollupArtifact', proof.binaryProof);
269
+
270
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
271
+ }
272
+
273
+ /**
274
+ * Simulates the block root rollup circuit from its inputs.
275
+ * @param input - Inputs to the circuit.
276
+ * @returns The public inputs as outputs of the simulation.
277
+ */
278
+ public async getBlockRootRollupProof(
279
+ input: BlockRootRollupInputs,
280
+ ): Promise<
281
+ PublicInputsAndRecursiveProof<BlockRootOrBlockMergePublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
282
+ > {
283
+ const { circuitOutput, proof } = await this.createRecursiveProof(
284
+ input,
285
+ 'BlockRootRollupArtifact',
286
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
287
+ convertBlockRootRollupInputsToWitnessMap,
288
+ convertBlockRootRollupOutputsFromWitnessMap,
289
+ );
290
+
291
+ const verificationKey = this.getVerificationKeyDataForCircuit('BlockRootRollupArtifact');
292
+
293
+ await this.verifyProof('BlockRootRollupArtifact', proof.binaryProof);
294
+
295
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
296
+ }
297
+
298
+ public async getSingleTxBlockRootRollupProof(
299
+ input: SingleTxBlockRootRollupInputs,
300
+ ): Promise<
301
+ PublicInputsAndRecursiveProof<BlockRootOrBlockMergePublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
302
+ > {
303
+ const { circuitOutput, proof } = await this.createRecursiveProof(
304
+ input,
305
+ 'SingleTxBlockRootRollupArtifact',
306
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
307
+ convertSingleTxBlockRootRollupInputsToWitnessMap,
308
+ convertSingleTxBlockRootRollupOutputsFromWitnessMap,
309
+ );
310
+
311
+ const verificationKey = this.getVerificationKeyDataForCircuit('SingleTxBlockRootRollupArtifact');
312
+
313
+ await this.verifyProof('SingleTxBlockRootRollupArtifact', proof.binaryProof);
314
+
315
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
316
+ }
317
+
318
+ /**
319
+ * Simulates the empty block root rollup circuit from its inputs.
320
+ * @param input - Inputs to the circuit.
321
+ * @returns The public inputs as outputs of the simulation.
322
+ */
323
+ public async getEmptyBlockRootRollupProof(
324
+ input: EmptyBlockRootRollupInputs,
325
+ ): Promise<
326
+ PublicInputsAndRecursiveProof<BlockRootOrBlockMergePublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
327
+ > {
328
+ const { circuitOutput, proof } = await this.createRecursiveProof(
329
+ input,
330
+ 'EmptyBlockRootRollupArtifact',
331
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
332
+ convertEmptyBlockRootRollupInputsToWitnessMap,
333
+ convertEmptyBlockRootRollupOutputsFromWitnessMap,
334
+ );
335
+
336
+ const verificationKey = this.getVerificationKeyDataForCircuit('EmptyBlockRootRollupArtifact');
337
+
338
+ await this.verifyProof('EmptyBlockRootRollupArtifact', proof.binaryProof);
339
+
340
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
341
+ }
342
+
343
+ /**
344
+ * Simulates the block merge rollup circuit from its inputs.
345
+ * @param input - Inputs to the circuit.
346
+ * @returns The public inputs as outputs of the simulation.
347
+ */
348
+ public async getBlockMergeRollupProof(
349
+ input: BlockMergeRollupInputs,
350
+ ): Promise<
351
+ PublicInputsAndRecursiveProof<BlockRootOrBlockMergePublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
352
+ > {
353
+ const { circuitOutput, proof } = await this.createRecursiveProof(
354
+ input,
355
+ 'BlockMergeRollupArtifact',
356
+ NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
357
+ convertBlockMergeRollupInputsToWitnessMap,
358
+ convertBlockMergeRollupOutputsFromWitnessMap,
359
+ );
360
+
361
+ const verificationKey = this.getVerificationKeyDataForCircuit('BlockMergeRollupArtifact');
362
+
363
+ await this.verifyProof('BlockMergeRollupArtifact', proof.binaryProof);
364
+
365
+ return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
366
+ }
367
+
368
+ /**
369
+ * Simulates the root rollup circuit from its inputs.
370
+ * @param input - Inputs to the circuit.
371
+ * @returns The public inputs as outputs of the simulation.
372
+ */
373
+ public async getRootRollupProof(
374
+ input: RootRollupInputs,
375
+ ): Promise<PublicInputsAndRecursiveProof<RootRollupPublicInputs>> {
376
+ const { circuitOutput, proof } = await this.createProof(
377
+ input,
378
+ 'RootRollupArtifact',
379
+ convertRootRollupInputsToWitnessMap,
380
+ convertRootRollupOutputsFromWitnessMap,
381
+ );
382
+
383
+ const recursiveProof = makeRecursiveProofFromBinary(proof, NESTED_RECURSIVE_PROOF_LENGTH);
384
+
385
+ const verificationKey = this.getVerificationKeyDataForCircuit('RootRollupArtifact');
386
+
387
+ await this.verifyProof('RootRollupArtifact', proof);
388
+
389
+ return makePublicInputsAndRecursiveProof(circuitOutput, recursiveProof, verificationKey);
390
+ }
391
+
392
+ private async generateProofWithBB<
393
+ Input extends { toBuffer: () => Buffer },
394
+ Output extends { toBuffer: () => Buffer },
395
+ >(
396
+ input: Input,
397
+ circuitType: ServerProtocolArtifact,
398
+ convertInput: (input: Input) => WitnessMap,
399
+ convertOutput: (outputWitness: WitnessMap) => Output,
400
+ workingDirectory: string,
401
+ ): Promise<{ circuitOutput: Output; provingResult: BBSuccess }> {
402
+ // Have the ACVM write the partial witness here
403
+ const outputWitnessFile = path.join(workingDirectory, 'partial-witness.gz');
404
+
405
+ // Generate the partial witness using the ACVM
406
+ // A further temp directory will be created beneath ours and then cleaned up after the partial witness has been copied to our specified location
407
+ const simulator = new NativeACVMSimulator(
408
+ this.config.acvmWorkingDirectory,
409
+ this.config.acvmBinaryPath,
410
+ outputWitnessFile,
411
+ );
412
+
413
+ const artifact = ServerCircuitArtifacts[circuitType];
414
+
415
+ logger.debug(`Generating witness data for ${circuitType}`);
416
+
417
+ const inputWitness = convertInput(input);
418
+ const timer = new Timer();
419
+ const outputWitness = await simulator.executeProtocolCircuit(inputWitness, artifact);
420
+ const output = convertOutput(outputWitness);
421
+
422
+ const circuitName = mapProtocolArtifactNameToCircuitName(circuitType);
423
+ this.instrumentation.recordDuration('witGenDuration', circuitName, timer);
424
+ this.instrumentation.recordSize('witGenInputSize', circuitName, input.toBuffer().length);
425
+ this.instrumentation.recordSize('witGenOutputSize', circuitName, output.toBuffer().length);
426
+
427
+ logger.info(`Generated witness`, {
428
+ circuitName,
429
+ duration: timer.ms(),
430
+ inputSize: input.toBuffer().length,
431
+ outputSize: output.toBuffer().length,
432
+ eventName: 'circuit-witness-generation',
433
+ } satisfies CircuitWitnessGenerationStats);
434
+
435
+ // Now prove the circuit from the generated witness
436
+ logger.debug(`Proving ${circuitType}...`);
437
+
438
+ const provingResult = await generateProof(
439
+ this.config.bbBinaryPath,
440
+ workingDirectory,
441
+ circuitType,
442
+ Buffer.from(artifact.bytecode, 'base64'),
443
+ SERVER_CIRCUIT_RECURSIVE,
444
+ outputWitnessFile,
445
+ getUltraHonkFlavorForCircuit(circuitType),
446
+ logger.debug,
447
+ );
448
+
449
+ if (provingResult.status === BB_RESULT.FAILURE) {
450
+ logger.error(`Failed to generate proof for ${circuitType}: ${provingResult.reason}`);
451
+ throw new ProvingError(provingResult.reason, provingResult, provingResult.retry);
452
+ }
453
+
454
+ return {
455
+ circuitOutput: output,
456
+ provingResult,
457
+ };
458
+ }
459
+
460
+ private async createProof<Input extends { toBuffer: () => Buffer }, Output extends { toBuffer: () => Buffer }>(
461
+ input: Input,
462
+ circuitType: ServerProtocolArtifact,
463
+ convertInput: (input: Input) => WitnessMap,
464
+ convertOutput: (outputWitness: WitnessMap) => Output,
465
+ ): Promise<{ circuitOutput: Output; proof: Proof }> {
466
+ const operation = async (bbWorkingDirectory: string) => {
467
+ const { provingResult, circuitOutput: output } = await this.generateProofWithBB(
468
+ input,
469
+ circuitType,
470
+ convertInput,
471
+ convertOutput,
472
+ bbWorkingDirectory,
473
+ );
474
+
475
+ // Read the binary proof
476
+ const rawProof = await fs.readFile(`${provingResult.proofPath!}/${PROOF_FILENAME}`);
477
+ const vkData = this.getVerificationKeyDataForCircuit(circuitType);
478
+ const proof = new Proof(rawProof, vkData.numPublicInputs);
479
+ const circuitName = mapProtocolArtifactNameToCircuitName(circuitType);
480
+
481
+ this.instrumentation.recordDuration('provingDuration', circuitName, provingResult.durationMs);
482
+ this.instrumentation.recordSize('proofSize', circuitName, proof.buffer.length);
483
+ this.instrumentation.recordSize('circuitPublicInputCount', circuitName, vkData.numPublicInputs);
484
+ this.instrumentation.recordSize('circuitSize', circuitName, vkData.circuitSize);
485
+
486
+ logger.info(`Generated proof for ${circuitType} in ${Math.ceil(provingResult.durationMs)} ms`, {
487
+ circuitName,
488
+ // does not include reading the proof from disk
489
+ duration: provingResult.durationMs,
490
+ proofSize: proof.buffer.length,
491
+ eventName: 'circuit-proving',
492
+ // circuitOutput is the partial witness that became the input to the proof
493
+ inputSize: output.toBuffer().length,
494
+ circuitSize: vkData.circuitSize,
495
+ numPublicInputs: vkData.numPublicInputs,
496
+ } satisfies CircuitProvingStats);
497
+
498
+ return { circuitOutput: output, proof };
499
+ };
500
+ return await this.runInDirectory(operation);
501
+ }
502
+
503
+ private async generateAvmProofWithBB(input: AvmCircuitInputs, workingDirectory: string): Promise<BBSuccess> {
504
+ logger.info(`Proving avm-circuit for ${input.functionName}...`);
505
+
506
+ const provingResult = await generateAvmProof(this.config.bbBinaryPath, workingDirectory, input, logger);
507
+
508
+ if (provingResult.status === BB_RESULT.FAILURE) {
509
+ logger.error(`Failed to generate AVM proof for ${input.functionName}: ${provingResult.reason}`);
510
+ throw new ProvingError(provingResult.reason, provingResult, provingResult.retry);
511
+ }
512
+
513
+ return provingResult;
514
+ }
515
+
516
+ private async generateTubeProofWithBB(bbWorkingDirectory: string, input: TubeInputs): Promise<BBSuccess> {
517
+ logger.debug(`Proving tube...`);
518
+
519
+ const hasher = crypto.createHash('sha256');
520
+ hasher.update(input.toBuffer());
521
+
522
+ await writeToOutputDirectory(input.clientIVCData, bbWorkingDirectory);
523
+ const provingResult = await generateTubeProof(this.config.bbBinaryPath, bbWorkingDirectory, logger.verbose);
524
+
525
+ if (provingResult.status === BB_RESULT.FAILURE) {
526
+ logger.error(`Failed to generate proof for tube circuit: ${provingResult.reason}`);
527
+ throw new ProvingError(provingResult.reason, provingResult, provingResult.retry);
528
+ }
529
+ return provingResult;
530
+ }
531
+
532
+ private async createAvmProof(
533
+ input: AvmCircuitInputs,
534
+ ): Promise<ProofAndVerificationKey<typeof AVM_PROOF_LENGTH_IN_FIELDS>> {
535
+ const operation = async (bbWorkingDirectory: string) => {
536
+ const provingResult = await this.generateAvmProofWithBB(input, bbWorkingDirectory);
537
+
538
+ // TODO(https://github.com/AztecProtocol/aztec-packages/issues/6773): this VK data format is wrong.
539
+ // In particular, the number of public inputs, etc will be wrong.
540
+ const verificationKey = await extractAvmVkData(provingResult.vkPath!);
541
+ const avmProof = await this.readAvmProofAsFields(provingResult.proofPath!, verificationKey);
542
+
543
+ const circuitType = 'avm-circuit' as const;
544
+ const appCircuitName = 'unknown' as const;
545
+ this.instrumentation.recordAvmDuration('provingDuration', appCircuitName, provingResult.durationMs);
546
+ this.instrumentation.recordAvmSize('proofSize', appCircuitName, avmProof.binaryProof.buffer.length);
547
+ this.instrumentation.recordAvmSize('circuitPublicInputCount', appCircuitName, verificationKey.numPublicInputs);
548
+ this.instrumentation.recordAvmSize('circuitSize', appCircuitName, verificationKey.circuitSize);
549
+
550
+ logger.info(
551
+ `Generated proof for ${circuitType}(${input.functionName}) in ${Math.ceil(provingResult.durationMs)} ms`,
552
+ {
553
+ circuitName: circuitType,
554
+ appCircuitName: input.functionName,
555
+ // does not include reading the proof from disk
556
+ duration: provingResult.durationMs,
557
+ proofSize: avmProof.binaryProof.buffer.length,
558
+ eventName: 'circuit-proving',
559
+ inputSize: input.serializeWithMessagePack().length,
560
+ circuitSize: verificationKey.circuitSize, // FIX: wrong in VK
561
+ numPublicInputs: verificationKey.numPublicInputs, // FIX: wrong in VK
562
+ } satisfies CircuitProvingStats,
563
+ );
564
+
565
+ return makeProofAndVerificationKey(avmProof, verificationKey);
566
+ };
567
+ return await this.runInDirectory(operation);
568
+ }
569
+
570
+ public async getTubeProof(input: TubeInputs): Promise<ProofAndVerificationKey<typeof TUBE_PROOF_LENGTH>> {
571
+ const operation = async (bbWorkingDirectory: string) => {
572
+ logger.debug(`createTubeProof: ${bbWorkingDirectory}`);
573
+ const provingResult = await this.generateTubeProofWithBB(bbWorkingDirectory, input);
574
+
575
+ // Read the proof as fields
576
+ // TODO(AD): this is the only remaining use of extractVkData.
577
+ const tubeVK = await extractVkData(provingResult.vkPath!);
578
+ const tubeProof = await this.readProofAsFields(provingResult.proofPath!, tubeVK, TUBE_PROOF_LENGTH);
579
+
580
+ this.instrumentation.recordDuration('provingDuration', 'tubeCircuit', provingResult.durationMs);
581
+ this.instrumentation.recordSize('proofSize', 'tubeCircuit', tubeProof.binaryProof.buffer.length);
582
+ this.instrumentation.recordSize('circuitPublicInputCount', 'tubeCircuit', tubeVK.numPublicInputs);
583
+ this.instrumentation.recordSize('circuitSize', 'tubeCircuit', tubeVK.circuitSize);
584
+
585
+ // Sanity check the tube proof (can be removed later)
586
+ await this.verifyWithKey('ultra_rollup_honk', tubeVK, tubeProof.binaryProof);
587
+
588
+ logger.info(
589
+ `Generated proof for tubeCircuit in ${Math.ceil(provingResult.durationMs)} ms, size: ${
590
+ tubeProof.proof.length
591
+ } fields`,
592
+ );
593
+
594
+ return makeProofAndVerificationKey(tubeProof, tubeVK);
595
+ };
596
+ return await this.runInDirectory(operation);
597
+ }
598
+
599
+ /**
600
+ * Executes a circuit and returns its outputs and corresponding proof with embedded aggregation object
601
+ * @param witnessMap - The input witness
602
+ * @param circuitType - The type of circuit to be executed
603
+ * @param proofLength - The length of the proof to be generated. This is a dummy parameter to aid in type checking
604
+ * @param convertInput - Function for mapping the input object to a witness map.
605
+ * @param convertOutput - Function for parsing the output witness to it's corresponding object
606
+ * @returns The circuits output object and it's proof
607
+ */
608
+ private async createRecursiveProof<
609
+ PROOF_LENGTH extends number,
610
+ CircuitInputType extends { toBuffer: () => Buffer },
611
+ CircuitOutputType extends { toBuffer: () => Buffer },
612
+ >(
613
+ input: CircuitInputType,
614
+ circuitType: ServerProtocolArtifact,
615
+ proofLength: PROOF_LENGTH,
616
+ convertInput: (input: CircuitInputType) => WitnessMap,
617
+ convertOutput: (outputWitness: WitnessMap) => CircuitOutputType,
618
+ ): Promise<{ circuitOutput: CircuitOutputType; proof: RecursiveProof<PROOF_LENGTH> }> {
619
+ // this probably is gonna need to call client ivc
620
+ const operation = async (bbWorkingDirectory: string) => {
621
+ const { provingResult, circuitOutput: output } = await this.generateProofWithBB(
622
+ input,
623
+ circuitType,
624
+ convertInput,
625
+ convertOutput,
626
+ bbWorkingDirectory,
627
+ );
628
+
629
+ const vkData = this.getVerificationKeyDataForCircuit(circuitType);
630
+ // Read the proof as fields
631
+ const proof = await this.readProofAsFields(provingResult.proofPath!, vkData, proofLength);
632
+
633
+ const circuitName = mapProtocolArtifactNameToCircuitName(circuitType);
634
+ this.instrumentation.recordDuration('provingDuration', circuitName, provingResult.durationMs);
635
+ this.instrumentation.recordSize('proofSize', circuitName, proof.binaryProof.buffer.length);
636
+ this.instrumentation.recordSize('circuitPublicInputCount', circuitName, vkData.numPublicInputs);
637
+ this.instrumentation.recordSize('circuitSize', circuitName, vkData.circuitSize);
638
+ logger.info(
639
+ `Generated proof for ${circuitType} in ${Math.ceil(provingResult.durationMs)} ms, size: ${
640
+ proof.proof.length
641
+ } fields`,
642
+ {
643
+ circuitName,
644
+ circuitSize: vkData.circuitSize,
645
+ duration: provingResult.durationMs,
646
+ inputSize: output.toBuffer().length,
647
+ proofSize: proof.binaryProof.buffer.length,
648
+ eventName: 'circuit-proving',
649
+ numPublicInputs: vkData.numPublicInputs,
650
+ } satisfies CircuitProvingStats,
651
+ );
652
+
653
+ return {
654
+ circuitOutput: output,
655
+ proof,
656
+ };
657
+ };
658
+ return await this.runInDirectory(operation);
659
+ }
660
+
661
+ /**
662
+ * Verifies a proof, will generate the verification key if one is not cached internally
663
+ * @param circuitType - The type of circuit whose proof is to be verified
664
+ * @param proof - The proof to be verified
665
+ */
666
+ public async verifyProof(circuitType: ServerProtocolArtifact, proof: Proof) {
667
+ const verificationKey = this.getVerificationKeyDataForCircuit(circuitType);
668
+ return await this.verifyWithKey(getUltraHonkFlavorForCircuit(circuitType), verificationKey, proof);
669
+ }
670
+
671
+ public async verifyAvmProof(proof: Proof, verificationKey: VerificationKeyData) {
672
+ return await this.verifyWithKeyInternal(proof, verificationKey, (proofPath, vkPath) =>
673
+ verifyAvmProof(this.config.bbBinaryPath, proofPath, vkPath, logger),
674
+ );
675
+ }
676
+
677
+ public async verifyWithKey(flavor: UltraHonkFlavor, verificationKey: VerificationKeyData, proof: Proof) {
678
+ return await this.verifyWithKeyInternal(proof, verificationKey, (proofPath, vkPath) =>
679
+ verifyProof(this.config.bbBinaryPath, proofPath, vkPath, flavor, logger),
680
+ );
681
+ }
682
+
683
+ private async verifyWithKeyInternal(
684
+ proof: Proof,
685
+ verificationKey: { keyAsBytes: Buffer },
686
+ verificationFunction: (proofPath: string, vkPath: string) => Promise<BBFailure | BBSuccess>,
687
+ ) {
688
+ const operation = async (bbWorkingDirectory: string) => {
689
+ const proofFileName = path.join(bbWorkingDirectory, PROOF_FILENAME);
690
+ const verificationKeyPath = path.join(bbWorkingDirectory, VK_FILENAME);
691
+
692
+ await fs.writeFile(proofFileName, proof.buffer);
693
+ await fs.writeFile(verificationKeyPath, verificationKey.keyAsBytes);
694
+
695
+ const result = await verificationFunction(proofFileName, verificationKeyPath!);
696
+
697
+ if (result.status === BB_RESULT.FAILURE) {
698
+ const errorMessage = `Failed to verify proof from key!`;
699
+ throw new ProvingError(errorMessage, result, result.retry);
700
+ }
701
+
702
+ logger.info(`Successfully verified proof from key in ${result.durationMs} ms`);
703
+ };
704
+
705
+ await this.runInDirectory(operation);
706
+ }
707
+
708
+ /**
709
+ * Returns the verification key data for a circuit.
710
+ * @param circuitType - The type of circuit for which the verification key is required
711
+ * @returns The verification key data
712
+ */
713
+ private getVerificationKeyDataForCircuit(circuitType: ServerProtocolArtifact): VerificationKeyData {
714
+ const vk = ServerCircuitVks[circuitType];
715
+ if (vk === undefined) {
716
+ throw new Error('Could not find VK for server artifact ' + circuitType);
717
+ }
718
+ return vk;
719
+ }
720
+
721
+ private async readProofAsFields<PROOF_LENGTH extends number>(
722
+ filePath: string,
723
+ vkData: VerificationKeyData,
724
+ proofLength: PROOF_LENGTH,
725
+ ): Promise<RecursiveProof<PROOF_LENGTH>> {
726
+ const proofFilename = path.join(filePath, PROOF_FILENAME);
727
+ const proofFieldsFilename = path.join(filePath, PROOF_FIELDS_FILENAME);
728
+
729
+ const [binaryProof, proofString] = await Promise.all([
730
+ fs.readFile(proofFilename),
731
+ fs.readFile(proofFieldsFilename, { encoding: 'utf-8' }),
732
+ ]);
733
+
734
+ const json = JSON.parse(proofString);
735
+
736
+ let numPublicInputs = vkData.numPublicInputs - AGGREGATION_OBJECT_LENGTH;
737
+ if (proofLength == NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH) {
738
+ numPublicInputs -= IPA_CLAIM_LENGTH;
739
+ }
740
+
741
+ assert(json.length - numPublicInputs == proofLength, 'Proof length mismatch');
742
+
743
+ const fieldsWithoutPublicInputs = json
744
+ .slice(0, 3)
745
+ .map(Fr.fromHexString)
746
+ .concat(json.slice(3 + numPublicInputs).map(Fr.fromHexString));
747
+ logger.debug(
748
+ `Circuit path: ${filePath}, complete proof length: ${json.length}, num public inputs: ${numPublicInputs}, circuit size: ${vkData.circuitSize}, is recursive: ${vkData.isRecursive}, raw length: ${binaryProof.length}`,
749
+ );
750
+
751
+ return new RecursiveProof(fieldsWithoutPublicInputs, new Proof(binaryProof, numPublicInputs), true, proofLength);
752
+ }
753
+
754
+ private async readAvmProofAsFields(
755
+ proofFilename: string,
756
+ vkData: VerificationKeyData,
757
+ ): Promise<RecursiveProof<typeof AVM_PROOF_LENGTH_IN_FIELDS>> {
758
+ const rawProof = await fs.readFile(proofFilename);
759
+
760
+ const reader = BufferReader.asReader(rawProof);
761
+ const fields = reader.readArray(rawProof.length / Fr.SIZE_IN_BYTES, Fr);
762
+ const fieldsWithoutPublicCols = fields.slice(-1 * AVM_PROOF_LENGTH_IN_FIELDS);
763
+
764
+ const proof = new Proof(rawProof, vkData.numPublicInputs);
765
+
766
+ return new RecursiveProof(fieldsWithoutPublicCols, proof, true, AVM_PROOF_LENGTH_IN_FIELDS);
767
+ }
768
+
769
+ private runInDirectory<T>(fn: (dir: string) => Promise<T>) {
770
+ return runInDirectory(
771
+ this.config.bbWorkingDirectory,
772
+ (dir: string) =>
773
+ fn(dir).catch(err => {
774
+ logger.error(`Error running operation at ${dir}: ${err}`);
775
+ throw err;
776
+ }),
777
+ this.config.bbSkipCleanup,
778
+ logger,
779
+ );
780
+ }
781
+ }