@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,38 +1,501 @@
1
- function _ts_decorate(decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1
+ function _ts_add_disposable_resource(env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() {
16
+ try {
17
+ inner.call(this);
18
+ } catch (e) {
19
+ return Promise.reject(e);
20
+ }
21
+ };
22
+ env.stack.push({
23
+ value: value,
24
+ dispose: dispose,
25
+ async: async
26
+ });
27
+ } else if (async) {
28
+ env.stack.push({
29
+ async: true
30
+ });
31
+ }
32
+ return value;
33
+ }
34
+ function _ts_dispose_resources(env) {
35
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
36
+ var e = new Error(message);
37
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
38
+ };
39
+ return (_ts_dispose_resources = function _ts_dispose_resources(env) {
40
+ function fail(e) {
41
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
42
+ env.hasError = true;
43
+ }
44
+ var r, s = 0;
45
+ function next() {
46
+ while(r = env.stack.pop()){
47
+ try {
48
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
49
+ if (r.dispose) {
50
+ var result = r.dispose.call(r.value);
51
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
52
+ fail(e);
53
+ return next();
54
+ });
55
+ } else s |= 1;
56
+ } catch (e) {
57
+ fail(e);
58
+ }
59
+ }
60
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
61
+ if (env.hasError) throw env.error;
62
+ }
63
+ return next();
64
+ })(env);
6
65
  }
