@aztec/bb-prover 0.0.1-commit.03f7ef2 → 0.0.1-commit.04d373f

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 (84) hide show
  1. package/dest/avm_proving_tests/avm_proving_tester.d.ts +13 -8
  2. package/dest/avm_proving_tests/avm_proving_tester.d.ts.map +1 -1
  3. package/dest/avm_proving_tests/avm_proving_tester.js +152 -107
  4. package/dest/bb/bb_js_backend.d.ts +196 -0
  5. package/dest/bb/bb_js_backend.d.ts.map +1 -0
  6. package/dest/bb/bb_js_backend.js +379 -0
  7. package/dest/bb/bb_js_debug.d.ts +52 -0
  8. package/dest/bb/bb_js_debug.d.ts.map +1 -0
  9. package/dest/bb/bb_js_debug.js +176 -0
  10. package/dest/bb/file_names.d.ts +4 -0
  11. package/dest/bb/file_names.d.ts.map +1 -0
  12. package/dest/bb/file_names.js +5 -0
  13. package/dest/config.d.ts +17 -1
  14. package/dest/config.d.ts.map +1 -1
  15. package/dest/index.d.ts +3 -2
  16. package/dest/index.d.ts.map +1 -1
  17. package/dest/index.js +2 -1
  18. package/dest/instrumentation.d.ts +1 -1
  19. package/dest/instrumentation.d.ts.map +1 -1
  20. package/dest/instrumentation.js +21 -43
  21. package/dest/prover/client/bb_private_kernel_prover.d.ts +18 -4
  22. package/dest/prover/client/bb_private_kernel_prover.d.ts.map +1 -1
  23. package/dest/prover/client/bb_private_kernel_prover.js +54 -8
  24. package/dest/prover/client/bundle.d.ts +3 -3
  25. package/dest/prover/client/bundle.d.ts.map +1 -1
  26. package/dest/prover/client/bundle.js +2 -3
  27. package/dest/prover/client/lazy.d.ts +3 -3
  28. package/dest/prover/client/lazy.d.ts.map +1 -1
  29. package/dest/prover/client/lazy.js +2 -3
  30. package/dest/prover/proof_utils.d.ts +11 -1
  31. package/dest/prover/proof_utils.d.ts.map +1 -1
  32. package/dest/prover/proof_utils.js +24 -1
  33. package/dest/prover/server/bb_prover.d.ts +8 -12
  34. package/dest/prover/server/bb_prover.d.ts.map +1 -1
  35. package/dest/prover/server/bb_prover.js +612 -107
  36. package/dest/test/delay_values.d.ts +1 -1
  37. package/dest/test/delay_values.d.ts.map +1 -1
  38. package/dest/test/delay_values.js +27 -25
  39. package/dest/test/index.d.ts +2 -1
  40. package/dest/test/index.d.ts.map +1 -1
  41. package/dest/test/index.js +1 -0
  42. package/dest/test/test_circuit_prover.d.ts +4 -4
  43. package/dest/test/test_circuit_prover.d.ts.map +1 -1
  44. package/dest/test/test_circuit_prover.js +462 -59
  45. package/dest/verification_key/verification_key_data.d.ts +1 -8
  46. package/dest/verification_key/verification_key_data.d.ts.map +1 -1
  47. package/dest/verification_key/verification_key_data.js +1 -20
  48. package/dest/verifier/batch_chonk_verifier.d.ts +45 -0
  49. package/dest/verifier/batch_chonk_verifier.d.ts.map +1 -0
  50. package/dest/verifier/batch_chonk_verifier.js +232 -0
  51. package/dest/verifier/bb_verifier.d.ts +4 -1
  52. package/dest/verifier/bb_verifier.d.ts.map +1 -1
  53. package/dest/verifier/bb_verifier.js +134 -48
  54. package/dest/verifier/index.d.ts +2 -1
  55. package/dest/verifier/index.d.ts.map +1 -1
  56. package/dest/verifier/index.js +1 -0
  57. package/dest/verifier/queued_chonk_verifier.d.ts +2 -3
  58. package/dest/verifier/queued_chonk_verifier.d.ts.map +1 -1
  59. package/dest/verifier/queued_chonk_verifier.js +15 -45
  60. package/package.json +20 -18
  61. package/src/avm_proving_tests/avm_proving_tester.ts +53 -136
  62. package/src/bb/bb_js_backend.ts +435 -0
  63. package/src/bb/bb_js_debug.ts +227 -0
  64. package/src/bb/file_names.ts +6 -0
  65. package/src/config.ts +16 -0
  66. package/src/index.ts +2 -1
  67. package/src/instrumentation.ts +20 -43
  68. package/src/prover/client/bb_private_kernel_prover.ts +135 -9
  69. package/src/prover/client/bundle.ts +3 -4
  70. package/src/prover/client/lazy.ts +3 -4
  71. package/src/prover/proof_utils.ts +41 -1
  72. package/src/prover/server/bb_prover.ts +138 -153
  73. package/src/test/delay_values.ts +28 -24
  74. package/src/test/index.ts +1 -0
  75. package/src/test/test_circuit_prover.ts +10 -13
  76. package/src/verification_key/verification_key_data.ts +1 -26
  77. package/src/verifier/batch_chonk_verifier.ts +276 -0
  78. package/src/verifier/bb_verifier.ts +66 -80
  79. package/src/verifier/index.ts +1 -0
  80. package/src/verifier/queued_chonk_verifier.ts +15 -47
  81. package/dest/bb/execute.d.ts +0 -107
  82. package/dest/bb/execute.d.ts.map +0 -1
  83. package/dest/bb/execute.js +0 -676
  84. package/src/bb/execute.ts +0 -706
