@aztec/bb-prover 0.0.1-commit.b33fc05d0 → 0.0.1-commit.b3d3157a

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