66
+ function applyDecs2203RFactory() {
67
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
68
+ return function addInitializer(initializer) {
69
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
70
+ assertCallable(initializer, "An initializer");
71
+ initializers.push(initializer);
72
+ };
73
+ }
74
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
75
+ var kindStr;
76
+ switch(kind){
77
+ case 1:
78
+ kindStr = "accessor";
79
+ break;
80
+ case 2:
81
+ kindStr = "method";
82
+ break;
83
+ case 3:
84
+ kindStr = "getter";
85
+ break;
86
+ case 4:
87
+ kindStr = "setter";
88
+ break;
89
+ default:
90
+ kindStr = "field";
91
+ }
92
+ var ctx = {
93
+ kind: kindStr,
94
+ name: isPrivate ? "#" + name : name,
95
+ static: isStatic,
96
+ private: isPrivate,
97
+ metadata: metadata
98
+ };
99
+ var decoratorFinishedRef = {
100
+ v: false
101
+ };
102
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
103
+ var get, set;
104
+ if (kind === 0) {
105
+ if (isPrivate) {
106
+ get = desc.get;
107
+ set = desc.set;
108
+ } else {
109
+ get = function() {
110
+ return this[name];
111
+ };
112
+ set = function(v) {
113
+ this[name] = v;
114
+ };
115
+ }
116
+ } else if (kind === 2) {
117
+ get = function() {
118
+ return desc.value;
119
+ };
120
+ } else {
121
+ if (kind === 1 || kind === 3) {
122
+ get = function() {
123
+ return desc.get.call(this);
124
+ };
125
+ }
126
+ if (kind === 1 || kind === 4) {
127
+ set = function(v) {
128
+ desc.set.call(this, v);
129
+ };
130
+ }
131
+ }
132
+ ctx.access = get && set ? {
133
+ get: get,
134
+ set: set
135
+ } : get ? {
136
+ get: get
137
+ } : {
138
+ set: set
139
+ };
140
+ try {
141
+ return dec(value, ctx);
142
+ } finally{
143
+ decoratorFinishedRef.v = true;
144
+ }
145
+ }
146
+ function assertNotFinished(decoratorFinishedRef, fnName) {
147
+ if (decoratorFinishedRef.v) {
148
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
149
+ }
150
+ }
151
+ function assertCallable(fn, hint) {
152
+ if (typeof fn !== "function") {
153
+ throw new TypeError(hint + " must be a function");
154
+ }
155
+ }
156
+ function assertValidReturnValue(kind, value) {
157
+ var type = typeof value;
158
+ if (kind === 1) {
159
+ if (type !== "object" || value === null) {
160
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
161
+ }
162
+ if (value.get !== undefined) {
163
+ assertCallable(value.get, "accessor.get");
164
+ }
165
+ if (value.set !== undefined) {
166
+ assertCallable(value.set, "accessor.set");
167
+ }
168
+ if (value.init !== undefined) {
169
+ assertCallable(value.init, "accessor.init");
170
+ }
171
+ } else if (type !== "function") {
172
+ var hint;
173
+ if (kind === 0) {
174
+ hint = "field";
175
+ } else if (kind === 10) {
176
+ hint = "class";
177
+ } else {
178
+ hint = "method";
179
+ }
180
+ throw new TypeError(hint + " decorators must return a function or void 0");
181
+ }
182
+ }
183
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
184
+ var decs = decInfo[0];
185
+ var desc, init, value;
186
+ if (isPrivate) {
187
+ if (kind === 0 || kind === 1) {
188
+ desc = {
189
+ get: decInfo[3],
190
+ set: decInfo[4]
191
+ };
192
+ } else if (kind === 3) {
193
+ desc = {
194
+ get: decInfo[3]
195
+ };
196
+ } else if (kind === 4) {
197
+ desc = {
198
+ set: decInfo[3]
199
+ };
200
+ } else {
201
+ desc = {
202
+ value: decInfo[3]
203
+ };
204
+ }
205
+ } else if (kind !== 0) {
206
+ desc = Object.getOwnPropertyDescriptor(base, name);
207
+ }
208
+ if (kind === 1) {
209
+ value = {
210
+ get: desc.get,
211
+ set: desc.set
212
+ };
213
+ } else if (kind === 2) {
214
+ value = desc.value;
215
+ } else if (kind === 3) {
216
+ value = desc.get;
217
+ } else if (kind === 4) {
218
+ value = desc.set;
219
+ }
220
+ var newValue, get, set;
221
+ if (typeof decs === "function") {
222
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
223
+ if (newValue !== void 0) {
224
+ assertValidReturnValue(kind, newValue);
225
+ if (kind === 0) {
226
+ init = newValue;
227
+ } else if (kind === 1) {
228
+ init = newValue.init;
229
+ get = newValue.get || value.get;
230
+ set = newValue.set || value.set;
231
+ value = {
232
+ get: get,
233
+ set: set
234
+ };
235
+ } else {
236
+ value = newValue;
237
+ }
238
+ }
239
+ } else {
240
+ for(var i = decs.length - 1; i >= 0; i--){
241
+ var dec = decs[i];
242
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
243
+ if (newValue !== void 0) {
244
+ assertValidReturnValue(kind, newValue);
245
+ var newInit;
246
+ if (kind === 0) {
247
+ newInit = newValue;
248
+ } else if (kind === 1) {
249
+ newInit = newValue.init;
250
+ get = newValue.get || value.get;
251
+ set = newValue.set || value.set;
252
+ value = {
253
+ get: get,
254
+ set: set
255
+ };
256
+ } else {
257
+ value = newValue;
258
+ }
259
+ if (newInit !== void 0) {
260
+ if (init === void 0) {
261
+ init = newInit;
262
+ } else if (typeof init === "function") {
263
+ init = [
264
+ init,
265
+ newInit
266
+ ];
267
+ } else {
268
+ init.push(newInit);
269
+ }
270
+ }
271
+ }
272
+ }
273
+ }
274
+ if (kind === 0 || kind === 1) {
275
+ if (init === void 0) {
276
+ init = function(instance, init) {
277
+ return init;
278
+ };
279
+ } else if (typeof init !== "function") {
280
+ var ownInitializers = init;
281
+ init = function(instance, init) {
282
+ var value = init;
283
+ for(var i = 0; i < ownInitializers.length; i++){
284
+ value = ownInitializers[i].call(instance, value);
285
+ }
286
+ return value;
287
+ };
288
+ } else {
289
+ var originalInitializer = init;
290
+ init = function(instance, init) {
291
+ return originalInitializer.call(instance, init);
292
+ };
293
+ }
294
+ ret.push(init);
295
+ }
296
+ if (kind !== 0) {
297
+ if (kind === 1) {
298
+ desc.get = value.get;
299
+ desc.set = value.set;
300
+ } else if (kind === 2) {
301
+ desc.value = value;
302
+ } else if (kind === 3) {
303
+ desc.get = value;
304
+ } else if (kind === 4) {
305
+ desc.set = value;
306
+ }
307
+ if (isPrivate) {
308
+ if (kind === 1) {
309
+ ret.push(function(instance, args) {
310
+ return value.get.call(instance, args);
311
+ });
312
+ ret.push(function(instance, args) {
313
+ return value.set.call(instance, args);
314
+ });
315
+ } else if (kind === 2) {
316
+ ret.push(value);
317
+ } else {
318
+ ret.push(function(instance, args) {
319
+ return value.call(instance, args);
320
+ });
321
+ }
322
+ } else {
323
+ Object.defineProperty(base, name, desc);
324
+ }
325
+ }
326
+ }
327
+ function applyMemberDecs(Class, decInfos, metadata) {
328
+ var ret = [];
329
+ var protoInitializers;
330
+ var staticInitializers;
331
+ var existingProtoNonFields = new Map();
332
+ var existingStaticNonFields = new Map();
333
+ for(var i = 0; i < decInfos.length; i++){
334
+ var decInfo = decInfos[i];
335
+ if (!Array.isArray(decInfo)) continue;
336
+ var kind = decInfo[1];
337
+ var name = decInfo[2];
338
+ var isPrivate = decInfo.length > 3;
339
+ var isStatic = kind >= 5;
340
+ var base;
341
+ var initializers;
342
+ if (isStatic) {
343
+ base = Class;
344
+ kind = kind - 5;
345
+ staticInitializers = staticInitializers || [];
346
+ initializers = staticInitializers;
347
+ } else {
348
+ base = Class.prototype;
349
+ protoInitializers = protoInitializers || [];
350
+ initializers = protoInitializers;
351
+ }
352
+ if (kind !== 0 && !isPrivate) {
353
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
354
+ var existingKind = existingNonFields.get(name) || 0;
355
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
356
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
357
+ } else if (!existingKind && kind > 2) {
358
+ existingNonFields.set(name, kind);
359
+ } else {
360
+ existingNonFields.set(name, true);
361
+ }
362
+ }
363
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
364
+ }
365
+ pushInitializers(ret, protoInitializers);
366
+ pushInitializers(ret, staticInitializers);
367
+ return ret;
368
+ }
369
+ function pushInitializers(ret, initializers) {
370
+ if (initializers) {
371
+ ret.push(function(instance) {
372
+ for(var i = 0; i < initializers.length; i++){
373
+ initializers[i].call(instance);
374
+ }
375
+ return instance;
376
+ });
377
+ }
378
+ }
379
+ function applyClassDecs(targetClass, classDecs, metadata) {
380
+ if (classDecs.length > 0) {
381
+ var initializers = [];
382
+ var newClass = targetClass;
383
+ var name = targetClass.name;
384
+ for(var i = classDecs.length - 1; i >= 0; i--){
385
+ var decoratorFinishedRef = {
386
+ v: false
387
+ };
388
+ try {
389
+ var nextNewClass = classDecs[i](newClass, {
390
+ kind: "class",
391
+ name: name,
392
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
393
+ metadata
394
+ });
395
+ } finally{
396
+ decoratorFinishedRef.v = true;
397
+ }
398
+ if (nextNewClass !== undefined) {
399
+ assertValidReturnValue(10, nextNewClass);
400
+ newClass = nextNewClass;
401
+ }
402
+ }
403
+ return [
404
+ defineMetadata(newClass, metadata),
405
+ function() {
406
+ for(var i = 0; i < initializers.length; i++){
407
+ initializers[i].call(newClass);
408
+ }
409
+ }
410
+ ];
411
+ }
412
+ }
413
+ function defineMetadata(Class, metadata) {
414
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
415
+ configurable: true,
416
+ enumerable: true,
417
+ value: metadata
418
+ });
419
+ }
420
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
421
+ if (parentClass !== void 0) {
422
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
423
+ }
424
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
425
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
426
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
427
+ return {
428
+ e: e,
429
+ get c () {
430
+ return applyClassDecs(targetClass, classDecs, metadata);
431
+ }
432
+ };
433
+ };
434
+ }
435
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
436
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
437
+ }
438
+ var _dec, _dec1, _dec2, _initProto;
7
439
  import { AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED, NESTED_RECURSIVE_PROOF_LENGTH, NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH, PAIRING_POINTS_SIZE, RECURSIVE_PROOF_LENGTH, ULTRA_KECCAK_PROOF_LENGTH } from '@aztec/constants';
