@aastar/sdk 0.20.8 → 0.20.9

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