@@ -1,676 +0,0 @@
1
- import { sha256 } from '@aztec/foundation/crypto/sha256';
2
- import { Timer } from '@aztec/foundation/timer';
3
- import * as proc from 'child_process';
4
- import { promises as fs } from 'fs';
5
- import { basename, dirname, join } from 'path';
6
- import readline from 'readline';
7
- export const VK_FILENAME = 'vk';
8
- export const PUBLIC_INPUTS_FILENAME = 'public_inputs';
9
- export const PROOF_FILENAME = 'proof';
10
- export const AVM_INPUTS_FILENAME = 'avm_inputs.bin';
11
- export const AVM_BYTECODE_FILENAME = 'avm_bytecode.bin';
12
- export const AVM_PUBLIC_INPUTS_FILENAME = 'avm_public_inputs.bin';
13
- export var BB_RESULT = /*#__PURE__*/ function(BB_RESULT) {
14
- BB_RESULT[BB_RESULT["SUCCESS"] = 0] = "SUCCESS";
15
- BB_RESULT[BB_RESULT["FAILURE"] = 1] = "FAILURE";
16
- BB_RESULT[BB_RESULT["ALREADY_PRESENT"] = 2] = "ALREADY_PRESENT";
17
- return BB_RESULT;
18
- }({});
19
- /**
20
- * Invokes the Barretenberg binary with the provided command and args
21
- * @param pathToBB - The path to the BB binary
22
- * @param command - The command to execute
23
- * @param args - The arguments to pass
24
- * @param logger - A log function
25
- * @param timeout - An optional timeout before killing the BB process
26
- * @param resultParser - An optional handler for detecting success or failure
27
- * @returns The completed partial witness outputted from the circuit
28
- */ export function executeBB(pathToBB, command, args, logger, concurrency, timeout, resultParser = (code)=>code === 0) {
29
- return new Promise((resolve)=>{
30
- // spawn the bb process
31
- const { HARDWARE_CONCURRENCY: _, ...envWithoutConcurrency } = process.env;
32
- const env = envWithoutConcurrency;
33
- // We prioritise the concurrency argument if provided and > 0
34
- if (concurrency && concurrency > 0) {
35
- env.HARDWARE_CONCURRENCY = concurrency.toString();
36
- } else if (process.env.HARDWARE_CONCURRENCY) {
37
- env.HARDWARE_CONCURRENCY = process.env.HARDWARE_CONCURRENCY;
38
- }
39
- logger(`BB concurrency: ${env.HARDWARE_CONCURRENCY}`);
40
- logger(`Executing BB with: ${pathToBB} ${command} ${args.join(' ')}`);
41
- const bb = proc.spawn(pathToBB, [
42
- command,
43
- ...args
44
- ], {
45
- stdio: [
46
- 'ignore',
47
- 'pipe',
48
- 'pipe'
49
- ],
50
- env
51
- });
52
- let timeoutId;
53
- if (timeout !== undefined) {
54
- timeoutId = setTimeout(()=>{
55
- logger(`BB execution timed out after ${timeout}ms, killing process`);
56
- if (bb.pid) {
57
- bb.kill('SIGKILL');
58
- }
59
- resolve({
60
- status: 1,
61
- exitCode: -1,
62
- signal: 'TIMEOUT'
63
- });
64
- }, timeout);
65
- }
66
- readline.createInterface({
67
- input: bb.stdout
68
- }).on('line', logger);
69
- readline.createInterface({
70
- input: bb.stderr
71
- }).on('line', logger);
72
- bb.on('close', (exitCode, signal)=>{
73
- if (timeoutId) {
74
- clearTimeout(timeoutId);
75
- }
76
- if (resultParser(exitCode)) {
77
- resolve({
78
- status: 0,
79
- exitCode,
80
- signal
81
- });
82
- } else {
83
- resolve({
84
- status: 1,
85
- exitCode,
86
- signal
87
- });
88
- }
89
- });
90
- }).catch((_)=>({
91
- status: 1,
92
- exitCode: -1,
93
- signal: undefined
94
- }));
95
- }
96
- export async function executeBbChonkProof(pathToBB, workingDirectory, inputsPath, log, writeVk = false) {
97
- // Check that the working directory exists
98
- try {
99
- await fs.access(workingDirectory);
100
- } catch {
101
- return {
102
- status: 1,
103
- reason: `Working directory ${workingDirectory} does not exist`
104
- };
105
- }
106
- // The proof is written to e.g. /workingDirectory/proof
107
- const outputPath = `${workingDirectory}`;
108
- const binaryPresent = await fs.access(pathToBB, fs.constants.R_OK).then((_)=>true).catch((_)=>false);
109
- if (!binaryPresent) {
110
- return {
111
- status: 1,
112
- reason: `Failed to find bb binary at ${pathToBB}`
113
- };
114
- }
115
- try {
116
- // Write the bytecode to the working directory
117
- log(`inputsPath ${inputsPath}`);
118
- const timer = new Timer();
119
- const logFunction = (message)=>{
120
- log(`bb - ${message}`);
121
- };
122
- const args = [
123
- '-o',
124
- outputPath,
125
- '--ivc_inputs_path',
126
- inputsPath,
127
- '-v',
128
- '--scheme',
129
- 'chonk'
130
- ];
131
- if (writeVk) {
132
- args.push('--write_vk');
133
- }
134
- const result = await executeBB(pathToBB, 'prove', args, logFunction);
135
- const durationMs = timer.ms();
136
- if (result.status == 0) {
137
- return {
138
- status: 0,
139
- durationMs,
140
- proofPath: `${outputPath}`,
141
- pkPath: undefined,
142
- vkDirectoryPath: `${outputPath}`
143
- };
144
- }
145
- // Not a great error message here but it is difficult to decipher what comes from bb
146
- return {
147
- status: 1,
148
- reason: `Failed to generate proof. Exit code ${result.exitCode}. Signal ${result.signal}.`,
149
- retry: !!result.signal
150
- };
151
- } catch (error) {
152
- return {
153
- status: 1,
154
- reason: `${error}`
155
- };
156
- }
157
- }
158
- function getArgs(flavor) {
159
- switch(flavor){
160
- case 'ultra_honk':
161
- {
162
- return [
163
- '--scheme',
164
- 'ultra_honk',
165
- '--oracle_hash',
166
- 'poseidon2'
167
- ];
168
- }
169
- case 'ultra_keccak_honk':
170
- {
171
- return [
172
- '--scheme',
173
- 'ultra_honk',
174
- '--oracle_hash',
175
- 'keccak'
176
- ];
177
- }
178
- case 'ultra_starknet_honk':
179
- {
180
- return [
181
- '--scheme',
182
- 'ultra_honk',
183
- '--oracle_hash',
184
- 'starknet'
185
- ];
186
- }
187
- case 'ultra_rollup_honk':
188
- {
189
- return [
190
- '--scheme',
191
- 'ultra_honk',
192
- '--oracle_hash',
193
- 'poseidon2',
194
- '--ipa_accumulation'
195
- ];
196
- }
197
- }
198
- }
199
- /**
200
- * Used for generating proofs of noir circuits.
201
- * It is assumed that the working directory is a temporary and/or random directory used solely for generating this proof.
202
- * @param pathToBB - The full path to the bb binary
203
- * @param workingDirectory - A working directory for use by bb
204
- * @param circuitName - An identifier for the circuit
205
- * @param bytecode - The compiled circuit bytecode
206
- * @param inputWitnessFile - The circuit input witness
207
- * @param log - A logging function
208
- * @returns An object containing a result indication, the location of the proof and the duration taken
209
- */ export async function generateProof(pathToBB, workingDirectory, circuitName, bytecode, verificationKey, inputWitnessFile, flavor, log) {
210
- // Check that the working directory exists
211
- try {
212
- await fs.access(workingDirectory);
213
- } catch {
214
- return {
215
- status: 1,
216
- reason: `Working directory ${workingDirectory} does not exist`
217
- };
218
- }
219
- // The bytecode is written to e.g. /workingDirectory/ParityBaseArtifact-bytecode
220
- const bytecodePath = `${workingDirectory}/${circuitName}-bytecode`;
221
- const vkPath = `${workingDirectory}/${circuitName}-vk`;
222
- // The proof is written to e.g. /workingDirectory/ultra_honk/proof
223
- const outputPath = `${workingDirectory}`;
224
- const binaryPresent = await fs.access(pathToBB, fs.constants.R_OK).then((_)=>true).catch((_)=>false);
225
- if (!binaryPresent) {
226
- return {
227
- status: 1,
228
- reason: `Failed to find bb binary at ${pathToBB}`
229
- };
230
- }
231
- try {
232
- // Write the bytecode and vk to the working directory
233
- await Promise.all([
234
- fs.writeFile(bytecodePath, bytecode),
235
- fs.writeFile(vkPath, verificationKey)
236
- ]);
237
- const args = getArgs(flavor).concat([
238
- '--disable_zk',
239
- '-o',
240
- outputPath,
241
- '-b',
242
- bytecodePath,
243
- '-k',
244
- vkPath,
245
- '-w',
246
- inputWitnessFile,
247
- '-v'
248
- ]);
249
- const loggingArg = log.level === 'debug' || log.level === 'trace' ? '-d' : log.level === 'verbose' ? '-v' : '';
250
- if (loggingArg !== '') {
251
- args.push(loggingArg);
252
- }
253
- const timer = new Timer();
254
- const logFunction = (message)=>{
255
- log.info(`${circuitName} BB out - ${message}`);
256
- };
257
- const result = await executeBB(pathToBB, `prove`, args, logFunction);
258
- const duration = timer.ms();
259
- if (result.status == 0) {
260
- return {
261
- status: 0,
262
- durationMs: duration,
263
- proofPath: `${outputPath}`,
264
- pkPath: undefined,
265
- vkDirectoryPath: `${outputPath}`
266
- };
267
- }
268
- // Not a great error message here but it is difficult to decipher what comes from bb
269
- return {
270
- status: 1,
271
- reason: `Failed to generate proof. Exit code ${result.exitCode}. Signal ${result.signal}.`,
272
- retry: !!result.signal
273
- };
274
- } catch (error) {
275
- return {
276
- status: 1,
277
- reason: `${error}`
278
- };
279
- }
280
- }
281
- /**
282
- * Used for generating AVM proofs.
283
- * It is assumed that the working directory is a temporary and/or random directory used solely for generating this proof.
284
- * @param pathToBB - The full path to the bb binary
285
- * @param workingDirectory - A working directory for use by bb
286
- * @param input - The inputs for the public function to be proven
287
- * @param logger - A logging function
288
- * @param checkCircuitOnly - A boolean to toggle a "check-circuit only" operation instead of proving.
289
- * @returns An object containing a result indication, the location of the proof and the duration taken
290
- */ export async function generateAvmProof(pathToBB, workingDirectory, input, logger, checkCircuitOnly = false) {
291
- // Check that the working directory exists
292
- try {
293
- await fs.access(workingDirectory);
294
- } catch {
295
- return {
296
- status: 1,
297
- reason: `Working directory ${workingDirectory} does not exist`
298
- };
299
- }
300
- // The proof is written to e.g. /workingDirectory/proof
301
- const outputPath = workingDirectory;
302
- const filePresent = async (file)=>await fs.access(file, fs.constants.R_OK).then((_)=>true).catch((_)=>false);
303
- const binaryPresent = await filePresent(pathToBB);
304
- if (!binaryPresent) {
305
- return {
306
- status: 1,
307
- reason: `Failed to find bb binary at ${pathToBB}`
308
- };
309
- }
310
- const inputsBuffer = input.serializeWithMessagePack();
311
- try {
312
- // Write the inputs to the working directory.
313
- const avmInputsPath = join(workingDirectory, AVM_INPUTS_FILENAME);
314
- await fs.writeFile(avmInputsPath, inputsBuffer);
315
- if (!await filePresent(avmInputsPath)) {
316
- return {
317
- status: 1,
318
- reason: `Could not write avm inputs to ${avmInputsPath}`
319
- };
320
- }
321
- const args = checkCircuitOnly ? [
322
- '--avm-inputs',
323
- avmInputsPath
324
- ] : [
325
- '--avm-inputs',
326
- avmInputsPath,
327
- '-o',
328
- outputPath
329
- ];
330
- const loggingArg = logger.level === 'debug' || logger.level === 'trace' ? '-d' : logger.level === 'verbose' ? '-v' : '';
331
- if (loggingArg !== '') {
332
- args.push(loggingArg);
333
- }
334
- const timer = new Timer();
335
- const cmd = checkCircuitOnly ? 'avm_check_circuit' : 'avm_prove';
336
- const logFunction = (message)=>{
337
- logger.verbose(`AvmCircuit (${cmd}) BB out - ${message}`);
338
- };
339
- const result = await executeBB(pathToBB, cmd, args, logFunction);
340
- const duration = timer.ms();
341
- if (result.status == 0) {
342
- return {
343
- status: 0,
344
- durationMs: duration,
345
- proofPath: join(outputPath, PROOF_FILENAME),
346
- pkPath: undefined,
347
- vkDirectoryPath: outputPath
348
- };
349
- }
350
- // Not a great error message here but it is difficult to decipher what comes from bb
351
- return {
352
- status: 1,
353
- reason: `Failed to generate proof. AVM proof for TX hash ${input.hints.tx.hash}. Exit code ${result.exitCode}. Signal ${result.signal}.`,
354
- retry: result.signal === 'SIGKILL'
355
- };
356
- } catch (error) {
357
- return {
358
- status: 1,
359
- reason: `${error}`
360
- };
361
- }
362
- }
363
- /**
364
- * Used for verifying proofs of noir circuits
365
- * @param pathToBB - The full path to the bb binary
366
- * @param proofFullPath - The full path to the proof to be verified
367
- * @param verificationKeyPath - The full path to the circuit verification key
368
- * @param log - A logging function
369
- * @returns An object containing a result indication and duration taken
370
- */ export async function verifyProof(pathToBB, proofFullPath, verificationKeyPath, ultraHonkFlavor, log) {
371
- return await verifyProofInternal(pathToBB, proofFullPath, verificationKeyPath, `verify`, log, getArgs(ultraHonkFlavor));
372
- }
373
- export async function verifyAvmProof(pathToBB, workingDirectory, proofFullPath, publicInputs, verificationKeyPath, logger) {
374
- const inputsBuffer = publicInputs.serializeWithMessagePack();
375
- // Write the inputs to the working directory.
376
- const filePresent = async (file)=>await fs.access(file, fs.constants.R_OK).then((_)=>true).catch((_)=>false);
377
- const avmInputsPath = join(workingDirectory, 'avm_public_inputs.bin');
378
- await fs.writeFile(avmInputsPath, inputsBuffer);
379
- if (!await filePresent(avmInputsPath)) {
380
- return {
381
- status: 1,
382
- reason: `Could not write avm inputs to ${avmInputsPath}`
383
- };
384
- }
385
- return await verifyProofInternal(pathToBB, proofFullPath, verificationKeyPath, 'avm_verify', logger, [
386
- '--avm-public-inputs',
387
- avmInputsPath
388
- ]);
389
- }
390
- /**
391
- * Verifies a ChonkProof
392
- * TODO(#7370) The verification keys should be supplied separately
393
- * @param pathToBB - The full path to the bb binary
394
- * @param targetPath - The path to the folder with the proof, accumulator, and verification keys
395
- * @param log - A logging function
396
- * @param concurrency - The number of threads to use for the verification
397
- * @returns An object containing a result indication and duration taken
398
- */ export async function verifyChonkProof(pathToBB, proofPath, keyPath, log, concurrency = 1) {
399
- const binaryPresent = await fs.access(pathToBB, fs.constants.R_OK).then((_)=>true).catch((_)=>false);
400
- if (!binaryPresent) {
401
- return {
402
- status: 1,
403
- reason: `Failed to find bb binary at ${pathToBB}`
404
- };
405
- }
406
- try {
407
- const args = [
408
- '--scheme',
409
- 'chonk',
410
- '-p',
411
- proofPath,
412
- '-k',
413
- keyPath,
414
- '-v'
415
- ];
416
- const timer = new Timer();
417
- const command = 'verify';
418
- const result = await executeBB(pathToBB, command, args, log, concurrency);
419
- const duration = timer.ms();
420
- if (result.status == 0) {
421
- return {
422
- status: 0,
423
- durationMs: duration
424
- };
425
- }
426
- // Not a great error message here but it is difficult to decipher what comes from bb
427
- return {
428
- status: 1,
429
- reason: `Failed to verify proof. Exit code ${result.exitCode}. Signal ${result.signal}.`,
430
- retry: !!result.signal
431
- };
432
- } catch (error) {
433
- return {
434
- status: 1,
435
- reason: `${error}`
436
- };
437
- }
438
- }
439
- /**
440
- * Used for verifying proofs with BB
441
- * @param pathToBB - The full path to the bb binary
442
- * @param proofFullPath - The full path to the proof to be verified
443
- * @param verificationKeyPath - The full path to the circuit verification key
444
- * @param command - The BB command to execute (verify/avm_verify)
445
- * @param log - A logging function
446
- * @returns An object containing a result indication and duration taken
447
- */ async function verifyProofInternal(pathToBB, proofFullPath, verificationKeyPath, command, logger, extraArgs = []) {
448
- const binaryPresent = await fs.access(pathToBB, fs.constants.R_OK).then((_)=>true).catch((_)=>false);
449
- if (!binaryPresent) {
450
- return {
451
- status: 1,
452
- reason: `Failed to find bb binary at ${pathToBB}`
453
- };
454
- }
455
- const logFunction = (message)=>{
456
- logger.verbose(`bb-prover (verify) BB out - ${message}`);
457
- };
458
- try {
459
- let args;
460
- if (command == 'verify') {
461
- // Specify the public inputs path in the case of UH verification.
462
- // Take proofFullPath and remove the suffix past the / to get the directory.
463
- const proofDir = proofFullPath.substring(0, proofFullPath.lastIndexOf('/'));
464
- const publicInputsFullPath = join(proofDir, '/public_inputs');
465
- logger.debug(`public inputs path: ${publicInputsFullPath}`);
466
- args = [
467
- '-p',
468
- proofFullPath,
469
- '-k',
470
- verificationKeyPath,
471
- '-i',
472
- publicInputsFullPath,
473
- '--disable_zk',
474
- ...extraArgs
475
- ];
476
- } else {
477
- args = [
478
- '-p',
479
- proofFullPath,
480
- '-k',
481
- verificationKeyPath,
482
- ...extraArgs
483
- ];
484
- }
485
- const loggingArg = logger.level === 'debug' || logger.level === 'trace' ? '-d' : logger.level === 'verbose' ? '-v' : '';
486
- if (loggingArg !== '') {
487
- args.push(loggingArg);
488
- }
489
- const timer = new Timer();
490
- const result = await executeBB(pathToBB, command, args, logFunction);
491
- const duration = timer.ms();
492
- if (result.status == 0) {
493
- return {
494
- status: 0,
495
- durationMs: duration
496
- };
497
- }
498
- // Not a great error message here but it is difficult to decipher what comes from bb
499
- return {
500
- status: 1,
501
- reason: `Failed to verify proof. Exit code ${result.exitCode}. Signal ${result.signal}.`,
502
- retry: !!result.signal
503
- };
504
- } catch (error) {
505
- return {
506
- status: 1,
507
- reason: `${error}`
508
- };
509
- }
510
- }
511
- export async function generateContractForVerificationKey(pathToBB, vkFilePath, contractPath, log) {
512
- const binaryPresent = await fs.access(pathToBB, fs.constants.R_OK).then((_)=>true).catch((_)=>false);
513
- if (!binaryPresent) {
514
- return {
515
- status: 1,
516
- reason: `Failed to find bb binary at ${pathToBB}`
517
- };
518
- }
519
- const outputDir = dirname(contractPath);
520
- const contractName = basename(contractPath);
521
- // cache contract generation based on vk file and contract name
522
- const cacheKey = sha256(Buffer.concat([
523
- Buffer.from(contractName),
524
- await fs.readFile(vkFilePath)
525
- ]));
526
- await fs.mkdir(outputDir, {
527
- recursive: true
528
- });
529
- const res = await fsCache(outputDir, cacheKey, log, false, async ()=>{
530
- try {
531
- const args = [
532
- '--scheme',
533
- 'ultra_honk',
534
- '-k',
535
- vkFilePath,
536
- '-o',
537
- contractPath,
538
- '-v'
539
- ];
540
- const timer = new Timer();
541
- const result = await executeBB(pathToBB, 'contract', args, log);
542
- const duration = timer.ms();
543
- if (result.status == 0) {
544
- return {
545
- status: 0,
546
- durationMs: duration,
547
- contractPath
548
- };
549
- }
550
- // Not a great error message here but it is difficult to decipher what comes from bb
551
- return {
552
- status: 1,
553
- reason: `Failed to write verifier contract. Exit code ${result.exitCode}. Signal ${result.signal}.`,
554
- retry: !!result.signal
555
- };
556
- } catch (error) {
557
- return {
558
- status: 1,
559
- reason: `${error}`
560
- };
561
- }
562
- });
563
- if (!res) {
564
- return {
565
- status: 2,
566
- durationMs: 0,
567
- contractPath
568
- };
569
- }
570
- return res;
571
- }
572
- /**
573
- * Compute bb gate count for a given circuit
574
- * @param pathToBB - The full path to the bb binary
575
- * @param workingDirectory - A temporary directory for writing the bytecode
576
- * @param circuitName - The name of the circuit
577
- * @param bytecode - The bytecode of the circuit
578
- * @param flavor - The flavor of the backend - mega_honk or ultra_honk variants
579
- * @returns An object containing the status, gate count, and time taken
580
- */ export async function computeGateCountForCircuit(pathToBB, workingDirectory, circuitName, bytecode, flavor, log) {
581
- // Check that the working directory exists
582
- try {
583
- await fs.access(workingDirectory);
584
- } catch {
585
- return {
586
- status: 1,
587
- reason: `Working directory ${workingDirectory} does not exist`
588
- };
589
- }
590
- // The bytecode is written to e.g. /workingDirectory/ParityBaseArtifact-bytecode
591
- const bytecodePath = `${workingDirectory}/${circuitName}-bytecode`;
592
- const binaryPresent = await fs.access(pathToBB, fs.constants.R_OK).then((_)=>true).catch((_)=>false);
593
- if (!binaryPresent) {
594
- return {
595
- status: 1,
596
- reason: `Failed to find bb binary at ${pathToBB}`
597
- };
598
- }
599
- // Accumulate the stdout from bb
600
- let stdout = '';
601
- const logHandler = (message)=>{
602
- stdout += message;
603
- log(message);
604
- };
605
- try {
606
- // Write the bytecode to the working directory
607
- await fs.writeFile(bytecodePath, bytecode);
608
- const timer = new Timer();
609
- const result = await executeBB(pathToBB, 'gates', [
610
- '--scheme',
611
- flavor === 'mega_honk' ? 'chonk' : 'ultra_honk',
612
- '-b',
613
- bytecodePath,
614
- '-v'
615
- ], logHandler);
616
- const duration = timer.ms();
617
- if (result.status == 0) {
618
- // Look for "circuit_size" in the stdout and parse the number
619
- const circuitSizeMatch = stdout.match(/circuit_size": (\d+)/);
620
- if (!circuitSizeMatch) {
621
- return {
622
- status: 1,
623
- reason: 'Failed to parse circuit_size from bb gates stdout.'
624
- };
625
- }
626
- const circuitSize = parseInt(circuitSizeMatch[1]);
627
- return {
628
- status: 0,
629
- durationMs: duration,
630
- circuitSize: circuitSize
631
- };
632
- }
633
- return {
634
- status: 1,
635
- reason: 'Failed getting the gate count.'
636
- };
637
- } catch (error) {
638
- return {
639
- status: 1,
640
- reason: `${error}`
641
- };
642
- }
643
- }
644
- const CACHE_FILENAME = '.cache';
645
- async function fsCache(dir, expectedCacheKey, logger, force, action) {
646
- const cacheFilePath = join(dir, CACHE_FILENAME);
647
- let run;
648
- if (force) {
649
- run = true;
650
- } else {
651
- try {
652
- run = !expectedCacheKey.equals(await fs.readFile(cacheFilePath));
653
- } catch (err) {
654
- if (err && 'code' in err && err.code === 'ENOENT') {
655
- // cache file doesn't exist, swallow error and run
656
- run = true;
657
- } else {
658
- throw err;
659
- }
660
- }
661
- }
662
- let res;
663
- if (run) {
664
- logger(`Cache miss or forced run. Running operation in ${dir}...`);
665
- res = await action();
666
- } else {
667
- logger(`Cache hit. Skipping operation in ${dir}...`);
668
- }
669
- try {
670
- await fs.writeFile(cacheFilePath, expectedCacheKey);
671
- } catch {
672
- logger(`Couldn't write cache data to ${cacheFilePath}. Skipping cache...`);
673
- // ignore
674
- }
675
- return res;
676
- }