8
440
  import { Fr } from '@aztec/foundation/curves/bn254';
9
441
  import { runInDirectory } from '@aztec/foundation/fs';
10
442
  import { createLogger } from '@aztec/foundation/log';
11
- import { BufferReader } from '@aztec/foundation/serialize';
12
443
  import { convertBlockMergeRollupOutputsFromWitnessMap, convertBlockMergeRollupPrivateInputsToWitnessMap, convertBlockRootEmptyTxFirstRollupOutputsFromWitnessMap, convertBlockRootEmptyTxFirstRollupPrivateInputsToWitnessMap, convertBlockRootFirstRollupOutputsFromWitnessMap, convertBlockRootFirstRollupPrivateInputsToWitnessMap, convertBlockRootRollupOutputsFromWitnessMap, convertBlockRootRollupPrivateInputsToWitnessMap, convertBlockRootSingleTxFirstRollupOutputsFromWitnessMap, convertBlockRootSingleTxFirstRollupPrivateInputsToWitnessMap, convertBlockRootSingleTxRollupOutputsFromWitnessMap, convertBlockRootSingleTxRollupPrivateInputsToWitnessMap, convertCheckpointMergeRollupOutputsFromWitnessMap, convertCheckpointMergeRollupPrivateInputsToWitnessMap, convertCheckpointPaddingRollupOutputsFromWitnessMap, convertCheckpointPaddingRollupPrivateInputsToWitnessMap, convertCheckpointRootRollupOutputsFromWitnessMap, convertCheckpointRootRollupPrivateInputsToWitnessMap, convertCheckpointRootSingleBlockRollupOutputsFromWitnessMap, convertCheckpointRootSingleBlockRollupPrivateInputsToWitnessMap, convertParityBaseOutputsFromWitnessMap, convertParityBasePrivateInputsToWitnessMap, convertParityRootOutputsFromWitnessMap, convertParityRootPrivateInputsToWitnessMap, convertPrivateTxBaseRollupOutputsFromWitnessMap, convertPrivateTxBaseRollupPrivateInputsToWitnessMap, convertPublicChonkVerifierOutputsFromWitnessMap, convertPublicChonkVerifierPrivateInputsToWitnessMap, convertPublicTxBaseRollupOutputsFromWitnessMap, convertPublicTxBaseRollupPrivateInputsToWitnessMap, convertRootRollupOutputsFromWitnessMap, convertRootRollupPrivateInputsToWitnessMap, convertTxMergeRollupOutputsFromWitnessMap, convertTxMergeRollupPrivateInputsToWitnessMap, getServerCircuitArtifact } from '@aztec/noir-protocol-circuits-types/server';
