@obolnetwork/obol-sdk 2.11.13 → 2.12.1

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 (40) hide show
  1. package/dist/browser/src/index.js +702 -212
  2. package/dist/browser/src/index.js.map +1 -1
  3. package/dist/cjs/src/blsUtils.js +3843 -0
  4. package/dist/cjs/src/blsUtils.js.map +1 -0
  5. package/dist/cjs/src/index.js +790 -299
  6. package/dist/cjs/src/index.js.map +1 -1
  7. package/dist/cjs/src/verification/clusterLockValidationWorker.js +14696 -0
  8. package/dist/cjs/src/verification/clusterLockValidationWorker.js.map +1 -0
  9. package/dist/cjs/src/verification/lockWorker.js +3840 -0
  10. package/dist/cjs/src/verification/lockWorker.js.map +1 -0
  11. package/dist/cjs/src/verification/parallelPool.js +4185 -0
  12. package/dist/cjs/src/verification/parallelPool.js.map +1 -0
  13. package/dist/esm/src/blsUtils.js +21 -0
  14. package/dist/esm/src/blsUtils.js.map +1 -0
  15. package/dist/esm/src/chunk-5ASVONSJ.js +10242 -0
  16. package/dist/esm/src/chunk-5ASVONSJ.js.map +1 -0
  17. package/dist/esm/src/chunk-LOSYOJC3.js +4370 -0
  18. package/dist/esm/src/chunk-LOSYOJC3.js.map +1 -0
  19. package/dist/esm/src/chunk-RYTIXFRX.js +382 -0
  20. package/dist/esm/src/chunk-RYTIXFRX.js.map +1 -0
  21. package/dist/esm/src/index.js +215 -14508
  22. package/dist/esm/src/index.js.map +1 -1
  23. package/dist/esm/src/verification/clusterLockValidationWorker.js +18 -0
  24. package/dist/esm/src/verification/clusterLockValidationWorker.js.map +1 -0
  25. package/dist/esm/src/verification/lockWorker.js +55 -0
  26. package/dist/esm/src/verification/lockWorker.js.map +1 -0
  27. package/dist/esm/src/verification/parallelPool.js +16 -0
  28. package/dist/esm/src/verification/parallelPool.js.map +1 -0
  29. package/dist/types/src/blsUtils.d.ts +5 -0
  30. package/dist/types/src/errors.d.ts +13 -0
  31. package/dist/types/src/index.d.ts +1 -1
  32. package/dist/types/src/services.d.ts +4 -1
  33. package/dist/types/src/types.d.ts +6 -0
  34. package/dist/types/src/verification/clusterLockValidationWorker.d.ts +1 -0
  35. package/dist/types/src/verification/common.d.ts +26 -7
  36. package/dist/types/src/verification/lockWorker.d.ts +18 -0
  37. package/dist/types/src/verification/parallelPool.d.ts +11 -0
  38. package/dist/types/test/verification/parallelPool.spec.d.ts +1 -0
  39. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  40. package/package.json +1 -1
