@voter-protocol/noir-prover 0.1.2 → 0.1.3

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.
@@ -1,1375 +0,0 @@
1
- (function () {
2
- 'use strict';
3
-
4
- /**
5
- * @license
6
- * Copyright 2019 Google LLC
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
9
- const proxyMarker = Symbol("Comlink.proxy");
10
- const createEndpoint = Symbol("Comlink.endpoint");
11
- const releaseProxy = Symbol("Comlink.releaseProxy");
12
- const finalizer = Symbol("Comlink.finalizer");
13
- const throwMarker = Symbol("Comlink.thrown");
14
- const isObject = (val) => (typeof val === "object" && val !== null) || typeof val === "function";
15
- /**
16
- * Internal transfer handle to handle objects marked to proxy.
17
- */
18
- const proxyTransferHandler = {
19
- canHandle: (val) => isObject(val) && val[proxyMarker],
20
- serialize(obj) {
21
- const { port1, port2 } = new MessageChannel();
22
- expose(obj, port1);
23
- return [port2, [port2]];
24
- },
25
- deserialize(port) {
26
- port.start();
27
- return wrap(port);
28
- },
29
- };
30
- /**
31
- * Internal transfer handler to handle thrown exceptions.
32
- */
33
- const throwTransferHandler = {
34
- canHandle: (value) => isObject(value) && throwMarker in value,
35
- serialize({ value }) {
36
- let serialized;
37
- if (value instanceof Error) {
38
- serialized = {
39
- isError: true,
40
- value: {
41
- message: value.message,
42
- name: value.name,
43
- stack: value.stack,
44
- },
45
- };
46
- }
47
- else {
48
- serialized = { isError: false, value };
49
- }
50
- return [serialized, []];
51
- },
52
- deserialize(serialized) {
53
- if (serialized.isError) {
54
- throw Object.assign(new Error(serialized.value.message), serialized.value);
55
- }
56
- throw serialized.value;
57
- },
58
- };
59
- /**
60
- * Allows customizing the serialization of certain values.
61
- */
62
- const transferHandlers = new Map([
63
- ["proxy", proxyTransferHandler],
64
- ["throw", throwTransferHandler],
65
- ]);
66
- function isAllowedOrigin(allowedOrigins, origin) {
67
- for (const allowedOrigin of allowedOrigins) {
68
- if (origin === allowedOrigin || allowedOrigin === "*") {
69
- return true;
70
- }
71
- if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {
72
- return true;
73
- }
74
- }
75
- return false;
76
- }
77
- function expose(obj, ep = globalThis, allowedOrigins = ["*"]) {
78
- ep.addEventListener("message", function callback(ev) {
79
- if (!ev || !ev.data) {
80
- return;
81
- }
82
- if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
83
- console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
84
- return;
85
- }
86
- const { id, type, path } = Object.assign({ path: [] }, ev.data);
87
- const argumentList = (ev.data.argumentList || []).map(fromWireValue);
88
- let returnValue;
89
- try {
90
- const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);
91
- const rawValue = path.reduce((obj, prop) => obj[prop], obj);
92
- switch (type) {
93
- case "GET" /* MessageType.GET */:
94
- {
95
- returnValue = rawValue;
96
- }
97
- break;
98
- case "SET" /* MessageType.SET */:
99
- {
100
- parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
101
- returnValue = true;
102
- }
103
- break;
104
- case "APPLY" /* MessageType.APPLY */:
105
- {
106
- returnValue = rawValue.apply(parent, argumentList);
107
- }
108
- break;
109
- case "CONSTRUCT" /* MessageType.CONSTRUCT */:
110
- {
111
- const value = new rawValue(...argumentList);
112
- returnValue = proxy(value);
113
- }
114
- break;
115
- case "ENDPOINT" /* MessageType.ENDPOINT */:
116
- {
117
- const { port1, port2 } = new MessageChannel();
118
- expose(obj, port2);
119
- returnValue = transfer(port1, [port1]);
120
- }
121
- break;
122
- case "RELEASE" /* MessageType.RELEASE */:
123
- {
124
- returnValue = undefined;
125
- }
126
- break;
127
- default:
128
- return;
129
- }
130
- }
131
- catch (value) {
132
- returnValue = { value, [throwMarker]: 0 };
133
- }
134
- Promise.resolve(returnValue)
135
- .catch((value) => {
136
- return { value, [throwMarker]: 0 };
137
- })
138
- .then((returnValue) => {
139
- const [wireValue, transferables] = toWireValue(returnValue);
140
- ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
141
- if (type === "RELEASE" /* MessageType.RELEASE */) {
142
- // detach and deactive after sending release response above.
143
- ep.removeEventListener("message", callback);
144
- closeEndPoint(ep);
145
- if (finalizer in obj && typeof obj[finalizer] === "function") {
146
- obj[finalizer]();
147
- }
148
- }
149
- })
150
- .catch((error) => {
151
- // Send Serialization Error To Caller
152
- const [wireValue, transferables] = toWireValue({
153
- value: new TypeError("Unserializable return value"),
154
- [throwMarker]: 0,
155
- });
156
- ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
157
- });
158
- });
159
- if (ep.start) {
160
- ep.start();
161
- }
162
- }
163
- function isMessagePort(endpoint) {
164
- return endpoint.constructor.name === "MessagePort";
165
- }
166
- function closeEndPoint(endpoint) {
167
- if (isMessagePort(endpoint))
168
- endpoint.close();
169
- }
170
- function wrap(ep, target) {
171
- const pendingListeners = new Map();
172
- ep.addEventListener("message", function handleMessage(ev) {
173
- const { data } = ev;
174
- if (!data || !data.id) {
175
- return;
176
- }
177
- const resolver = pendingListeners.get(data.id);
178
- if (!resolver) {
179
- return;
180
- }
181
- try {
182
- resolver(data);
183
- }
184
- finally {
185
- pendingListeners.delete(data.id);
186
- }
187
- });
188
- return createProxy(ep, pendingListeners, [], target);
189
- }
190
- function throwIfProxyReleased(isReleased) {
191
- if (isReleased) {
192
- throw new Error("Proxy has been released and is not useable");
193
- }
194
- }
195
- function releaseEndpoint(ep) {
196
- return requestResponseMessage(ep, new Map(), {
197
- type: "RELEASE" /* MessageType.RELEASE */,
198
- }).then(() => {
199
- closeEndPoint(ep);
200
- });
201
- }
202
- const proxyCounter = new WeakMap();
203
- const proxyFinalizers = "FinalizationRegistry" in globalThis &&
204
- new FinalizationRegistry((ep) => {
205
- const newCount = (proxyCounter.get(ep) || 0) - 1;
206
- proxyCounter.set(ep, newCount);
207
- if (newCount === 0) {
208
- releaseEndpoint(ep);
209
- }
210
- });
211
- function registerProxy(proxy, ep) {
212
- const newCount = (proxyCounter.get(ep) || 0) + 1;
213
- proxyCounter.set(ep, newCount);
214
- if (proxyFinalizers) {
215
- proxyFinalizers.register(proxy, ep, proxy);
216
- }
217
- }
218
- function unregisterProxy(proxy) {
219
- if (proxyFinalizers) {
220
- proxyFinalizers.unregister(proxy);
221
- }
222
- }
223
- function createProxy(ep, pendingListeners, path = [], target = function () { }) {
224
- let isProxyReleased = false;
225
- const proxy = new Proxy(target, {
226
- get(_target, prop) {
227
- throwIfProxyReleased(isProxyReleased);
228
- if (prop === releaseProxy) {
229
- return () => {
230
- unregisterProxy(proxy);
231
- releaseEndpoint(ep);
232
- pendingListeners.clear();
233
- isProxyReleased = true;
234
- };
235
- }
236
- if (prop === "then") {
237
- if (path.length === 0) {
238
- return { then: () => proxy };
239
- }
240
- const r = requestResponseMessage(ep, pendingListeners, {
241
- type: "GET" /* MessageType.GET */,
242
- path: path.map((p) => p.toString()),
243
- }).then(fromWireValue);
244
- return r.then.bind(r);
245
- }
246
- return createProxy(ep, pendingListeners, [...path, prop]);
247
- },
248
- set(_target, prop, rawValue) {
249
- throwIfProxyReleased(isProxyReleased);
250
- // FIXME: ES6 Proxy Handler `set` methods are supposed to return a
251
- // boolean. To show good will, we return true asynchronously ¯\_(ツ)_/¯
252
- const [value, transferables] = toWireValue(rawValue);
253
- return requestResponseMessage(ep, pendingListeners, {
254
- type: "SET" /* MessageType.SET */,
255
- path: [...path, prop].map((p) => p.toString()),
256
- value,
257
- }, transferables).then(fromWireValue);
258
- },
259
- apply(_target, _thisArg, rawArgumentList) {
260
- throwIfProxyReleased(isProxyReleased);
261
- const last = path[path.length - 1];
262
- if (last === createEndpoint) {
263
- return requestResponseMessage(ep, pendingListeners, {
264
- type: "ENDPOINT" /* MessageType.ENDPOINT */,
265
- }).then(fromWireValue);
266
- }
267
- // We just pretend that `bind()` didn’t happen.
268
- if (last === "bind") {
269
- return createProxy(ep, pendingListeners, path.slice(0, -1));
270
- }
271
- const [argumentList, transferables] = processArguments(rawArgumentList);
272
- return requestResponseMessage(ep, pendingListeners, {
273
- type: "APPLY" /* MessageType.APPLY */,
274
- path: path.map((p) => p.toString()),
275
- argumentList,
276
- }, transferables).then(fromWireValue);
277
- },
278
- construct(_target, rawArgumentList) {
279
- throwIfProxyReleased(isProxyReleased);
280
- const [argumentList, transferables] = processArguments(rawArgumentList);
281
- return requestResponseMessage(ep, pendingListeners, {
282
- type: "CONSTRUCT" /* MessageType.CONSTRUCT */,
283
- path: path.map((p) => p.toString()),
284
- argumentList,
285
- }, transferables).then(fromWireValue);
286
- },
287
- });
288
- registerProxy(proxy, ep);
289
- return proxy;
290
- }
291
- function myFlat(arr) {
292
- return Array.prototype.concat.apply([], arr);
293
- }
294
- function processArguments(argumentList) {
295
- const processed = argumentList.map(toWireValue);
296
- return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
297
- }
298
- const transferCache = new WeakMap();
299
- function transfer(obj, transfers) {
300
- transferCache.set(obj, transfers);
301
- return obj;
302
- }
303
- function proxy(obj) {
304
- return Object.assign(obj, { [proxyMarker]: true });
305
- }
306
- function toWireValue(value) {
307
- for (const [name, handler] of transferHandlers) {
308
- if (handler.canHandle(value)) {
309
- const [serializedValue, transferables] = handler.serialize(value);
310
- return [
311
- {
312
- type: "HANDLER" /* WireValueType.HANDLER */,
313
- name,
314
- value: serializedValue,
315
- },
316
- transferables,
317
- ];
318
- }
319
- }
320
- return [
321
- {
322
- type: "RAW" /* WireValueType.RAW */,
323
- value,
324
- },
325
- transferCache.get(value) || [],
326
- ];
327
- }
328
- function fromWireValue(value) {
329
- switch (value.type) {
330
- case "HANDLER" /* WireValueType.HANDLER */:
331
- return transferHandlers.get(value.name).deserialize(value.value);
332
- case "RAW" /* WireValueType.RAW */:
333
- return value.value;
334
- }
335
- }
336
- function requestResponseMessage(ep, pendingListeners, msg, transfers) {
337
- return new Promise((resolve) => {
338
- const id = generateUUID();
339
- pendingListeners.set(id, resolve);
340
- if (ep.start) {
341
- ep.start();
342
- }
343
- ep.postMessage(Object.assign({ id }, msg), transfers);
344
- });
345
- }
346
- function generateUUID() {
347
- return new Array(4)
348
- .fill(0)
349
- .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))
350
- .join("-");
351
- }
352
-
353
- function getSharedMemoryAvailable() {
354
- const globalScope = typeof window !== 'undefined' ? window : globalThis;
355
- return typeof SharedArrayBuffer !== 'undefined' && globalScope.crossOriginIsolated;
356
- }
357
- function getRemoteBarretenbergWasm(worker) {
358
- return wrap(worker);
359
- }
360
- function getNumCpu() {
361
- return navigator.hardwareConcurrency;
362
- }
363
- // Solution to async initialization of workers, taken from
364
- // https://github.com/GoogleChromeLabs/comlink/issues/635#issuecomment-1598913044
365
- /** The message expected by the `readinessListener`. */
366
- const Ready = { ready: true };
367
- /** Listen for the readiness message from the Worker and call the `callback` once. */
368
- function readinessListener(worker, callback) {
369
- worker.addEventListener('message', function ready(event) {
370
- if (!!event.data && event.data.ready === true) {
371
- worker.removeEventListener('message', ready);
372
- callback();
373
- }
374
- });
375
- }
376
-
377
- var browser = {exports: {}};
378
-
379
- function tryStringify (o) {
380
- try { return JSON.stringify(o) } catch(e) { return '"[Circular]"' }
381
- }
382
-
383
- var quickFormatUnescaped = format$1;
384
-
385
- function format$1(f, args, opts) {
386
- var ss = (opts && opts.stringify) || tryStringify;
387
- var offset = 1;
388
- if (typeof f === 'object' && f !== null) {
389
- var len = args.length + offset;
390
- if (len === 1) return f
391
- var objects = new Array(len);
392
- objects[0] = ss(f);
393
- for (var index = 1; index < len; index++) {
394
- objects[index] = ss(args[index]);
395
- }
396
- return objects.join(' ')
397
- }
398
- if (typeof f !== 'string') {
399
- return f
400
- }
401
- var argLen = args.length;
402
- if (argLen === 0) return f
403
- var str = '';
404
- var a = 1 - offset;
405
- var lastPos = -1;
406
- var flen = (f && f.length) || 0;
407
- for (var i = 0; i < flen;) {
408
- if (f.charCodeAt(i) === 37 && i + 1 < flen) {
409
- lastPos = lastPos > -1 ? lastPos : 0;
410
- switch (f.charCodeAt(i + 1)) {
411
- case 100: // 'd'
412
- case 102: // 'f'
413
- if (a >= argLen)
414
- break
415
- if (args[a] == null) break
416
- if (lastPos < i)
417
- str += f.slice(lastPos, i);
418
- str += Number(args[a]);
419
- lastPos = i + 2;
420
- i++;
421
- break
422
- case 105: // 'i'
423
- if (a >= argLen)
424
- break
425
- if (args[a] == null) break
426
- if (lastPos < i)
427
- str += f.slice(lastPos, i);
428
- str += Math.floor(Number(args[a]));
429
- lastPos = i + 2;
430
- i++;
431
- break
432
- case 79: // 'O'
433
- case 111: // 'o'
434
- case 106: // 'j'
435
- if (a >= argLen)
436
- break
437
- if (args[a] === undefined) break
438
- if (lastPos < i)
439
- str += f.slice(lastPos, i);
440
- var type = typeof args[a];
441
- if (type === 'string') {
442
- str += '\'' + args[a] + '\'';
443
- lastPos = i + 2;
444
- i++;
445
- break
446
- }
447
- if (type === 'function') {
448
- str += args[a].name || '<anonymous>';
449
- lastPos = i + 2;
450
- i++;
451
- break
452
- }
453
- str += ss(args[a]);
454
- lastPos = i + 2;
455
- i++;
456
- break
457
- case 115: // 's'
458
- if (a >= argLen)
459
- break
460
- if (lastPos < i)
461
- str += f.slice(lastPos, i);
462
- str += String(args[a]);
463
- lastPos = i + 2;
464
- i++;
465
- break
466
- case 37: // '%'
467
- if (lastPos < i)
468
- str += f.slice(lastPos, i);
469
- str += '%';
470
- lastPos = i + 2;
471
- i++;
472
- a--;
473
- break
474
- }
475
- ++a;
476
- }
477
- ++i;
478
- }
479
- if (lastPos === -1)
480
- return f
481
- else if (lastPos < flen) {
482
- str += f.slice(lastPos);
483
- }
484
-
485
- return str
486
- }
487
-
488
- const format = quickFormatUnescaped;
489
-
490
- browser.exports = pino;
491
-
492
- const _console = pfGlobalThisOrFallback().console || {};
493
- const stdSerializers = {
494
- mapHttpRequest: mock,
495
- mapHttpResponse: mock,
496
- wrapRequestSerializer: passthrough,
497
- wrapResponseSerializer: passthrough,
498
- wrapErrorSerializer: passthrough,
499
- req: mock,
500
- res: mock,
501
- err: asErrValue,
502
- errWithCause: asErrValue
503
- };
504
- function levelToValue (level, logger) {
505
- return level === 'silent'
506
- ? Infinity
507
- : logger.levels.values[level]
508
- }
509
- const baseLogFunctionSymbol = Symbol('pino.logFuncs');
510
- const hierarchySymbol = Symbol('pino.hierarchy');
511
-
512
- const logFallbackMap = {
513
- error: 'log',
514
- fatal: 'error',
515
- warn: 'error',
516
- info: 'log',
517
- debug: 'log',
518
- trace: 'log'
519
- };
520
-
521
- function appendChildLogger (parentLogger, childLogger) {
522
- const newEntry = {
523
- logger: childLogger,
524
- parent: parentLogger[hierarchySymbol]
525
- };
526
- childLogger[hierarchySymbol] = newEntry;
527
- }
528
-
529
- function setupBaseLogFunctions (logger, levels, proto) {
530
- const logFunctions = {};
531
- levels.forEach(level => {
532
- logFunctions[level] = proto[level] ? proto[level] : (_console[level] || _console[logFallbackMap[level] || 'log'] || noop);
533
- });
534
- logger[baseLogFunctionSymbol] = logFunctions;
535
- }
536
-
537
- function shouldSerialize (serialize, serializers) {
538
- if (Array.isArray(serialize)) {
539
- const hasToFilter = serialize.filter(function (k) {
540
- return k !== '!stdSerializers.err'
541
- });
542
- return hasToFilter
543
- } else if (serialize === true) {
544
- return Object.keys(serializers)
545
- }
546
-
547
- return false
548
- }
549
-
550
- function pino (opts) {
551
- opts = opts || {};
552
- opts.browser = opts.browser || {};
553
-
554
- const transmit = opts.browser.transmit;
555
- if (transmit && typeof transmit.send !== 'function') { throw Error('pino: transmit option must have a send function') }
556
-
557
- const proto = opts.browser.write || _console;
558
- if (opts.browser.write) opts.browser.asObject = true;
559
- const serializers = opts.serializers || {};
560
- const serialize = shouldSerialize(opts.browser.serialize, serializers);
561
- let stdErrSerialize = opts.browser.serialize;
562
-
563
- if (
564
- Array.isArray(opts.browser.serialize) &&
565
- opts.browser.serialize.indexOf('!stdSerializers.err') > -1
566
- ) stdErrSerialize = false;
567
-
568
- const customLevels = Object.keys(opts.customLevels || {});
569
- const levels = ['error', 'fatal', 'warn', 'info', 'debug', 'trace'].concat(customLevels);
570
-
571
- if (typeof proto === 'function') {
572
- levels.forEach(function (level) {
573
- proto[level] = proto;
574
- });
575
- }
576
- if (opts.enabled === false || opts.browser.disabled) opts.level = 'silent';
577
- const level = opts.level || 'info';
578
- const logger = Object.create(proto);
579
- if (!logger.log) logger.log = noop;
580
-
581
- setupBaseLogFunctions(logger, levels, proto);
582
- // setup root hierarchy entry
583
- appendChildLogger({}, logger);
584
-
585
- Object.defineProperty(logger, 'levelVal', {
586
- get: getLevelVal
587
- });
588
- Object.defineProperty(logger, 'level', {
589
- get: getLevel,
590
- set: setLevel
591
- });
592
-
593
- const setOpts = {
594
- transmit,
595
- serialize,
596
- asObject: opts.browser.asObject,
597
- asObjectBindingsOnly: opts.browser.asObjectBindingsOnly,
598
- formatters: opts.browser.formatters,
599
- levels,
600
- timestamp: getTimeFunction(opts),
601
- messageKey: opts.messageKey || 'msg',
602
- onChild: opts.onChild || noop
603
- };
604
- logger.levels = getLevels(opts);
605
- logger.level = level;
606
-
607
- logger.isLevelEnabled = function (level) {
608
- if (!this.levels.values[level]) {
609
- return false
610
- }
611
-
612
- return this.levels.values[level] >= this.levels.values[this.level]
613
- };
614
- logger.setMaxListeners = logger.getMaxListeners =
615
- logger.emit = logger.addListener = logger.on =
616
- logger.prependListener = logger.once =
617
- logger.prependOnceListener = logger.removeListener =
618
- logger.removeAllListeners = logger.listeners =
619
- logger.listenerCount = logger.eventNames =
620
- logger.write = logger.flush = noop;
621
- logger.serializers = serializers;
622
- logger._serialize = serialize;
623
- logger._stdErrSerialize = stdErrSerialize;
624
- logger.child = function (...args) { return child.call(this, setOpts, ...args) };
625
-
626
- if (transmit) logger._logEvent = createLogEventShape();
627
-
628
- function getLevelVal () {
629
- return levelToValue(this.level, this)
630
- }
631
-
632
- function getLevel () {
633
- return this._level
634
- }
635
- function setLevel (level) {
636
- if (level !== 'silent' && !this.levels.values[level]) {
637
- throw Error('unknown level ' + level)
638
- }
639
- this._level = level;
640
-
641
- set(this, setOpts, logger, 'error'); // <-- must stay first
642
- set(this, setOpts, logger, 'fatal');
643
- set(this, setOpts, logger, 'warn');
644
- set(this, setOpts, logger, 'info');
645
- set(this, setOpts, logger, 'debug');
646
- set(this, setOpts, logger, 'trace');
647
-
648
- customLevels.forEach((level) => {
649
- set(this, setOpts, logger, level);
650
- });
651
- }
652
-
653
- function child (setOpts, bindings, childOptions) {
654
- if (!bindings) {
655
- throw new Error('missing bindings for child Pino')
656
- }
657
- childOptions = childOptions || {};
658
- if (serialize && bindings.serializers) {
659
- childOptions.serializers = bindings.serializers;
660
- }
661
- const childOptionsSerializers = childOptions.serializers;
662
- if (serialize && childOptionsSerializers) {
663
- var childSerializers = Object.assign({}, serializers, childOptionsSerializers);
664
- var childSerialize = opts.browser.serialize === true
665
- ? Object.keys(childSerializers)
666
- : serialize;
667
- delete bindings.serializers;
668
- applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize);
669
- }
670
- function Child (parent) {
671
- this._childLevel = (parent._childLevel | 0) + 1;
672
-
673
- // make sure bindings are available in the `set` function
674
- this.bindings = bindings;
675
-
676
- if (childSerializers) {
677
- this.serializers = childSerializers;
678
- this._serialize = childSerialize;
679
- }
680
- if (transmit) {
681
- this._logEvent = createLogEventShape(
682
- [].concat(parent._logEvent.bindings, bindings)
683
- );
684
- }
685
- }
686
- Child.prototype = this;
687
- const newLogger = new Child(this);
688
-
689
- // must happen before the level is assigned
690
- appendChildLogger(this, newLogger);
691
- newLogger.child = function (...args) { return child.call(this, setOpts, ...args) };
692
- // required to actually initialize the logger functions for any given child
693
- newLogger.level = childOptions.level || this.level; // allow level to be set by childOptions
694
- setOpts.onChild(newLogger);
695
-
696
- return newLogger
697
- }
698
- return logger
699
- }
700
-
701
- function getLevels (opts) {
702
- const customLevels = opts.customLevels || {};
703
-
704
- const values = Object.assign({}, pino.levels.values, customLevels);
705
- const labels = Object.assign({}, pino.levels.labels, invertObject(customLevels));
706
-
707
- return {
708
- values,
709
- labels
710
- }
711
- }
712
-
713
- function invertObject (obj) {
714
- const inverted = {};
715
- Object.keys(obj).forEach(function (key) {
716
- inverted[obj[key]] = key;
717
- });
718
- return inverted
719
- }
720
-
721
- pino.levels = {
722
- values: {
723
- fatal: 60,
724
- error: 50,
725
- warn: 40,
726
- info: 30,
727
- debug: 20,
728
- trace: 10
729
- },
730
- labels: {
731
- 10: 'trace',
732
- 20: 'debug',
733
- 30: 'info',
734
- 40: 'warn',
735
- 50: 'error',
736
- 60: 'fatal'
737
- }
738
- };
739
-
740
- pino.stdSerializers = stdSerializers;
741
- pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime });
742
-
743
- function getBindingChain (logger) {
744
- const bindings = [];
745
- if (logger.bindings) {
746
- bindings.push(logger.bindings);
747
- }
748
-
749
- // traverse up the tree to get all bindings
750
- let hierarchy = logger[hierarchySymbol];
751
- while (hierarchy.parent) {
752
- hierarchy = hierarchy.parent;
753
- if (hierarchy.logger.bindings) {
754
- bindings.push(hierarchy.logger.bindings);
755
- }
756
- }
757
-
758
- return bindings.reverse()
759
- }
760
-
761
- function set (self, opts, rootLogger, level) {
762
- // override the current log functions with either `noop` or the base log function
763
- Object.defineProperty(self, level, {
764
- value: (levelToValue(self.level, rootLogger) > levelToValue(level, rootLogger)
765
- ? noop
766
- : rootLogger[baseLogFunctionSymbol][level]),
767
- writable: true,
768
- enumerable: true,
769
- configurable: true
770
- });
771
-
772
- if (self[level] === noop) {
773
- if (!opts.transmit) return
774
-
775
- const transmitLevel = opts.transmit.level || self.level;
776
- const transmitValue = levelToValue(transmitLevel, rootLogger);
777
- const methodValue = levelToValue(level, rootLogger);
778
- if (methodValue < transmitValue) return
779
- }
780
-
781
- // make sure the log format is correct
782
- self[level] = createWrap(self, opts, rootLogger, level);
783
-
784
- // prepend bindings if it is not the root logger
785
- const bindings = getBindingChain(self);
786
- if (bindings.length === 0) {
787
- // early exit in case for rootLogger
788
- return
789
- }
790
- self[level] = prependBindingsInArguments(bindings, self[level]);
791
- }
792
-
793
- function prependBindingsInArguments (bindings, logFunc) {
794
- return function () {
795
- return logFunc.apply(this, [...bindings, ...arguments])
796
- }
797
- }
798
-
799
- function createWrap (self, opts, rootLogger, level) {
800
- return (function (write) {
801
- return function LOG () {
802
- const ts = opts.timestamp();
803
- const args = new Array(arguments.length);
804
- const proto = (Object.getPrototypeOf && Object.getPrototypeOf(this) === _console) ? _console : this;
805
- for (var i = 0; i < args.length; i++) args[i] = arguments[i];
806
-
807
- var argsIsSerialized = false;
808
- if (opts.serialize) {
809
- applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize);
810
- argsIsSerialized = true;
811
- }
812
- if (opts.asObject || opts.formatters) {
813
- write.call(proto, ...asObject(this, level, args, ts, opts));
814
- } else write.apply(proto, args);
815
-
816
- if (opts.transmit) {
817
- const transmitLevel = opts.transmit.level || self._level;
818
- const transmitValue = levelToValue(transmitLevel, rootLogger);
819
- const methodValue = levelToValue(level, rootLogger);
820
- if (methodValue < transmitValue) return
821
- transmit(this, {
822
- ts,
823
- methodLevel: level,
824
- methodValue,
825
- transmitValue: rootLogger.levels.values[opts.transmit.level || self._level],
826
- send: opts.transmit.send,
827
- val: levelToValue(self._level, rootLogger)
828
- }, args, argsIsSerialized);
829
- }
830
- }
831
- })(self[baseLogFunctionSymbol][level])
832
- }
833
-
834
- function asObject (logger, level, args, ts, opts) {
835
- const {
836
- level: levelFormatter,
837
- log: logObjectFormatter = (obj) => obj
838
- } = opts.formatters || {};
839
- const argsCloned = args.slice();
840
- let msg = argsCloned[0];
841
- const logObject = {};
842
-
843
- let lvl = (logger._childLevel | 0) + 1;
844
- if (lvl < 1) lvl = 1;
845
-
846
- if (ts) {
847
- logObject.time = ts;
848
- }
849
-
850
- if (levelFormatter) {
851
- const formattedLevel = levelFormatter(level, logger.levels.values[level]);
852
- Object.assign(logObject, formattedLevel);
853
- } else {
854
- logObject.level = logger.levels.values[level];
855
- }
856
-
857
- if (opts.asObjectBindingsOnly) {
858
- if (msg !== null && typeof msg === 'object') {
859
- while (lvl-- && typeof argsCloned[0] === 'object') {
860
- Object.assign(logObject, argsCloned.shift());
861
- }
862
- }
863
-
864
- const formattedLogObject = logObjectFormatter(logObject);
865
- return [formattedLogObject, ...argsCloned]
866
- } else {
867
- // deliberate, catching objects, arrays
868
- if (msg !== null && typeof msg === 'object') {
869
- while (lvl-- && typeof argsCloned[0] === 'object') {
870
- Object.assign(logObject, argsCloned.shift());
871
- }
872
- msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : undefined;
873
- } else if (typeof msg === 'string') msg = format(argsCloned.shift(), argsCloned);
874
- if (msg !== undefined) logObject[opts.messageKey] = msg;
875
-
876
- const formattedLogObject = logObjectFormatter(logObject);
877
- return [formattedLogObject]
878
- }
879
- }
880
-
881
- function applySerializers (args, serialize, serializers, stdErrSerialize) {
882
- for (const i in args) {
883
- if (stdErrSerialize && args[i] instanceof Error) {
884
- args[i] = pino.stdSerializers.err(args[i]);
885
- } else if (typeof args[i] === 'object' && !Array.isArray(args[i]) && serialize) {
886
- for (const k in args[i]) {
887
- if (serialize.indexOf(k) > -1 && k in serializers) {
888
- args[i][k] = serializers[k](args[i][k]);
889
- }
890
- }
891
- }
892
- }
893
- }
894
-
895
- function transmit (logger, opts, args, argsIsSerialized = false) {
896
- const send = opts.send;
897
- const ts = opts.ts;
898
- const methodLevel = opts.methodLevel;
899
- const methodValue = opts.methodValue;
900
- const val = opts.val;
901
- const bindings = logger._logEvent.bindings;
902
-
903
- if (!argsIsSerialized) {
904
- applySerializers(
905
- args,
906
- logger._serialize || Object.keys(logger.serializers),
907
- logger.serializers,
908
- logger._stdErrSerialize === undefined ? true : logger._stdErrSerialize
909
- );
910
- }
911
-
912
- logger._logEvent.ts = ts;
913
- logger._logEvent.messages = args.filter(function (arg) {
914
- // bindings can only be objects, so reference equality check via indexOf is fine
915
- return bindings.indexOf(arg) === -1
916
- });
917
-
918
- logger._logEvent.level.label = methodLevel;
919
- logger._logEvent.level.value = methodValue;
920
-
921
- send(methodLevel, logger._logEvent, val);
922
-
923
- logger._logEvent = createLogEventShape(bindings);
924
- }
925
-
926
- function createLogEventShape (bindings) {
927
- return {
928
- ts: 0,
929
- messages: [],
930
- bindings: bindings || [],
931
- level: { label: '', value: 0 }
932
- }
933
- }
934
-
935
- function asErrValue (err) {
936
- const obj = {
937
- type: err.constructor.name,
938
- msg: err.message,
939
- stack: err.stack
940
- };
941
- for (const key in err) {
942
- if (obj[key] === undefined) {
943
- obj[key] = err[key];
944
- }
945
- }
946
- return obj
947
- }
948
-
949
- function getTimeFunction (opts) {
950
- if (typeof opts.timestamp === 'function') {
951
- return opts.timestamp
952
- }
953
- if (opts.timestamp === false) {
954
- return nullTime
955
- }
956
- return epochTime
957
- }
958
-
959
- function mock () { return {} }
960
- function passthrough (a) { return a }
961
- function noop () {}
962
-
963
- function nullTime () { return false }
964
- function epochTime () { return Date.now() }
965
- function unixTime () { return Math.round(Date.now() / 1000.0) }
966
- function isoTime () { return new Date(Date.now()).toISOString() } // using Date.now() for testability
967
-
968
- /* eslint-disable */
969
- /* istanbul ignore next */
970
- function pfGlobalThisOrFallback () {
971
- function defd (o) { return typeof o !== 'undefined' && o }
972
- try {
973
- if (typeof globalThis !== 'undefined') return globalThis
974
- Object.defineProperty(Object.prototype, 'globalThis', {
975
- get: function () {
976
- delete Object.prototype.globalThis;
977
- return (this.globalThis = this)
978
- },
979
- configurable: true
980
- });
981
- return globalThis
982
- } catch (e) {
983
- return defd(self) || defd(window) || defd(this) || {}
984
- }
985
- }
986
- /* eslint-enable */
987
-
988
- browser.exports.default = pino;
989
- var pino_1 = browser.exports.pino = pino;
990
-
991
- const defaultOptions = {
992
- name: 'bb.js',
993
- useOnlyCustomLevels: false,
994
- customLevels: { verbose: 25 },
995
- browser: { asObject: false },
996
- };
997
- // Options must be exposed so they can be provided to threads upon creation
998
- // This way we ensure all loggers are spawned with the same options
999
- let logOptions;
1000
- let logger;
1001
- function initLogger({ level = 'info' } = { level: 'info', useStdErr: false }) {
1002
- if (logger) {
1003
- return logger;
1004
- }
1005
- logOptions = { level, useStdErr: false };
1006
- logger = pino_1({ ...defaultOptions, level });
1007
- }
1008
- function createDebugLogger(name) {
1009
- initLogger();
1010
- const sublogger = logger.child({
1011
- name,
1012
- });
1013
- return (msg) => {
1014
- sublogger.debug(msg);
1015
- };
1016
- }
1017
-
1018
- async function createThreadWorker() {
1019
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1020
- // @ts-ignore
1021
- const worker = new Worker(new URL(/* @vite-ignore */ "/assets/thread.worker-I9-Z0yRJ.js", self.location.href), { type: 'module' });
1022
- worker.postMessage({ log: logOptions });
1023
- await new Promise(resolve => readinessListener(worker, resolve));
1024
- return worker;
1025
- }
1026
-
1027
- const randomBytes = (len) => {
1028
- const getWebCrypto = () => {
1029
- if (typeof window !== 'undefined' && window.crypto)
1030
- return window.crypto;
1031
- if (typeof globalThis !== 'undefined' && globalThis.crypto)
1032
- return globalThis.crypto;
1033
- return undefined;
1034
- };
1035
- const crypto = getWebCrypto();
1036
- if (!crypto) {
1037
- throw new Error('randomBytes UnsupportedEnvironment');
1038
- }
1039
- const buf = new Uint8Array(len);
1040
- // limit of Crypto.getRandomValues()
1041
- // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
1042
- const MAX_BYTES = 65536;
1043
- if (len > MAX_BYTES) {
1044
- // this is the max bytes crypto.getRandomValues
1045
- // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
1046
- for (let generated = 0; generated < len; generated += MAX_BYTES) {
1047
- // buffer.slice automatically checks if the end is past the end of
1048
- // the buffer so we don't have to here
1049
- crypto.getRandomValues(buf.subarray(generated, generated + MAX_BYTES));
1050
- }
1051
- }
1052
- else {
1053
- crypto.getRandomValues(buf);
1054
- }
1055
- return buf;
1056
- };
1057
-
1058
- /**
1059
- * Base implementation of BarretenbergWasm.
1060
- * Contains code that is common to the "main thread" implementation and the "child thread" implementation.
1061
- */
1062
- class BarretenbergWasmBase {
1063
- constructor() {
1064
- this.memStore = {};
1065
- this.logger = createDebugLogger('bb_wasm_base');
1066
- }
1067
- getImportObj(memory) {
1068
- /* eslint-disable camelcase */
1069
- const importObj = {
1070
- // We need to implement a part of the wasi api:
1071
- // https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md
1072
- // We literally only need to support random_get, everything else is noop implementated in barretenberg.wasm.
1073
- wasi_snapshot_preview1: {
1074
- random_get: (out, length) => {
1075
- out = out >>> 0;
1076
- const randomData = randomBytes(length);
1077
- const mem = this.getMemory();
1078
- mem.set(randomData, out);
1079
- },
1080
- clock_time_get: (a1, a2, out) => {
1081
- out = out >>> 0;
1082
- const ts = BigInt(new Date().getTime()) * 1000000n;
1083
- const view = new DataView(this.getMemory().buffer);
1084
- view.setBigUint64(out, ts, true);
1085
- },
1086
- proc_exit: () => {
1087
- this.logger('PANIC: proc_exit was called.');
1088
- throw new Error();
1089
- },
1090
- },
1091
- // These are functions implementations for imports we've defined are needed.
1092
- // The native C++ build defines these in a module called "env". We must implement TypeScript versions here.
1093
- env: {
1094
- /**
1095
- * The 'info' call we use for logging in C++, calls this under the hood.
1096
- * The native code will just print to std:err (to avoid std::cout which is used for IPC).
1097
- * Here we just emit the log line for the client to decide what to do with.
1098
- */
1099
- logstr: (addr) => {
1100
- const str = this.stringFromAddress(addr);
1101
- const m = this.getMemory();
1102
- const str2 = `${str} (mem: ${(m.length / (1024 * 1024)).toFixed(2)}MiB)`;
1103
- this.logger(str2);
1104
- },
1105
- throw_or_abort_impl: (addr) => {
1106
- const str = this.stringFromAddress(addr);
1107
- throw new Error(str);
1108
- },
1109
- get_data: (keyAddr, outBufAddr) => {
1110
- const key = this.stringFromAddress(keyAddr);
1111
- outBufAddr = outBufAddr >>> 0;
1112
- const data = this.memStore[key];
1113
- if (!data) {
1114
- this.logger(`get_data miss ${key}`);
1115
- return;
1116
- }
1117
- // this.logger(`get_data hit ${key} size: ${data.length} dest: ${outBufAddr}`);
1118
- // this.logger(Buffer.from(data.slice(0, 64)).toString('hex'));
1119
- this.writeMemory(outBufAddr, data);
1120
- },
1121
- set_data: (keyAddr, dataAddr, dataLength) => {
1122
- const key = this.stringFromAddress(keyAddr);
1123
- dataAddr = dataAddr >>> 0;
1124
- this.memStore[key] = this.getMemorySlice(dataAddr, dataAddr + dataLength);
1125
- // this.logger(`set_data: ${key} length: ${dataLength}`);
1126
- },
1127
- memory,
1128
- },
1129
- };
1130
- /* eslint-enable camelcase */
1131
- return importObj;
1132
- }
1133
- exports() {
1134
- return this.instance.exports;
1135
- }
1136
- /**
1137
- * When returning values from the WASM, use >>> operator to convert signed representation to unsigned representation.
1138
- */
1139
- call(name, ...args) {
1140
- if (!this.exports()[name]) {
1141
- throw new Error(`WASM function ${name} not found.`);
1142
- }
1143
- try {
1144
- return this.exports()[name](...args) >>> 0;
1145
- }
1146
- catch (err) {
1147
- const message = `WASM function ${name} aborted, error: ${err}`;
1148
- this.logger(message);
1149
- this.logger(err.stack);
1150
- throw err;
1151
- }
1152
- }
1153
- memSize() {
1154
- return this.getMemory().length;
1155
- }
1156
- /**
1157
- * Returns a copy of the data, not a view.
1158
- */
1159
- getMemorySlice(start, end) {
1160
- return this.getMemory().subarray(start, end).slice();
1161
- }
1162
- writeMemory(offset, arr) {
1163
- const mem = this.getMemory();
1164
- mem.set(arr, offset);
1165
- }
1166
- // PRIVATE METHODS
1167
- getMemory() {
1168
- return new Uint8Array(this.memory.buffer);
1169
- }
1170
- stringFromAddress(addr) {
1171
- addr = addr >>> 0;
1172
- const m = this.getMemory();
1173
- let i = addr;
1174
- for (; m[i] !== 0; ++i)
1175
- ;
1176
- const textDecoder = new TextDecoder('ascii');
1177
- return textDecoder.decode(m.slice(addr, i));
1178
- }
1179
- }
1180
-
1181
- /**
1182
- * Keeps track of heap allocations so they can be easily freed.
1183
- * The WASM memory layout has 1024 bytes of unused "scratch" space at the start (addresses 0-1023).
1184
- * We can leverage this for IO rather than making expensive bb_malloc bb_free calls.
1185
- * Heap allocations will be created for input/output args that don't fit into the scratch space.
1186
- * Input and output args can use the same scratch space as it's assume all input reads will be performed before any
1187
- * output writes are performed.
1188
- */
1189
- class HeapAllocator {
1190
- constructor(wasm) {
1191
- this.wasm = wasm;
1192
- this.allocs = [];
1193
- this.inScratchRemaining = 1024;
1194
- this.outScratchRemaining = 1024;
1195
- }
1196
- getInputs(buffers) {
1197
- return buffers.map(bufOrNum => {
1198
- if (typeof bufOrNum === 'object') {
1199
- if (bufOrNum.length <= this.inScratchRemaining) {
1200
- const ptr = (this.inScratchRemaining -= bufOrNum.length);
1201
- this.wasm.writeMemory(ptr, bufOrNum);
1202
- return ptr;
1203
- }
1204
- else {
1205
- const ptr = this.wasm.call('bbmalloc', bufOrNum.length);
1206
- this.wasm.writeMemory(ptr, bufOrNum);
1207
- this.allocs.push(ptr);
1208
- return ptr;
1209
- }
1210
- }
1211
- else {
1212
- return bufOrNum;
1213
- }
1214
- });
1215
- }
1216
- getOutputPtrs(outLens) {
1217
- return outLens.map(len => {
1218
- // If the obj is variable length, we need a 4 byte ptr to write the serialized data address to.
1219
- // WARNING: 4 only works with WASM as it has 32 bit memory.
1220
- const size = len || 4;
1221
- if (size <= this.outScratchRemaining) {
1222
- return (this.outScratchRemaining -= size);
1223
- }
1224
- else {
1225
- const ptr = this.wasm.call('bbmalloc', size);
1226
- this.allocs.push(ptr);
1227
- return ptr;
1228
- }
1229
- });
1230
- }
1231
- addOutputPtr(ptr) {
1232
- if (ptr >= 1024) {
1233
- this.allocs.push(ptr);
1234
- }
1235
- }
1236
- freeAll() {
1237
- for (const ptr of this.allocs) {
1238
- this.wasm.call('bbfree', ptr);
1239
- }
1240
- }
1241
- }
1242
-
1243
- /**
1244
- * This is the "main thread" implementation of BarretenbergWasm.
1245
- * It spawns a bunch of "child thread" implementations.
1246
- * In a browser context, this still runs on a worker, as it will block waiting on child threads.
1247
- */
1248
- class BarretenbergWasmMain extends BarretenbergWasmBase {
1249
- constructor() {
1250
- super(...arguments);
1251
- this.workers = [];
1252
- this.remoteWasms = [];
1253
- this.nextWorker = 0;
1254
- this.nextThreadId = 1;
1255
- }
1256
- getNumThreads() {
1257
- return this.workers.length + 1;
1258
- }
1259
- /**
1260
- * Init as main thread. Spawn child threads.
1261
- */
1262
- async init(module, threads = Math.min(getNumCpu(), BarretenbergWasmMain.MAX_THREADS), logger = createDebugLogger('bb_wasm'), initial = 32, maximum = this.getDefaultMaximumMemoryPages()) {
1263
- this.logger = logger;
1264
- const initialMb = (initial * 2 ** 16) / (1024 * 1024);
1265
- const maxMb = (maximum * 2 ** 16) / (1024 * 1024);
1266
- const shared = getSharedMemoryAvailable();
1267
- this.logger(`Initializing bb wasm: initial memory ${initial} pages ${initialMb}MiB; ` +
1268
- `max memory: ${maximum} pages, ${maxMb}MiB; ` +
1269
- `threads: ${threads}; shared memory: ${shared}`);
1270
- this.memory = new WebAssembly.Memory({ initial, maximum, shared });
1271
- const instance = await WebAssembly.instantiate(module, this.getImportObj(this.memory));
1272
- this.instance = instance;
1273
- // Init all global/static data.
1274
- this.call('_initialize');
1275
- // Create worker threads. Create 1 less than requested, as main thread counts as a thread.
1276
- if (threads > 1) {
1277
- this.logger(`Creating ${threads} worker threads`);
1278
- this.workers = await Promise.all(Array.from({ length: threads - 1 }).map(createThreadWorker));
1279
- this.remoteWasms = await Promise.all(this.workers.map((getRemoteBarretenbergWasm)));
1280
- await Promise.all(this.remoteWasms.map(w => w.initThread(module, this.memory)));
1281
- }
1282
- }
1283
- getDefaultMaximumMemoryPages() {
1284
- // iOS browser is very aggressive with memory. Check if running in browser and on iOS
1285
- // We at any rate expect the mobile iOS browser to kill us >=1GB, so we don't set a maximum higher than that.
1286
- if (typeof window !== 'undefined' && /iPad|iPhone/.test(navigator.userAgent)) {
1287
- return 2 ** 14;
1288
- }
1289
- return 2 ** 16;
1290
- }
1291
- /**
1292
- * Called on main thread. Signals child threads to gracefully exit.
1293
- */
1294
- async destroy() {
1295
- await Promise.all(this.workers.map(w => w.terminate()));
1296
- }
1297
- getImportObj(memory) {
1298
- const baseImports = super.getImportObj(memory);
1299
- /* eslint-disable camelcase */
1300
- return {
1301
- ...baseImports,
1302
- wasi: {
1303
- 'thread-spawn': (arg) => {
1304
- arg = arg >>> 0;
1305
- const id = this.nextThreadId++;
1306
- const worker = this.nextWorker++ % this.remoteWasms.length;
1307
- // this.logger(`spawning thread ${id} on worker ${worker} with arg ${arg >>> 0}`);
1308
- this.remoteWasms[worker].call('wasi_thread_start', id, arg).catch(this.logger);
1309
- // this.remoteWasms[worker].postMessage({ msg: 'thread', data: { id, arg } });
1310
- return id;
1311
- },
1312
- },
1313
- env: {
1314
- ...baseImports.env,
1315
- env_hardware_concurrency: () => {
1316
- // If there are no workers (we're already running as a worker, or the main thread requested no workers)
1317
- // then we return 1, which should cause any algos using threading to just not create a thread.
1318
- return this.remoteWasms.length + 1;
1319
- },
1320
- },
1321
- };
1322
- /* eslint-enable camelcase */
1323
- }
1324
- callWasmExport(funcName, inArgs, outLens) {
1325
- const alloc = new HeapAllocator(this);
1326
- const inPtrs = alloc.getInputs(inArgs);
1327
- const outPtrs = alloc.getOutputPtrs(outLens);
1328
- this.call(funcName, ...inPtrs, ...outPtrs);
1329
- const outArgs = this.getOutputArgs(outLens, outPtrs, alloc);
1330
- alloc.freeAll();
1331
- return outArgs;
1332
- }
1333
- getOutputArgs(outLens, outPtrs, alloc) {
1334
- return outLens.map((len, i) => {
1335
- if (len) {
1336
- return this.getMemorySlice(outPtrs[i], outPtrs[i] + len);
1337
- }
1338
- const slice = this.getMemorySlice(outPtrs[i], outPtrs[i] + 4);
1339
- const ptr = new DataView(slice.buffer, slice.byteOffset, slice.byteLength).getUint32(0, true);
1340
- // Add our heap buffer to the dealloc list.
1341
- alloc.addOutputPtr(ptr);
1342
- // The length will be found in the first 4 bytes of the buffer, big endian. See to_heap_buffer.
1343
- const lslice = this.getMemorySlice(ptr, ptr + 4);
1344
- const length = new DataView(lslice.buffer, lslice.byteOffset, lslice.byteLength).getUint32(0, false);
1345
- return this.getMemorySlice(ptr + 4, ptr + 4 + length);
1346
- });
1347
- }
1348
- cbindCall(cbind, inputBuffer) {
1349
- const outputSizePtr = this.call('bbmalloc', 4);
1350
- const outputMsgpackPtr = this.call('bbmalloc', 4);
1351
- const inputPtr = this.call('bbmalloc', inputBuffer.length);
1352
- this.writeMemory(inputPtr, inputBuffer);
1353
- this.call(cbind, inputPtr, inputBuffer.length, outputMsgpackPtr, outputSizePtr);
1354
- const readPtr32 = (ptr32) => {
1355
- const dataView = new DataView(this.getMemorySlice(ptr32, ptr32 + 4).buffer);
1356
- return dataView.getUint32(0, true);
1357
- };
1358
- const encodedResult = this.getMemorySlice(readPtr32(outputMsgpackPtr), readPtr32(outputMsgpackPtr) + readPtr32(outputSizePtr));
1359
- this.call('bbfree', inputPtr);
1360
- this.call('bbfree', outputSizePtr);
1361
- this.call('bbfree', outputMsgpackPtr);
1362
- return encodedResult;
1363
- }
1364
- }
1365
- BarretenbergWasmMain.MAX_THREADS = 32;
1366
-
1367
- addEventListener('message', e => {
1368
- if (e.data.log) {
1369
- initLogger(e.data.log);
1370
- }
1371
- });
1372
- expose(new BarretenbergWasmMain());
1373
- postMessage(Ready);
1374
-
1375
- })();