13
444
  import { ServerCircuitVks } from '@aztec/noir-protocol-circuits-types/server/vks';
14
445
  import { mapProtocolArtifactNameToCircuitName } from '@aztec/noir-protocol-circuits-types/types';
15
446
  import { NativeACVMSimulator } from '@aztec/simulator/server';
16
447
  import { ProvingError } from '@aztec/stdlib/errors';
17
- import { makeProofAndVerificationKey, makePublicInputsAndRecursiveProof } from '@aztec/stdlib/interfaces/server';
448
+ import { makePublicInputsAndRecursiveProof } from '@aztec/stdlib/interfaces/server';
18
449
  import { Proof, RecursiveProof, makeRecursiveProofFromBinary } from '@aztec/stdlib/proofs';
19
450
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
20
451
  import { promises as fs } from 'fs';
452
+ import { ungzip } from 'pako';
21
453
  import * as path from 'path';
22
- import { BB_RESULT, PROOF_FILENAME, PUBLIC_INPUTS_FILENAME, VK_FILENAME, generateAvmProof, generateProof, verifyAvmProof, verifyProof } from '../../bb/execute.js';
454
+ import { BBJsFactory } from '../../bb/bb_js_backend.js';
23
455
  import { getUltraHonkFlavorForCircuit } from '../../honk.js';
24
456
  import { ProverInstrumentation } from '../../instrumentation.js';
25
- import { extractAvmVkData } from '../../verification_key/verification_key_data.js';
26
- import { readProofsFromOutputDirectory } from '../proof_utils.js';
457
+ import { constructRecursiveProofFromBuffers } from '../proof_utils.js';
27
458
  const logger = createLogger('bb-prover');
459
+ _dec = trackSpan('BBNativeRollupProver.getBaseParityProof', {
460
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-base'
461
+ }), _dec1 = trackSpan('BBNativeRollupProver.getRootParityProof', {
462
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-root'
463
+ }), _dec2 = trackSpan('BBNativeRollupProver.getAvmProof', (inputs)=>({
464
+ [Attributes.APP_CIRCUIT_NAME]: inputs.hints.tx.hash
465
+ }));
28
466
  /**
29
467
  * Prover implementation that uses barretenberg native proving
30
468
  */ export class BBNativeRollupProver {
31
469
  config;
470
+ static{
471
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
472
+ [
473
+ _dec,
474
+ 2,
475
+ "getBaseParityProof"
476
+ ],
477
+ [
478
+ _dec1,
479
+ 2,
480
+ "getRootParityProof"
481
+ ],
482
+ [
483
+ _dec2,
484
+ 2,
485
+ "getAvmProof"
486
+ ]
487
+ ], []));
488
+ }
32
489
  instrumentation;
490
+ bbJsFactory;
33
491
  constructor(config, telemetry){
34
492
  this.config = config;
493
+ _initProto(this);
35
494
  this.instrumentation = new ProverInstrumentation(telemetry, 'BBNativeRollupProver');
495
+ this.bbJsFactory = new BBJsFactory(config.bbBinaryPath, {
496
+ logger,
497
+ debugDir: config.bbDebugOutputDir
498
+ });
36
499
  }
37
500
  get tracer() {
38
501
  return this.instrumentation.tracer;
@@ -46,7 +509,7 @@ const logger = createLogger('bb-prover');
46
509
  await fs.mkdir(config.bbWorkingDirectory, {
47
510
  recursive: true
48
511
  });
49
- logger.info(`Using native BB at ${config.bbBinaryPath} and working directory ${config.bbWorkingDirectory}`);
512
+ logger.info(`Using bb.js API with binary at ${config.bbBinaryPath}`);
50
513
  logger.info(`Using native ACVM at ${config.acvmBinaryPath} and working directory ${config.acvmWorkingDirectory}`);
51
514
  return new BBNativeRollupProver(config, telemetry);
52
515
  }
@@ -69,9 +532,9 @@ const logger = createLogger('bb-prover');
69
532
  * @param inputs - The inputs to the AVM circuit.
70
533
  * @returns The proof.