@@ -0,0 +1,4370 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
25
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
26
+ }) : x)(function(x) {
27
+ if (typeof require !== "undefined") return require.apply(this, arguments);
28
+ throw Error('Dynamic require of "' + x + '" is not supported');
29
+ });
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, { get: all[name], enumerable: true });
33
+ };
34
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
35
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
36
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
37
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
38
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
39
+ var __async = (__this, __arguments, generator) => {
40
+ return new Promise((resolve, reject) => {
41
+ var fulfilled = (value) => {
42
+ try {
43
+ step(generator.next(value));
44
+ } catch (e) {
45
+ reject(e);
46
+ }
47
+ };
48
+ var rejected = (value) => {
49
+ try {
50
+ step(generator.throw(value));
51
+ } catch (e) {
52
+ reject(e);
53
+ }
54
+ };
55
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
56
+ step((generator = generator.apply(__this, __arguments)).next());
57
+ });
58
+ };
59
+ var __await = function(promise, isYieldStar) {
60
+ this[0] = promise;
61
+ this[1] = isYieldStar;
62
+ };
63
+ var __yieldStar = (value) => {
64
+ var obj = value[__knownSymbol("asyncIterator")], isAwait = false, method, it = {};
65
+ if (obj == null) {
66
+ obj = value[__knownSymbol("iterator")]();
67
+ method = (k) => it[k] = (x) => obj[k](x);
68
+ } else {
69
+ obj = obj.call(value);
70
+ method = (k) => it[k] = (v) => {
71
+ if (isAwait) {
72
+ isAwait = false;
73
+ if (k === "throw") throw v;
74
+ return v;
75
+ }
76
+ isAwait = true;
77
+ return {
78
+ done: false,
79
+ value: new __await(new Promise((resolve) => {
80
+ var x = obj[k](v);
81
+ if (!(x instanceof Object)) __typeError("Object expected");
82
+ resolve(x);
83
+ }), 1)
84
+ };
85
+ };
86
+ }
87
+ return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => {
88
+ throw x;
89
+ }, "return" in obj && method("return"), it;
90
+ };
91
+
92
+ // node_modules/@noble/curves/node_modules/@noble/hashes/utils.js
93
+ function isBytes(a) {
94
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
95
+ }
96
+ function anumber(n, title = "") {
97
+ if (typeof n !== "number") {
98
+ const prefix = title && `"${title}" `;
99
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
100
+ }
101
+ if (!Number.isSafeInteger(n) || n < 0) {
102
+ const prefix = title && `"${title}" `;
103
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
104
+ }
105
+ }
106
+ function abytes(value, length, title = "") {
107
+ const bytes = isBytes(value);
108
+ const len = value == null ? void 0 : value.length;
109
+ const needsLen = length !== void 0;
110
+ if (!bytes || needsLen && len !== length) {
111
+ const prefix = title && `"${title}" `;
112
+ const ofLen = needsLen ? ` of length ${length}` : "";
113
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
114
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
115
+ if (!bytes)
116
+ throw new TypeError(message);
117
+ throw new RangeError(message);
118
+ }
119
+ return value;
120
+ }
121
+ function ahash(h) {
122
+ if (typeof h !== "function" || typeof h.create !== "function")
123
+ throw new TypeError("Hash must wrapped by utils.createHasher");
124
+ anumber(h.outputLen);
125
+ anumber(h.blockLen);
126
+ if (h.outputLen < 1)
127
+ throw new Error('"outputLen" must be >= 1');
128
+ if (h.blockLen < 1)
129
+ throw new Error('"blockLen" must be >= 1');
130
+ }
131
+ function aexists(instance, checkFinished = true) {
132
+ if (instance.destroyed)
133
+ throw new Error("Hash instance has been destroyed");
134
+ if (checkFinished && instance.finished)
135
+ throw new Error("Hash#digest() has already been called");
136
+ }
137
+ function aoutput(out, instance) {
138
+ abytes(out, void 0, "digestInto() output");
139
+ const min = instance.outputLen;
140
+ if (out.length < min) {
141
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
142
+ }
143
+ }
144
+ function clean(...arrays) {
145
+ for (let i = 0; i < arrays.length; i++) {
146
+ arrays[i].fill(0);
147
+ }
148
+ }
149
+ function createView(arr) {
150
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
151
+ }
152
+ function rotr(word, shift) {
153
+ return word << 32 - shift | word >>> shift;
154
+ }
155
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
156
+ // @ts-ignore
157
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
158
+ ))();
159
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
160
+ function bytesToHex(bytes) {
161
+ abytes(bytes);
162
+ if (hasHexBuiltin)
163
+ return bytes.toHex();
164
+ let hex = "";
165
+ for (let i = 0; i < bytes.length; i++) {
166
+ hex += hexes[bytes[i]];
167
+ }
168
+ return hex;
169
+ }
170
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
171
+ function asciiToBase16(ch) {
172
+ if (ch >= asciis._0 && ch <= asciis._9)
173
+ return ch - asciis._0;
174
+ if (ch >= asciis.A && ch <= asciis.F)
175
+ return ch - (asciis.A - 10);
176
+ if (ch >= asciis.a && ch <= asciis.f)
177
+ return ch - (asciis.a - 10);
178
+ return;
179
+ }
180
+ function hexToBytes(hex) {
181
+ if (typeof hex !== "string")
182
+ throw new TypeError("hex string expected, got " + typeof hex);
183
+ if (hasHexBuiltin) {
184
+ try {
185
+ return Uint8Array.fromHex(hex);
186
+ } catch (error) {
187
+ if (error instanceof SyntaxError)
188
+ throw new RangeError(error.message);
189
+ throw error;
190
+ }
191
+ }
192
+ const hl = hex.length;
193
+ const al = hl / 2;
194
+ if (hl % 2)
195
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
196
+ const array = new Uint8Array(al);
197
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
198
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
199
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
200
+ if (n1 === void 0 || n2 === void 0) {
201
+ const char = hex[hi] + hex[hi + 1];
202
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
203
+ }
204
+ array[ai] = n1 * 16 + n2;
205
+ }
206
+ return array;
207
+ }
208
+ function concatBytes(...arrays) {
209
+ let sum = 0;
210
+ for (let i = 0; i < arrays.length; i++) {
211
+ const a = arrays[i];
212
+ abytes(a);
213
+ sum += a.length;
214
+ }
215
+ const res = new Uint8Array(sum);
216
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
217
+ const a = arrays[i];
218
+ res.set(a, pad);
219
+ pad += a.length;
220
+ }
221
+ return res;
222
+ }
223
+ function createHasher(hashCons, info = {}) {
224
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
225
+ const tmp = hashCons(void 0);
226
+ hashC.outputLen = tmp.outputLen;
227
+ hashC.blockLen = tmp.blockLen;
228
+ hashC.canXOF = tmp.canXOF;
229
+ hashC.create = (opts) => hashCons(opts);
230
+ Object.assign(hashC, info);
231
+ return Object.freeze(hashC);
232
+ }
233
+ function randomBytes(bytesLength = 32) {
234
+ anumber(bytesLength, "bytesLength");
235
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
236
+ if (typeof (cr == null ? void 0 : cr.getRandomValues) !== "function")
237
+ throw new Error("crypto.getRandomValues must be defined");
238
+ if (bytesLength > 65536)
239
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
240
+ return cr.getRandomValues(new Uint8Array(bytesLength));
241
+ }
242
+ var oidNist = (suffix) => ({
243
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
244
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
245
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
246
+ });
247
+
248
+ // node_modules/@noble/curves/node_modules/@noble/hashes/_md.js
249
+ function Chi(a, b, c) {
250
+ return a & b ^ ~a & c;
251
+ }
252
+ function Maj(a, b, c) {
253
+ return a & b ^ a & c ^ b & c;
254
+ }
255
+ var HashMD = class {
256
+ constructor(blockLen, outputLen, padOffset, isLE) {
257
+ __publicField(this, "blockLen");
258
+ __publicField(this, "outputLen");
259
+ __publicField(this, "canXOF", false);
260
+ __publicField(this, "padOffset");
261
+ __publicField(this, "isLE");
262
+ // For partial updates less than block size
263
+ __publicField(this, "buffer");
264
+ __publicField(this, "view");
265
+ __publicField(this, "finished", false);
266
+ __publicField(this, "length", 0);
267
+ __publicField(this, "pos", 0);
268
+ __publicField(this, "destroyed", false);
269
+ this.blockLen = blockLen;
270
+ this.outputLen = outputLen;
271
+ this.padOffset = padOffset;
272
+ this.isLE = isLE;
273
+ this.buffer = new Uint8Array(blockLen);
274
+ this.view = createView(this.buffer);
275
+ }
276
+ update(data) {
277
+ aexists(this);
278
+ abytes(data);
279
+ const { view, buffer, blockLen } = this;
280
+ const len = data.length;
281
+ for (let pos = 0; pos < len; ) {
282
+ const take = Math.min(blockLen - this.pos, len - pos);
283
+ if (take === blockLen) {
284
+ const dataView = createView(data);
285
+ for (; blockLen <= len - pos; pos += blockLen)
286
+ this.process(dataView, pos);
287
+ continue;
288
+ }
289
+ buffer.set(data.subarray(pos, pos + take), this.pos);
290
+ this.pos += take;
291
+ pos += take;
292
+ if (this.pos === blockLen) {
293
+ this.process(view, 0);
294
+ this.pos = 0;
295
+ }
296
+ }
297
+ this.length += data.length;
298
+ this.roundClean();
299
+ return this;
300
+ }
301
+ digestInto(out) {
302
+ aexists(this);
303
+ aoutput(out, this);
304
+ this.finished = true;
305
+ const { buffer, view, blockLen, isLE } = this;
306
+ let { pos } = this;
307
+ buffer[pos++] = 128;
308
+ clean(this.buffer.subarray(pos));
309
+ if (this.padOffset > blockLen - pos) {
310
+ this.process(view, 0);
311
+ pos = 0;
312
+ }
313
+ for (let i = pos; i < blockLen; i++)
314
+ buffer[i] = 0;
315
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
316
+ this.process(view, 0);
317
+ const oview = createView(out);
318
+ const len = this.outputLen;
319
+ if (len % 4)
320
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
321
+ const outLen = len / 4;
322
+ const state = this.get();
323
+ if (outLen > state.length)
324
+ throw new Error("_sha2: outputLen bigger than state");
325
+ for (let i = 0; i < outLen; i++)
326
+ oview.setUint32(4 * i, state[i], isLE);
327
+ }
328
+ digest() {
329
+ const { buffer, outputLen } = this;
330
+ this.digestInto(buffer);
331
+ const res = buffer.slice(0, outputLen);
332
+ this.destroy();
333
+ return res;
334
+ }
335
+ _cloneInto(to) {
336
+ to || (to = new this.constructor());
337
+ to.set(...this.get());
338
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
339
+ to.destroyed = destroyed;
340
+ to.finished = finished;
341
+ to.length = length;
342
+ to.pos = pos;
343
+ if (length % blockLen)
344
+ to.buffer.set(buffer);
345
+ return to;
346
+ }
347
+ clone() {
348
+ return this._cloneInto();
349
+ }
350
+ };
351
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
352
+ 1779033703,
353
+ 3144134277,
354
+ 1013904242,
355
+ 2773480762,
356
+ 1359893119,
357
+ 2600822924,
358
+ 528734635,
359
+ 1541459225
360
+ ]);
361
+
362
+ // node_modules/@noble/curves/node_modules/@noble/hashes/sha2.js
363
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
364
+ 1116352408,
365
+ 1899447441,
366
+ 3049323471,
367
+ 3921009573,
368
+ 961987163,
369
+ 1508970993,
370
+ 2453635748,
371
+ 2870763221,
372
+ 3624381080,
373
+ 310598401,
374
+ 607225278,
375
+ 1426881987,
376
+ 1925078388,
377
+ 2162078206,
378
+ 2614888103,
379
+ 3248222580,
380
+ 3835390401,
381
+ 4022224774,
382
+ 264347078,
383
+ 604807628,
384
+ 770255983,
385
+ 1249150122,
386
+ 1555081692,
387
+ 1996064986,
388
+ 2554220882,
389
+ 2821834349,
390
+ 2952996808,
391
+ 3210313671,
392
+ 3336571891,
393
+ 3584528711,
394
+ 113926993,
395
+ 338241895,
396
+ 666307205,
397
+ 773529912,
398
+ 1294757372,
399
+ 1396182291,
400
+ 1695183700,
401
+ 1986661051,
402
+ 2177026350,
403
+ 2456956037,
404
+ 2730485921,
405
+ 2820302411,
406
+ 3259730800,
407
+ 3345764771,
408
+ 3516065817,
409
+ 3600352804,
410
+ 4094571909,
411
+ 275423344,
412
+ 430227734,
413
+ 506948616,
414
+ 659060556,
415
+ 883997877,
416
+ 958139571,
417
+ 1322822218,
418
+ 1537002063,
419
+ 1747873779,
420
+ 1955562222,
421
+ 2024104815,
422
+ 2227730452,
423
+ 2361852424,
424
+ 2428436474,
425
+ 2756734187,
426
+ 3204031479,
427
+ 3329325298
428
+ ]);
429
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
430
+ var SHA2_32B = class extends HashMD {
431
+ constructor(outputLen) {
432
+ super(64, outputLen, 8, false);
433
+ }
434
+ get() {
435
+ const { A, B, C, D, E, F, G, H } = this;
436
+ return [A, B, C, D, E, F, G, H];
437
+ }
438
+ // prettier-ignore
439
+ set(A, B, C, D, E, F, G, H) {
440
+ this.A = A | 0;
441
+ this.B = B | 0;
442
+ this.C = C | 0;
443
+ this.D = D | 0;
444
+ this.E = E | 0;
445
+ this.F = F | 0;
446
+ this.G = G | 0;
447
+ this.H = H | 0;
448
+ }
449
+ process(view, offset) {
450
+ for (let i = 0; i < 16; i++, offset += 4)
451
+ SHA256_W[i] = view.getUint32(offset, false);
452
+ for (let i = 16; i < 64; i++) {
453
+ const W15 = SHA256_W[i - 15];
454
+ const W2 = SHA256_W[i - 2];
455
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
456
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
457
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
458
+ }
459
+ let { A, B, C, D, E, F, G, H } = this;
460
+ for (let i = 0; i < 64; i++) {
461
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
462
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
463
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
464
+ const T2 = sigma0 + Maj(A, B, C) | 0;
465
+ H = G;
466
+ G = F;
467
+ F = E;
468
+ E = D + T1 | 0;
469
+ D = C;
470
+ C = B;
471
+ B = A;
472
+ A = T1 + T2 | 0;
473
+ }
474
+ A = A + this.A | 0;
475
+ B = B + this.B | 0;
476
+ C = C + this.C | 0;
477
+ D = D + this.D | 0;
478
+ E = E + this.E | 0;
479
+ F = F + this.F | 0;
480
+ G = G + this.G | 0;
481
+ H = H + this.H | 0;
482
+ this.set(A, B, C, D, E, F, G, H);
483
+ }
484
+ roundClean() {
485
+ clean(SHA256_W);
486
+ }
487
+ destroy() {
488
+ this.destroyed = true;
489
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
490
+ clean(this.buffer);
491
+ }
492
+ };
493
+ var _SHA256 = class extends SHA2_32B {
494
+ constructor() {
495
+ super(32);
496
+ // We cannot use array here since array allows indexing by variable
497
+ // which means optimizer/compiler cannot use registers.
498
+ __publicField(this, "A", SHA256_IV[0] | 0);
499
+ __publicField(this, "B", SHA256_IV[1] | 0);
500
+ __publicField(this, "C", SHA256_IV[2] | 0);
501
+ __publicField(this, "D", SHA256_IV[3] | 0);
502
+ __publicField(this, "E", SHA256_IV[4] | 0);
503
+ __publicField(this, "F", SHA256_IV[5] | 0);
504
+ __publicField(this, "G", SHA256_IV[6] | 0);
505
+ __publicField(this, "H", SHA256_IV[7] | 0);
506
+ }
507
+ };
508
+ var sha256 = /* @__PURE__ */ createHasher(
509
+ () => new _SHA256(),
510
+ /* @__PURE__ */ oidNist(1)
511
+ );
512
+
513
+ // node_modules/@noble/curves/utils.js
514
+ var abytes2 = (value, length, title) => abytes(value, length, title);
515
+ var anumber2 = anumber;
516
+ var bytesToHex2 = bytesToHex;
517
+ var concatBytes2 = (...arrays) => concatBytes(...arrays);
518
+ var hexToBytes2 = (hex) => hexToBytes(hex);
519
+ var isBytes2 = isBytes;
520
+ var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
521
+ var _0n = /* @__PURE__ */ BigInt(0);
522
+ var _1n = /* @__PURE__ */ BigInt(1);
523
+ function abool(value, title = "") {
524
+ if (typeof value !== "boolean") {
525
+ const prefix = title && `"${title}" `;
526
+ throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
527
+ }
528
+ return value;
529
+ }
530
+ function abignumber(n) {
531
+ if (typeof n === "bigint") {
532
+ if (!isPosBig(n))
533
+ throw new RangeError("positive bigint expected, got " + n);
534
+ } else
535
+ anumber2(n);
536
+ return n;
537
+ }
538
+ function asafenumber(value, title = "") {
539
+ if (typeof value !== "number") {
540
+ const prefix = title && `"${title}" `;
541
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
542
+ }
543
+ if (!Number.isSafeInteger(value)) {
544
+ const prefix = title && `"${title}" `;
545
+ throw new RangeError(prefix + "expected safe integer, got " + value);
546
+ }
547
+ }
548
+ function numberToHexUnpadded(num) {
549
+ const hex = abignumber(num).toString(16);
550
+ return hex.length & 1 ? "0" + hex : hex;
551
+ }
552
+ function hexToNumber(hex) {
553
+ if (typeof hex !== "string")
554
+ throw new TypeError("hex string expected, got " + typeof hex);
555
+ return hex === "" ? _0n : BigInt("0x" + hex);
556
+ }
557
+ function bytesToNumberBE(bytes) {
558
+ return hexToNumber(bytesToHex(bytes));
559
+ }
560
+ function bytesToNumberLE(bytes) {
561
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
562
+ }
563
+ function numberToBytesBE(n, len) {
564
+ anumber(len);
565
+ if (len === 0)
566
+ throw new RangeError("zero length");
567
+ n = abignumber(n);
568
+ const hex = n.toString(16);
569
+ if (hex.length > len * 2)
570
+ throw new RangeError("number too large");
571
+ return hexToBytes(hex.padStart(len * 2, "0"));
572
+ }
573
+ function numberToBytesLE(n, len) {
574
+ return numberToBytesBE(n, len).reverse();
575
+ }
576
+ function copyBytes(bytes) {
577
+ return Uint8Array.from(abytes2(bytes));
578
+ }
579
+ function asciiToBytes(ascii) {
580
+ if (typeof ascii !== "string")
581
+ throw new TypeError("ascii string expected, got " + typeof ascii);
582
+ return Uint8Array.from(ascii, (c, i) => {
583
+ const charCode = c.charCodeAt(0);
584
+ if (c.length !== 1 || charCode > 127) {
585
+ throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
586
+ }
587
+ return charCode;
588
+ });
589
+ }
590
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
591
+ function inRange(n, min, max) {
592
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
593
+ }
594
+ function aInRange(title, n, min, max) {
595
+ if (!inRange(n, min, max))
596
+ throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
597
+ }
598
+ function bitLen(n) {
599
+ if (n < _0n)
600
+ throw new Error("expected non-negative bigint, got " + n);
601
+ let len;
602
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
603
+ ;
604
+ return len;
605
+ }
606
+ function bitGet(n, pos) {
607
+ return n >> BigInt(pos) & _1n;
608
+ }
609
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
610
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
611
+ anumber(hashLen, "hashLen");
612
+ anumber(qByteLen, "qByteLen");
613
+ if (typeof hmacFn !== "function")
614
+ throw new TypeError("hmacFn must be a function");
615
+ const u8n = (len) => new Uint8Array(len);
616
+ const NULL = Uint8Array.of();
617
+ const byte0 = Uint8Array.of(0);
618
+ const byte1 = Uint8Array.of(1);
619
+ const _maxDrbgIters = 1e3;
620
+ let v = u8n(hashLen);
621
+ let k = u8n(hashLen);
622
+ let i = 0;
623
+ const reset = () => {
624
+ v.fill(1);
625
+ k.fill(0);
626
+ i = 0;
627
+ };
628
+ const h = (...msgs) => hmacFn(k, concatBytes2(v, ...msgs));
629
+ const reseed = (seed = NULL) => {
630
+ k = h(byte0, seed);
631
+ v = h();
632
+ if (seed.length === 0)
633
+ return;
634
+ k = h(byte1, seed);
635
+ v = h();
636
+ };
637
+ const gen = () => {
638
+ if (i++ >= _maxDrbgIters)
639
+ throw new Error("drbg: tried max amount of iterations");
640
+ let len = 0;
641
+ const out = [];
642
+ while (len < qByteLen) {
643
+ v = h();
644
+ const sl = v.slice();
645
+ out.push(sl);
646
+ len += v.length;
647
+ }
648
+ return concatBytes2(...out);
649
+ };
650
+ const genUntil = (seed, pred) => {
651
+ reset();
652
+ reseed(seed);
653
+ let res = void 0;
654
+ while ((res = pred(gen())) === void 0)
655
+ reseed();
656
+ reset();
657
+ return res;
658
+ };
659
+ return genUntil;
660
+ }
661
+ function validateObject(object, fields2 = {}, optFields = {}) {
662
+ if (Object.prototype.toString.call(object) !== "[object Object]")
663
+ throw new TypeError("expected valid options object");
664
+ function checkField(fieldName, expectedType, isOpt) {
665
+ if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
666
+ throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
667
+ const val = object[fieldName];
668
+ if (isOpt && val === void 0)
669
+ return;
670
+ const current = typeof val;
671
+ if (current !== expectedType || val === null)
672
+ throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
673
+ }
674
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
675
+ iter(fields2, false);
676
+ iter(optFields, true);
677
+ }
678
+ var notImplemented = () => {
679
+ throw new Error("not implemented");
680
+ };
681
+
682
+ // node_modules/@noble/curves/abstract/modular.js
683
+ var _0n2 = /* @__PURE__ */ BigInt(0);
684
+ var _1n2 = /* @__PURE__ */ BigInt(1);
685
+ var _2n = /* @__PURE__ */ BigInt(2);
686
+ var _3n = /* @__PURE__ */ BigInt(3);
687
+ var _4n = /* @__PURE__ */ BigInt(4);
688
+ var _5n = /* @__PURE__ */ BigInt(5);
689
+ var _7n = /* @__PURE__ */ BigInt(7);
690
+ var _8n = /* @__PURE__ */ BigInt(8);
691
+ var _9n = /* @__PURE__ */ BigInt(9);
692
+ var _16n = /* @__PURE__ */ BigInt(16);
693
+ function mod(a, b) {
694
+ if (b <= _0n2)
695
+ throw new Error("mod: expected positive modulus, got " + b);
696
+ const result = a % b;
697
+ return result >= _0n2 ? result : b + result;
698
+ }
699
+ function pow2(x, power, modulo) {
700
+ if (power < _0n2)
701
+ throw new Error("pow2: expected non-negative exponent, got " + power);
702
+ let res = x;
703
+ while (power-- > _0n2) {
704
+ res *= res;
705
+ res %= modulo;
706
+ }
707
+ return res;
708
+ }
709
+ function invert(number, modulo) {
710
+ if (number === _0n2)
711
+ throw new Error("invert: expected non-zero number");
712
+ if (modulo <= _0n2)
713
+ throw new Error("invert: expected positive modulus, got " + modulo);
714
+ let a = mod(number, modulo);
715
+ let b = modulo;
716
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
717
+ while (a !== _0n2) {
718
+ const q = b / a;
719
+ const r = b - a * q;
720
+ const m = x - u * q;
721
+ const n = y - v * q;
722
+ b = a, a = r, x = u, y = v, u = m, v = n;
723
+ }
724
+ const gcd = b;
725
+ if (gcd !== _1n2)
726
+ throw new Error("invert: does not exist");
727
+ return mod(x, modulo);
728
+ }
729
+ function assertIsSquare(Fp3, root, n) {
730
+ const F = Fp3;
731
+ if (!F.eql(F.sqr(root), n))
732
+ throw new Error("Cannot find square root");
733
+ }
734
+ function sqrt3mod4(Fp3, n) {
735
+ const F = Fp3;
736
+ const p1div4 = (F.ORDER + _1n2) / _4n;
737
+ const root = F.pow(n, p1div4);
738
+ assertIsSquare(F, root, n);
739
+ return root;
740
+ }
741
+ function sqrt5mod8(Fp3, n) {
742
+ const F = Fp3;
743
+ const p5div8 = (F.ORDER - _5n) / _8n;
744
+ const n2 = F.mul(n, _2n);
745
+ const v = F.pow(n2, p5div8);
746
+ const nv = F.mul(n, v);
747
+ const i = F.mul(F.mul(nv, _2n), v);
748
+ const root = F.mul(nv, F.sub(i, F.ONE));
749
+ assertIsSquare(F, root, n);
750
+ return root;
751
+ }
752
+ function sqrt9mod16(P) {
753
+ const Fp_ = Field(P);
754
+ const tn = tonelliShanks(P);
755
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
756
+ const c2 = tn(Fp_, c1);
757
+ const c3 = tn(Fp_, Fp_.neg(c1));
758
+ const c4 = (P + _7n) / _16n;
759
+ return ((Fp3, n) => {
760
+ const F = Fp3;
761
+ let tv1 = F.pow(n, c4);
762
+ let tv2 = F.mul(tv1, c1);
763
+ const tv3 = F.mul(tv1, c2);
764
+ const tv4 = F.mul(tv1, c3);
765
+ const e1 = F.eql(F.sqr(tv2), n);
766
+ const e2 = F.eql(F.sqr(tv3), n);
767
+ tv1 = F.cmov(tv1, tv2, e1);
768
+ tv2 = F.cmov(tv4, tv3, e2);
769
+ const e3 = F.eql(F.sqr(tv2), n);
770
+ const root = F.cmov(tv1, tv2, e3);
771
+ assertIsSquare(F, root, n);
772
+ return root;
773
+ });
774
+ }
775
+ function tonelliShanks(P) {
776
+ if (P < _3n)
777
+ throw new Error("sqrt is not defined for small field");
778
+ let Q = P - _1n2;
779
+ let S = 0;
780
+ while (Q % _2n === _0n2) {
781
+ Q /= _2n;
782
+ S++;
783
+ }
784
+ let Z = _2n;
785
+ const _Fp = Field(P);
786
+ while (FpLegendre(_Fp, Z) === 1) {
787
+ if (Z++ > 1e3)
788
+ throw new Error("Cannot find square root: probably non-prime P");
789
+ }
790
+ if (S === 1)
791
+ return sqrt3mod4;
792
+ let cc = _Fp.pow(Z, Q);
793
+ const Q1div2 = (Q + _1n2) / _2n;
794
+ return function tonelliSlow(Fp3, n) {
795
+ const F = Fp3;
796
+ if (F.is0(n))
797
+ return n;
798
+ if (FpLegendre(F, n) !== 1)
799
+ throw new Error("Cannot find square root");
800
+ let M = S;
801
+ let c = F.mul(F.ONE, cc);
802
+ let t = F.pow(n, Q);
803
+ let R = F.pow(n, Q1div2);
804
+ while (!F.eql(t, F.ONE)) {
805
+ if (F.is0(t))
806
+ return F.ZERO;
807
+ let i = 1;
808
+ let t_tmp = F.sqr(t);
809
+ while (!F.eql(t_tmp, F.ONE)) {
810
+ i++;
811
+ t_tmp = F.sqr(t_tmp);
812
+ if (i === M)
813
+ throw new Error("Cannot find square root");
814
+ }
815
+ const exponent = _1n2 << BigInt(M - i - 1);
816
+ const b = F.pow(c, exponent);
817
+ M = i;
818
+ c = F.sqr(b);
819
+ t = F.mul(t, c);
820
+ R = F.mul(R, b);
821
+ }
822
+ return R;
823
+ };
824
+ }
825
+ function FpSqrt(P) {
826
+ if (P % _4n === _3n)
827
+ return sqrt3mod4;
828
+ if (P % _8n === _5n)
829
+ return sqrt5mod8;
830
+ if (P % _16n === _9n)
831
+ return sqrt9mod16(P);
832
+ return tonelliShanks(P);
833
+ }
834
+ var FIELD_FIELDS = [
835
+ "create",
836
+ "isValid",
837
+ "is0",
838
+ "neg",
839
+ "inv",
840
+ "sqrt",
841
+ "sqr",
842
+ "eql",
843
+ "add",
844
+ "sub",
845
+ "mul",
846
+ "pow",
847
+ "div",
848
+ "addN",
849
+ "subN",
850
+ "mulN",
851
+ "sqrN"
852
+ ];
853
+ function validateField(field) {
854
+ const initial = {
855
+ ORDER: "bigint",
856
+ BYTES: "number",
857
+ BITS: "number"
858
+ };
859
+ const opts = FIELD_FIELDS.reduce((map, val) => {
860
+ map[val] = "function";
861
+ return map;
862
+ }, initial);
863
+ validateObject(field, opts);
864
+ asafenumber(field.BYTES, "BYTES");
865
+ asafenumber(field.BITS, "BITS");
866
+ if (field.BYTES < 1 || field.BITS < 1)
867
+ throw new Error("invalid field: expected BYTES/BITS > 0");
868
+ if (field.ORDER <= _1n2)
869
+ throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
870
+ return field;
871
+ }
872
+ function FpPow(Fp3, num, power) {
873
+ const F = Fp3;
874
+ if (power < _0n2)
875
+ throw new Error("invalid exponent, negatives unsupported");
876
+ if (power === _0n2)
877
+ return F.ONE;
878
+ if (power === _1n2)
879
+ return num;
880
+ let p = F.ONE;
881
+ let d = num;
882
+ while (power > _0n2) {
883
+ if (power & _1n2)
884
+ p = F.mul(p, d);
885
+ d = F.sqr(d);
886
+ power >>= _1n2;
887
+ }
888
+ return p;
889
+ }
890
+ function FpInvertBatch(Fp3, nums, passZero = false) {
891
+ const F = Fp3;
892
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
893
+ const multipliedAcc = nums.reduce((acc, num, i) => {
894
+ if (F.is0(num))
895
+ return acc;
896
+ inverted[i] = acc;
897
+ return F.mul(acc, num);
898
+ }, F.ONE);
899
+ const invertedAcc = F.inv(multipliedAcc);
900
+ nums.reduceRight((acc, num, i) => {
901
+ if (F.is0(num))
902
+ return acc;
903
+ inverted[i] = F.mul(acc, inverted[i]);
904
+ return F.mul(acc, num);
905
+ }, invertedAcc);
906
+ return inverted;
907
+ }
908
+ function FpLegendre(Fp3, n) {
909
+ const F = Fp3;
910
+ const p1mod2 = (F.ORDER - _1n2) / _2n;
911
+ const powered = F.pow(n, p1mod2);
912
+ const yes = F.eql(powered, F.ONE);
913
+ const zero = F.eql(powered, F.ZERO);
914
+ const no = F.eql(powered, F.neg(F.ONE));
915
+ if (!yes && !zero && !no)
916
+ throw new Error("invalid Legendre symbol result");
917
+ return yes ? 1 : zero ? 0 : -1;
918
+ }
919
+ function FpIsSquare(Fp3, n) {
920
+ const l = FpLegendre(Fp3, n);
921
+ return l !== -1;
922
+ }
923
+ function nLength(n, nBitLength) {
924
+ if (nBitLength !== void 0)
925
+ anumber2(nBitLength);
926
+ if (n <= _0n2)
927
+ throw new Error("invalid n length: expected positive n, got " + n);
928
+ if (nBitLength !== void 0 && nBitLength < 1)
929
+ throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
930
+ const bits = bitLen(n);
931
+ if (nBitLength !== void 0 && nBitLength < bits)
932
+ throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
933
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
934
+ const nByteLength = Math.ceil(_nBitLength / 8);
935
+ return { nBitLength: _nBitLength, nByteLength };
936
+ }
937
+ var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
938
+ var _Field = class {
939
+ constructor(ORDER, opts = {}) {
940
+ __publicField(this, "ORDER");
941
+ __publicField(this, "BITS");
942
+ __publicField(this, "BYTES");
943
+ __publicField(this, "isLE");
944
+ __publicField(this, "ZERO", _0n2);
945
+ __publicField(this, "ONE", _1n2);
946
+ __publicField(this, "_lengths");
947
+ __publicField(this, "_mod");
948
+ if (ORDER <= _1n2)
949
+ throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
950
+ let _nbitLength = void 0;
951
+ this.isLE = false;
952
+ if (opts != null && typeof opts === "object") {
953
+ if (typeof opts.BITS === "number")
954
+ _nbitLength = opts.BITS;
955
+ if (typeof opts.sqrt === "function")
956
+ Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
957
+ if (typeof opts.isLE === "boolean")
958
+ this.isLE = opts.isLE;
959
+ if (opts.allowedLengths)
960
+ this._lengths = Object.freeze(opts.allowedLengths.slice());
961
+ if (typeof opts.modFromBytes === "boolean")
962
+ this._mod = opts.modFromBytes;
963
+ }
964
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
965
+ if (nByteLength > 2048)
966
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
967
+ this.ORDER = ORDER;
968
+ this.BITS = nBitLength;
969
+ this.BYTES = nByteLength;
970
+ Object.freeze(this);
971
+ }
972
+ create(num) {
973
+ return mod(num, this.ORDER);
974
+ }
975
+ isValid(num) {
976
+ if (typeof num !== "bigint")
977
+ throw new TypeError("invalid field element: expected bigint, got " + typeof num);
978
+ return _0n2 <= num && num < this.ORDER;
979
+ }
980
+ is0(num) {
981
+ return num === _0n2;
982
+ }
983
+ // is valid and invertible
984
+ isValidNot0(num) {
985
+ return !this.is0(num) && this.isValid(num);
986
+ }
987
+ isOdd(num) {
988
+ return (num & _1n2) === _1n2;
989
+ }
990
+ neg(num) {
991
+ return mod(-num, this.ORDER);
992
+ }
993
+ eql(lhs, rhs) {
994
+ return lhs === rhs;
995
+ }
996
+ sqr(num) {
997
+ return mod(num * num, this.ORDER);
998
+ }
999
+ add(lhs, rhs) {
1000
+ return mod(lhs + rhs, this.ORDER);
1001
+ }
1002
+ sub(lhs, rhs) {
1003
+ return mod(lhs - rhs, this.ORDER);
1004
+ }
1005
+ mul(lhs, rhs) {
1006
+ return mod(lhs * rhs, this.ORDER);
1007
+ }
1008
+ pow(num, power) {
1009
+ return FpPow(this, num, power);
1010
+ }
1011
+ div(lhs, rhs) {
1012
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
1013
+ }
1014
+ // Same as above, but doesn't normalize
1015
+ sqrN(num) {
1016
+ return num * num;
1017
+ }
1018
+ addN(lhs, rhs) {
1019
+ return lhs + rhs;
1020
+ }
1021
+ subN(lhs, rhs) {
1022
+ return lhs - rhs;
1023
+ }
1024
+ mulN(lhs, rhs) {
1025
+ return lhs * rhs;
1026
+ }
1027
+ inv(num) {
1028
+ return invert(num, this.ORDER);
1029
+ }
1030
+ sqrt(num) {
1031
+ let sqrt = FIELD_SQRT.get(this);
1032
+ if (!sqrt)
1033
+ FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
1034
+ return sqrt(this, num);
1035
+ }
1036
+ toBytes(num) {
1037
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1038
+ }
1039
+ fromBytes(bytes, skipValidation = false) {
1040
+ abytes2(bytes);
1041
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
1042
+ if (allowedLengths) {
1043
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1044
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1045
+ }
1046
+ const padded = new Uint8Array(BYTES);
1047
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
1048
+ bytes = padded;
1049
+ }
1050
+ if (bytes.length !== BYTES)
1051
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1052
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1053
+ if (modFromBytes)
1054
+ scalar = mod(scalar, ORDER);
1055
+ if (!skipValidation) {
1056
+ if (!this.isValid(scalar))
1057
+ throw new Error("invalid field element: outside of range 0..ORDER");
1058
+ }
1059
+ return scalar;
1060
+ }
1061
+ // TODO: we don't need it here, move out to separate fn
1062
+ invertBatch(lst) {
1063
+ return FpInvertBatch(this, lst);
1064
+ }
1065
+ // We can't move this out because Fp6, Fp12 implement it
1066
+ // and it's unclear what to return in there.
1067
+ cmov(a, b, condition) {
1068
+ abool(condition, "condition");
1069
+ return condition ? b : a;
1070
+ }
1071
+ };
1072
+ Object.freeze(_Field.prototype);
1073
+ function Field(ORDER, opts = {}) {
1074
+ return new _Field(ORDER, opts);
1075
+ }
1076
+ function getFieldBytesLength(fieldOrder) {
1077
+ if (typeof fieldOrder !== "bigint")
1078
+ throw new Error("field order must be bigint");
1079
+ if (fieldOrder <= _1n2)
1080
+ throw new Error("field order must be greater than 1");
1081
+ const bitLength = bitLen(fieldOrder - _1n2);
1082
+ return Math.ceil(bitLength / 8);
1083
+ }
1084
+ function getMinHashLength(fieldOrder) {
1085
+ const length = getFieldBytesLength(fieldOrder);
1086
+ return length + Math.ceil(length / 2);
1087
+ }
1088
+ function mapHashToField(key, fieldOrder, isLE = false) {
1089
+ abytes2(key);
1090
+ const len = key.length;
1091
+ const fieldLen = getFieldBytesLength(fieldOrder);
1092
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
1093
+ if (len < minLen || len > 1024)
1094
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
1095
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
1096
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
1097
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1098
+ }
1099
+
1100
+ // node_modules/@noble/curves/abstract/curve.js
1101
+ var _0n3 = /* @__PURE__ */ BigInt(0);
1102
+ var _1n3 = /* @__PURE__ */ BigInt(1);
1103
+ function negateCt(condition, item) {
1104
+ const neg = item.negate();
1105
+ return condition ? neg : item;
1106
+ }
1107
+ function normalizeZ(c, points) {
1108
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1109
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1110
+ }
1111
+ function validateW(W, bits) {
1112
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1113
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1114
+ }
1115
+ function calcWOpts(W, scalarBits) {
1116
+ validateW(W, scalarBits);
1117
+ const windows = Math.ceil(scalarBits / W) + 1;
1118
+ const windowSize = 2 ** (W - 1);
1119
+ const maxNumber = 2 ** W;
1120
+ const mask = bitMask(W);
1121
+ const shiftBy = BigInt(W);
1122
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1123
+ }
1124
+ function calcOffsets(n, window, wOpts) {
1125
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1126
+ let wbits = Number(n & mask);
1127
+ let nextN = n >> shiftBy;
1128
+ if (wbits > windowSize) {
1129
+ wbits -= maxNumber;
1130
+ nextN += _1n3;
1131
+ }
1132
+ const offsetStart = window * windowSize;
1133
+ const offset = offsetStart + Math.abs(wbits) - 1;
1134
+ const isZero = wbits === 0;
1135
+ const isNeg = wbits < 0;
1136
+ const isNegF = window % 2 !== 0;
1137
+ const offsetF = offsetStart;
1138
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1139
+ }
1140
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1141
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1142
+ function getW(P) {
1143
+ return pointWindowSizes.get(P) || 1;
1144
+ }
1145
+ function assert0(n) {
1146
+ if (n !== _0n3)
1147
+ throw new Error("invalid wNAF");
1148
+ }
1149
+ var wNAF = class {
1150
+ // Parametrized with a given Point class (not individual point)
1151
+ constructor(Point, bits) {
1152
+ __publicField(this, "BASE");
1153
+ __publicField(this, "ZERO");
1154
+ __publicField(this, "Fn");
1155
+ __publicField(this, "bits");
1156
+ this.BASE = Point.BASE;
1157
+ this.ZERO = Point.ZERO;
1158
+ this.Fn = Point.Fn;
1159
+ this.bits = bits;
1160
+ }
1161
+ // non-const time multiplication ladder
1162
+ _unsafeLadder(elm, n, p = this.ZERO) {
1163
+ let d = elm;
1164
+ while (n > _0n3) {
1165
+ if (n & _1n3)
1166
+ p = p.add(d);
1167
+ d = d.double();
1168
+ n >>= _1n3;
1169
+ }
1170
+ return p;
1171
+ }
1172
+ /**
1173
+ * Creates a wNAF precomputation window. Used for caching.
1174
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1175
+ * Number of precomputed points depends on the curve size:
1176
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1177
+ * - 𝑊 is the window size
1178
+ * - 𝑛 is the bitlength of the curve order.
1179
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1180
+ * @param point - Point instance
1181
+ * @param W - window size
1182
+ * @returns precomputed point tables flattened to a single array
1183
+ */
1184
+ precomputeWindow(point, W) {
1185
+ const { windows, windowSize } = calcWOpts(W, this.bits);
1186
+ const points = [];
1187
+ let p = point;
1188
+ let base = p;
1189
+ for (let window = 0; window < windows; window++) {
1190
+ base = p;
1191
+ points.push(base);
1192
+ for (let i = 1; i < windowSize; i++) {
1193
+ base = base.add(p);
1194
+ points.push(base);
1195
+ }
1196
+ p = base.double();
1197
+ }
1198
+ return points;
1199
+ }
1200
+ /**
1201
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1202
+ * More compact implementation:
1203
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1204
+ * @returns real and fake (for const-time) points
1205
+ */
1206
+ wNAF(W, precomputes, n) {
1207
+ if (!this.Fn.isValid(n))
1208
+ throw new Error("invalid scalar");
1209
+ let p = this.ZERO;
1210
+ let f = this.BASE;
1211
+ const wo = calcWOpts(W, this.bits);
1212
+ for (let window = 0; window < wo.windows; window++) {
1213
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1214
+ n = nextN;
1215
+ if (isZero) {
1216
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
1217
+ } else {
1218
+ p = p.add(negateCt(isNeg, precomputes[offset]));
1219
+ }
1220
+ }
1221
+ assert0(n);
1222
+ return { p, f };
1223
+ }
1224
+ /**
1225
+ * Implements unsafe EC multiplication using precomputed tables
1226
+ * and w-ary non-adjacent form.
1227
+ * @param acc - accumulator point to add result of multiplication
1228
+ * @returns point
1229
+ */
1230
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1231
+ const wo = calcWOpts(W, this.bits);
1232
+ for (let window = 0; window < wo.windows; window++) {
1233
+ if (n === _0n3)
1234
+ break;
1235
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1236
+ n = nextN;
1237
+ if (isZero) {
1238
+ continue;
1239
+ } else {
1240
+ const item = precomputes[offset];
1241
+ acc = acc.add(isNeg ? item.negate() : item);
1242
+ }
1243
+ }
1244
+ assert0(n);
1245
+ return acc;
1246
+ }
1247
+ getPrecomputes(W, point, transform) {
1248
+ let comp = pointPrecomputes.get(point);
1249
+ if (!comp) {
1250
+ comp = this.precomputeWindow(point, W);
1251
+ if (W !== 1) {
1252
+ if (typeof transform === "function")
1253
+ comp = transform(comp);
1254
+ pointPrecomputes.set(point, comp);
1255
+ }
1256
+ }
1257
+ return comp;
1258
+ }
1259
+ cached(point, scalar, transform) {
1260
+ const W = getW(point);
1261
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1262
+ }
1263
+ unsafe(point, scalar, transform, prev) {
1264
+ const W = getW(point);
1265
+ if (W === 1)
1266
+ return this._unsafeLadder(point, scalar, prev);
1267
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1268
+ }
1269
+ // We calculate precomputes for elliptic curve point multiplication
1270
+ // using windowed method. This specifies window size and
1271
+ // stores precomputed values. Usually only base point would be precomputed.
1272
+ createCache(P, W) {
1273
+ validateW(W, this.bits);
1274
+ pointWindowSizes.set(P, W);
1275
+ pointPrecomputes.delete(P);
1276
+ }
1277
+ hasCache(elm) {
1278
+ return getW(elm) !== 1;
1279
+ }
1280
+ };
1281
+ function mulEndoUnsafe(Point, point, k1, k2) {
1282
+ let acc = point;
1283
+ let p1 = Point.ZERO;
1284
+ let p2 = Point.ZERO;
1285
+ while (k1 > _0n3 || k2 > _0n3) {
1286
+ if (k1 & _1n3)
1287
+ p1 = p1.add(acc);
1288
+ if (k2 & _1n3)
1289
+ p2 = p2.add(acc);
1290
+ acc = acc.double();
1291
+ k1 >>= _1n3;
1292
+ k2 >>= _1n3;
1293
+ }
1294
+ return { p1, p2 };
1295
+ }
1296
+ function createField(order, field, isLE) {
1297
+ if (field) {
1298
+ if (field.ORDER !== order)
1299
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1300
+ validateField(field);
1301
+ return field;
1302
+ } else {
1303
+ return Field(order, { isLE });
1304
+ }
1305
+ }
1306
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1307
+ if (FpFnLE === void 0)
1308
+ FpFnLE = type === "edwards";
1309
+ if (!CURVE || typeof CURVE !== "object")
1310
+ throw new Error(`expected valid ${type} CURVE object`);
1311
+ for (const p of ["p", "n", "h"]) {
1312
+ const val = CURVE[p];
1313
+ if (!(typeof val === "bigint" && val > _0n3))
1314
+ throw new Error(`CURVE.${p} must be positive bigint`);
1315
+ }
1316
+ const Fp3 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1317
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1318
+ const _b = type === "weierstrass" ? "b" : "d";
1319
+ const params = ["Gx", "Gy", "a", _b];
1320
+ for (const p of params) {
1321
+ if (!Fp3.isValid(CURVE[p]))
1322
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1323
+ }
1324
+ CURVE = Object.freeze(Object.assign({}, CURVE));
1325
+ return { CURVE, Fp: Fp3, Fn };
1326
+ }
1327
+ function createKeygen(randomSecretKey, getPublicKey) {
1328
+ return function keygen(seed) {
1329
+ const secretKey = randomSecretKey(seed);
1330
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1331
+ };
1332
+ }
1333
+
1334
+ // node_modules/@noble/curves/abstract/hash-to-curve.js
1335
+ var os2ip = bytesToNumberBE;
1336
+ function i2osp(value, length) {
1337
+ asafenumber(value);
1338
+ asafenumber(length);
1339
+ if (length < 0 || length > 4)
1340
+ throw new Error("invalid I2OSP length: " + length);
1341
+ if (value < 0 || value > 2 ** (8 * length) - 1)
1342
+ throw new Error("invalid I2OSP input: " + value);
1343
+ const res = Array.from({ length }).fill(0);
1344
+ for (let i = length - 1; i >= 0; i--) {
1345
+ res[i] = value & 255;
1346
+ value >>>= 8;
1347
+ }
1348
+ return new Uint8Array(res);
1349
+ }
1350
+ function strxor(a, b) {
1351
+ const arr = new Uint8Array(a.length);
1352
+ for (let i = 0; i < a.length; i++) {
1353
+ arr[i] = a[i] ^ b[i];
1354
+ }
1355
+ return arr;
1356
+ }
1357
+ function normDST(DST) {
1358
+ if (!isBytes2(DST) && typeof DST !== "string")
1359
+ throw new Error("DST must be Uint8Array or ascii string");
1360
+ const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
1361
+ if (dst.length === 0)
1362
+ throw new Error("DST must be non-empty");
1363
+ return dst;
1364
+ }
1365
+ function expand_message_xmd(msg, DST, lenInBytes, H) {
1366
+ abytes2(msg);
1367
+ asafenumber(lenInBytes);
1368
+ DST = normDST(DST);
1369
+ if (DST.length > 255)
1370
+ DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
1371
+ const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1372
+ const ell = Math.ceil(lenInBytes / b_in_bytes);
1373
+ if (lenInBytes > 65535 || ell > 255)
1374
+ throw new Error("expand_message_xmd: invalid lenInBytes");
1375
+ const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
1376
+ const Z_pad = new Uint8Array(r_in_bytes);
1377
+ const l_i_b_str = i2osp(lenInBytes, 2);
1378
+ const b = new Array(ell);
1379
+ const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1380
+ b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
1381
+ for (let i = 1; i < ell; i++) {
1382
+ const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1383
+ b[i] = H(concatBytes2(...args));
1384
+ }
1385
+ const pseudo_random_bytes = concatBytes2(...b);
1386
+ return pseudo_random_bytes.slice(0, lenInBytes);
1387
+ }
1388
+ function expand_message_xof(msg, DST, lenInBytes, k, H) {
1389
+ abytes2(msg);
1390
+ asafenumber(lenInBytes);
1391
+ DST = normDST(DST);
1392
+ if (DST.length > 255) {
1393
+ const dkLen = Math.ceil(2 * k / 8);
1394
+ DST = H.create({ dkLen }).update(asciiToBytes("H2C-OVERSIZE-DST-")).update(DST).digest();
1395
+ }
1396
+ if (lenInBytes > 65535 || DST.length > 255)
1397
+ throw new Error("expand_message_xof: invalid lenInBytes");
1398
+ return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
1399
+ }
1400
+ function hash_to_field(msg, count, options) {
1401
+ validateObject(options, {
1402
+ p: "bigint",
1403
+ m: "number",
1404
+ k: "number",
1405
+ hash: "function"
1406
+ });
1407
+ const { p, k, m, hash, expand, DST } = options;
1408
+ asafenumber(hash.outputLen, "valid hash");
1409
+ abytes2(msg);
1410
+ asafenumber(count);
1411
+ if (count < 1)
1412
+ throw new Error("hash_to_field: expected count >= 1");
1413
+ if (m < 1)
1414
+ throw new Error("hash_to_field: expected m >= 1");
1415
+ const log2p = p.toString(2).length;
1416
+ const L = Math.ceil((log2p + k) / 8);
1417
+ const len_in_bytes = count * m * L;
1418
+ let prb;
1419
+ if (expand === "xmd") {
1420
+ prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
1421
+ } else if (expand === "xof") {
1422
+ prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
1423
+ } else if (expand === "_internal_pass") {
1424
+ prb = msg;
1425
+ } else {
1426
+ throw new Error('expand must be "xmd" or "xof"');
1427
+ }
1428
+ const u = new Array(count);
1429
+ for (let i = 0; i < count; i++) {
1430
+ const e = new Array(m);
1431
+ for (let j = 0; j < m; j++) {
1432
+ const elm_offset = L * (j + i * m);
1433
+ const tv = prb.subarray(elm_offset, elm_offset + L);
1434
+ e[j] = mod(os2ip(tv), p);
1435
+ }
1436
+ u[i] = e;
1437
+ }
1438
+ return u;
1439
+ }
1440
+ function isogenyMap(field, map) {
1441
+ const coeff = map.map((i) => Array.from(i).reverse());
1442
+ return (x, y) => {
1443
+ const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
1444
+ const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
1445
+ x = field.mul(xn, xd_inv);
1446
+ y = field.mul(y, field.mul(yn, yd_inv));
1447
+ return { x, y };
1448
+ };
1449
+ }
1450
+ var _DST_scalar = "HashToScalar-";
1451
+ function createHasher2(Point, mapToCurve, defaults) {
1452
+ if (typeof mapToCurve !== "function")
1453
+ throw new Error("mapToCurve() must be defined");
1454
+ const snapshot = (src) => Object.freeze(__spreadValues(__spreadProps(__spreadValues({}, src), {
1455
+ DST: isBytes2(src.DST) ? copyBytes(src.DST) : src.DST
1456
+ }), src.encodeDST === void 0 ? {} : { encodeDST: isBytes2(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }));
1457
+ const safeDefaults = snapshot(defaults);
1458
+ function map(num) {
1459
+ return Point.fromAffine(mapToCurve(num));
1460
+ }
1461
+ function clear(initial) {
1462
+ const P = initial.clearCofactor();
1463
+ if (P.equals(Point.ZERO))
1464
+ return Point.ZERO;
1465
+ P.assertValidity();
1466
+ return P;
1467
+ }
1468
+ return Object.freeze({
1469
+ get defaults() {
1470
+ return snapshot(safeDefaults);
1471
+ },
1472
+ Point,
1473
+ hashToCurve(msg, options) {
1474
+ const opts = Object.assign({}, safeDefaults, options);
1475
+ const u = hash_to_field(msg, 2, opts);
1476
+ const u0 = map(u[0]);
1477
+ const u1 = map(u[1]);
1478
+ return clear(u0.add(u1));
1479
+ },
1480
+ encodeToCurve(msg, options) {
1481
+ const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};
1482
+ const opts = Object.assign({}, safeDefaults, optsDst, options);
1483
+ const u = hash_to_field(msg, 1, opts);
1484
+ const u0 = map(u[0]);
1485
+ return clear(u0);
1486
+ },
1487
+ /** See {@link H2CHasher} */
1488
+ mapToCurve(scalars) {
1489
+ if (safeDefaults.m === 1) {
1490
+ if (typeof scalars !== "bigint")
1491
+ throw new Error("expected bigint (m=1)");
1492
+ return clear(map([scalars]));
1493
+ }
1494
+ if (!Array.isArray(scalars))
1495
+ throw new Error("expected array of bigints");
1496
+ for (const i of scalars)
1497
+ if (typeof i !== "bigint")
1498
+ throw new Error("expected array of bigints");
1499
+ return clear(map(scalars));
1500
+ },
1501
+ // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
1502
+ // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic
1503
+ // `HashToScalar-` prefix above unless the caller overrides it per invocation.
1504
+ hashToScalar(msg, options) {
1505
+ const N = Point.Fn.ORDER;
1506
+ const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);
1507
+ return hash_to_field(msg, 1, opts)[0][0];
1508
+ }
1509
+ });
1510
+ }
1511
+
1512
+ // node_modules/@noble/curves/node_modules/@noble/hashes/hmac.js
1513
+ var _HMAC = class {
1514
+ constructor(hash, key) {
1515
+ __publicField(this, "oHash");
1516
+ __publicField(this, "iHash");
1517
+ __publicField(this, "blockLen");
1518
+ __publicField(this, "outputLen");
1519
+ __publicField(this, "canXOF", false);
1520
+ __publicField(this, "finished", false);
1521
+ __publicField(this, "destroyed", false);
1522
+ ahash(hash);
1523
+ abytes(key, void 0, "key");
1524
+ this.iHash = hash.create();
1525
+ if (typeof this.iHash.update !== "function")
1526
+ throw new Error("Expected instance of class which extends utils.Hash");
1527
+ this.blockLen = this.iHash.blockLen;
1528
+ this.outputLen = this.iHash.outputLen;
1529
+ const blockLen = this.blockLen;
1530
+ const pad = new Uint8Array(blockLen);
1531
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1532
+ for (let i = 0; i < pad.length; i++)
1533
+ pad[i] ^= 54;
1534
+ this.iHash.update(pad);
1535
+ this.oHash = hash.create();
1536
+ for (let i = 0; i < pad.length; i++)
1537
+ pad[i] ^= 54 ^ 92;
1538
+ this.oHash.update(pad);
1539
+ clean(pad);
1540
+ }
1541
+ update(buf) {
1542
+ aexists(this);
1543
+ this.iHash.update(buf);
1544
+ return this;
1545
+ }
1546
+ digestInto(out) {
1547
+ aexists(this);
1548
+ aoutput(out, this);
1549
+ this.finished = true;
1550
+ const buf = out.subarray(0, this.outputLen);
1551
+ this.iHash.digestInto(buf);
1552
+ this.oHash.update(buf);
1553
+ this.oHash.digestInto(buf);
1554
+ this.destroy();
1555
+ }
1556
+ digest() {
1557
+ const out = new Uint8Array(this.oHash.outputLen);
1558
+ this.digestInto(out);
1559
+ return out;
1560
+ }
1561
+ _cloneInto(to) {
1562
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
1563
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1564
+ to = to;
1565
+ to.finished = finished;
1566
+ to.destroyed = destroyed;
1567
+ to.blockLen = blockLen;
1568
+ to.outputLen = outputLen;
1569
+ to.oHash = oHash._cloneInto(to.oHash);
1570
+ to.iHash = iHash._cloneInto(to.iHash);
1571
+ return to;
1572
+ }
1573
+ clone() {
1574
+ return this._cloneInto();
1575
+ }
1576
+ destroy() {
1577
+ this.destroyed = true;
1578
+ this.oHash.destroy();
1579
+ this.iHash.destroy();
1580
+ }
1581
+ };
1582
+ var hmac = /* @__PURE__ */ (() => {
1583
+ const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
1584
+ hmac_.create = (hash, key) => new _HMAC(hash, key);
1585
+ return hmac_;
1586
+ })();
1587
+
1588
+ // node_modules/@noble/curves/abstract/weierstrass.js
1589
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
1590
+ function _splitEndoScalar(k, basis, n) {
1591
+ aInRange("scalar", k, _0n4, n);
1592
+ const [[a1, b1], [a2, b2]] = basis;
1593
+ const c1 = divNearest(b2 * k, n);
1594
+ const c2 = divNearest(-b1 * k, n);
1595
+ let k1 = k - c1 * a1 - c2 * a2;
1596
+ let k2 = -c1 * b1 - c2 * b2;
1597
+ const k1neg = k1 < _0n4;
1598
+ const k2neg = k2 < _0n4;
1599
+ if (k1neg)
1600
+ k1 = -k1;
1601
+ if (k2neg)
1602
+ k2 = -k2;
1603
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
1604
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
1605
+ throw new Error("splitScalar (endomorphism): failed for k");
1606
+ }
1607
+ return { k1neg, k1, k2neg, k2 };
1608
+ }
1609
+ function validateSigFormat(format) {
1610
+ if (!["compact", "recovered", "der"].includes(format))
1611
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
1612
+ return format;
1613
+ }
1614
+ function validateSigOpts(opts, def) {
1615
+ validateObject(opts);
1616
+ const optsn = {};
1617
+ for (let optName of Object.keys(def)) {
1618
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
1619
+ }
1620
+ abool(optsn.lowS, "lowS");
1621
+ abool(optsn.prehash, "prehash");
1622
+ if (optsn.format !== void 0)
1623
+ validateSigFormat(optsn.format);
1624
+ return optsn;
1625
+ }
1626
+ var DERErr = class extends Error {
1627
+ constructor(m = "") {
1628
+ super(m);
1629
+ }
1630
+ };
1631
+ var DER = {
1632
+ // asn.1 DER encoding utils
1633
+ Err: DERErr,
1634
+ // Basic building block is TLV (Tag-Length-Value)
1635
+ _tlv: {
1636
+ encode: (tag, data) => {
1637
+ const { Err: E } = DER;
1638
+ asafenumber(tag, "tag");
1639
+ if (tag < 0 || tag > 255)
1640
+ throw new E("tlv.encode: wrong tag");
1641
+ if (typeof data !== "string")
1642
+ throw new TypeError('"data" expected string, got type=' + typeof data);
1643
+ if (data.length & 1)
1644
+ throw new E("tlv.encode: unpadded data");
1645
+ const dataLen = data.length / 2;
1646
+ const len = numberToHexUnpadded(dataLen);
1647
+ if (len.length / 2 & 128)
1648
+ throw new E("tlv.encode: long form length too big");
1649
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
1650
+ const t = numberToHexUnpadded(tag);
1651
+ return t + lenLen + len + data;
1652
+ },
1653
+ // v - value, l - left bytes (unparsed)
1654
+ decode(tag, data) {
1655
+ const { Err: E } = DER;
1656
+ data = abytes2(data, void 0, "DER data");
1657
+ let pos = 0;
1658
+ if (tag < 0 || tag > 255)
1659
+ throw new E("tlv.encode: wrong tag");
1660
+ if (data.length < 2 || data[pos++] !== tag)
1661
+ throw new E("tlv.decode: wrong tlv");
1662
+ const first = data[pos++];
1663
+ const isLong = !!(first & 128);
1664
+ let length = 0;
1665
+ if (!isLong)
1666
+ length = first;
1667
+ else {
1668
+ const lenLen = first & 127;
1669
+ if (!lenLen)
1670
+ throw new E("tlv.decode(long): indefinite length not supported");
1671
+ if (lenLen > 4)
1672
+ throw new E("tlv.decode(long): byte length is too big");
1673
+ const lengthBytes = data.subarray(pos, pos + lenLen);
1674
+ if (lengthBytes.length !== lenLen)
1675
+ throw new E("tlv.decode: length bytes not complete");
1676
+ if (lengthBytes[0] === 0)
1677
+ throw new E("tlv.decode(long): zero leftmost byte");
1678
+ for (const b of lengthBytes)
1679
+ length = length << 8 | b;
1680
+ pos += lenLen;
1681
+ if (length < 128)
1682
+ throw new E("tlv.decode(long): not minimal encoding");
1683
+ }
1684
+ const v = data.subarray(pos, pos + length);
1685
+ if (v.length !== length)
1686
+ throw new E("tlv.decode: wrong value length");
1687
+ return { v, l: data.subarray(pos + length) };
1688
+ }
1689
+ },
1690
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
1691
+ // since we always use positive integers here. It must always be empty:
1692
+ // - add zero byte if exists
1693
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
1694
+ _int: {
1695
+ encode(num) {
1696
+ const { Err: E } = DER;
1697
+ abignumber(num);
1698
+ if (num < _0n4)
1699
+ throw new E("integer: negative integers are not allowed");
1700
+ let hex = numberToHexUnpadded(num);
1701
+ if (Number.parseInt(hex[0], 16) & 8)
1702
+ hex = "00" + hex;
1703
+ if (hex.length & 1)
1704
+ throw new E("unexpected DER parsing assertion: unpadded hex");
1705
+ return hex;
1706
+ },
1707
+ decode(data) {
1708
+ const { Err: E } = DER;
1709
+ if (data.length < 1)
1710
+ throw new E("invalid signature integer: empty");
1711
+ if (data[0] & 128)
1712
+ throw new E("invalid signature integer: negative");
1713
+ if (data.length > 1 && data[0] === 0 && !(data[1] & 128))
1714
+ throw new E("invalid signature integer: unnecessary leading zero");
1715
+ return bytesToNumberBE(data);
1716
+ }
1717
+ },
1718
+ toSig(bytes) {
1719
+ const { Err: E, _int: int, _tlv: tlv } = DER;
1720
+ const data = abytes2(bytes, void 0, "signature");
1721
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
1722
+ if (seqLeftBytes.length)
1723
+ throw new E("invalid signature: left bytes after parsing");
1724
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
1725
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
1726
+ if (sLeftBytes.length)
1727
+ throw new E("invalid signature: left bytes after parsing");
1728
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
1729
+ },
1730
+ hexFromSig(sig) {
1731
+ const { _tlv: tlv, _int: int } = DER;
1732
+ const rs = tlv.encode(2, int.encode(sig.r));
1733
+ const ss = tlv.encode(2, int.encode(sig.s));
1734
+ const seq = rs + ss;
1735
+ return tlv.encode(48, seq);
1736
+ }
1737
+ };
1738
+ Object.freeze(DER._tlv);
1739
+ Object.freeze(DER._int);
1740
+ Object.freeze(DER);
1741
+ var _0n4 = /* @__PURE__ */ BigInt(0);
1742
+ var _1n4 = /* @__PURE__ */ BigInt(1);
1743
+ var _2n2 = /* @__PURE__ */ BigInt(2);
1744
+ var _3n2 = /* @__PURE__ */ BigInt(3);
1745
+ var _4n2 = /* @__PURE__ */ BigInt(4);
1746
+ function weierstrass(params, extraOpts = {}) {
1747
+ const validated = createCurveFields("weierstrass", params, extraOpts);
1748
+ const Fp3 = validated.Fp;
1749
+ const Fn = validated.Fn;
1750
+ let CURVE = validated.CURVE;
1751
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
1752
+ validateObject(extraOpts, {}, {
1753
+ allowInfinityPoint: "boolean",
1754
+ clearCofactor: "function",
1755
+ isTorsionFree: "function",
1756
+ fromBytes: "function",
1757
+ toBytes: "function",
1758
+ endo: "object"
1759
+ });
1760
+ const { endo, allowInfinityPoint } = extraOpts;
1761
+ if (endo) {
1762
+ if (!Fp3.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
1763
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
1764
+ }
1765
+ }
1766
+ const lengths = getWLengths(Fp3, Fn);
1767
+ function assertCompressionIsSupported() {
1768
+ if (!Fp3.isOdd)
1769
+ throw new Error("compression is not supported: Field does not have .isOdd()");
1770
+ }
1771
+ function pointToBytes(_c, point, isCompressed) {
1772
+ if (allowInfinityPoint && point.is0())
1773
+ return Uint8Array.of(0);
1774
+ const { x, y } = point.toAffine();
1775
+ const bx = Fp3.toBytes(x);
1776
+ abool(isCompressed, "isCompressed");
1777
+ if (isCompressed) {
1778
+ assertCompressionIsSupported();
1779
+ const hasEvenY = !Fp3.isOdd(y);
1780
+ return concatBytes2(pprefix(hasEvenY), bx);
1781
+ } else {
1782
+ return concatBytes2(Uint8Array.of(4), bx, Fp3.toBytes(y));
1783
+ }
1784
+ }
1785
+ function pointFromBytes(bytes) {
1786
+ abytes2(bytes, void 0, "Point");
1787
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
1788
+ const length = bytes.length;
1789
+ const head = bytes[0];
1790
+ const tail = bytes.subarray(1);
1791
+ if (allowInfinityPoint && length === 1 && head === 0)
1792
+ return { x: Fp3.ZERO, y: Fp3.ZERO };
1793
+ if (length === comp && (head === 2 || head === 3)) {
1794
+ const x = Fp3.fromBytes(tail);
1795
+ if (!Fp3.isValid(x))
1796
+ throw new Error("bad point: is not on curve, wrong x");
1797
+ const y2 = weierstrassEquation(x);
1798
+ let y;
1799
+ try {
1800
+ y = Fp3.sqrt(y2);
1801
+ } catch (sqrtError) {
1802
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1803
+ throw new Error("bad point: is not on curve, sqrt error" + err);
1804
+ }
1805
+ assertCompressionIsSupported();
1806
+ const evenY = Fp3.isOdd(y);
1807
+ const evenH = (head & 1) === 1;
1808
+ if (evenH !== evenY)
1809
+ y = Fp3.neg(y);
1810
+ return { x, y };
1811
+ } else if (length === uncomp && head === 4) {
1812
+ const L = Fp3.BYTES;
1813
+ const x = Fp3.fromBytes(tail.subarray(0, L));
1814
+ const y = Fp3.fromBytes(tail.subarray(L, L * 2));
1815
+ if (!isValidXY(x, y))
1816
+ throw new Error("bad point: is not on curve");
1817
+ return { x, y };
1818
+ } else {
1819
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
1820
+ }
1821
+ }
1822
+ const encodePoint = extraOpts.toBytes === void 0 ? pointToBytes : extraOpts.toBytes;
1823
+ const decodePoint = extraOpts.fromBytes === void 0 ? pointFromBytes : extraOpts.fromBytes;
1824
+ function weierstrassEquation(x) {
1825
+ const x2 = Fp3.sqr(x);
1826
+ const x3 = Fp3.mul(x2, x);
1827
+ return Fp3.add(Fp3.add(x3, Fp3.mul(x, CURVE.a)), CURVE.b);
1828
+ }
1829
+ function isValidXY(x, y) {
1830
+ const left = Fp3.sqr(y);
1831
+ const right = weierstrassEquation(x);
1832
+ return Fp3.eql(left, right);
1833
+ }
1834
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
1835
+ throw new Error("bad curve params: generator point");
1836
+ const _4a3 = Fp3.mul(Fp3.pow(CURVE.a, _3n2), _4n2);
1837
+ const _27b2 = Fp3.mul(Fp3.sqr(CURVE.b), BigInt(27));
1838
+ if (Fp3.is0(Fp3.add(_4a3, _27b2)))
1839
+ throw new Error("bad curve params: a or b");
1840
+ function acoord(title, n, banZero = false) {
1841
+ if (!Fp3.isValid(n) || banZero && Fp3.is0(n))
1842
+ throw new Error(`bad point coordinate ${title}`);
1843
+ return n;
1844
+ }
1845
+ function aprjpoint(other) {
1846
+ if (!(other instanceof Point))
1847
+ throw new Error("Weierstrass Point expected");
1848
+ }
1849
+ function splitEndoScalarN(k) {
1850
+ if (!endo || !endo.basises)
1851
+ throw new Error("no endo");
1852
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
1853
+ }
1854
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
1855
+ k2p = new Point(Fp3.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
1856
+ k1p = negateCt(k1neg, k1p);
1857
+ k2p = negateCt(k2neg, k2p);
1858
+ return k1p.add(k2p);
1859
+ }
1860
+ const _Point = class _Point {
1861
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1862
+ constructor(X, Y, Z) {
1863
+ __publicField(this, "X");
1864
+ __publicField(this, "Y");
1865
+ __publicField(this, "Z");
1866
+ this.X = acoord("x", X);
1867
+ this.Y = acoord("y", Y, true);
1868
+ this.Z = acoord("z", Z);
1869
+ Object.freeze(this);
1870
+ }
1871
+ static CURVE() {
1872
+ return CURVE;
1873
+ }
1874
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1875
+ static fromAffine(p) {
1876
+ const { x, y } = p || {};
1877
+ if (!p || !Fp3.isValid(x) || !Fp3.isValid(y))
1878
+ throw new Error("invalid affine point");
1879
+ if (p instanceof _Point)
1880
+ throw new Error("projective point not allowed");
1881
+ if (Fp3.is0(x) && Fp3.is0(y))
1882
+ return _Point.ZERO;
1883
+ return new _Point(x, y, Fp3.ONE);
1884
+ }
1885
+ static fromBytes(bytes) {
1886
+ const P = _Point.fromAffine(decodePoint(abytes2(bytes, void 0, "point")));
1887
+ P.assertValidity();
1888
+ return P;
1889
+ }
1890
+ static fromHex(hex) {
1891
+ return _Point.fromBytes(hexToBytes2(hex));
1892
+ }
1893
+ get x() {
1894
+ return this.toAffine().x;
1895
+ }
1896
+ get y() {
1897
+ return this.toAffine().y;
1898
+ }
1899
+ /**
1900
+ *
1901
+ * @param windowSize
1902
+ * @param isLazy - true will defer table computation until the first multiplication
1903
+ * @returns
1904
+ */
1905
+ precompute(windowSize = 8, isLazy = true) {
1906
+ wnaf.createCache(this, windowSize);
1907
+ if (!isLazy)
1908
+ this.multiply(_3n2);
1909
+ return this;
1910
+ }
1911
+ // TODO: return `this`
1912
+ /** A point on curve is valid if it conforms to equation. */
1913
+ assertValidity() {
1914
+ const p = this;
1915
+ if (p.is0()) {
1916
+ if (extraOpts.allowInfinityPoint && Fp3.is0(p.X) && Fp3.eql(p.Y, Fp3.ONE) && Fp3.is0(p.Z))
1917
+ return;
1918
+ throw new Error("bad point: ZERO");
1919
+ }
1920
+ const { x, y } = p.toAffine();
1921
+ if (!Fp3.isValid(x) || !Fp3.isValid(y))
1922
+ throw new Error("bad point: x or y not field elements");
1923
+ if (!isValidXY(x, y))
1924
+ throw new Error("bad point: equation left != right");
1925
+ if (!p.isTorsionFree())
1926
+ throw new Error("bad point: not in prime-order subgroup");
1927
+ }
1928
+ hasEvenY() {
1929
+ const { y } = this.toAffine();
1930
+ if (!Fp3.isOdd)
1931
+ throw new Error("Field doesn't support isOdd");
1932
+ return !Fp3.isOdd(y);
1933
+ }
1934
+ /** Compare one point to another. */
1935
+ equals(other) {
1936
+ aprjpoint(other);
1937
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1938
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1939
+ const U1 = Fp3.eql(Fp3.mul(X1, Z2), Fp3.mul(X2, Z1));
1940
+ const U2 = Fp3.eql(Fp3.mul(Y1, Z2), Fp3.mul(Y2, Z1));
1941
+ return U1 && U2;
1942
+ }
1943
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
1944
+ negate() {
1945
+ return new _Point(this.X, Fp3.neg(this.Y), this.Z);
1946
+ }
1947
+ // Renes-Costello-Batina exception-free doubling formula.
1948
+ // There is 30% faster Jacobian formula, but it is not complete.
1949
+ // https://eprint.iacr.org/2015/1060, algorithm 3
1950
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1951
+ double() {
1952
+ const { a, b } = CURVE;
1953
+ const b3 = Fp3.mul(b, _3n2);
1954
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1955
+ let X3 = Fp3.ZERO, Y3 = Fp3.ZERO, Z3 = Fp3.ZERO;
1956
+ let t0 = Fp3.mul(X1, X1);
1957
+ let t1 = Fp3.mul(Y1, Y1);
1958
+ let t2 = Fp3.mul(Z1, Z1);
1959
+ let t3 = Fp3.mul(X1, Y1);
1960
+ t3 = Fp3.add(t3, t3);
1961
+ Z3 = Fp3.mul(X1, Z1);
1962
+ Z3 = Fp3.add(Z3, Z3);
1963
+ X3 = Fp3.mul(a, Z3);
1964
+ Y3 = Fp3.mul(b3, t2);
1965
+ Y3 = Fp3.add(X3, Y3);
1966
+ X3 = Fp3.sub(t1, Y3);
1967
+ Y3 = Fp3.add(t1, Y3);
1968
+ Y3 = Fp3.mul(X3, Y3);
1969
+ X3 = Fp3.mul(t3, X3);
1970
+ Z3 = Fp3.mul(b3, Z3);
1971
+ t2 = Fp3.mul(a, t2);
1972
+ t3 = Fp3.sub(t0, t2);
1973
+ t3 = Fp3.mul(a, t3);
1974
+ t3 = Fp3.add(t3, Z3);
1975
+ Z3 = Fp3.add(t0, t0);
1976
+ t0 = Fp3.add(Z3, t0);
1977
+ t0 = Fp3.add(t0, t2);
1978
+ t0 = Fp3.mul(t0, t3);
1979
+ Y3 = Fp3.add(Y3, t0);
1980
+ t2 = Fp3.mul(Y1, Z1);
1981
+ t2 = Fp3.add(t2, t2);
1982
+ t0 = Fp3.mul(t2, t3);
1983
+ X3 = Fp3.sub(X3, t0);
1984
+ Z3 = Fp3.mul(t2, t1);
1985
+ Z3 = Fp3.add(Z3, Z3);
1986
+ Z3 = Fp3.add(Z3, Z3);
1987
+ return new _Point(X3, Y3, Z3);
1988
+ }
1989
+ // Renes-Costello-Batina exception-free addition formula.
1990
+ // There is 30% faster Jacobian formula, but it is not complete.
1991
+ // https://eprint.iacr.org/2015/1060, algorithm 1
1992
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
1993
+ add(other) {
1994
+ aprjpoint(other);
1995
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1996
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1997
+ let X3 = Fp3.ZERO, Y3 = Fp3.ZERO, Z3 = Fp3.ZERO;
1998
+ const a = CURVE.a;
1999
+ const b3 = Fp3.mul(CURVE.b, _3n2);
2000
+ let t0 = Fp3.mul(X1, X2);
2001
+ let t1 = Fp3.mul(Y1, Y2);
2002
+ let t2 = Fp3.mul(Z1, Z2);
2003
+ let t3 = Fp3.add(X1, Y1);
2004
+ let t4 = Fp3.add(X2, Y2);
2005
+ t3 = Fp3.mul(t3, t4);
2006
+ t4 = Fp3.add(t0, t1);
2007
+ t3 = Fp3.sub(t3, t4);
2008
+ t4 = Fp3.add(X1, Z1);
2009
+ let t5 = Fp3.add(X2, Z2);
2010
+ t4 = Fp3.mul(t4, t5);
2011
+ t5 = Fp3.add(t0, t2);
2012
+ t4 = Fp3.sub(t4, t5);
2013
+ t5 = Fp3.add(Y1, Z1);
2014
+ X3 = Fp3.add(Y2, Z2);
2015
+ t5 = Fp3.mul(t5, X3);
2016
+ X3 = Fp3.add(t1, t2);
2017
+ t5 = Fp3.sub(t5, X3);
2018
+ Z3 = Fp3.mul(a, t4);
2019
+ X3 = Fp3.mul(b3, t2);
2020
+ Z3 = Fp3.add(X3, Z3);
2021
+ X3 = Fp3.sub(t1, Z3);
2022
+ Z3 = Fp3.add(t1, Z3);
2023
+ Y3 = Fp3.mul(X3, Z3);
2024
+ t1 = Fp3.add(t0, t0);
2025
+ t1 = Fp3.add(t1, t0);
2026
+ t2 = Fp3.mul(a, t2);
2027
+ t4 = Fp3.mul(b3, t4);
2028
+ t1 = Fp3.add(t1, t2);
2029
+ t2 = Fp3.sub(t0, t2);
2030
+ t2 = Fp3.mul(a, t2);
2031
+ t4 = Fp3.add(t4, t2);
2032
+ t0 = Fp3.mul(t1, t4);
2033
+ Y3 = Fp3.add(Y3, t0);
2034
+ t0 = Fp3.mul(t5, t4);
2035
+ X3 = Fp3.mul(t3, X3);
2036
+ X3 = Fp3.sub(X3, t0);
2037
+ t0 = Fp3.mul(t3, t1);
2038
+ Z3 = Fp3.mul(t5, Z3);
2039
+ Z3 = Fp3.add(Z3, t0);
2040
+ return new _Point(X3, Y3, Z3);
2041
+ }
2042
+ subtract(other) {
2043
+ aprjpoint(other);
2044
+ return this.add(other.negate());
2045
+ }
2046
+ is0() {
2047
+ return this.equals(_Point.ZERO);
2048
+ }
2049
+ /**
2050
+ * Constant time multiplication.
2051
+ * Uses wNAF method. Windowed method may be 10% faster,
2052
+ * but takes 2x longer to generate and consumes 2x memory.
2053
+ * Uses precomputes when available.
2054
+ * Uses endomorphism for Koblitz curves.
2055
+ * @param scalar - by which the point would be multiplied
2056
+ * @returns New point
2057
+ */
2058
+ multiply(scalar) {
2059
+ const { endo: endo2 } = extraOpts;
2060
+ if (!Fn.isValidNot0(scalar))
2061
+ throw new RangeError("invalid scalar: out of range");
2062
+ let point, fake;
2063
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(_Point, p));
2064
+ if (endo2) {
2065
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
2066
+ const { p: k1p, f: k1f } = mul(k1);
2067
+ const { p: k2p, f: k2f } = mul(k2);
2068
+ fake = k1f.add(k2f);
2069
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
2070
+ } else {
2071
+ const { p, f } = mul(scalar);
2072
+ point = p;
2073
+ fake = f;
2074
+ }
2075
+ return normalizeZ(_Point, [point, fake])[0];
2076
+ }
2077
+ /**
2078
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
2079
+ * It's faster, but should only be used when you don't care about
2080
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
2081
+ */
2082
+ multiplyUnsafe(scalar) {
2083
+ const { endo: endo2 } = extraOpts;
2084
+ const p = this;
2085
+ const sc = scalar;
2086
+ if (!Fn.isValid(sc))
2087
+ throw new RangeError("invalid scalar: out of range");
2088
+ if (sc === _0n4 || p.is0())
2089
+ return _Point.ZERO;
2090
+ if (sc === _1n4)
2091
+ return p;
2092
+ if (wnaf.hasCache(this))
2093
+ return this.multiply(sc);
2094
+ if (endo2) {
2095
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
2096
+ const { p1, p2 } = mulEndoUnsafe(_Point, p, k1, k2);
2097
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
2098
+ } else {
2099
+ return wnaf.unsafe(p, sc);
2100
+ }
2101
+ }
2102
+ /**
2103
+ * Converts Projective point to affine (x, y) coordinates.
2104
+ * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
2105
+ * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
2106
+ */
2107
+ toAffine(invertedZ) {
2108
+ const p = this;
2109
+ let iz = invertedZ;
2110
+ const { X, Y, Z } = p;
2111
+ if (Fp3.eql(Z, Fp3.ONE))
2112
+ return { x: X, y: Y };
2113
+ const is0 = p.is0();
2114
+ if (iz == null)
2115
+ iz = is0 ? Fp3.ONE : Fp3.inv(Z);
2116
+ const x = Fp3.mul(X, iz);
2117
+ const y = Fp3.mul(Y, iz);
2118
+ const zz = Fp3.mul(Z, iz);
2119
+ if (is0)
2120
+ return { x: Fp3.ZERO, y: Fp3.ZERO };
2121
+ if (!Fp3.eql(zz, Fp3.ONE))
2122
+ throw new Error("invZ was invalid");
2123
+ return { x, y };
2124
+ }
2125
+ /**
2126
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
2127
+ * Always torsion-free for cofactor=1 curves.
2128
+ */
2129
+ isTorsionFree() {
2130
+ const { isTorsionFree } = extraOpts;
2131
+ if (cofactor === _1n4)
2132
+ return true;
2133
+ if (isTorsionFree)
2134
+ return isTorsionFree(_Point, this);
2135
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
2136
+ }
2137
+ clearCofactor() {
2138
+ const { clearCofactor } = extraOpts;
2139
+ if (cofactor === _1n4)
2140
+ return this;
2141
+ if (clearCofactor)
2142
+ return clearCofactor(_Point, this);
2143
+ return this.multiplyUnsafe(cofactor);
2144
+ }
2145
+ isSmallOrder() {
2146
+ if (cofactor === _1n4)
2147
+ return this.is0();
2148
+ return this.clearCofactor().is0();
2149
+ }
2150
+ toBytes(isCompressed = true) {
2151
+ abool(isCompressed, "isCompressed");
2152
+ this.assertValidity();
2153
+ return encodePoint(_Point, this, isCompressed);
2154
+ }
2155
+ toHex(isCompressed = true) {
2156
+ return bytesToHex2(this.toBytes(isCompressed));
2157
+ }
2158
+ toString() {
2159
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2160
+ }
2161
+ };
2162
+ // base / generator point
2163
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp3.ONE));
2164
+ // zero / infinity / identity point
2165
+ __publicField(_Point, "ZERO", new _Point(Fp3.ZERO, Fp3.ONE, Fp3.ZERO));
2166
+ // 0, 1, 0
2167
+ // math field
2168
+ __publicField(_Point, "Fp", Fp3);
2169
+ // scalar field
2170
+ __publicField(_Point, "Fn", Fn);
2171
+ let Point = _Point;
2172
+ const bits = Fn.BITS;
2173
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
2174
+ if (bits >= 8)
2175
+ Point.BASE.precompute(8);
2176
+ Object.freeze(Point.prototype);
2177
+ Object.freeze(Point);
2178
+ return Point;
2179
+ }
2180
+ function pprefix(hasEvenY) {
2181
+ return Uint8Array.of(hasEvenY ? 2 : 3);
2182
+ }
2183
+ function SWUFpSqrtRatio(Fp3, Z) {
2184
+ const F = validateField(Fp3);
2185
+ const q = F.ORDER;
2186
+ let l = _0n4;
2187
+ for (let o = q - _1n4; o % _2n2 === _0n4; o /= _2n2)
2188
+ l += _1n4;
2189
+ const c1 = l;
2190
+ const _2n_pow_c1_1 = _2n2 << c1 - _1n4 - _1n4;
2191
+ const _2n_pow_c1 = _2n_pow_c1_1 * _2n2;
2192
+ const c2 = (q - _1n4) / _2n_pow_c1;
2193
+ const c3 = (c2 - _1n4) / _2n2;
2194
+ const c4 = _2n_pow_c1 - _1n4;
2195
+ const c5 = _2n_pow_c1_1;
2196
+ const c6 = F.pow(Z, c2);
2197
+ const c7 = F.pow(Z, (c2 + _1n4) / _2n2);
2198
+ let sqrtRatio = (u, v) => {
2199
+ let tv1 = c6;
2200
+ let tv2 = F.pow(v, c4);
2201
+ let tv3 = F.sqr(tv2);
2202
+ tv3 = F.mul(tv3, v);
2203
+ let tv5 = F.mul(u, tv3);
2204
+ tv5 = F.pow(tv5, c3);
2205
+ tv5 = F.mul(tv5, tv2);
2206
+ tv2 = F.mul(tv5, v);
2207
+ tv3 = F.mul(tv5, u);
2208
+ let tv4 = F.mul(tv3, tv2);
2209
+ tv5 = F.pow(tv4, c5);
2210
+ let isQR = F.eql(tv5, F.ONE);
2211
+ tv2 = F.mul(tv3, c7);
2212
+ tv5 = F.mul(tv4, tv1);
2213
+ tv3 = F.cmov(tv2, tv3, isQR);
2214
+ tv4 = F.cmov(tv5, tv4, isQR);
2215
+ for (let i = c1; i > _1n4; i--) {
2216
+ let tv52 = i - _2n2;
2217
+ tv52 = _2n2 << tv52 - _1n4;
2218
+ let tvv5 = F.pow(tv4, tv52);
2219
+ const e1 = F.eql(tvv5, F.ONE);
2220
+ tv2 = F.mul(tv3, tv1);
2221
+ tv1 = F.mul(tv1, tv1);
2222
+ tvv5 = F.mul(tv4, tv1);
2223
+ tv3 = F.cmov(tv2, tv3, e1);
2224
+ tv4 = F.cmov(tvv5, tv4, e1);
2225
+ }
2226
+ return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };
2227
+ };
2228
+ if (F.ORDER % _4n2 === _3n2) {
2229
+ const c12 = (F.ORDER - _3n2) / _4n2;
2230
+ const c22 = F.sqrt(F.neg(Z));
2231
+ sqrtRatio = (u, v) => {
2232
+ let tv1 = F.sqr(v);
2233
+ const tv2 = F.mul(u, v);
2234
+ tv1 = F.mul(tv1, tv2);
2235
+ let y1 = F.pow(tv1, c12);
2236
+ y1 = F.mul(y1, tv2);
2237
+ const y2 = F.mul(y1, c22);
2238
+ const tv3 = F.mul(F.sqr(y1), v);
2239
+ const isQR = F.eql(tv3, u);
2240
+ let y = F.cmov(y2, y1, isQR);
2241
+ return { isValid: !F.is0(v) && isQR, value: y };
2242
+ };
2243
+ }
2244
+ return sqrtRatio;
2245
+ }
2246
+ function mapToCurveSimpleSWU(Fp3, opts) {
2247
+ const F = validateField(Fp3);
2248
+ const { A, B, Z } = opts;
2249
+ if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))
2250
+ throw new Error("mapToCurveSimpleSWU: invalid opts");
2251
+ if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z))
2252
+ throw new Error("mapToCurveSimpleSWU: invalid opts");
2253
+ const x = F.mul(B, F.inv(F.mul(Z, A)));
2254
+ const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);
2255
+ if (!FpIsSquare(F, gx))
2256
+ throw new Error("mapToCurveSimpleSWU: invalid opts");
2257
+ const sqrtRatio = SWUFpSqrtRatio(F, Z);
2258
+ if (!F.isOdd)
2259
+ throw new Error("Field does not have .isOdd()");
2260
+ return (u) => {
2261
+ let tv1, tv2, tv3, tv4, tv5, tv6, x2, y;
2262
+ tv1 = F.sqr(u);
2263
+ tv1 = F.mul(tv1, Z);
2264
+ tv2 = F.sqr(tv1);
2265
+ tv2 = F.add(tv2, tv1);
2266
+ tv3 = F.add(tv2, F.ONE);
2267
+ tv3 = F.mul(tv3, B);
2268
+ tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO));
2269
+ tv4 = F.mul(tv4, A);
2270
+ tv2 = F.sqr(tv3);
2271
+ tv6 = F.sqr(tv4);
2272
+ tv5 = F.mul(tv6, A);
2273
+ tv2 = F.add(tv2, tv5);
2274
+ tv2 = F.mul(tv2, tv3);
2275
+ tv6 = F.mul(tv6, tv4);
2276
+ tv5 = F.mul(tv6, B);
2277
+ tv2 = F.add(tv2, tv5);
2278
+ x2 = F.mul(tv1, tv3);
2279
+ const { isValid, value } = sqrtRatio(tv2, tv6);
2280
+ y = F.mul(tv1, u);
2281
+ y = F.mul(y, value);
2282
+ x2 = F.cmov(x2, tv3, isValid);
2283
+ y = F.cmov(y, value, isValid);
2284
+ const e1 = F.isOdd(u) === F.isOdd(y);
2285
+ y = F.cmov(F.neg(y), y, e1);
2286
+ const tv4_inv = FpInvertBatch(F, [tv4], true)[0];
2287
+ x2 = F.mul(x2, tv4_inv);
2288
+ return { x: x2, y };
2289
+ };
2290
+ }
2291
+ function getWLengths(Fp3, Fn) {
2292
+ return {
2293
+ secretKey: Fn.BYTES,
2294
+ publicKey: 1 + Fp3.BYTES,
2295
+ publicKeyUncompressed: 1 + 2 * Fp3.BYTES,
2296
+ publicKeyHasPrefix: true,
2297
+ // Raw compact `(r || s)` signature width; DER and recovered signatures use
2298
+ // different lengths outside this helper.
2299
+ signature: 2 * Fn.BYTES
2300
+ };
2301
+ }
2302
+ function ecdh(Point, ecdhOpts = {}) {
2303
+ const { Fn } = Point;
2304
+ const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes2 : ecdhOpts.randomBytes;
2305
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), {
2306
+ seed: Math.max(getMinHashLength(Fn.ORDER), 16)
2307
+ });
2308
+ function isValidSecretKey(secretKey) {
2309
+ try {
2310
+ const num = Fn.fromBytes(secretKey);
2311
+ return Fn.isValidNot0(num);
2312
+ } catch (error) {
2313
+ return false;
2314
+ }
2315
+ }
2316
+ function isValidPublicKey(publicKey, isCompressed) {
2317
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
2318
+ try {
2319
+ const l = publicKey.length;
2320
+ if (isCompressed === true && l !== comp)
2321
+ return false;
2322
+ if (isCompressed === false && l !== publicKeyUncompressed)
2323
+ return false;
2324
+ return !!Point.fromBytes(publicKey);
2325
+ } catch (error) {
2326
+ return false;
2327
+ }
2328
+ }
2329
+ function randomSecretKey(seed) {
2330
+ seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
2331
+ return mapHashToField(abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
2332
+ }
2333
+ function getPublicKey(secretKey, isCompressed = true) {
2334
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
2335
+ }
2336
+ function isProbPub(item) {
2337
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
2338
+ const allowedLengths = Fn._lengths;
2339
+ if (!isBytes2(item))
2340
+ return void 0;
2341
+ const l = abytes2(item, void 0, "key").length;
2342
+ const isPub = l === publicKey || l === publicKeyUncompressed;
2343
+ const isSec = l === secretKey || !!(allowedLengths == null ? void 0 : allowedLengths.includes(l));
2344
+ if (isPub && isSec)
2345
+ return void 0;
2346
+ return isPub;
2347
+ }
2348
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
2349
+ if (isProbPub(secretKeyA) === true)
2350
+ throw new Error("first arg must be private key");
2351
+ if (isProbPub(publicKeyB) === false)
2352
+ throw new Error("second arg must be public key");
2353
+ const s = Fn.fromBytes(secretKeyA);
2354
+ const b = Point.fromBytes(publicKeyB);
2355
+ return b.multiply(s).toBytes(isCompressed);
2356
+ }
2357
+ const utils = {
2358
+ isValidSecretKey,
2359
+ isValidPublicKey,
2360
+ randomSecretKey
2361
+ };
2362
+ const keygen = createKeygen(randomSecretKey, getPublicKey);
2363
+ Object.freeze(utils);
2364
+ Object.freeze(lengths);
2365
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
2366
+ }
2367
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
2368
+ const hash_ = hash;
2369
+ ahash(hash_);
2370
+ validateObject(ecdsaOpts, {}, {
2371
+ hmac: "function",
2372
+ lowS: "boolean",
2373
+ randomBytes: "function",
2374
+ bits2int: "function",
2375
+ bits2int_modN: "function"
2376
+ });
2377
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
2378
+ const randomBytes3 = ecdsaOpts.randomBytes === void 0 ? randomBytes2 : ecdsaOpts.randomBytes;
2379
+ const hmac2 = ecdsaOpts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : ecdsaOpts.hmac;
2380
+ const { Fp: Fp3, Fn } = Point;
2381
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
2382
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
2383
+ const defaultSigOpts = {
2384
+ prehash: true,
2385
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
2386
+ format: "compact",
2387
+ extraEntropy: false
2388
+ };
2389
+ const hasLargeRecoveryLifts = CURVE_ORDER * _2n2 + _1n4 < Fp3.ORDER;
2390
+ function isBiggerThanHalfOrder(number) {
2391
+ const HALF = CURVE_ORDER >> _1n4;
2392
+ return number > HALF;
2393
+ }
2394
+ function validateRS(title, num) {
2395
+ if (!Fn.isValidNot0(num))
2396
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
2397
+ return num;
2398
+ }
2399
+ function assertRecoverableCurve() {
2400
+ if (hasLargeRecoveryLifts)
2401
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
2402
+ }
2403
+ function validateSigLength(bytes, format) {
2404
+ validateSigFormat(format);
2405
+ const size = lengths.signature;
2406
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
2407
+ return abytes2(bytes, sizer);
2408
+ }
2409
+ class Signature {
2410
+ constructor(r, s, recovery) {
2411
+ __publicField(this, "r");
2412
+ __publicField(this, "s");
2413
+ __publicField(this, "recovery");
2414
+ this.r = validateRS("r", r);
2415
+ this.s = validateRS("s", s);
2416
+ if (recovery != null) {
2417
+ assertRecoverableCurve();
2418
+ if (![0, 1, 2, 3].includes(recovery))
2419
+ throw new Error("invalid recovery id");
2420
+ this.recovery = recovery;
2421
+ }
2422
+ Object.freeze(this);
2423
+ }
2424
+ static fromBytes(bytes, format = defaultSigOpts.format) {
2425
+ validateSigLength(bytes, format);
2426
+ let recid;
2427
+ if (format === "der") {
2428
+ const { r: r2, s: s2 } = DER.toSig(abytes2(bytes));
2429
+ return new Signature(r2, s2);
2430
+ }
2431
+ if (format === "recovered") {
2432
+ recid = bytes[0];
2433
+ format = "compact";
2434
+ bytes = bytes.subarray(1);
2435
+ }
2436
+ const L = lengths.signature / 2;
2437
+ const r = bytes.subarray(0, L);
2438
+ const s = bytes.subarray(L, L * 2);
2439
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
2440
+ }
2441
+ static fromHex(hex, format) {
2442
+ return this.fromBytes(hexToBytes2(hex), format);
2443
+ }
2444
+ assertRecovery() {
2445
+ const { recovery } = this;
2446
+ if (recovery == null)
2447
+ throw new Error("invalid recovery id: must be present");
2448
+ return recovery;
2449
+ }
2450
+ addRecoveryBit(recovery) {
2451
+ return new Signature(this.r, this.s, recovery);
2452
+ }
2453
+ // Unlike the top-level helper below, this method expects a digest that has
2454
+ // already been hashed to the curve's message representative.
2455
+ recoverPublicKey(messageHash) {
2456
+ const { r, s } = this;
2457
+ const recovery = this.assertRecovery();
2458
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
2459
+ if (!Fp3.isValid(radj))
2460
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
2461
+ const x = Fp3.toBytes(radj);
2462
+ const R = Point.fromBytes(concatBytes2(pprefix((recovery & 1) === 0), x));
2463
+ const ir = Fn.inv(radj);
2464
+ const h = bits2int_modN(abytes2(messageHash, void 0, "msgHash"));
2465
+ const u1 = Fn.create(-h * ir);
2466
+ const u2 = Fn.create(s * ir);
2467
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
2468
+ if (Q.is0())
2469
+ throw new Error("invalid recovery: point at infinify");
2470
+ Q.assertValidity();
2471
+ return Q;
2472
+ }
2473
+ // Signatures should be low-s, to prevent malleability.
2474
+ hasHighS() {
2475
+ return isBiggerThanHalfOrder(this.s);
2476
+ }
2477
+ toBytes(format = defaultSigOpts.format) {
2478
+ validateSigFormat(format);
2479
+ if (format === "der")
2480
+ return hexToBytes2(DER.hexFromSig(this));
2481
+ const { r, s } = this;
2482
+ const rb = Fn.toBytes(r);
2483
+ const sb = Fn.toBytes(s);
2484
+ if (format === "recovered") {
2485
+ assertRecoverableCurve();
2486
+ return concatBytes2(Uint8Array.of(this.assertRecovery()), rb, sb);
2487
+ }
2488
+ return concatBytes2(rb, sb);
2489
+ }
2490
+ toHex(format) {
2491
+ return bytesToHex2(this.toBytes(format));
2492
+ }
2493
+ }
2494
+ Object.freeze(Signature.prototype);
2495
+ Object.freeze(Signature);
2496
+ const bits2int = ecdsaOpts.bits2int === void 0 ? function bits2int_def(bytes) {
2497
+ if (bytes.length > 8192)
2498
+ throw new Error("input is too large");
2499
+ const num = bytesToNumberBE(bytes);
2500
+ const delta = bytes.length * 8 - fnBits;
2501
+ return delta > 0 ? num >> BigInt(delta) : num;
2502
+ } : ecdsaOpts.bits2int;
2503
+ const bits2int_modN = ecdsaOpts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
2504
+ return Fn.create(bits2int(bytes));
2505
+ } : ecdsaOpts.bits2int_modN;
2506
+ const ORDER_MASK = bitMask(fnBits);
2507
+ function int2octets(num) {
2508
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
2509
+ return Fn.toBytes(num);
2510
+ }
2511
+ function validateMsgAndHash(message, prehash) {
2512
+ abytes2(message, void 0, "message");
2513
+ return prehash ? abytes2(hash_(message), void 0, "prehashed message") : message;
2514
+ }
2515
+ function prepSig(message, secretKey, opts) {
2516
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
2517
+ message = validateMsgAndHash(message, prehash);
2518
+ const h1int = bits2int_modN(message);
2519
+ const d = Fn.fromBytes(secretKey);
2520
+ if (!Fn.isValidNot0(d))
2521
+ throw new Error("invalid private key");
2522
+ const seedArgs = [int2octets(d), int2octets(h1int)];
2523
+ if (extraEntropy != null && extraEntropy !== false) {
2524
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
2525
+ seedArgs.push(abytes2(e, void 0, "extraEntropy"));
2526
+ }
2527
+ const seed = concatBytes2(...seedArgs);
2528
+ const m = h1int;
2529
+ function k2sig(kBytes) {
2530
+ const k = bits2int(kBytes);
2531
+ if (!Fn.isValidNot0(k))
2532
+ return;
2533
+ const ik = Fn.inv(k);
2534
+ const q = Point.BASE.multiply(k).toAffine();
2535
+ const r = Fn.create(q.x);
2536
+ if (r === _0n4)
2537
+ return;
2538
+ const s = Fn.create(ik * Fn.create(m + r * d));
2539
+ if (s === _0n4)
2540
+ return;
2541
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
2542
+ let normS = s;
2543
+ if (lowS && isBiggerThanHalfOrder(s)) {
2544
+ normS = Fn.neg(s);
2545
+ recovery ^= 1;
2546
+ }
2547
+ return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
2548
+ }
2549
+ return { seed, k2sig };
2550
+ }
2551
+ function sign(message, secretKey, opts = {}) {
2552
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
2553
+ const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac2);
2554
+ const sig = drbg(seed, k2sig);
2555
+ return sig.toBytes(opts.format);
2556
+ }
2557
+ function verify(signature, message, publicKey, opts = {}) {
2558
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
2559
+ publicKey = abytes2(publicKey, void 0, "publicKey");
2560
+ message = validateMsgAndHash(message, prehash);
2561
+ if (!isBytes2(signature)) {
2562
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
2563
+ throw new Error("verify expects Uint8Array signature" + end);
2564
+ }
2565
+ validateSigLength(signature, format);
2566
+ try {
2567
+ const sig = Signature.fromBytes(signature, format);
2568
+ const P = Point.fromBytes(publicKey);
2569
+ if (lowS && sig.hasHighS())
2570
+ return false;
2571
+ const { r, s } = sig;
2572
+ const h = bits2int_modN(message);
2573
+ const is = Fn.inv(s);
2574
+ const u1 = Fn.create(h * is);
2575
+ const u2 = Fn.create(r * is);
2576
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
2577
+ if (R.is0())
2578
+ return false;
2579
+ const v = Fn.create(R.x);
2580
+ return v === r;
2581
+ } catch (e) {
2582
+ return false;
2583
+ }
2584
+ }
2585
+ function recoverPublicKey(signature, message, opts = {}) {
2586
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
2587
+ message = validateMsgAndHash(message, prehash);
2588
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
2589
+ }
2590
+ return Object.freeze({
2591
+ keygen,
2592
+ getPublicKey,
2593
+ getSharedSecret,
2594
+ utils,
2595
+ lengths,
2596
+ Point,
2597
+ sign,
2598
+ verify,
2599
+ recoverPublicKey,
2600
+ Signature,
2601
+ hash: hash_
2602
+ });
2603
+ }
2604
+
2605
+ // node_modules/@noble/curves/abstract/bls.js
2606
+ var _0n5 = BigInt(0);
2607
+ var _1n5 = BigInt(1);
2608
+ var _2n3 = BigInt(2);
2609
+ var _3n3 = BigInt(3);
2610
+ function NAfDecomposition(a) {
2611
+ const res = [];
2612
+ for (; a > _1n5; a >>= _1n5) {
2613
+ if ((a & _1n5) === _0n5)
2614
+ res.unshift(0);
2615
+ else if ((a & _3n3) === _3n3) {
2616
+ res.unshift(-1);
2617
+ a += _1n5;
2618
+ } else
2619
+ res.unshift(1);
2620
+ }
2621
+ return res;
2622
+ }
2623
+ function aNonEmpty(arr) {
2624
+ if (!Array.isArray(arr) || arr.length === 0)
2625
+ throw new Error("expected non-empty array");
2626
+ }
2627
+ function createBlsPairing(fields2, G1, G2, params) {
2628
+ const { Fr, Fp2: Fp22, Fp12: Fp122 } = fields2;
2629
+ const { twistType, ateLoopSize, xNegative, postPrecompute } = params;
2630
+ let lineFunction;
2631
+ if (twistType === "multiplicative") {
2632
+ lineFunction = (c0, c1, c2, f, Px, Py) => Fp122.mul014(f, c0, Fp22.mul(c1, Px), Fp22.mul(c2, Py));
2633
+ } else if (twistType === "divisive") {
2634
+ lineFunction = (c0, c1, c2, f, Px, Py) => Fp122.mul034(f, Fp22.mul(c2, Py), Fp22.mul(c1, Px), c0);
2635
+ } else
2636
+ throw new Error("bls: unknown twist type");
2637
+ const Fp2div2 = Fp22.div(Fp22.ONE, Fp22.mul(Fp22.ONE, _2n3));
2638
+ function pointDouble(ell, Rx, Ry, Rz) {
2639
+ const t0 = Fp22.sqr(Ry);
2640
+ const t1 = Fp22.sqr(Rz);
2641
+ const t2 = Fp22.mulByB(Fp22.mul(t1, _3n3));
2642
+ const t3 = Fp22.mul(t2, _3n3);
2643
+ const t4 = Fp22.sub(Fp22.sub(Fp22.sqr(Fp22.add(Ry, Rz)), t1), t0);
2644
+ const c0 = Fp22.sub(t2, t0);
2645
+ const c1 = Fp22.mul(Fp22.sqr(Rx), _3n3);
2646
+ const c2 = Fp22.neg(t4);
2647
+ ell.push([c0, c1, c2]);
2648
+ Rx = Fp22.mul(Fp22.mul(Fp22.mul(Fp22.sub(t0, t3), Rx), Ry), Fp2div2);
2649
+ Ry = Fp22.sub(Fp22.sqr(Fp22.mul(Fp22.add(t0, t3), Fp2div2)), Fp22.mul(Fp22.sqr(t2), _3n3));
2650
+ Rz = Fp22.mul(t0, t4);
2651
+ return { Rx, Ry, Rz };
2652
+ }
2653
+ function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) {
2654
+ const t0 = Fp22.sub(Ry, Fp22.mul(Qy, Rz));
2655
+ const t1 = Fp22.sub(Rx, Fp22.mul(Qx, Rz));
2656
+ const c0 = Fp22.sub(Fp22.mul(t0, Qx), Fp22.mul(t1, Qy));
2657
+ const c1 = Fp22.neg(t0);
2658
+ const c2 = t1;
2659
+ ell.push([c0, c1, c2]);
2660
+ const t2 = Fp22.sqr(t1);
2661
+ const t3 = Fp22.mul(t2, t1);
2662
+ const t4 = Fp22.mul(t2, Rx);
2663
+ const t5 = Fp22.add(Fp22.sub(t3, Fp22.mul(t4, _2n3)), Fp22.mul(Fp22.sqr(t0), Rz));
2664
+ Rx = Fp22.mul(t1, t5);
2665
+ Ry = Fp22.sub(Fp22.mul(Fp22.sub(t4, t5), t0), Fp22.mul(t3, Ry));
2666
+ Rz = Fp22.mul(Rz, t3);
2667
+ return { Rx, Ry, Rz };
2668
+ }
2669
+ const ATE_NAF = NAfDecomposition(ateLoopSize);
2670
+ const calcPairingPrecomputes = (point) => {
2671
+ const p = point;
2672
+ const { x, y } = p.toAffine();
2673
+ const Qx = x, Qy = y, negQy = Fp22.neg(y);
2674
+ let Rx = Qx, Ry = Qy, Rz = Fp22.ONE;
2675
+ const ell = [];
2676
+ for (const bit of ATE_NAF) {
2677
+ const cur = [];
2678
+ ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));
2679
+ if (bit)
2680
+ ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));
2681
+ ell.push(cur);
2682
+ }
2683
+ if (postPrecompute) {
2684
+ const last = ell[ell.length - 1];
2685
+ postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));
2686
+ }
2687
+ return ell;
2688
+ };
2689
+ function millerLoopBatch(pairs, withFinalExponent = false) {
2690
+ let f12 = Fp122.ONE;
2691
+ if (pairs.length) {
2692
+ const ellLen = pairs[0][0].length;
2693
+ for (let i = 0; i < ellLen; i++) {
2694
+ f12 = Fp122.sqr(f12);
2695
+ for (const [ell, Px, Py] of pairs) {
2696
+ for (const [c0, c1, c2] of ell[i])
2697
+ f12 = lineFunction(c0, c1, c2, f12, Px, Py);
2698
+ }
2699
+ }
2700
+ }
2701
+ if (xNegative)
2702
+ f12 = Fp122.conjugate(f12);
2703
+ return withFinalExponent ? Fp122.finalExponentiate(f12) : f12;
2704
+ }
2705
+ function pairingBatch(pairs, withFinalExponent = true) {
2706
+ const res = [];
2707
+ for (const { g1: g12, g2: g22 } of pairs) {
2708
+ if (g12.is0() || g22.is0())
2709
+ throw new Error("pairing is not available for ZERO point");
2710
+ g12.assertValidity();
2711
+ g22.assertValidity();
2712
+ const Qa = g12.toAffine();
2713
+ res.push([calcPairingPrecomputes(g22), Qa.x, Qa.y]);
2714
+ }
2715
+ return millerLoopBatch(res, withFinalExponent);
2716
+ }
2717
+ function pairing(Q, P, withFinalExponent = true) {
2718
+ return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);
2719
+ }
2720
+ const lengths = {
2721
+ seed: getMinHashLength(Fr.ORDER)
2722
+ };
2723
+ const rand = params.randomBytes === void 0 ? randomBytes2 : params.randomBytes;
2724
+ const randomSecretKey = (seed) => {
2725
+ seed = seed === void 0 ? rand(lengths.seed) : seed;
2726
+ abytes2(seed, lengths.seed, "seed");
2727
+ return mapHashToField(seed, Fr.ORDER);
2728
+ };
2729
+ Object.freeze(lengths);
2730
+ return {
2731
+ lengths,
2732
+ Fr,
2733
+ Fp12: Fp122,
2734
+ // NOTE: we re-export Fp12 here because pairing results are Fp12!
2735
+ millerLoopBatch,
2736
+ pairing,
2737
+ pairingBatch,
2738
+ calcPairingPrecomputes,
2739
+ randomSecretKey
2740
+ };
2741
+ }
2742
+ function createBlsSig(blsPairing, PubPoint, SigPoint, isSigG1, hashToSigCurve, SignatureCoder) {
2743
+ const { Fr, Fp12: Fp122, pairingBatch, randomSecretKey, lengths } = blsPairing;
2744
+ if (!SignatureCoder) {
2745
+ SignatureCoder = {
2746
+ fromBytes: notImplemented,
2747
+ fromHex: notImplemented,
2748
+ toBytes: notImplemented,
2749
+ toHex: notImplemented
2750
+ };
2751
+ }
2752
+ function normPub(point) {
2753
+ return point instanceof PubPoint ? point : PubPoint.fromBytes(point);
2754
+ }
2755
+ function normSig(point) {
2756
+ return point instanceof SigPoint ? point : SigPoint.fromBytes(point);
2757
+ }
2758
+ function amsg(m) {
2759
+ if (!(m instanceof SigPoint))
2760
+ throw new Error(`expected valid message hashed to ${!isSigG1 ? "G2" : "G1"} curve`);
2761
+ return m;
2762
+ }
2763
+ const pair = !isSigG1 ? (a, b) => ({ g1: a, g2: b }) : (a, b) => ({ g1: b, g2: a });
2764
+ return Object.freeze({
2765
+ lengths: Object.freeze(__spreadProps(__spreadValues({}, lengths), { secretKey: Fr.BYTES })),
2766
+ keygen(seed) {
2767
+ const secretKey = randomSecretKey(seed);
2768
+ const publicKey = this.getPublicKey(secretKey);
2769
+ return { secretKey, publicKey };
2770
+ },
2771
+ // P = pk x G
2772
+ getPublicKey(secretKey) {
2773
+ let sec;
2774
+ try {
2775
+ sec = PubPoint.Fn.fromBytes(secretKey);
2776
+ } catch (error) {
2777
+ throw new Error("invalid private key: " + typeof secretKey, { cause: error });
2778
+ }
2779
+ return PubPoint.BASE.multiply(sec);
2780
+ },
2781
+ // S = pk x H(m)
2782
+ sign(message, secretKey, unusedArg) {
2783
+ if (unusedArg != null)
2784
+ throw new Error("sign() expects 2 arguments");
2785
+ const sec = PubPoint.Fn.fromBytes(secretKey);
2786
+ amsg(message).assertValidity();
2787
+ return message.multiply(sec);
2788
+ },
2789
+ // Checks if pairing of public key & hash is equal to pairing of generator & signature.
2790
+ // e(P, H(m)) == e(G, S)
2791
+ // e(S, G) == e(H(m), P)
2792
+ verify(signature, message, publicKey, unusedArg) {
2793
+ if (unusedArg != null)
2794
+ throw new Error("verify() expects 3 arguments");
2795
+ signature = normSig(signature);
2796
+ publicKey = normPub(publicKey);
2797
+ const P = publicKey.negate();
2798
+ const G = PubPoint.BASE;
2799
+ const Hm = amsg(message);
2800
+ const S = signature;
2801
+ try {
2802
+ const exp = pairingBatch([pair(P, Hm), pair(G, S)]);
2803
+ return Fp122.eql(exp, Fp122.ONE);
2804
+ } catch (e) {
2805
+ return false;
2806
+ }
2807
+ },
2808
+ // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407
2809
+ // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))
2810
+ // TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead?
2811
+ verifyBatch(signature, items) {
2812
+ aNonEmpty(items);
2813
+ const sig = normSig(signature);
2814
+ const nMessages = items.map((i) => i.message);
2815
+ const nPublicKeys = items.map((i) => normPub(i.publicKey));
2816
+ const messagePubKeyMap = /* @__PURE__ */ new Map();
2817
+ for (let i = 0; i < nPublicKeys.length; i++) {
2818
+ const pub = nPublicKeys[i];
2819
+ const msg = nMessages[i];
2820
+ let keys = messagePubKeyMap.get(msg);
2821
+ if (keys === void 0) {
2822
+ keys = [];
2823
+ messagePubKeyMap.set(msg, keys);
2824
+ }
2825
+ keys.push(pub);
2826
+ }
2827
+ const paired = [];
2828
+ const G = PubPoint.BASE;
2829
+ try {
2830
+ for (const [msg, keys] of messagePubKeyMap) {
2831
+ const groupPublicKey = keys.reduce((acc, msg2) => acc.add(msg2));
2832
+ paired.push(pair(groupPublicKey, msg));
2833
+ }
2834
+ paired.push(pair(G.negate(), sig));
2835
+ return Fp122.eql(pairingBatch(paired), Fp122.ONE);
2836
+ } catch (e) {
2837
+ return false;
2838
+ }
2839
+ },
2840
+ // Adds a bunch of public key points together.
2841
+ // pk1 + pk2 + pk3 = pkA
2842
+ aggregatePublicKeys(publicKeys) {
2843
+ aNonEmpty(publicKeys);
2844
+ publicKeys = publicKeys.map((pub) => normPub(pub));
2845
+ const agg = publicKeys.reduce((sum, p) => sum.add(p), PubPoint.ZERO);
2846
+ agg.assertValidity();
2847
+ return agg;
2848
+ },
2849
+ // Adds a bunch of signature points together.
2850
+ // pk1 + pk2 + pk3 = pkA
2851
+ aggregateSignatures(signatures) {
2852
+ aNonEmpty(signatures);
2853
+ signatures = signatures.map((sig) => normSig(sig));
2854
+ const agg = signatures.reduce((sum, s) => sum.add(s), SigPoint.ZERO);
2855
+ agg.assertValidity();
2856
+ return agg;
2857
+ },
2858
+ hash(messageBytes, DST) {
2859
+ abytes2(messageBytes);
2860
+ const opts = DST ? { DST } : void 0;
2861
+ return hashToSigCurve(messageBytes, opts);
2862
+ },
2863
+ Signature: Object.freeze(__spreadValues({}, SignatureCoder))
2864
+ });
2865
+ }
2866
+ function blsBasic(fields2, G1_Point2, G2_Point2, params) {
2867
+ const { Fp: Fp3, Fr, Fp2: Fp22, Fp6: Fp62, Fp12: Fp122 } = fields2;
2868
+ const G1 = { Point: G1_Point2 };
2869
+ const G2 = { Point: G2_Point2 };
2870
+ const pairingRes = createBlsPairing(fields2, G1_Point2, G2_Point2, params);
2871
+ const { millerLoopBatch, pairing, pairingBatch, calcPairingPrecomputes, randomSecretKey, lengths } = pairingRes;
2872
+ G1.Point.BASE.precompute(4);
2873
+ Object.freeze(G1);
2874
+ Object.freeze(G2);
2875
+ return Object.freeze({
2876
+ lengths: Object.freeze(lengths),
2877
+ millerLoopBatch,
2878
+ pairing,
2879
+ pairingBatch,
2880
+ G1,
2881
+ G2,
2882
+ fields: Object.freeze({ Fr, Fp: Fp3, Fp2: Fp22, Fp6: Fp62, Fp12: Fp122 }),
2883
+ params: Object.freeze({
2884
+ ateLoopSize: params.ateLoopSize,
2885
+ twistType: params.twistType
2886
+ }),
2887
+ utils: Object.freeze({
2888
+ randomSecretKey,
2889
+ calcPairingPrecomputes
2890
+ })
2891
+ });
2892
+ }
2893
+ function blsHashers(fields2, G1_Point2, G2_Point2, params, hasherParams) {
2894
+ const base = blsBasic(fields2, G1_Point2, G2_Point2, params);
2895
+ const G1Hasher = createHasher2(G1_Point2, hasherParams.mapToG1 === void 0 ? notImplemented : hasherParams.mapToG1, __spreadValues(__spreadValues({}, hasherParams.hasherOpts), hasherParams.hasherOptsG1));
2896
+ const G2Hasher = createHasher2(G2_Point2, hasherParams.mapToG2 === void 0 ? notImplemented : hasherParams.mapToG2, __spreadValues(__spreadValues({}, hasherParams.hasherOpts), hasherParams.hasherOptsG2));
2897
+ return Object.freeze(__spreadProps(__spreadValues({}, base), { G1: G1Hasher, G2: G2Hasher }));
2898
+ }
2899
+ function bls(fields2, G1_Point2, G2_Point2, params, hasherParams, signatureCoders2) {
2900
+ const base = blsHashers(fields2, G1_Point2, G2_Point2, params, hasherParams);
2901
+ const pairingRes = __spreadProps(__spreadValues({}, base), {
2902
+ Fr: base.fields.Fr,
2903
+ Fp12: base.fields.Fp12,
2904
+ calcPairingPrecomputes: base.utils.calcPairingPrecomputes,
2905
+ randomSecretKey: base.utils.randomSecretKey
2906
+ });
2907
+ const longSignatures = createBlsSig(pairingRes, G1_Point2, G2_Point2, false, base.G2.hashToCurve, signatureCoders2 == null ? void 0 : signatureCoders2.LongSignature);
2908
+ const shortSignatures = createBlsSig(pairingRes, G2_Point2, G1_Point2, true, base.G1.hashToCurve, signatureCoders2 == null ? void 0 : signatureCoders2.ShortSignature);
2909
+ return Object.freeze(__spreadProps(__spreadValues({}, base), { longSignatures, shortSignatures }));
2910
+ }
2911
+
2912
+ // node_modules/@noble/curves/abstract/tower.js
2913
+ var _0n6 = /* @__PURE__ */ BigInt(0);
2914
+ var _1n6 = /* @__PURE__ */ BigInt(1);
2915
+ var _2n4 = /* @__PURE__ */ BigInt(2);
2916
+ var _3n4 = /* @__PURE__ */ BigInt(3);
2917
+ var _6n = /* @__PURE__ */ BigInt(6);
2918
+ var _12n = /* @__PURE__ */ BigInt(12);
2919
+ var isObj = (value) => !!value && typeof value === "object";
2920
+ function calcFrobeniusCoefficients(Fp3, nonResidue, modulus, degree, num = 1, divisor) {
2921
+ asafenumber(num, "num");
2922
+ const F = Fp3;
2923
+ if (num <= 0)
2924
+ throw new Error("calcFrobeniusCoefficients: expected positive row count, got " + num);
2925
+ const _divisor = BigInt(divisor === void 0 ? degree : divisor);
2926
+ const towerModulus = modulus ** BigInt(degree);
2927
+ const res = [];
2928
+ for (let i = 0; i < num; i++) {
2929
+ const a = BigInt(i + 1);
2930
+ const powers = [];
2931
+ for (let j = 0, qPower = _1n6; j < degree; j++) {
2932
+ const numer = a * qPower - a;
2933
+ if (numer % _divisor)
2934
+ throw new Error("calcFrobeniusCoefficients: inexact tower exponent");
2935
+ const power = numer / _divisor % towerModulus;
2936
+ powers.push(F.pow(nonResidue, power));
2937
+ qPower *= modulus;
2938
+ }
2939
+ res.push(powers);
2940
+ }
2941
+ return res;
2942
+ }
2943
+ function psiFrobenius(Fp3, Fp22, base) {
2944
+ const PSI_X = Fp22.pow(base, (Fp3.ORDER - _1n6) / _3n4);
2945
+ const PSI_Y = Fp22.pow(base, (Fp3.ORDER - _1n6) / _2n4);
2946
+ function psi(x, y) {
2947
+ const x2 = Fp22.mul(Fp22.frobeniusMap(x, 1), PSI_X);
2948
+ const y2 = Fp22.mul(Fp22.frobeniusMap(y, 1), PSI_Y);
2949
+ return [x2, y2];
2950
+ }
2951
+ const PSI2_X = Fp22.pow(base, (Fp3.ORDER ** _2n4 - _1n6) / _3n4);
2952
+ const PSI2_Y = Fp22.pow(base, (Fp3.ORDER ** _2n4 - _1n6) / _2n4);
2953
+ if (!Fp22.eql(PSI2_Y, Fp22.neg(Fp22.ONE)))
2954
+ throw new Error("psiFrobenius: PSI2_Y!==-1");
2955
+ function psi2(x, y) {
2956
+ return [Fp22.mul(x, PSI2_X), Fp22.neg(y)];
2957
+ }
2958
+ const mapAffine = (fn) => (c, P) => {
2959
+ const affine = P.toAffine();
2960
+ const p = fn(affine.x, affine.y);
2961
+ return c.fromAffine({ x: p[0], y: p[1] });
2962
+ };
2963
+ const G2psi3 = mapAffine(psi);
2964
+ const G2psi22 = mapAffine(psi2);
2965
+ return { psi, psi2, G2psi: G2psi3, G2psi2: G2psi22, PSI_X, PSI_Y, PSI2_X, PSI2_Y };
2966
+ }
2967
+ var _Field2 = class {
2968
+ constructor(Fp3, opts = {}) {
2969
+ __publicField(this, "ORDER");
2970
+ __publicField(this, "BITS");
2971
+ __publicField(this, "BYTES");
2972
+ __publicField(this, "isLE");
2973
+ __publicField(this, "ZERO");
2974
+ __publicField(this, "ONE");
2975
+ __publicField(this, "Fp");
2976
+ __publicField(this, "NONRESIDUE");
2977
+ __publicField(this, "mulByB");
2978
+ __publicField(this, "Fp_NONRESIDUE");
2979
+ __publicField(this, "Fp_div2");
2980
+ __publicField(this, "FROBENIUS_COEFFICIENTS");
2981
+ const { NONRESIDUE = BigInt(-1), FP2_NONRESIDUE, Fp2mulByB } = opts;
2982
+ const ORDER = Fp3.ORDER;
2983
+ const FP2_ORDER = ORDER * ORDER;
2984
+ this.Fp = Fp3;
2985
+ this.ORDER = FP2_ORDER;
2986
+ this.BITS = bitLen(FP2_ORDER);
2987
+ this.BYTES = Math.ceil(bitLen(FP2_ORDER) / 8);
2988
+ this.isLE = Fp3.isLE;
2989
+ this.ZERO = this.create({ c0: Fp3.ZERO, c1: Fp3.ZERO });
2990
+ this.ONE = this.create({ c0: Fp3.ONE, c1: Fp3.ZERO });
2991
+ this.Fp_NONRESIDUE = Fp3.create(NONRESIDUE);
2992
+ this.Fp_div2 = Fp3.div(Fp3.ONE, _2n4);
2993
+ this.NONRESIDUE = this.create({ c0: FP2_NONRESIDUE[0], c1: FP2_NONRESIDUE[1] });
2994
+ this.FROBENIUS_COEFFICIENTS = Object.freeze(calcFrobeniusCoefficients(Fp3, this.Fp_NONRESIDUE, Fp3.ORDER, 2)[0]);
2995
+ this.mulByB = (num) => {
2996
+ const { c0, c1 } = Fp2mulByB(num);
2997
+ return Object.freeze({ c0, c1 });
2998
+ };
2999
+ Object.freeze(this);
3000
+ }
3001
+ fromBigTuple(tuple) {
3002
+ if (!Array.isArray(tuple) || tuple.length !== 2)
3003
+ throw new Error("invalid Fp2.fromBigTuple");
3004
+ const [c0, c1] = tuple;
3005
+ if (typeof c0 !== "bigint" || typeof c1 !== "bigint")
3006
+ throw new Error("invalid Fp2.fromBigTuple");
3007
+ return this.create({ c0, c1 });
3008
+ }
3009
+ create(num) {
3010
+ const { Fp: Fp3 } = this;
3011
+ const c0 = Fp3.create(num.c0);
3012
+ const c1 = Fp3.create(num.c1);
3013
+ return Object.freeze({ c0, c1 });
3014
+ }
3015
+ isValid(num) {
3016
+ if (!isObj(num))
3017
+ throw new TypeError("invalid field element: expected object, got " + typeof num);
3018
+ const { c0, c1 } = num;
3019
+ const { Fp: Fp3 } = this;
3020
+ return Fp3.isValid(c0) && Fp3.isValid(c1);
3021
+ }
3022
+ is0(num) {
3023
+ if (!isObj(num))
3024
+ return false;
3025
+ const { c0, c1 } = num;
3026
+ const { Fp: Fp3 } = this;
3027
+ return Fp3.is0(c0) && Fp3.is0(c1);
3028
+ }
3029
+ isValidNot0(num) {
3030
+ return !this.is0(num) && this.isValid(num);
3031
+ }
3032
+ eql({ c0, c1 }, { c0: r0, c1: r1 }) {
3033
+ const { Fp: Fp3 } = this;
3034
+ return Fp3.eql(c0, r0) && Fp3.eql(c1, r1);
3035
+ }
3036
+ neg({ c0, c1 }) {
3037
+ const { Fp: Fp3 } = this;
3038
+ return Object.freeze({ c0: Fp3.neg(c0), c1: Fp3.neg(c1) });
3039
+ }
3040
+ pow(num, power) {
3041
+ return FpPow(this, num, power);
3042
+ }
3043
+ invertBatch(nums) {
3044
+ return FpInvertBatch(this, nums);
3045
+ }
3046
+ // Normalized
3047
+ add(f1, f2) {
3048
+ const { Fp: Fp3 } = this;
3049
+ const { c0, c1 } = f1;
3050
+ const { c0: r0, c1: r1 } = f2;
3051
+ return Object.freeze({
3052
+ c0: Fp3.add(c0, r0),
3053
+ c1: Fp3.add(c1, r1)
3054
+ });
3055
+ }
3056
+ sub({ c0, c1 }, { c0: r0, c1: r1 }) {
3057
+ const { Fp: Fp3 } = this;
3058
+ return Object.freeze({
3059
+ c0: Fp3.sub(c0, r0),
3060
+ c1: Fp3.sub(c1, r1)
3061
+ });
3062
+ }
3063
+ mul({ c0, c1 }, rhs) {
3064
+ const { Fp: Fp3 } = this;
3065
+ if (typeof rhs === "bigint")
3066
+ return Object.freeze({ c0: Fp3.mul(c0, rhs), c1: Fp3.mul(c1, rhs) });
3067
+ const { c0: r0, c1: r1 } = rhs;
3068
+ let t1 = Fp3.mul(c0, r0);
3069
+ let t2 = Fp3.mul(c1, r1);
3070
+ const o0 = Fp3.sub(t1, t2);
3071
+ const o1 = Fp3.sub(Fp3.mul(Fp3.add(c0, c1), Fp3.add(r0, r1)), Fp3.add(t1, t2));
3072
+ return Object.freeze({ c0: o0, c1: o1 });
3073
+ }
3074
+ sqr({ c0, c1 }) {
3075
+ const { Fp: Fp3 } = this;
3076
+ const a = Fp3.add(c0, c1);
3077
+ const b = Fp3.sub(c0, c1);
3078
+ const c = Fp3.add(c0, c0);
3079
+ return Object.freeze({ c0: Fp3.mul(a, b), c1: Fp3.mul(c, c1) });
3080
+ }
3081
+ // NonNormalized stuff
3082
+ addN(a, b) {
3083
+ return this.add(a, b);
3084
+ }
3085
+ subN(a, b) {
3086
+ return this.sub(a, b);
3087
+ }
3088
+ mulN(a, b) {
3089
+ return this.mul(a, b);
3090
+ }
3091
+ sqrN(a) {
3092
+ return this.sqr(a);
3093
+ }
3094
+ // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context?
3095
+ div(lhs, rhs) {
3096
+ const { Fp: Fp3 } = this;
3097
+ return this.mul(lhs, typeof rhs === "bigint" ? Fp3.inv(Fp3.create(rhs)) : this.inv(rhs));
3098
+ }
3099
+ inv({ c0: a, c1: b }) {
3100
+ const { Fp: Fp3 } = this;
3101
+ const factor = Fp3.inv(Fp3.create(a * a + b * b));
3102
+ return Object.freeze({ c0: Fp3.mul(factor, Fp3.create(a)), c1: Fp3.mul(factor, Fp3.create(-b)) });
3103
+ }
3104
+ sqrt(num) {
3105
+ const { Fp: Fp3 } = this;
3106
+ const Fp22 = this;
3107
+ const { c0, c1 } = num;
3108
+ if (Fp3.is0(c1)) {
3109
+ if (FpLegendre(Fp3, c0) === 1)
3110
+ return Fp22.create({ c0: Fp3.sqrt(c0), c1: Fp3.ZERO });
3111
+ else
3112
+ return Fp22.create({ c0: Fp3.ZERO, c1: Fp3.sqrt(Fp3.div(c0, this.Fp_NONRESIDUE)) });
3113
+ }
3114
+ const a = Fp3.sqrt(Fp3.sub(Fp3.sqr(c0), Fp3.mul(Fp3.sqr(c1), this.Fp_NONRESIDUE)));
3115
+ let d = Fp3.mul(Fp3.add(a, c0), this.Fp_div2);
3116
+ const legendre = FpLegendre(Fp3, d);
3117
+ if (legendre === -1)
3118
+ d = Fp3.sub(d, a);
3119
+ const a0 = Fp3.sqrt(d);
3120
+ const candidateSqrt = Fp22.create({ c0: a0, c1: Fp3.div(Fp3.mul(c1, this.Fp_div2), a0) });
3121
+ if (!Fp22.eql(Fp22.sqr(candidateSqrt), num))
3122
+ throw new Error("Cannot find square root");
3123
+ const x1 = candidateSqrt;
3124
+ const x2 = Fp22.neg(x1);
3125
+ const { re: re1, im: im1 } = Fp22.reim(x1);
3126
+ const { re: re2, im: im2 } = Fp22.reim(x2);
3127
+ if (im1 > im2 || im1 === im2 && re1 > re2)
3128
+ return x1;
3129
+ return x2;
3130
+ }
3131
+ // Same as sgn0_m_eq_2 in RFC 9380
3132
+ isOdd(x) {
3133
+ const { re: x0, im: x1 } = this.reim(x);
3134
+ const sign_0 = x0 % _2n4;
3135
+ const zero_0 = x0 === _0n6;
3136
+ const sign_1 = x1 % _2n4;
3137
+ return BigInt(sign_0 || zero_0 && sign_1) == _1n6;
3138
+ }
3139
+ // Bytes util
3140
+ fromBytes(b) {
3141
+ const { Fp: Fp3 } = this;
3142
+ abytes2(b);
3143
+ if (b.length !== this.BYTES)
3144
+ throw new Error("fromBytes invalid length=" + b.length);
3145
+ return this.create({
3146
+ c0: Fp3.fromBytes(b.subarray(0, Fp3.BYTES)),
3147
+ c1: Fp3.fromBytes(b.subarray(Fp3.BYTES))
3148
+ });
3149
+ }
3150
+ toBytes({ c0, c1 }) {
3151
+ return concatBytes2(this.Fp.toBytes(c0), this.Fp.toBytes(c1));
3152
+ }
3153
+ cmov({ c0, c1 }, { c0: r0, c1: r1 }, c) {
3154
+ const { Fp: Fp3 } = this;
3155
+ return this.create({
3156
+ c0: Fp3.cmov(c0, r0, c),
3157
+ c1: Fp3.cmov(c1, r1, c)
3158
+ });
3159
+ }
3160
+ reim({ c0, c1 }) {
3161
+ return { re: c0, im: c1 };
3162
+ }
3163
+ Fp4Square(a, b) {
3164
+ const Fp22 = this;
3165
+ const a2 = Fp22.sqr(a);
3166
+ const b2 = Fp22.sqr(b);
3167
+ return {
3168
+ first: Fp22.add(Fp22.mulByNonresidue(b2), a2),
3169
+ // b² * Nonresidue + a²
3170
+ second: Fp22.sub(Fp22.sub(Fp22.sqr(Fp22.add(a, b)), a2), b2)
3171
+ // (a + b)² - a² - b²
3172
+ };
3173
+ }
3174
+ // multiply by u + 1
3175
+ mulByNonresidue({ c0, c1 }) {
3176
+ return this.mul({ c0, c1 }, this.NONRESIDUE);
3177
+ }
3178
+ frobeniusMap({ c0, c1 }, power) {
3179
+ return Object.freeze({
3180
+ c0,
3181
+ c1: this.Fp.mul(c1, this.FROBENIUS_COEFFICIENTS[power % 2])
3182
+ });
3183
+ }
3184
+ };
3185
+ var _Field6 = class {
3186
+ constructor(Fp22) {
3187
+ __publicField(this, "ORDER");
3188
+ __publicField(this, "BITS");
3189
+ __publicField(this, "BYTES");
3190
+ __publicField(this, "isLE");
3191
+ __publicField(this, "ZERO");
3192
+ __publicField(this, "ONE");
3193
+ __publicField(this, "Fp2");
3194
+ this.Fp2 = Fp22;
3195
+ this.ORDER = Fp22.Fp.ORDER ** _6n;
3196
+ this.BITS = 3 * Fp22.BITS;
3197
+ this.BYTES = 3 * Fp22.BYTES;
3198
+ this.isLE = Fp22.isLE;
3199
+ this.ZERO = this.create({ c0: Fp22.ZERO, c1: Fp22.ZERO, c2: Fp22.ZERO });
3200
+ this.ONE = this.create({ c0: Fp22.ONE, c1: Fp22.ZERO, c2: Fp22.ZERO });
3201
+ Object.freeze(this);
3202
+ }
3203
+ // Most callers never touch Frobenius maps, so keep the sextic tables lazy:
3204
+ // eagerly deriving them dominates `bls12-381.js` / `bn254.js` import time.
3205
+ get FROBENIUS_COEFFICIENTS_1() {
3206
+ const frob2 = _FROBENIUS_COEFFICIENTS_6.get(this);
3207
+ if (frob2)
3208
+ return frob2[0];
3209
+ const { Fp2: Fp22 } = this;
3210
+ const { Fp: Fp3 } = Fp22;
3211
+ const rows = calcFrobeniusCoefficients(Fp22, Fp22.NONRESIDUE, Fp3.ORDER, 6, 2, 3);
3212
+ const cache = [Object.freeze(rows[0]), Object.freeze(rows[1])];
3213
+ _FROBENIUS_COEFFICIENTS_6.set(this, cache);
3214
+ return cache[0];
3215
+ }
3216
+ get FROBENIUS_COEFFICIENTS_2() {
3217
+ const frob2 = _FROBENIUS_COEFFICIENTS_6.get(this);
3218
+ if (frob2)
3219
+ return frob2[1];
3220
+ void this.FROBENIUS_COEFFICIENTS_1;
3221
+ return _FROBENIUS_COEFFICIENTS_6.get(this)[1];
3222
+ }
3223
+ add({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) {
3224
+ const { Fp2: Fp22 } = this;
3225
+ return Object.freeze({
3226
+ c0: Fp22.add(c0, r0),
3227
+ c1: Fp22.add(c1, r1),
3228
+ c2: Fp22.add(c2, r2)
3229
+ });
3230
+ }
3231
+ sub({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) {
3232
+ const { Fp2: Fp22 } = this;
3233
+ return Object.freeze({
3234
+ c0: Fp22.sub(c0, r0),
3235
+ c1: Fp22.sub(c1, r1),
3236
+ c2: Fp22.sub(c2, r2)
3237
+ });
3238
+ }
3239
+ mul({ c0, c1, c2 }, rhs) {
3240
+ const { Fp2: Fp22 } = this;
3241
+ if (typeof rhs === "bigint") {
3242
+ return Object.freeze({
3243
+ c0: Fp22.mul(c0, rhs),
3244
+ c1: Fp22.mul(c1, rhs),
3245
+ c2: Fp22.mul(c2, rhs)
3246
+ });
3247
+ }
3248
+ const { c0: r0, c1: r1, c2: r2 } = rhs;
3249
+ const t0 = Fp22.mul(c0, r0);
3250
+ const t1 = Fp22.mul(c1, r1);
3251
+ const t2 = Fp22.mul(c2, r2);
3252
+ return Object.freeze({
3253
+ // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)
3254
+ c0: Fp22.add(t0, Fp22.mulByNonresidue(Fp22.sub(Fp22.mul(Fp22.add(c1, c2), Fp22.add(r1, r2)), Fp22.add(t1, t2)))),
3255
+ // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)
3256
+ c1: Fp22.add(Fp22.sub(Fp22.mul(Fp22.add(c0, c1), Fp22.add(r0, r1)), Fp22.add(t0, t1)), Fp22.mulByNonresidue(t2)),
3257
+ // T1 + (c0 + c2) * (r0 + r2) - T0 + T2
3258
+ c2: Fp22.sub(Fp22.add(t1, Fp22.mul(Fp22.add(c0, c2), Fp22.add(r0, r2))), Fp22.add(t0, t2))
3259
+ });
3260
+ }
3261
+ sqr({ c0, c1, c2 }) {
3262
+ const { Fp2: Fp22 } = this;
3263
+ let t0 = Fp22.sqr(c0);
3264
+ let t1 = Fp22.mul(Fp22.mul(c0, c1), _2n4);
3265
+ let t3 = Fp22.mul(Fp22.mul(c1, c2), _2n4);
3266
+ let t4 = Fp22.sqr(c2);
3267
+ return Object.freeze({
3268
+ c0: Fp22.add(Fp22.mulByNonresidue(t3), t0),
3269
+ // T3 * (u + 1) + T0
3270
+ c1: Fp22.add(Fp22.mulByNonresidue(t4), t1),
3271
+ // T4 * (u + 1) + T1
3272
+ // T1 + (c0 - c1 + c2)² + T3 - T0 - T4
3273
+ c2: Fp22.sub(Fp22.sub(Fp22.add(Fp22.add(t1, Fp22.sqr(Fp22.add(Fp22.sub(c0, c1), c2))), t3), t0), t4)
3274
+ });
3275
+ }
3276
+ addN(a, b) {
3277
+ return this.add(a, b);
3278
+ }
3279
+ subN(a, b) {
3280
+ return this.sub(a, b);
3281
+ }
3282
+ mulN(a, b) {
3283
+ return this.mul(a, b);
3284
+ }
3285
+ sqrN(a) {
3286
+ return this.sqr(a);
3287
+ }
3288
+ create(num) {
3289
+ const { Fp2: Fp22 } = this;
3290
+ const c0 = Fp22.create(num.c0);
3291
+ const c1 = Fp22.create(num.c1);
3292
+ const c2 = Fp22.create(num.c2);
3293
+ return Object.freeze({ c0, c1, c2 });
3294
+ }
3295
+ isValid(num) {
3296
+ if (!isObj(num))
3297
+ throw new TypeError("invalid field element: expected object, got " + typeof num);
3298
+ const { c0, c1, c2 } = num;
3299
+ const { Fp2: Fp22 } = this;
3300
+ return Fp22.isValid(c0) && Fp22.isValid(c1) && Fp22.isValid(c2);
3301
+ }
3302
+ is0(num) {
3303
+ if (!isObj(num))
3304
+ return false;
3305
+ const { c0, c1, c2 } = num;
3306
+ const { Fp2: Fp22 } = this;
3307
+ return Fp22.is0(c0) && Fp22.is0(c1) && Fp22.is0(c2);
3308
+ }
3309
+ isValidNot0(num) {
3310
+ return !this.is0(num) && this.isValid(num);
3311
+ }
3312
+ neg({ c0, c1, c2 }) {
3313
+ const { Fp2: Fp22 } = this;
3314
+ return Object.freeze({ c0: Fp22.neg(c0), c1: Fp22.neg(c1), c2: Fp22.neg(c2) });
3315
+ }
3316
+ eql({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) {
3317
+ const { Fp2: Fp22 } = this;
3318
+ return Fp22.eql(c0, r0) && Fp22.eql(c1, r1) && Fp22.eql(c2, r2);
3319
+ }
3320
+ sqrt(_) {
3321
+ return notImplemented();
3322
+ }
3323
+ // Do we need division by bigint at all? Should be done via order:
3324
+ div(lhs, rhs) {
3325
+ const { Fp2: Fp22 } = this;
3326
+ const { Fp: Fp3 } = Fp22;
3327
+ return this.mul(lhs, typeof rhs === "bigint" ? Fp3.inv(Fp3.create(rhs)) : this.inv(rhs));
3328
+ }
3329
+ pow(num, power) {
3330
+ return FpPow(this, num, power);
3331
+ }
3332
+ invertBatch(nums) {
3333
+ return FpInvertBatch(this, nums);
3334
+ }
3335
+ inv({ c0, c1, c2 }) {
3336
+ const { Fp2: Fp22 } = this;
3337
+ let t0 = Fp22.sub(Fp22.sqr(c0), Fp22.mulByNonresidue(Fp22.mul(c2, c1)));
3338
+ let t1 = Fp22.sub(Fp22.mulByNonresidue(Fp22.sqr(c2)), Fp22.mul(c0, c1));
3339
+ let t2 = Fp22.sub(Fp22.sqr(c1), Fp22.mul(c0, c2));
3340
+ let t4 = Fp22.inv(Fp22.add(Fp22.mulByNonresidue(Fp22.add(Fp22.mul(c2, t1), Fp22.mul(c1, t2))), Fp22.mul(c0, t0)));
3341
+ return Object.freeze({ c0: Fp22.mul(t4, t0), c1: Fp22.mul(t4, t1), c2: Fp22.mul(t4, t2) });
3342
+ }
3343
+ // Bytes utils
3344
+ fromBytes(b) {
3345
+ const { Fp2: Fp22 } = this;
3346
+ abytes2(b);
3347
+ if (b.length !== this.BYTES)
3348
+ throw new Error("fromBytes invalid length=" + b.length);
3349
+ const B2 = Fp22.BYTES;
3350
+ return this.create({
3351
+ c0: Fp22.fromBytes(b.subarray(0, B2)),
3352
+ c1: Fp22.fromBytes(b.subarray(B2, B2 * 2)),
3353
+ c2: Fp22.fromBytes(b.subarray(2 * B2))
3354
+ });
3355
+ }
3356
+ toBytes({ c0, c1, c2 }) {
3357
+ const { Fp2: Fp22 } = this;
3358
+ return concatBytes2(Fp22.toBytes(c0), Fp22.toBytes(c1), Fp22.toBytes(c2));
3359
+ }
3360
+ cmov({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) {
3361
+ const { Fp2: Fp22 } = this;
3362
+ return this.create({
3363
+ c0: Fp22.cmov(c0, r0, c),
3364
+ c1: Fp22.cmov(c1, r1, c),
3365
+ c2: Fp22.cmov(c2, r2, c)
3366
+ });
3367
+ }
3368
+ fromBigSix(tuple) {
3369
+ const { Fp2: Fp22 } = this;
3370
+ if (!Array.isArray(tuple) || tuple.length !== 6)
3371
+ throw new Error("invalid Fp6.fromBigSix");
3372
+ for (let i = 0; i < 6; i++)
3373
+ if (typeof tuple[i] !== "bigint")
3374
+ throw new Error("invalid Fp6.fromBigSix");
3375
+ const t = tuple;
3376
+ return this.create({
3377
+ c0: Fp22.fromBigTuple(t.slice(0, 2)),
3378
+ c1: Fp22.fromBigTuple(t.slice(2, 4)),
3379
+ c2: Fp22.fromBigTuple(t.slice(4, 6))
3380
+ });
3381
+ }
3382
+ frobeniusMap({ c0, c1, c2 }, power) {
3383
+ const { Fp2: Fp22 } = this;
3384
+ return Object.freeze({
3385
+ c0: Fp22.frobeniusMap(c0, power),
3386
+ c1: Fp22.mul(Fp22.frobeniusMap(c1, power), this.FROBENIUS_COEFFICIENTS_1[power % 6]),
3387
+ c2: Fp22.mul(Fp22.frobeniusMap(c2, power), this.FROBENIUS_COEFFICIENTS_2[power % 6])
3388
+ });
3389
+ }
3390
+ mulByFp2({ c0, c1, c2 }, rhs) {
3391
+ const { Fp2: Fp22 } = this;
3392
+ return Object.freeze({
3393
+ c0: Fp22.mul(c0, rhs),
3394
+ c1: Fp22.mul(c1, rhs),
3395
+ c2: Fp22.mul(c2, rhs)
3396
+ });
3397
+ }
3398
+ mulByNonresidue({ c0, c1, c2 }) {
3399
+ const { Fp2: Fp22 } = this;
3400
+ return Object.freeze({ c0: Fp22.mulByNonresidue(c2), c1: c0, c2: c1 });
3401
+ }
3402
+ // Sparse multiplication
3403
+ mul1({ c0, c1, c2 }, b1) {
3404
+ const { Fp2: Fp22 } = this;
3405
+ return Object.freeze({
3406
+ c0: Fp22.mulByNonresidue(Fp22.mul(c2, b1)),
3407
+ c1: Fp22.mul(c0, b1),
3408
+ c2: Fp22.mul(c1, b1)
3409
+ });
3410
+ }
3411
+ // Sparse multiplication
3412
+ mul01({ c0, c1, c2 }, b0, b1) {
3413
+ const { Fp2: Fp22 } = this;
3414
+ let t0 = Fp22.mul(c0, b0);
3415
+ let t1 = Fp22.mul(c1, b1);
3416
+ return Object.freeze({
3417
+ // ((c1 + c2) * b1 - T1) * (u + 1) + T0
3418
+ c0: Fp22.add(Fp22.mulByNonresidue(Fp22.sub(Fp22.mul(Fp22.add(c1, c2), b1), t1)), t0),
3419
+ // (b0 + b1) * (c0 + c1) - T0 - T1
3420
+ c1: Fp22.sub(Fp22.sub(Fp22.mul(Fp22.add(b0, b1), Fp22.add(c0, c1)), t0), t1),
3421
+ // (c0 + c2) * b0 - T0 + T1
3422
+ c2: Fp22.add(Fp22.sub(Fp22.mul(Fp22.add(c0, c2), b0), t0), t1)
3423
+ });
3424
+ }
3425
+ };
3426
+ var _FROBENIUS_COEFFICIENTS_6 = /* @__PURE__ */ new WeakMap();
3427
+ var _Field12 = class {
3428
+ constructor(Fp62, opts) {
3429
+ __publicField(this, "ORDER");
3430
+ __publicField(this, "BITS");
3431
+ __publicField(this, "BYTES");
3432
+ __publicField(this, "isLE");
3433
+ __publicField(this, "ZERO");
3434
+ __publicField(this, "ONE");
3435
+ __publicField(this, "Fp6");
3436
+ __publicField(this, "X_LEN");
3437
+ __publicField(this, "finalExponentiate");
3438
+ const { X_LEN, Fp12finalExponentiate } = opts;
3439
+ const { Fp2: Fp22 } = Fp62;
3440
+ const { Fp: Fp3 } = Fp22;
3441
+ this.Fp6 = Fp62;
3442
+ this.ORDER = Fp3.ORDER ** _12n;
3443
+ this.BITS = 2 * Fp62.BITS;
3444
+ this.BYTES = 2 * Fp62.BYTES;
3445
+ this.isLE = Fp62.isLE;
3446
+ this.ZERO = this.create({ c0: Fp62.ZERO, c1: Fp62.ZERO });
3447
+ this.ONE = this.create({ c0: Fp62.ONE, c1: Fp62.ZERO });
3448
+ this.X_LEN = X_LEN;
3449
+ this.finalExponentiate = (num) => {
3450
+ const copy2 = ({ c0, c1 }) => Object.freeze({ c0, c1 });
3451
+ const copy6 = ({ c0, c1, c2 }) => Object.freeze({ c0: copy2(c0), c1: copy2(c1), c2: copy2(c2) });
3452
+ const res = Fp12finalExponentiate(num);
3453
+ return Object.freeze({ c0: copy6(res.c0), c1: copy6(res.c1) });
3454
+ };
3455
+ Object.freeze(this);
3456
+ }
3457
+ // Keep the degree-12 Frobenius row lazy too; after the first lookup the cached
3458
+ // array is reused exactly like the old eager table.
3459
+ get FROBENIUS_COEFFICIENTS() {
3460
+ const frob2 = _FROBENIUS_COEFFICIENTS_12.get(this);
3461
+ if (frob2)
3462
+ return frob2;
3463
+ const { Fp2: Fp22 } = this.Fp6;
3464
+ const { Fp: Fp3 } = Fp22;
3465
+ const cache = Object.freeze(calcFrobeniusCoefficients(Fp22, Fp22.NONRESIDUE, Fp3.ORDER, 12, 1, 6)[0]);
3466
+ _FROBENIUS_COEFFICIENTS_12.set(this, cache);
3467
+ return cache;
3468
+ }
3469
+ create(num) {
3470
+ const { Fp6: Fp62 } = this;
3471
+ const c0 = Fp62.create(num.c0);
3472
+ const c1 = Fp62.create(num.c1);
3473
+ return Object.freeze({ c0, c1 });
3474
+ }
3475
+ isValid(num) {
3476
+ if (!isObj(num))
3477
+ throw new TypeError("invalid field element: expected object, got " + typeof num);
3478
+ const { c0, c1 } = num;
3479
+ const { Fp6: Fp62 } = this;
3480
+ return Fp62.isValid(c0) && Fp62.isValid(c1);
3481
+ }
3482
+ is0(num) {
3483
+ if (!isObj(num))
3484
+ return false;
3485
+ const { c0, c1 } = num;
3486
+ const { Fp6: Fp62 } = this;
3487
+ return Fp62.is0(c0) && Fp62.is0(c1);
3488
+ }
3489
+ isValidNot0(num) {
3490
+ return !this.is0(num) && this.isValid(num);
3491
+ }
3492
+ neg({ c0, c1 }) {
3493
+ const { Fp6: Fp62 } = this;
3494
+ return Object.freeze({ c0: Fp62.neg(c0), c1: Fp62.neg(c1) });
3495
+ }
3496
+ eql({ c0, c1 }, { c0: r0, c1: r1 }) {
3497
+ const { Fp6: Fp62 } = this;
3498
+ return Fp62.eql(c0, r0) && Fp62.eql(c1, r1);
3499
+ }
3500
+ sqrt(_) {
3501
+ return notImplemented();
3502
+ }
3503
+ inv({ c0, c1 }) {
3504
+ const { Fp6: Fp62 } = this;
3505
+ let t = Fp62.inv(Fp62.sub(Fp62.sqr(c0), Fp62.mulByNonresidue(Fp62.sqr(c1))));
3506
+ return Object.freeze({ c0: Fp62.mul(c0, t), c1: Fp62.neg(Fp62.mul(c1, t)) });
3507
+ }
3508
+ div(lhs, rhs) {
3509
+ const { Fp6: Fp62 } = this;
3510
+ const { Fp2: Fp22 } = Fp62;
3511
+ const { Fp: Fp3 } = Fp22;
3512
+ return this.mul(lhs, typeof rhs === "bigint" ? Fp3.inv(Fp3.create(rhs)) : this.inv(rhs));
3513
+ }
3514
+ pow(num, power) {
3515
+ return FpPow(this, num, power);
3516
+ }
3517
+ invertBatch(nums) {
3518
+ return FpInvertBatch(this, nums);
3519
+ }
3520
+ // Normalized
3521
+ add({ c0, c1 }, { c0: r0, c1: r1 }) {
3522
+ const { Fp6: Fp62 } = this;
3523
+ return Object.freeze({
3524
+ c0: Fp62.add(c0, r0),
3525
+ c1: Fp62.add(c1, r1)
3526
+ });
3527
+ }
3528
+ sub({ c0, c1 }, { c0: r0, c1: r1 }) {
3529
+ const { Fp6: Fp62 } = this;
3530
+ return Object.freeze({
3531
+ c0: Fp62.sub(c0, r0),
3532
+ c1: Fp62.sub(c1, r1)
3533
+ });
3534
+ }
3535
+ mul({ c0, c1 }, rhs) {
3536
+ const { Fp6: Fp62 } = this;
3537
+ if (typeof rhs === "bigint")
3538
+ return Object.freeze({ c0: Fp62.mul(c0, rhs), c1: Fp62.mul(c1, rhs) });
3539
+ let { c0: r0, c1: r1 } = rhs;
3540
+ let t1 = Fp62.mul(c0, r0);
3541
+ let t2 = Fp62.mul(c1, r1);
3542
+ return Object.freeze({
3543
+ c0: Fp62.add(t1, Fp62.mulByNonresidue(t2)),
3544
+ // T1 + T2 * v
3545
+ // (c0 + c1) * (r0 + r1) - (T1 + T2)
3546
+ c1: Fp62.sub(Fp62.mul(Fp62.add(c0, c1), Fp62.add(r0, r1)), Fp62.add(t1, t2))
3547
+ });
3548
+ }
3549
+ sqr({ c0, c1 }) {
3550
+ const { Fp6: Fp62 } = this;
3551
+ let ab = Fp62.mul(c0, c1);
3552
+ return Object.freeze({
3553
+ // (c1 * v + c0) * (c0 + c1) - AB - AB * v
3554
+ c0: Fp62.sub(Fp62.sub(Fp62.mul(Fp62.add(Fp62.mulByNonresidue(c1), c0), Fp62.add(c0, c1)), ab), Fp62.mulByNonresidue(ab)),
3555
+ c1: Fp62.add(ab, ab)
3556
+ });
3557
+ }
3558
+ // NonNormalized stuff
3559
+ addN(a, b) {
3560
+ return this.add(a, b);
3561
+ }
3562
+ subN(a, b) {
3563
+ return this.sub(a, b);
3564
+ }
3565
+ mulN(a, b) {
3566
+ return this.mul(a, b);
3567
+ }
3568
+ sqrN(a) {
3569
+ return this.sqr(a);
3570
+ }
3571
+ // Bytes utils
3572
+ fromBytes(b) {
3573
+ const { Fp6: Fp62 } = this;
3574
+ abytes2(b);
3575
+ if (b.length !== this.BYTES)
3576
+ throw new Error("fromBytes invalid length=" + b.length);
3577
+ return this.create({
3578
+ c0: Fp62.fromBytes(b.subarray(0, Fp62.BYTES)),
3579
+ c1: Fp62.fromBytes(b.subarray(Fp62.BYTES))
3580
+ });
3581
+ }
3582
+ toBytes({ c0, c1 }) {
3583
+ const { Fp6: Fp62 } = this;
3584
+ return concatBytes2(Fp62.toBytes(c0), Fp62.toBytes(c1));
3585
+ }
3586
+ cmov({ c0, c1 }, { c0: r0, c1: r1 }, c) {
3587
+ const { Fp6: Fp62 } = this;
3588
+ return this.create({
3589
+ c0: Fp62.cmov(c0, r0, c),
3590
+ c1: Fp62.cmov(c1, r1, c)
3591
+ });
3592
+ }
3593
+ // Utils
3594
+ // toString() {
3595
+ // return '' + 'Fp12(' + this.c0 + this.c1 + '* w');
3596
+ // },
3597
+ // fromTuple(c: [Fp6, Fp6]) {
3598
+ // return new Fp12(...c);
3599
+ // }
3600
+ fromBigTwelve(tuple) {
3601
+ const { Fp6: Fp62 } = this;
3602
+ if (!Array.isArray(tuple) || tuple.length !== 12)
3603
+ throw new Error("invalid Fp12.fromBigTwelve");
3604
+ for (let i = 0; i < 12; i++)
3605
+ if (typeof tuple[i] !== "bigint")
3606
+ throw new Error("invalid Fp12.fromBigTwelve");
3607
+ const t = tuple;
3608
+ return this.create({
3609
+ c0: Fp62.fromBigSix(t.slice(0, 6)),
3610
+ c1: Fp62.fromBigSix(t.slice(6, 12))
3611
+ });
3612
+ }
3613
+ // Raises to q**i -th power
3614
+ frobeniusMap(lhs, power) {
3615
+ const { Fp6: Fp62 } = this;
3616
+ const { Fp2: Fp22 } = Fp62;
3617
+ const { c0, c1, c2 } = Fp62.frobeniusMap(lhs.c1, power);
3618
+ const coeff = this.FROBENIUS_COEFFICIENTS[power % 12];
3619
+ return Object.freeze({
3620
+ c0: Fp62.frobeniusMap(lhs.c0, power),
3621
+ c1: Object.freeze({
3622
+ c0: Fp22.mul(c0, coeff),
3623
+ c1: Fp22.mul(c1, coeff),
3624
+ c2: Fp22.mul(c2, coeff)
3625
+ })
3626
+ });
3627
+ }
3628
+ mulByFp2({ c0, c1 }, rhs) {
3629
+ const { Fp6: Fp62 } = this;
3630
+ return Object.freeze({
3631
+ c0: Fp62.mulByFp2(c0, rhs),
3632
+ c1: Fp62.mulByFp2(c1, rhs)
3633
+ });
3634
+ }
3635
+ conjugate({ c0, c1 }) {
3636
+ return Object.freeze({ c0, c1: this.Fp6.neg(c1) });
3637
+ }
3638
+ // Sparse multiplication
3639
+ mul014({ c0, c1 }, o0, o1, o4) {
3640
+ const { Fp6: Fp62 } = this;
3641
+ const { Fp2: Fp22 } = Fp62;
3642
+ let t0 = Fp62.mul01(c0, o0, o1);
3643
+ let t1 = Fp62.mul1(c1, o4);
3644
+ return Object.freeze({
3645
+ c0: Fp62.add(Fp62.mulByNonresidue(t1), t0),
3646
+ // T1 * v + T0
3647
+ // (c1 + c0) * [o0, o1+o4] - T0 - T1
3648
+ c1: Fp62.sub(Fp62.sub(Fp62.mul01(Fp62.add(c1, c0), o0, Fp22.add(o1, o4)), t0), t1)
3649
+ });
3650
+ }
3651
+ mul034({ c0, c1 }, o0, o3, o4) {
3652
+ const { Fp6: Fp62 } = this;
3653
+ const { Fp2: Fp22 } = Fp62;
3654
+ const a = Object.freeze({
3655
+ c0: Fp22.mul(c0.c0, o0),
3656
+ c1: Fp22.mul(c0.c1, o0),
3657
+ c2: Fp22.mul(c0.c2, o0)
3658
+ });
3659
+ const b = Fp62.mul01(c1, o3, o4);
3660
+ const e = Fp62.mul01(Fp62.add(c0, c1), Fp22.add(o0, o3), o4);
3661
+ return Object.freeze({
3662
+ c0: Fp62.add(Fp62.mulByNonresidue(b), a),
3663
+ c1: Fp62.sub(e, Fp62.add(a, b))
3664
+ });
3665
+ }
3666
+ // A cyclotomic group is a subgroup of Fp^n defined by
3667
+ // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}
3668
+ // The result of any pairing is in a cyclotomic subgroup
3669
+ // https://eprint.iacr.org/2009/565.pdf
3670
+ // https://eprint.iacr.org/2010/354.pdf
3671
+ _cyclotomicSquare({ c0, c1 }) {
3672
+ const { Fp6: Fp62 } = this;
3673
+ const { Fp2: Fp22 } = Fp62;
3674
+ const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0;
3675
+ const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1;
3676
+ const { first: t3, second: t4 } = Fp22.Fp4Square(c0c0, c1c1);
3677
+ const { first: t5, second: t6 } = Fp22.Fp4Square(c1c0, c0c2);
3678
+ const { first: t7, second: t8 } = Fp22.Fp4Square(c0c1, c1c2);
3679
+ const t9 = Fp22.mulByNonresidue(t8);
3680
+ return Object.freeze({
3681
+ c0: Object.freeze({
3682
+ c0: Fp22.add(Fp22.mul(Fp22.sub(t3, c0c0), _2n4), t3),
3683
+ // 2 * (T3 - c0c0) + T3
3684
+ c1: Fp22.add(Fp22.mul(Fp22.sub(t5, c0c1), _2n4), t5),
3685
+ // 2 * (T5 - c0c1) + T5
3686
+ c2: Fp22.add(Fp22.mul(Fp22.sub(t7, c0c2), _2n4), t7)
3687
+ }),
3688
+ // 2 * (T7 - c0c2) + T7
3689
+ c1: Object.freeze({
3690
+ c0: Fp22.add(Fp22.mul(Fp22.add(t9, c1c0), _2n4), t9),
3691
+ // 2 * (T9 + c1c0) + T9
3692
+ c1: Fp22.add(Fp22.mul(Fp22.add(t4, c1c1), _2n4), t4),
3693
+ // 2 * (T4 + c1c1) + T4
3694
+ c2: Fp22.add(Fp22.mul(Fp22.add(t6, c1c2), _2n4), t6)
3695
+ })
3696
+ });
3697
+ }
3698
+ // https://eprint.iacr.org/2009/565.pdf
3699
+ _cyclotomicExp(num, n) {
3700
+ aInRange("cyclotomic exponent", n, _0n6, _1n6 << BigInt(this.X_LEN));
3701
+ let z = this.ONE;
3702
+ for (let i = this.X_LEN - 1; i >= 0; i--) {
3703
+ z = this._cyclotomicSquare(z);
3704
+ if (bitGet(n, i))
3705
+ z = this.mul(z, num);
3706
+ }
3707
+ return z;
3708
+ }
3709
+ };
3710
+ var _FROBENIUS_COEFFICIENTS_12 = /* @__PURE__ */ new WeakMap();
3711
+ function tower12(opts) {
3712
+ validateObject(opts, {
3713
+ ORDER: "bigint",
3714
+ X_LEN: "number",
3715
+ FP2_NONRESIDUE: "object",
3716
+ Fp2mulByB: "function",
3717
+ Fp12finalExponentiate: "function"
3718
+ }, { NONRESIDUE: "bigint" });
3719
+ asafenumber(opts.X_LEN, "X_LEN");
3720
+ if (opts.X_LEN < 1)
3721
+ throw new Error("invalid X_LEN");
3722
+ const nonresidue = opts.FP2_NONRESIDUE;
3723
+ if (!Array.isArray(nonresidue) || nonresidue.length !== 2)
3724
+ throw new Error("invalid FP2_NONRESIDUE");
3725
+ if (typeof nonresidue[0] !== "bigint" || typeof nonresidue[1] !== "bigint")
3726
+ throw new Error("invalid FP2_NONRESIDUE");
3727
+ const Fp3 = Field(opts.ORDER);
3728
+ const Fp22 = new _Field2(Fp3, opts);
3729
+ const Fp62 = new _Field6(Fp22);
3730
+ const Fp122 = new _Field12(Fp62, opts);
3731
+ return { Fp: Fp3, Fp2: Fp22, Fp6: Fp62, Fp12: Fp122 };
3732
+ }
3733
+
3734
+ // node_modules/@noble/curves/bls12-381.js
3735
+ var _0n7 = BigInt(0);
3736
+ var _1n7 = BigInt(1);
3737
+ var _2n5 = BigInt(2);
3738
+ var _3n5 = BigInt(3);
3739
+ var _4n3 = BigInt(4);
3740
+ var BLS_X = BigInt("0xd201000000010000");
3741
+ var BLS_X_LEN = bitLen(BLS_X);
3742
+ var bls12_381_CURVE_G1 = {
3743
+ p: BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),
3744
+ n: BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),
3745
+ h: BigInt("0x396c8c005555e1568c00aaab0000aaab"),
3746
+ a: _0n7,
3747
+ b: _4n3,
3748
+ Gx: BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),
3749
+ Gy: BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")
3750
+ };
3751
+ var bls12_381_Fr = Field(bls12_381_CURVE_G1.n, {
3752
+ modFromBytes: true
3753
+ });
3754
+ var { Fp, Fp2, Fp6, Fp12 } = tower12({
3755
+ ORDER: bls12_381_CURVE_G1.p,
3756
+ X_LEN: BLS_X_LEN,
3757
+ // Finite extension field over irreducible polynominal.
3758
+ // Fp(u) / (u² - β) where β = -1
3759
+ // Public `Fp2.NONRESIDUE` below is the sextic-tower value `(1, 1) = u + 1`;
3760
+ // the quadratic non-residue for the base Fp2 construction is still `-1`.
3761
+ FP2_NONRESIDUE: [_1n7, _1n7],
3762
+ Fp2mulByB: ({ c0, c1 }) => {
3763
+ const t0 = Fp.mul(c0, _4n3);
3764
+ const t1 = Fp.mul(c1, _4n3);
3765
+ return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) };
3766
+ },
3767
+ Fp12finalExponentiate: (num) => {
3768
+ const x = BLS_X;
3769
+ const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num);
3770
+ const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0);
3771
+ const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x));
3772
+ const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2);
3773
+ const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x));
3774
+ const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x));
3775
+ const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2));
3776
+ const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x));
3777
+ const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2);
3778
+ const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3);
3779
+ const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1);
3780
+ const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1);
3781
+ return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1);
3782
+ }
3783
+ });
3784
+ var frob;
3785
+ var getFrob = () => frob || (frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)));
3786
+ var G2psi = (c, P) => {
3787
+ const fn = getFrob().G2psi;
3788
+ G2psi = fn;
3789
+ return fn(c, P);
3790
+ };
3791
+ var G2psi2 = (c, P) => {
3792
+ const fn = getFrob().G2psi2;
3793
+ G2psi2 = fn;
3794
+ return fn(c, P);
3795
+ };
3796
+ var hasher_opts = Object.freeze({
3797
+ DST: "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",
3798
+ encodeDST: "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",
3799
+ p: Fp.ORDER,
3800
+ m: 2,
3801
+ k: 128,
3802
+ expand: "xmd",
3803
+ hash: sha256
3804
+ });
3805
+ var bls12_381_CURVE_G2 = {
3806
+ p: Fp2.ORDER,
3807
+ n: bls12_381_CURVE_G1.n,
3808
+ h: BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),
3809
+ a: Fp2.ZERO,
3810
+ b: Fp2.fromBigTuple([_4n3, _4n3]),
3811
+ Gx: Fp2.fromBigTuple([
3812
+ BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),
3813
+ BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")
3814
+ ]),
3815
+ Gy: Fp2.fromBigTuple([
3816
+ BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),
3817
+ BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")
3818
+ ])
3819
+ };
3820
+ var sortBit = (parts, p) => {
3821
+ for (const part of parts) {
3822
+ if (part !== _0n7)
3823
+ return Boolean(part * _2n5 / p);
3824
+ }
3825
+ return false;
3826
+ };
3827
+ var fp2 = {
3828
+ // Generic tower bytes use `c0 || c1`, but the BLS12-381 G2 point/signature wire encoding uses
3829
+ // `c1 || c0`, so keep this local wrapper instead of changing generic field serialization.
3830
+ encode({ c0, c1 }) {
3831
+ const { BYTES: L } = Fp;
3832
+ return concatBytes2(numberToBytesBE(c1, L), numberToBytesBE(c0, L));
3833
+ },
3834
+ decode(bytes) {
3835
+ const { BYTES: L } = Fp;
3836
+ return Fp2.create({
3837
+ c0: Fp.create(bytesToNumberBE(bytes.subarray(L))),
3838
+ c1: Fp.create(bytesToNumberBE(bytes.subarray(0, L)))
3839
+ });
3840
+ }
3841
+ };
3842
+ var BaseFp = Fp;
3843
+ var coder = (name, Fp3, b, encode, decode, yparts) => {
3844
+ const F = Fp3;
3845
+ const enc = encode;
3846
+ const dec = decode;
3847
+ const W = F.BYTES;
3848
+ return (allowUncompressed) => ({
3849
+ encode(point, compressed = true) {
3850
+ if (!compressed && !allowUncompressed)
3851
+ throw new Error("invalid signature: expected compressed encoding");
3852
+ const infinity = point.is0();
3853
+ const { x, y } = point.toAffine();
3854
+ const bytes = compressed ? enc(x) : concatBytes2(enc(x), enc(y));
3855
+ let sort;
3856
+ if (compressed && !infinity)
3857
+ sort = sortBit(yparts(y), BaseFp.ORDER);
3858
+ return setMask(bytes, { compressed, infinity, sort });
3859
+ },
3860
+ decode(bytes) {
3861
+ const raw = allowUncompressed ? abytes2(bytes, void 0, "point") : abytes2(bytes, W, "signature");
3862
+ const { compressed, infinity, sort, value } = parseMask(raw);
3863
+ if (!allowUncompressed && !compressed)
3864
+ throw new Error("invalid signature: expected compressed encoding");
3865
+ const len = compressed ? W : 2 * W;
3866
+ if (value.length !== len)
3867
+ throw new Error(`invalid ${name} point: expected ${len} bytes`);
3868
+ if (infinity) {
3869
+ for (const b2 of value) {
3870
+ if (b2)
3871
+ throw new Error(`invalid ${name} point: non-canonical zero`);
3872
+ }
3873
+ return { x: F.ZERO, y: F.ZERO };
3874
+ }
3875
+ const x = dec(compressed ? value : value.subarray(0, W));
3876
+ let y;
3877
+ if (compressed) {
3878
+ y = F.sqrt(F.add(F.pow(x, _3n5), b));
3879
+ if (!y)
3880
+ throw new Error(`invalid ${name} point: compressed`);
3881
+ if (sortBit(yparts(y), BaseFp.ORDER) !== sort)
3882
+ y = F.neg(y);
3883
+ } else {
3884
+ y = dec(value.subarray(W));
3885
+ }
3886
+ if (!compressed && F.is0(x) && F.is0(y))
3887
+ throw new Error(`invalid ${name} point: uncompressed`);
3888
+ return { x, y };
3889
+ }
3890
+ });
3891
+ };
3892
+ function validateMask({ compressed, infinity, sort }) {
3893
+ if (!compressed && !infinity && sort || // 0010_0000 = 0x20
3894
+ !compressed && infinity && sort || // 0110_0000 = 0x60
3895
+ compressed && infinity && sort)
3896
+ throw new Error("invalid encoding flag");
3897
+ }
3898
+ function parseMask(bytes) {
3899
+ bytes = copyBytes(bytes);
3900
+ const mask = bytes[0] & 224;
3901
+ const compressed = !!(mask >> 7 & 1);
3902
+ const infinity = !!(mask >> 6 & 1);
3903
+ const sort = !!(mask >> 5 & 1);
3904
+ validateMask({ compressed, infinity, sort });
3905
+ bytes[0] &= 31;
3906
+ return { compressed, infinity, sort, value: bytes };
3907
+ }
3908
+ function setMask(bytes, mask) {
3909
+ if (bytes[0] & 224)
3910
+ throw new Error("setMask: non-empty mask");
3911
+ validateMask({ compressed: !!mask.compressed, infinity: !!mask.infinity, sort: !!mask.sort });
3912
+ if (mask.compressed)
3913
+ bytes[0] |= 128;
3914
+ if (mask.infinity)
3915
+ bytes[0] |= 64;
3916
+ if (mask.sort)
3917
+ bytes[0] |= 32;
3918
+ return bytes;
3919
+ }
3920
+ var g1coder = coder("G1", Fp, Fp.create(bls12_381_CURVE_G1.b), (x) => numberToBytesBE(x, Fp.BYTES), (bytes) => Fp.create(bytesToNumberBE(bytes) & bitMask(Fp.BITS)), (y) => [y]);
3921
+ var g1 = { point: g1coder(true), sig: g1coder(false) };
3922
+ var signatureG1ToBytes = (point) => {
3923
+ point.assertValidity();
3924
+ return g1.sig.encode(point);
3925
+ };
3926
+ function signatureG1FromBytes(bytes) {
3927
+ const Point = bls12_381.G1.Point;
3928
+ const point = Point.fromAffine(g1.sig.decode(bytes));
3929
+ point.assertValidity();
3930
+ return point;
3931
+ }
3932
+ var g2coder = coder("G2", Fp2, bls12_381_CURVE_G2.b, fp2.encode, fp2.decode, (y) => [
3933
+ y.c1,
3934
+ y.c0
3935
+ ]);
3936
+ var g2 = { point: g2coder(true), sig: g2coder(false) };
3937
+ var signatureG2ToBytes = (point) => {
3938
+ point.assertValidity();
3939
+ return g2.sig.encode(point);
3940
+ };
3941
+ function signatureG2FromBytes(bytes) {
3942
+ const Point = bls12_381.G2.Point;
3943
+ const point = Point.fromAffine(g2.sig.decode(bytes));
3944
+ point.assertValidity();
3945
+ return point;
3946
+ }
3947
+ var signatureCoders = {
3948
+ ShortSignature: {
3949
+ fromBytes(bytes) {
3950
+ return signatureG1FromBytes(abytes2(bytes));
3951
+ },
3952
+ fromHex(hex) {
3953
+ return signatureG1FromBytes(hexToBytes2(hex));
3954
+ },
3955
+ toBytes(point) {
3956
+ return signatureG1ToBytes(point);
3957
+ },
3958
+ // Historical alias: BLS signatures have a single compressed byte format here.
3959
+ toRawBytes(point) {
3960
+ return signatureG1ToBytes(point);
3961
+ },
3962
+ toHex(point) {
3963
+ return bytesToHex2(signatureG1ToBytes(point));
3964
+ }
3965
+ },
3966
+ LongSignature: {
3967
+ fromBytes(bytes) {
3968
+ return signatureG2FromBytes(abytes2(bytes));
3969
+ },
3970
+ fromHex(hex) {
3971
+ return signatureG2FromBytes(hexToBytes2(hex));
3972
+ },
3973
+ toBytes(point) {
3974
+ return signatureG2ToBytes(point);
3975
+ },
3976
+ // Historical alias: BLS signatures have a single compressed byte format here.
3977
+ toRawBytes(point) {
3978
+ return signatureG2ToBytes(point);
3979
+ },
3980
+ toHex(point) {
3981
+ return bytesToHex2(signatureG2ToBytes(point));
3982
+ }
3983
+ }
3984
+ };
3985
+ var fields = {
3986
+ Fp,
3987
+ Fp2,
3988
+ Fp6,
3989
+ Fp12,
3990
+ Fr: bls12_381_Fr
3991
+ };
3992
+ var G1_Point = weierstrass(bls12_381_CURVE_G1, {
3993
+ // Public point APIs still accept infinity, even though the Zcash proof
3994
+ // encoding rules cited above only define nonzero point encodings.
3995
+ allowInfinityPoint: true,
3996
+ Fn: bls12_381_Fr,
3997
+ fromBytes: g1.point.decode,
3998
+ toBytes: (_c, point, isComp) => g1.point.encode(point, isComp),
3999
+ // Checks is the point resides in prime-order subgroup.
4000
+ // point.isTorsionFree() should return true for valid points
4001
+ // It returns false for shitty points.
4002
+ // https://eprint.iacr.org/2021/1130.pdf
4003
+ isTorsionFree: (c, point) => {
4004
+ const beta = BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe");
4005
+ const phi = new c(Fp.mul(point.X, beta), point.Y, point.Z);
4006
+ const xP = point.multiplyUnsafe(BLS_X).negate();
4007
+ const u2P = xP.multiplyUnsafe(BLS_X);
4008
+ return u2P.equals(phi);
4009
+ },
4010
+ // Clear cofactor of G1
4011
+ // https://eprint.iacr.org/2019/403
4012
+ clearCofactor: (_c, point) => {
4013
+ return point.multiplyUnsafe(BLS_X).add(point);
4014
+ }
4015
+ });
4016
+ var G2_Point = weierstrass(bls12_381_CURVE_G2, {
4017
+ Fp: Fp2,
4018
+ // Public point APIs still accept infinity, even though the Zcash proof
4019
+ // encoding rules cited above only define nonzero point encodings.
4020
+ allowInfinityPoint: true,
4021
+ Fn: bls12_381_Fr,
4022
+ fromBytes: g2.point.decode,
4023
+ toBytes: (_c, point, isComp) => g2.point.encode(point, isComp),
4024
+ // https://eprint.iacr.org/2021/1130.pdf
4025
+ // Older version: https://eprint.iacr.org/2019/814.pdf
4026
+ isTorsionFree: (c, P) => {
4027
+ return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P));
4028
+ },
4029
+ // clear_cofactor_bls12381_g2 from RFC 9380.
4030
+ // https://eprint.iacr.org/2017/419.pdf
4031
+ // prettier-ignore
4032
+ clearCofactor: (c, P) => {
4033
+ const x = BLS_X;
4034
+ let t1 = P.multiplyUnsafe(x).negate();
4035
+ let t2 = G2psi(c, P);
4036
+ let t3 = P.double();
4037
+ t3 = G2psi2(c, t3);
4038
+ t3 = t3.subtract(t2);
4039
+ t2 = t1.add(t2);
4040
+ t2 = t2.multiplyUnsafe(x).negate();
4041
+ t3 = t3.add(t2);
4042
+ t3 = t3.subtract(t1);
4043
+ const Q = t3.subtract(P);
4044
+ return Q;
4045
+ }
4046
+ });
4047
+ var bls12_hasher_opts = {
4048
+ mapToG1,
4049
+ mapToG2,
4050
+ hasherOpts: hasher_opts,
4051
+ // RFC 9380 Appendix J defines distinct G1/G2 RO and NU suite IDs, and
4052
+ // draft-irtf-cfrg-bls-signature-06 §4.2.1 gives separate G1/G2 `_NUL_` DSTs.
4053
+ // Keep G1 encode-to-curve on the G1 domain instead of inheriting G2's `encodeDST`.
4054
+ hasherOptsG1: __spreadProps(__spreadValues({}, hasher_opts), {
4055
+ m: 1,
4056
+ DST: "BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_",
4057
+ encodeDST: "BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"
4058
+ }),
4059
+ hasherOptsG2: __spreadValues({}, hasher_opts)
4060
+ };
4061
+ var bls12_params = {
4062
+ ateLoopSize: BLS_X,
4063
+ // The BLS parameter x for BLS12-381
4064
+ xNegative: true,
4065
+ twistType: "multiplicative",
4066
+ randomBytes: randomBytes2
4067
+ };
4068
+ var bls12_381 = bls(fields, G1_Point, G2_Point, bls12_params, bls12_hasher_opts, signatureCoders);
4069
+ var isogenyMapG2 = isogenyMap(Fp2, [
4070
+ // xNum
4071
+ [
4072
+ [
4073
+ "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6",
4074
+ "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"
4075
+ ],
4076
+ [
4077
+ "0x0",
4078
+ "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"
4079
+ ],
4080
+ [
4081
+ "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e",
4082
+ "0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"
4083
+ ],
4084
+ [
4085
+ "0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1",
4086
+ "0x0"
4087
+ ]
4088
+ ],
4089
+ // xDen
4090
+ [
4091
+ [
4092
+ "0x0",
4093
+ "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"
4094
+ ],
4095
+ [
4096
+ "0xc",
4097
+ "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"
4098
+ ],
4099
+ ["0x1", "0x0"]
4100
+ // LAST 1
4101
+ ],
4102
+ // yNum
4103
+ [
4104
+ [
4105
+ "0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706",
4106
+ "0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"
4107
+ ],
4108
+ [
4109
+ "0x0",
4110
+ "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"
4111
+ ],
4112
+ [
4113
+ "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c",
4114
+ "0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"
4115
+ ],
4116
+ [
4117
+ "0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10",
4118
+ "0x0"
4119
+ ]
4120
+ ],
4121
+ // yDen
4122
+ [
4123
+ [
4124
+ "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb",
4125
+ "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"
4126
+ ],
4127
+ [
4128
+ "0x0",
4129
+ "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"
4130
+ ],
4131
+ [
4132
+ "0x12",
4133
+ "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"
4134
+ ],
4135
+ ["0x1", "0x0"]
4136
+ // LAST 1
4137
+ ]
4138
+ ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt)))));
4139
+ var isogenyMapG1 = isogenyMap(Fp, [
4140
+ // xNum
4141
+ [
4142
+ "0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7",
4143
+ "0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb",
4144
+ "0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0",
4145
+ "0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861",
4146
+ "0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9",
4147
+ "0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983",
4148
+ "0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84",
4149
+ "0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e",
4150
+ "0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317",
4151
+ "0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e",
4152
+ "0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b",
4153
+ "0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"
4154
+ ],
4155
+ // xDen
4156
+ [
4157
+ "0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c",
4158
+ "0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff",
4159
+ "0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19",
4160
+ "0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8",
4161
+ "0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e",
4162
+ "0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5",
4163
+ "0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a",
4164
+ "0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e",
4165
+ "0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641",
4166
+ "0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a",
4167
+ "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"
4168
+ // LAST 1
4169
+ ],
4170
+ // yNum
4171
+ [
4172
+ "0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33",
4173
+ "0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696",
4174
+ "0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6",
4175
+ "0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb",
4176
+ "0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb",
4177
+ "0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0",
4178
+ "0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2",
4179
+ "0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29",
4180
+ "0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587",
4181
+ "0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30",
4182
+ "0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132",
4183
+ "0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e",
4184
+ "0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8",
4185
+ "0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133",
4186
+ "0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b",
4187
+ "0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"
4188
+ ],
4189
+ // yDen
4190
+ [
4191
+ "0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1",
4192
+ "0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d",
4193
+ "0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2",
4194
+ "0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416",
4195
+ "0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d",
4196
+ "0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac",
4197
+ "0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c",
4198
+ "0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9",
4199
+ "0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a",
4200
+ "0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55",
4201
+ "0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8",
4202
+ "0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092",
4203
+ "0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc",
4204
+ "0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7",
4205
+ "0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f",
4206
+ "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"
4207
+ // LAST 1
4208
+ ]
4209
+ ].map((i) => i.map((j) => BigInt(j))));
4210
+ var G1_SWU;
4211
+ var G2_SWU;
4212
+ var getG1_SWU = () => G1_SWU || (G1_SWU = mapToCurveSimpleSWU(Fp, {
4213
+ A: Fp.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),
4214
+ B: Fp.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),
4215
+ Z: Fp.create(BigInt(11))
4216
+ }));
4217
+ var getG2_SWU = () => G2_SWU || (G2_SWU = mapToCurveSimpleSWU(Fp2, {
4218
+ // SWU map for the RFC 9380 §8.8.2 pre-isogeny G2 curve E':
4219
+ // y² = x³ + 240i * x + 1012 + 1012i
4220
+ A: Fp2.create({ c0: Fp.create(_0n7), c1: Fp.create(BigInt(240)) }),
4221
+ // A' = 240 * I
4222
+ B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }),
4223
+ // B' = 1012 * (1 + I)
4224
+ Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) })
4225
+ // Z: -(2 + I)
4226
+ }));
4227
+ function mapToG1(scalars) {
4228
+ const { x, y } = getG1_SWU()(Fp.create(scalars[0]));
4229
+ return isogenyMapG1(x, y);
4230
+ }
4231
+ function mapToG2(scalars) {
4232
+ const { x, y } = getG2_SWU()(Fp2.fromBigTuple(scalars));
4233
+ return isogenyMapG2(x, y);
4234
+ }
4235
+
4236
+ // src/blsUtils.ts
4237
+ var { longSignatures: ls } = bls12_381;
4238
+ var ETH2_DST = "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_";
4239
+ function blsVerify(pubkey, message, signature) {
4240
+ try {
4241
+ return ls.verify(signature, ls.hash(message, ETH2_DST), pubkey);
4242
+ } catch (e) {
4243
+ return false;
4244
+ }
4245
+ }
4246
+ function blsAggregatePublicKeys(pubkeys) {
4247
+ if (pubkeys.length === 0) {
4248
+ throw new Error("cannot aggregate empty pubkey set");
4249
+ }
4250
+ return ls.aggregatePublicKeys(pubkeys).toBytes();
4251
+ }
4252
+ function blsVerifyAggregate(pubkeys, message, signature) {
4253
+ try {
4254
+ return ls.verify(
4255
+ signature,
4256
+ ls.hash(message, ETH2_DST),
4257
+ ls.aggregatePublicKeys(pubkeys)
4258
+ );
4259
+ } catch (e) {
4260
+ return false;
4261
+ }
4262
+ }
4263
+ function blsVerifyWithAggregatedPubkey(aggregatedPubkey, message, signature) {
4264
+ try {
4265
+ return ls.verify(signature, ls.hash(message, ETH2_DST), aggregatedPubkey);
4266
+ } catch (e) {
4267
+ return false;
4268
+ }
4269
+ }
4270
+ function blsVerifyMultiple(pubkeys, messages, signature) {
4271
+ try {
4272
+ if (pubkeys.length !== messages.length) return false;
4273
+ const items = messages.map((msg, i) => ({
4274
+ message: ls.hash(msg, ETH2_DST),
4275
+ publicKey: pubkeys[i]
4276
+ }));
4277
+ return ls.verifyBatch(signature, items);
4278
+ } catch (e) {
4279
+ return false;
4280
+ }
4281
+ }
4282
+ function blsAggregateSignatures(signatures) {
4283
+ return ls.Signature.toBytes(ls.aggregateSignatures(signatures));
4284
+ }
4285
+ function lagrangeCoeffAtZero(shareIndex, indices) {
4286
+ const { Fr } = bls12_381.fields;
4287
+ let num = BigInt(1);
4288
+ let den = BigInt(1);
4289
+ for (const j of indices) {
4290
+ if (j === shareIndex) continue;
4291
+ num = Fr.mul(num, Fr.neg(j));
4292
+ den = Fr.mul(den, Fr.sub(shareIndex, j));
4293
+ }
4294
+ return Fr.mul(num, Fr.inv(den));
4295
+ }
4296
+ function blsRecoverWithIndices(shares, indices) {
4297
+ try {
4298
+ let recovered = bls12_381.G1.Point.ZERO;
4299
+ for (let i = 0; i < shares.length; i++) {
4300
+ const point = bls12_381.G1.Point.fromBytes(shares[i]);
4301
+ const coeff = lagrangeCoeffAtZero(indices[i], indices);
4302
+ recovered = recovered.add(point.multiply(coeff));
4303
+ }
4304
+ return recovered.toBytes();
4305
+ } catch (e) {
4306
+ return null;
4307
+ }
4308
+ }
4309
+ function blsRecoverDistributedPubkeyFromShares(pubshares, threshold) {
4310
+ if (threshold <= 0 || pubshares.length < threshold) return null;
4311
+ const selected = pubshares.slice(0, threshold);
4312
+ const indices = selected.map((_, i) => BigInt(i + 1));
4313
+ return blsRecoverWithIndices(selected, indices);
4314
+ }
4315
+ function blsVerifyExtraShares(pubshares, threshold, distributedPubkey) {
4316
+ if (threshold <= 0 || pubshares.length < threshold) return false;
4317
+ try {
4318
+ const baseShares = pubshares.slice(0, threshold - 1);
4319
+ const baseIndices = baseShares.map((_, i) => BigInt(i + 1));
4320
+ for (let i = threshold; i < pubshares.length; i++) {
4321
+ const shares = [...baseShares, pubshares[i]];
4322
+ const indices = [...baseIndices, BigInt(i + 1)];
4323
+ const recovered = blsRecoverWithIndices(shares, indices);
4324
+ if (!recovered || recovered.length !== distributedPubkey.length || !recovered.every((b, j) => b === distributedPubkey[j])) {
4325
+ return false;
4326
+ }
4327
+ }
4328
+ return true;
4329
+ } catch (e) {
4330
+ return false;
4331
+ }
4332
+ }
4333
+
4334
+ export {
4335
+ __spreadValues,
4336
+ __spreadProps,
4337
+ __require,
4338
+ __export,
4339
+ __publicField,
4340
+ __privateGet,
4341
+ __privateAdd,
4342
+ __privateSet,
4343
+ __async,
4344
+ __yieldStar,
4345
+ sha256,
4346
+ pow2,
4347
+ Field,
4348
+ weierstrass,
4349
+ ecdsa,
4350
+ blsVerify,
4351
+ blsAggregatePublicKeys,
4352
+ blsVerifyAggregate,
4353
+ blsVerifyWithAggregatedPubkey,
4354
+ blsVerifyMultiple,
4355
+ blsAggregateSignatures,
4356
+ blsRecoverDistributedPubkeyFromShares,
4357
+ blsVerifyExtraShares
4358
+ };
4359
+ /*! Bundled license information:
4360
+
4361
+ @noble/curves/utils.js:
4362
+ @noble/curves/abstract/modular.js:
4363
+ @noble/curves/abstract/curve.js:
4364
+ @noble/curves/abstract/weierstrass.js:
4365
+ @noble/curves/abstract/bls.js:
4366
+ @noble/curves/abstract/tower.js:
4367
+ @noble/curves/bls12-381.js:
4368
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4369
+ */
4370
+ //# sourceMappingURL=chunk-LOSYOJC3.js.map