71
534
  */ async getAvmProof(inputs) {
72
- const proofAndVk = await this.createAvmProof(inputs);
73
- await this.verifyAvmProof(proofAndVk.proof.binaryProof, proofAndVk.verificationKey, inputs.publicInputs);
74
- return proofAndVk;
535
+ const proof = await this.createAvmProof(inputs);
536
+ await this.verifyAvmProof(proof.binaryProof, inputs.publicInputs);
537
+ return proof;
75
538
  }
76
539
  async getPublicChonkVerifierProof(inputs) {
77
540
  const artifactName = 'PublicChonkVerifier';
@@ -152,15 +615,14 @@ const logger = createLogger('bb-prover');
152
615
  return makePublicInputsAndRecursiveProof(circuitOutput, proof, verificationKey);
153
616
  }
154
617
  async generateProofWithBB(input, circuitType, convertInput, convertOutput, workingDirectory) {
155
- // Have the ACVM write the partial witness here
618
+ // Have the ACVM write the partial witness here (still needs a temp directory)
156
619
  const outputWitnessFile = path.join(workingDirectory, 'partial-witness.gz');
157
620
  // Generate the partial witness using the ACVM
158
- // A further temp directory will be created beneath ours and then cleaned up after the partial witness has been copied to our specified location
159
- const simulator = new NativeACVMSimulator(this.config.acvmWorkingDirectory, this.config.acvmBinaryPath, outputWitnessFile);
621
+ const simulator = new NativeACVMSimulator(this.config.acvmWorkingDirectory, this.config.acvmBinaryPath, outputWitnessFile, logger);
160
622
  const artifact = getServerCircuitArtifact(circuitType);
161
623
  logger.debug(`Generating witness data for ${circuitType}`);
162
624
  const inputWitness = convertInput(input);
163
- const foreignCallHandler = undefined; // We don't handle foreign calls in the native ACVM simulator
625
+ const foreignCallHandler = undefined;
164
626
  const witnessResult = await simulator.executeProtocolCircuit(inputWitness, artifact, foreignCallHandler);
165
627
  const output = convertOutput(witnessResult.witness);
166
628
  const circuitName = mapProtocolArtifactNameToCircuitName(circuitType);
@@ -174,50 +636,82 @@ const logger = createLogger('bb-prover');
174
636
  outputSize: output.toBuffer().length,
175
637
  eventName: 'circuit-witness-generation'
176
638
  });
177
- // Now prove the circuit from the generated witness
178
- logger.debug(`Proving ${circuitType}...`);
179
- const provingResult = await generateProof(this.config.bbBinaryPath, workingDirectory, circuitType, Buffer.from(artifact.bytecode, 'base64'), this.getVerificationKeyDataForCircuit(circuitType).keyAsBytes, outputWitnessFile, getUltraHonkFlavorForCircuit(circuitType), logger);
180
- if (provingResult.status === BB_RESULT.FAILURE) {
181
- logger.error(`Failed to generate proof for ${circuitType}: ${provingResult.reason}`);
182
- throw new ProvingError(provingResult.reason, provingResult, provingResult.retry);
639
+ // Read and decompress the witness for bb.js
640
+ const witnessGz = await fs.readFile(outputWitnessFile);
641
+ const witness = ungzip(witnessGz);
642
+ // Decompress bytecode for bb.js
643
+ const bytecode = ungzip(Buffer.from(artifact.bytecode, 'base64'));
644
+ // Prove the circuit via bb.js API
645
+ logger.debug(`Proving ${circuitType} via bb.js...`);
646
+ let proofResult;
647
+ try {
648
+ const env = {
649
+ stack: [],
650
+ error: void 0,
651
+ hasError: false
652
+ };
653
+ try {
654
+ const instance = _ts_add_disposable_resource(env, await this.bbJsFactory.getInstance(), true);
655
+ proofResult = await instance.generateProof(circuitType, bytecode, this.getVerificationKeyDataForCircuit(circuitType).keyAsBytes, witness, getUltraHonkFlavorForCircuit(circuitType));
656
+ } catch (e) {
657
+ env.error = e;
658
+ env.hasError = true;
659
+ } finally{
660
+ const result = _ts_dispose_resources(env);
661
+ if (result) await result;
662
+ }
663
+ } catch (error) {
664
+ throw new ProvingError(`Failed to generate proof for ${circuitType}: ${error}`);
183
665
  }
184
666
  return {
185
667
  circuitOutput: output,
186
- provingResult
668
+ proofResult
187
669
  };
188
670
  }
189
- async generateAvmProofWithBB(input, workingDirectory) {
190
- logger.info(`Proving avm-circuit for TX ${input.hints.tx.hash}...`);
191
- const provingResult = await generateAvmProof(this.config.bbBinaryPath, workingDirectory, input, logger);
192
- if (provingResult.status === BB_RESULT.FAILURE) {
193
- logger.error(`Failed to generate AVM proof for TX ${input.hints.tx.hash}: ${provingResult.reason}`);
194
- throw new ProvingError(provingResult.reason, provingResult, provingResult.retry);
195
- }
196
- return provingResult;
197
- }
198
671
  async createAvmProof(input) {
199
- const operation = async (bbWorkingDirectory)=>{
200
- const provingResult = await this.generateAvmProofWithBB(input, bbWorkingDirectory);
201
- const avmVK = await extractAvmVkData(provingResult.vkDirectoryPath);
202
- const avmProof = await this.readAvmProofAsFields(provingResult.proofPath);
672
+ const env = {
673
+ stack: [],
674
+ error: void 0,
675
+ hasError: false
676
+ };
677
+ try {
678
+ logger.info(`Proving avm-circuit for TX ${input.hints.tx.hash}...`);
679
+ const inputsBuffer = input.serializeWithMessagePack();
680
+ const instance = _ts_add_disposable_resource(env, await this.bbJsFactory.getInstance(), true);
681
+ const { proof: proofFieldArrays, durationMs } = await instance.generateAvmProof(inputsBuffer);
682
+ // Convert Uint8Array[] (32-byte field elements) to Fr[]
683
+ const proofFields = proofFieldArrays.map((f)=>Fr.fromBuffer(Buffer.from(f)));
684
+ // Pad to fixed size (during development the proof length may vary)
685
+ if (proofFields.length > AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED) {
686
+ throw new Error(`Proof has ${proofFields.length} fields, expected no more than ${AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED}.`);
687
+ }
688
+ const proofFieldsPadded = proofFields.concat(Array(AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED - proofFields.length).fill(new Fr(0)));
689
+ // Build the binary proof from the raw field data
690
+ const rawProofBuffer = Buffer.concat(proofFieldArrays.map((f)=>Buffer.from(f)));
691
+ const binaryProof = new Proof(rawProofBuffer, /*numPublicInputs=*/ 0);
692
+ const avmProof = new RecursiveProof(proofFieldsPadded, binaryProof, true, AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED);
203
693
  const circuitType = 'avm-circuit';
204
694
  const appCircuitName = 'unknown';
205
- this.instrumentation.recordAvmDuration('provingDuration', appCircuitName, provingResult.durationMs);
695
+ this.instrumentation.recordAvmDuration('provingDuration', appCircuitName, durationMs);
206
696
  this.instrumentation.recordAvmSize('proofSize', appCircuitName, avmProof.binaryProof.buffer.length);
207
- logger.info(`Generated proof for ${circuitType}(${input.hints.tx.hash}) in ${Math.ceil(provingResult.durationMs)} ms`, {
697
+ logger.info(`Generated proof for ${circuitType}(${input.hints.tx.hash}) in ${Math.ceil(durationMs)} ms`, {
208
698
  circuitName: circuitType,
209
699
  appCircuitName: input.hints.tx.hash,
210
- // does not include reading the proof from disk
211
- duration: provingResult.durationMs,
700
+ duration: durationMs,
212
701
  proofSize: avmProof.binaryProof.buffer.length,
213
702
  eventName: 'circuit-proving',
214
- inputSize: input.serializeWithMessagePack().length,
703
+ inputSize: inputsBuffer.length,
215
704
  circuitSize: 1 << 21,
216
705
  numPublicInputs: 0
217
706
  });
218
- return makeProofAndVerificationKey(avmProof, avmVK);
219
- };
220
- return await this.runInDirectory(operation);
707
+ return avmProof;
708
+ } catch (e) {
709
+ env.error = e;
710
+ env.hasError = true;
711
+ } finally{
712
+ const result = _ts_dispose_resources(env);
713
+ if (result) await result;
714
+ }
221
715
  }
222
716
  /**
223
717
  * Executes a circuit and returns its outputs and corresponding proof with embedded aggregation object
@@ -228,21 +722,21 @@ const logger = createLogger('bb-prover');
228
722
  * @param convertOutput - Function for parsing the output witness to it's corresponding object
229
723
  * @returns The circuits output object and it's proof
230
724
  */ async createRecursiveProof(input, circuitType, proofLength, convertInput, convertOutput) {
231
- // this probably is gonna need to call chonk
232
- const operation = async (bbWorkingDirectory)=>{
233
- const { provingResult, circuitOutput: output } = await this.generateProofWithBB(input, circuitType, convertInput, convertOutput, bbWorkingDirectory);
725
+ // Still need runInDirectory for ACVM witness generation temp files
726
+ const operation = async (workingDirectory)=>{
727
+ const { proofResult, circuitOutput: output } = await this.generateProofWithBB(input, circuitType, convertInput, convertOutput, workingDirectory);
234
728
  const vkData = this.getVerificationKeyDataForCircuit(circuitType);
235
- // Read the proof as fields
236
- const proof = await readProofsFromOutputDirectory(provingResult.proofPath, vkData, proofLength, logger);
729
+ // Construct proof from in-memory buffers (no file I/O needed)
730
+ const proof = constructRecursiveProofFromBuffers(proofResult.proofFields, proofResult.publicInputFields, vkData, proofLength);
237
731
  const circuitName = mapProtocolArtifactNameToCircuitName(circuitType);
238
- this.instrumentation.recordDuration('provingDuration', circuitName, provingResult.durationMs);
732
+ this.instrumentation.recordDuration('provingDuration', circuitName, proofResult.durationMs);
239
733
  this.instrumentation.recordSize('proofSize', circuitName, proof.binaryProof.buffer.length);
240
734
  this.instrumentation.recordSize('circuitPublicInputCount', circuitName, vkData.numPublicInputs);
241
735
  this.instrumentation.recordSize('circuitSize', circuitName, vkData.circuitSize);
242
- logger.info(`Generated proof for ${circuitType} in ${Math.ceil(provingResult.durationMs)} ms, size: ${proof.proof.length} fields`, {
736
+ logger.info(`Generated proof for ${circuitType} in ${Math.ceil(proofResult.durationMs)} ms, size: ${proof.proof.length} fields`, {
243
737
  circuitName,
244
738
  circuitSize: vkData.circuitSize,
245
- duration: provingResult.durationMs,
739
+ duration: proofResult.durationMs,
246
740
  inputSize: output.toBuffer().length,
247
741
  proofSize: proof.binaryProof.buffer.length,
248
742
  eventName: 'circuit-proving',
@@ -256,36 +750,69 @@ const logger = createLogger('bb-prover');
256
750
  return await this.runInDirectory(operation);
257
751
  }
258
752
  /**
259
- * Verifies a proof, will generate the verification key if one is not cached internally
753
+ * Verifies a proof via bb.js API (no temp files needed).
260
754
  * @param circuitType - The type of circuit whose proof is to be verified
261
755
  * @param proof - The proof to be verified
262
756
  */ async verifyProof(circuitType, proof) {
263
757
  const verificationKey = this.getVerificationKeyDataForCircuit(circuitType);
264
- return await this.verifyWithKey(getUltraHonkFlavorForCircuit(circuitType), verificationKey, proof);
265
- }
266
- async verifyAvmProof(proof, verificationKey, publicInputs) {
267
- return await this.verifyWithKeyInternal(proof, verificationKey, (proofPath, vkPath)=>verifyAvmProof(this.config.bbBinaryPath, this.config.bbWorkingDirectory, proofPath, publicInputs, vkPath, logger));
268
- }
269
- async verifyWithKey(flavor, verificationKey, proof) {
270
- return await this.verifyWithKeyInternal(proof, verificationKey, (proofPath, vkPath)=>verifyProof(this.config.bbBinaryPath, proofPath, vkPath, flavor, logger));
271
- }
272
- async verifyWithKeyInternal(proof, verificationKey, verificationFunction) {
273
- const operation = async (bbWorkingDirectory)=>{
274
- const publicInputsFileName = path.join(bbWorkingDirectory, PUBLIC_INPUTS_FILENAME);
275
- const proofFileName = path.join(bbWorkingDirectory, PROOF_FILENAME);
276
- const verificationKeyPath = path.join(bbWorkingDirectory, VK_FILENAME);
277
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/13189): Put this proof parsing logic in the proof class.
278
- await fs.writeFile(publicInputsFileName, proof.buffer.slice(0, proof.numPublicInputs * 32));
279
- await fs.writeFile(proofFileName, proof.buffer.slice(proof.numPublicInputs * 32));
280
- await fs.writeFile(verificationKeyPath, verificationKey.keyAsBytes);
281
- const result = await verificationFunction(proofFileName, verificationKeyPath);
282
- if (result.status === BB_RESULT.FAILURE) {
283
- const errorMessage = `Failed to verify proof from key!`;
284
- throw new ProvingError(errorMessage, result, result.retry);
758
+ const flavor = getUltraHonkFlavorForCircuit(circuitType);
759
+ // Split proof buffer into public input fields and proof fields (32-byte each)
760
+ const publicInputFields = splitBufferToFieldArrays(proof.buffer.subarray(0, proof.numPublicInputs * 32));
761
+ const proofFields = splitBufferToFieldArrays(proof.buffer.subarray(proof.numPublicInputs * 32));
762
+ let verified;
763
+ let durationMs;
764
+ try {
765
+ const env = {
766
+ stack: [],
767
+ error: void 0,
768
+ hasError: false
769
+ };
770
+ try {
771
+ const instance = _ts_add_disposable_resource(env, await this.bbJsFactory.getInstance(), true);
772
+ ({ verified, durationMs } = await instance.verifyProof(proofFields, verificationKey.keyAsBytes, publicInputFields, flavor));
773
+ } catch (e) {
774
+ env.error = e;
775
+ env.hasError = true;
776
+ } finally{
777
+ const result = _ts_dispose_resources(env);
778
+ if (result) await result;
285
779
  }
286
- logger.info(`Successfully verified proof from key in ${result.durationMs} ms`);
780
+ } catch (error) {
781
+ throw new ProvingError(`Failed to verify proof for ${circuitType}: ${error}`);
782
+ }
783
+ if (!verified) {
784
+ throw new ProvingError('Failed to verify proof from key!');
785
+ }
786
+ logger.info(`Successfully verified proof from key in ${durationMs} ms`);
787
+ }
788
+ /** Verify an AVM proof via bb.js API. */ async verifyAvmProof(proof, publicInputs) {
789
+ const env = {
790
+ stack: [],
791
+ error: void 0,
792
+ hasError: false
287
793
  };
288
- await this.runInDirectory(operation);
794
+ try {
795
+ // For AVM proofs, numPublicInputs is 0, so the full buffer is the proof.
796
+ const proofBuffer = proof.buffer.subarray(proof.numPublicInputs * 32);
797
+ // Split the raw proof buffer into 32-byte field element arrays
798
+ const proofFields = [];
799
+ for(let i = 0; i < proofBuffer.length; i += Fr.SIZE_IN_BYTES){
800
+ proofFields.push(new Uint8Array(proofBuffer.subarray(i, i + Fr.SIZE_IN_BYTES)));
801
+ }
802
+ const piBuffer = publicInputs.serializeWithMessagePack();
803
+ const instance = _ts_add_disposable_resource(env, await this.bbJsFactory.getInstance(), true);
804
+ const { verified, durationMs } = await instance.verifyAvmProof(proofFields, piBuffer);
805
+ if (!verified) {
806
+ throw new ProvingError('Failed to verify AVM proof!');
807
+ }
808
+ logger.info(`Successfully verified AVM proof in ${durationMs} ms`);
809
+ } catch (e) {
810
+ env.error = e;
811
+ env.hasError = true;
812
+ } finally{
813
+ const result = _ts_dispose_resources(env);
814
+ if (result) await result;
815
+ }
289
816
  }
290
817
  /**
291
818
  * Returns the verification key data for a circuit.
@@ -298,20 +825,6 @@ const logger = createLogger('bb-prover');
298
825
  }
299
826
  return vk;
300
827
  }
301
- async readAvmProofAsFields(proofFilename) {
302
- const rawProofBuffer = await fs.readFile(proofFilename);
303
- const reader = BufferReader.asReader(rawProofBuffer);
304
- const proofFields = reader.readArray(rawProofBuffer.length / Fr.SIZE_IN_BYTES, Fr);
305
- // We extend to a fixed-size padded proof as during development any new AVM circuit column changes the
306
- // proof length and we do not have a mechanism to feedback a cpp constant to noir/TS.
307
- // TODO(#13390): Revive a non-padded AVM proof
308
- if (proofFields.length > AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED) {
309
- throw new Error(`Proof has ${proofFields.length} fields, expected no more than ${AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED}.`);
310
- }
311
- const proofFieldsPadded = proofFields.concat(Array(AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED - proofFields.length).fill(new Fr(0)));
312
- const proof = new Proof(rawProofBuffer, /*numPublicInputs=*/ 0);
313
- return new RecursiveProof(proofFieldsPadded, proof, true, AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED);
314
- }
315
828
  runInDirectory(fn) {
316
829
  return runInDirectory(this.config.bbWorkingDirectory, (dir)=>fn(dir).catch((err)=>{
317
830
  logger.error(`Error running operation at ${dir}: ${err}`);
@@ -319,18 +832,10 @@ const logger = createLogger('bb-prover');
319
832
  }), this.config.bbSkipCleanup, logger);
320
833
  }
321
834
  }
322
- _ts_decorate([
323
- trackSpan('BBNativeRollupProver.getBaseParityProof', {
324
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-base'
325
- })
326
- ], BBNativeRollupProver.prototype, "getBaseParityProof", null);
327
- _ts_decorate([
328
- trackSpan('BBNativeRollupProver.getRootParityProof', {
329
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'parity-root'
330
- })
331
- ], BBNativeRollupProver.prototype, "getRootParityProof", null);
332
- _ts_decorate([
333
- trackSpan('BBNativeRollupProver.getAvmProof', (inputs)=>({
334
- [Attributes.APP_CIRCUIT_NAME]: inputs.hints.tx.hash
335
- }))
336
- ], BBNativeRollupProver.prototype, "getAvmProof", null);
835
+ /** Split a buffer into 32-byte Uint8Array field elements. */ function splitBufferToFieldArrays(buffer) {
836
+ const fields = [];
837
+ for(let i = 0; i < buffer.length; i += 32){
838
+ fields.push(new Uint8Array(buffer.subarray(i, i + 32)));
839
+ }
840
+ return fields;
841
+ }