@decentnetwork/beagle-ui 0.2.32 → 0.2.34

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.
@@ -0,0 +1,3903 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+
8
+ // src/wallet-proof.js
9
+ var WALLET_PROOF_VERSION = 1;
10
+ var WALLET_CHAINS = ["eth", "sol"];
11
+ var COIN_TYPE = { eth: "60", sol: "501" };
12
+ var PROOF_KEY = { eth: "proof.eth", sol: "proof.sol" };
13
+ var HEAD = "Beagle wallet binding";
14
+ var LINE = "I bind this wallet to my Beagle identity.";
15
+ var ADDRESS_RE = { eth: /^0x[0-9a-fA-F]{40}$/, sol: /^[1-9A-HJ-NP-Za-km-z]{32,44}$/ };
16
+ var USERID_RE = /^[1-9A-HJ-NP-Za-km-z]{32,48}$/;
17
+ var ISSUED_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
18
+ function isWalletAddress(chain, address) {
19
+ const re = ADDRESS_RE[chain];
20
+ return !!re && typeof address === "string" && re.test(address);
21
+ }
22
+ function proofTime(date = /* @__PURE__ */ new Date()) {
23
+ return new Date(Math.floor(date.getTime() / 1e3) * 1e3).toISOString().replace(".000Z", "Z");
24
+ }
25
+ function walletProofMessage({ userid, chain, address, issued }) {
26
+ if (!USERID_RE.test(String(userid || "")))
27
+ throw new Error("wallet proof: bad userid");
28
+ if (!isWalletAddress(chain, address))
29
+ throw new Error("wallet proof: bad chain or address");
30
+ if (!ISSUED_RE.test(String(issued || "")))
31
+ throw new Error("wallet proof: bad issued time");
32
+ return [HEAD, "", LINE, "", `userid: ${userid}`, `chain: ${chain}`, `address: ${address}`, `issued: ${issued}`].join("\n");
33
+ }
34
+ function parseWalletProofMessage(msg) {
35
+ if (typeof msg !== "string")
36
+ return null;
37
+ const f = {};
38
+ for (const line of msg.split("\n")) {
39
+ const m = /^(userid|chain|address|issued): (.+)$/.exec(line);
40
+ if (m)
41
+ f[m[1]] = m[2];
42
+ }
43
+ try {
44
+ return walletProofMessage(f) === msg ? { userid: f.userid, chain: f.chain, address: f.address, issued: f.issued } : null;
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ function encodeWalletProof({ message, signature }) {
50
+ return JSON.stringify({ v: WALLET_PROOF_VERSION, msg: message, sig: signature });
51
+ }
52
+ function decodeWalletProof(text) {
53
+ try {
54
+ const p = typeof text === "string" ? JSON.parse(text) : text;
55
+ if (!p || p.v !== WALLET_PROOF_VERSION || typeof p.msg !== "string" || typeof p.sig !== "string")
56
+ return null;
57
+ return { message: p.msg, signature: p.sig };
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+ var B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
63
+ function base58Encode(bytes) {
64
+ const digits = [];
65
+ for (const b of bytes) {
66
+ let carry = b;
67
+ for (let j = 0; j < digits.length; j++) {
68
+ carry += digits[j] << 8;
69
+ digits[j] = carry % 58;
70
+ carry = carry / 58 | 0;
71
+ }
72
+ while (carry > 0) {
73
+ digits.push(carry % 58);
74
+ carry = carry / 58 | 0;
75
+ }
76
+ }
77
+ let out = "";
78
+ for (const b of bytes) {
79
+ if (b !== 0)
80
+ break;
81
+ out += "1";
82
+ }
83
+ for (let i = digits.length - 1; i >= 0; i--)
84
+ out += B58[digits[i]];
85
+ return out;
86
+ }
87
+ function base58Decode(str) {
88
+ const bytes = [];
89
+ for (const c of String(str)) {
90
+ let carry = B58.indexOf(c);
91
+ if (carry < 0)
92
+ throw new Error("not base58");
93
+ for (let j = 0; j < bytes.length; j++) {
94
+ carry += bytes[j] * 58;
95
+ bytes[j] = carry & 255;
96
+ carry >>= 8;
97
+ }
98
+ while (carry > 0) {
99
+ bytes.push(carry & 255);
100
+ carry >>= 8;
101
+ }
102
+ }
103
+ for (const c of String(str)) {
104
+ if (c !== "1")
105
+ break;
106
+ bytes.push(0);
107
+ }
108
+ return Uint8Array.from(bytes.reverse());
109
+ }
110
+ var utf8Hex = (s) => "0x" + Array.from(new TextEncoder().encode(s), (b) => b.toString(16).padStart(2, "0")).join("");
111
+ async function signEthProof(provider, { userid, address, issued = proofTime() }) {
112
+ const message = walletProofMessage({ userid, chain: "eth", address, issued });
113
+ const signature = await provider.request({ method: "personal_sign", params: [utf8Hex(message), address] });
114
+ return { message, signature: String(signature) };
115
+ }
116
+ async function signSolProof(wallet, { userid, address, issued = proofTime() }) {
117
+ const message = walletProofMessage({ userid, chain: "sol", address, issued });
118
+ const r = await wallet.signMessage(new TextEncoder().encode(message), "utf8");
119
+ const sig = r && r.signature ? r.signature : r;
120
+ return { message, signature: base58Encode(Uint8Array.from(sig)) };
121
+ }
122
+
123
+ // ../../node_modules/@noble/hashes/_u64.js
124
+ var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
125
+ var _32n = /* @__PURE__ */ BigInt(32);
126
+ function fromBig(n, le = false) {
127
+ if (le)
128
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
129
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
130
+ }
131
+ function split(lst, le = false) {
132
+ const len = lst.length;
133
+ let Ah = new Uint32Array(len);
134
+ let Al = new Uint32Array(len);
135
+ for (let i = 0; i < len; i++) {
136
+ const { h, l } = fromBig(lst[i], le);
137
+ [Ah[i], Al[i]] = [h, l];
138
+ }
139
+ return [Ah, Al];
140
+ }
141
+ var fromNumH = (n) => n / 2 ** 32 | 0;
142
+ var fromNumL = (n) => n >>> 0;
143
+ function setU64FromNum(view, byteOffset, n, isLE2) {
144
+ const h = fromNumH(n);
145
+ const l = fromNumL(n);
146
+ view.setUint32(byteOffset, isLE2 ? l : h, isLE2);
147
+ view.setUint32(byteOffset + 4, isLE2 ? h : l, isLE2);
148
+ }
149
+ var shrSH = (h, _l, s) => h >>> s;
150
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
151
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
152
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
153
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
154
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
155
+ function add(Ah, Al, Bh, Bl) {
156
+ const l = (Al >>> 0) + (Bl >>> 0);
157
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
158
+ }
159
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
160
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
161
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
162
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
163
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
164
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
165
+
166
+ // ../../node_modules/@noble/hashes/utils.js
167
+ function isBytes(a) {
168
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
169
+ }
170
+ var atitle = (title) => title ? `"${title}" ` : "";
171
+ function anumber(n, title = "") {
172
+ if (typeof n !== "number")
173
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
174
+ if (!Number.isSafeInteger(n) || n < 0)
175
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
176
+ return n;
177
+ }
178
+ function abool(value, title = "") {
179
+ if (typeof value !== "boolean")
180
+ throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
181
+ return value;
182
+ }
183
+ function abytes(value, length, title = "") {
184
+ if (isBytes(value) && (length === void 0 || value.length === length))
185
+ return value;
186
+ if (length !== void 0)
187
+ anumber(length, "length");
188
+ const bytes = isBytes(value);
189
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
190
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
191
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
192
+ if (!bytes)
193
+ throw new TypeError(message);
194
+ throw new RangeError(message);
195
+ }
196
+ function ahash(h) {
197
+ if (typeof h !== "function" || typeof h.create !== "function")
198
+ throw new TypeError("expected hash wrapped by utils.createHasher");
199
+ anumber(h.outputLen);
200
+ anumber(h.blockLen);
201
+ if (h.outputLen < 1 || h.blockLen < 1)
202
+ throw new Error("hash blockLen / outputLen must be >= 1");
203
+ }
204
+ var aobject = (value, label) => {
205
+ if (value === null || typeof value !== "object" || Array.isArray(value))
206
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
207
+ };
208
+ var aopts = (value, label) => {
209
+ aobject(value, label);
210
+ const proto = Object.getPrototypeOf(value);
211
+ if (proto !== Object.prototype && proto !== null)
212
+ throw new TypeError(`"${label}" expected plain object`);
213
+ if (Object.hasOwn(value, "__proto__"))
214
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
215
+ };
216
+ function aexists(instance, checkFinished = true) {
217
+ if (instance.destroyed)
218
+ throw new Error("hash was destroyed");
219
+ if (checkFinished && instance.finished)
220
+ throw new Error("digest() was already called");
221
+ }
222
+ function aoutput(out, instance) {
223
+ abytes(out, void 0, "output");
224
+ const min = instance.outputLen;
225
+ if (!(out.length >= min)) {
226
+ throw new RangeError('"output" expected length >= ' + min);
227
+ }
228
+ }
229
+ function u32(arr) {
230
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
231
+ }
232
+ function clean(...arrays) {
233
+ for (let i = 0; i < arrays.length; i++) {
234
+ arrays[i].fill(0);
235
+ }
236
+ }
237
+ function createView(arr) {
238
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
239
+ }
240
+ function rotr(word, shift) {
241
+ return word << 32 - shift | word >>> shift;
242
+ }
243
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
244
+ function byteSwap(word) {
245
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
246
+ }
247
+ function byteSwap32(arr) {
248
+ for (let i = 0; i < arr.length; i++) {
249
+ arr[i] = byteSwap(arr[i]);
250
+ }
251
+ return arr;
252
+ }
253
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
254
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
255
+ // @ts-ignore
256
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
257
+ ))();
258
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
259
+ function bytesToHex(bytes) {
260
+ abytes(bytes);
261
+ if (hasHexBuiltin)
262
+ return bytes.toHex();
263
+ let hex = "";
264
+ for (let i = 0; i < bytes.length; i++) {
265
+ hex += hexes[bytes[i]];
266
+ }
267
+ return hex;
268
+ }
269
+ function asciiToBase16(ch) {
270
+ return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
271
+ }
272
+ function hexToBytes(hex) {
273
+ if (typeof hex !== "string")
274
+ throw new TypeError("hex string expected, got " + typeof hex);
275
+ if (hasHexBuiltin) {
276
+ try {
277
+ return Uint8Array.fromHex(hex);
278
+ } catch (error) {
279
+ if (error instanceof SyntaxError)
280
+ throw new RangeError(error.message);
281
+ throw error;
282
+ }
283
+ }
284
+ const hl = hex.length;
285
+ const al = hl / 2;
286
+ if (hl % 2)
287
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
288
+ const array = new Uint8Array(al);
289
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
290
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
291
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
292
+ if (n1 === void 0 || n2 === void 0) {
293
+ const char = hex[hi] + hex[hi + 1];
294
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
295
+ }
296
+ array[ai] = n1 * 16 + n2;
297
+ }
298
+ return array;
299
+ }
300
+ function concatBytes(...arrays) {
301
+ let sum = 0;
302
+ for (let i = 0; i < arrays.length; i++) {
303
+ const a = arrays[i];
304
+ abytes(a);
305
+ sum += a.length;
306
+ }
307
+ const res = new Uint8Array(sum);
308
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
309
+ const a = arrays[i];
310
+ res.set(a, pad);
311
+ pad += a.length;
312
+ }
313
+ return res;
314
+ }
315
+ function checkOpts(defaults, opts, title = "opts") {
316
+ aopts(defaults, "defaults");
317
+ if (opts !== void 0)
318
+ aopts(opts, title);
319
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
320
+ return merged;
321
+ }
322
+ function createHasher(hashCons, info = {}) {
323
+ if (typeof hashCons !== "function")
324
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
325
+ info = checkOpts({}, info, "info");
326
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
327
+ const tmp = hashCons(void 0);
328
+ hashC.outputLen = tmp.outputLen;
329
+ hashC.blockLen = tmp.blockLen;
330
+ hashC.canXOF = tmp.canXOF;
331
+ hashC.create = (opts) => hashCons(opts);
332
+ Object.assign(hashC, info);
333
+ return Object.freeze(hashC);
334
+ }
335
+ function randomBytes(bytesLength = 32) {
336
+ anumber(bytesLength, "bytesLength");
337
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
338
+ if (typeof cr?.getRandomValues !== "function")
339
+ throw new Error("crypto.getRandomValues must be defined");
340
+ if (bytesLength > 65536)
341
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
342
+ return cr.getRandomValues(new Uint8Array(bytesLength));
343
+ }
344
+ var oidNist = (suffix) => ({
345
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
346
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
347
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
348
+ });
349
+
350
+ // ../../node_modules/@noble/hashes/_md.js
351
+ function Chi(a, b, c) {
352
+ return a & b ^ ~a & c;
353
+ }
354
+ function Maj(a, b, c) {
355
+ return a & b ^ a & c ^ b & c;
356
+ }
357
+ var HashMD = class {
358
+ constructor(blockLen, outputLen, padOffset, isLE2) {
359
+ __publicField(this, "blockLen");
360
+ __publicField(this, "outputLen");
361
+ __publicField(this, "canXOF", false);
362
+ __publicField(this, "padOffset");
363
+ __publicField(this, "isLE");
364
+ // For partial updates less than block size
365
+ __publicField(this, "buffer");
366
+ __publicField(this, "view");
367
+ __publicField(this, "finished", false);
368
+ __publicField(this, "length", 0);
369
+ __publicField(this, "pos", 0);
370
+ __publicField(this, "destroyed", false);
371
+ this.blockLen = blockLen;
372
+ this.outputLen = outputLen;
373
+ this.padOffset = padOffset;
374
+ this.isLE = isLE2;
375
+ this.buffer = new Uint8Array(blockLen);
376
+ this.view = createView(this.buffer);
377
+ }
378
+ update(data) {
379
+ aexists(this);
380
+ abytes(data);
381
+ const { view, buffer, blockLen } = this;
382
+ const len = data.length;
383
+ let processed = false;
384
+ for (let pos = 0; pos < len; ) {
385
+ const take = Math.min(blockLen - this.pos, len - pos);
386
+ if (take === blockLen) {
387
+ const dataView = createView(data);
388
+ for (; blockLen <= len - pos; pos += blockLen)
389
+ this.process(dataView, pos);
390
+ processed = true;
391
+ continue;
392
+ }
393
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
394
+ this.pos += take;
395
+ pos += take;
396
+ if (this.pos === blockLen) {
397
+ this.process(view, 0);
398
+ this.pos = 0;
399
+ processed = true;
400
+ }
401
+ }
402
+ this.length += data.length;
403
+ if (processed)
404
+ this.roundClean();
405
+ return this;
406
+ }
407
+ digestInto(out) {
408
+ aexists(this);
409
+ aoutput(out, this);
410
+ this.finished = true;
411
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
412
+ let { pos } = this;
413
+ buffer[pos++] = 128;
414
+ buffer.fill(0, pos);
415
+ if (this.padOffset > blockLen - pos) {
416
+ this.process(view, 0);
417
+ buffer.fill(0);
418
+ }
419
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE2);
420
+ this.process(view, 0);
421
+ this.roundClean();
422
+ const oview = out === buffer ? view : createView(out);
423
+ const len = this.outputLen;
424
+ const outLen = len / 4;
425
+ const state = this.get();
426
+ if (len % 4 || outLen > state.length)
427
+ throw new Error("invalid outputLen");
428
+ for (let i = 0; i < outLen; i++)
429
+ oview.setUint32(4 * i, state[i], isLE2);
430
+ }
431
+ digest() {
432
+ const { buffer, outputLen } = this;
433
+ this.digestInto(buffer);
434
+ const res = buffer.slice(0, outputLen);
435
+ this.destroy();
436
+ return res;
437
+ }
438
+ _cloneIntoMeta(to) {
439
+ const { buffer, length, finished, destroyed, pos } = this;
440
+ to.destroyed = destroyed;
441
+ to.finished = finished;
442
+ to.length = length;
443
+ to.pos = pos;
444
+ if (pos)
445
+ to.buffer.set(buffer);
446
+ return to;
447
+ }
448
+ clone() {
449
+ return this._cloneInto();
450
+ }
451
+ };
452
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
453
+ 1779033703,
454
+ 3144134277,
455
+ 1013904242,
456
+ 2773480762,
457
+ 1359893119,
458
+ 2600822924,
459
+ 528734635,
460
+ 1541459225
461
+ ]);
462
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
463
+ 1779033703,
464
+ 4089235720,
465
+ 3144134277,
466
+ 2227873595,
467
+ 1013904242,
468
+ 4271175723,
469
+ 2773480762,
470
+ 1595750129,
471
+ 1359893119,
472
+ 2917565137,
473
+ 2600822924,
474
+ 725511199,
475
+ 528734635,
476
+ 4215389547,
477
+ 1541459225,
478
+ 327033209
479
+ ]);
480
+
481
+ // ../../node_modules/@noble/hashes/sha2.js
482
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
483
+ 1116352408,
484
+ 1899447441,
485
+ 3049323471,
486
+ 3921009573,
487
+ 961987163,
488
+ 1508970993,
489
+ 2453635748,
490
+ 2870763221,
491
+ 3624381080,
492
+ 310598401,
493
+ 607225278,
494
+ 1426881987,
495
+ 1925078388,
496
+ 2162078206,
497
+ 2614888103,
498
+ 3248222580,
499
+ 3835390401,
500
+ 4022224774,
501
+ 264347078,
502
+ 604807628,
503
+ 770255983,
504
+ 1249150122,
505
+ 1555081692,
506
+ 1996064986,
507
+ 2554220882,
508
+ 2821834349,
509
+ 2952996808,
510
+ 3210313671,
511
+ 3336571891,
512
+ 3584528711,
513
+ 113926993,
514
+ 338241895,
515
+ 666307205,
516
+ 773529912,
517
+ 1294757372,
518
+ 1396182291,
519
+ 1695183700,
520
+ 1986661051,
521
+ 2177026350,
522
+ 2456956037,
523
+ 2730485921,
524
+ 2820302411,
525
+ 3259730800,
526
+ 3345764771,
527
+ 3516065817,
528
+ 3600352804,
529
+ 4094571909,
530
+ 275423344,
531
+ 430227734,
532
+ 506948616,
533
+ 659060556,
534
+ 883997877,
535
+ 958139571,
536
+ 1322822218,
537
+ 1537002063,
538
+ 1747873779,
539
+ 1955562222,
540
+ 2024104815,
541
+ 2227730452,
542
+ 2361852424,
543
+ 2428436474,
544
+ 2756734187,
545
+ 3204031479,
546
+ 3329325298
547
+ ]);
548
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
549
+ var SHA2_32B = class extends HashMD {
550
+ constructor(outputLen, IV) {
551
+ super(64, outputLen, 8, false);
552
+ // We cannot use array here since array allows indexing by variable
553
+ // which means optimizer/compiler cannot use registers.
554
+ // Numeric initializers matter: starting the fields as `undefined` changes
555
+ // V8's field representation and makes sha256 3x slower (measured).
556
+ __publicField(this, "A", 0);
557
+ __publicField(this, "B", 0);
558
+ __publicField(this, "C", 0);
559
+ __publicField(this, "D", 0);
560
+ __publicField(this, "E", 0);
561
+ __publicField(this, "F", 0);
562
+ __publicField(this, "G", 0);
563
+ __publicField(this, "H", 0);
564
+ this.A = IV[0] | 0;
565
+ this.B = IV[1] | 0;
566
+ this.C = IV[2] | 0;
567
+ this.D = IV[3] | 0;
568
+ this.E = IV[4] | 0;
569
+ this.F = IV[5] | 0;
570
+ this.G = IV[6] | 0;
571
+ this.H = IV[7] | 0;
572
+ }
573
+ get() {
574
+ const { A, B: B2, C, D, E, F, G, H } = this;
575
+ return [A, B2, C, D, E, F, G, H];
576
+ }
577
+ // prettier-ignore
578
+ set(A, B2, C, D, E, F, G, H) {
579
+ this.A = A | 0;
580
+ this.B = B2 | 0;
581
+ this.C = C | 0;
582
+ this.D = D | 0;
583
+ this.E = E | 0;
584
+ this.F = F | 0;
585
+ this.G = G | 0;
586
+ this.H = H | 0;
587
+ }
588
+ _cloneInto(to) {
589
+ (to || (to = new this.constructor())).set(...this.get());
590
+ return this._cloneIntoMeta(to);
591
+ }
592
+ process(view, offset) {
593
+ for (let i = 0; i < 16; i++, offset += 4)
594
+ SHA256_W[i] = view.getUint32(offset, false);
595
+ for (let i = 16; i < 64; i++) {
596
+ const W15 = SHA256_W[i - 15];
597
+ const W2 = SHA256_W[i - 2];
598
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
599
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
600
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
601
+ }
602
+ let { A, B: B2, C, D, E, F, G, H } = this;
603
+ for (let i = 0; i < 64; i++) {
604
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
605
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
606
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
607
+ const T2 = sigma0 + Maj(A, B2, C) | 0;
608
+ H = G;
609
+ G = F;
610
+ F = E;
611
+ E = D + T1 | 0;
612
+ D = C;
613
+ C = B2;
614
+ B2 = A;
615
+ A = T1 + T2 | 0;
616
+ }
617
+ A = A + this.A | 0;
618
+ B2 = B2 + this.B | 0;
619
+ C = C + this.C | 0;
620
+ D = D + this.D | 0;
621
+ E = E + this.E | 0;
622
+ F = F + this.F | 0;
623
+ G = G + this.G | 0;
624
+ H = H + this.H | 0;
625
+ this.set(A, B2, C, D, E, F, G, H);
626
+ }
627
+ roundClean() {
628
+ clean(SHA256_W);
629
+ }
630
+ destroy() {
631
+ this.destroyed = true;
632
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
633
+ clean(this.buffer);
634
+ }
635
+ };
636
+ var _SHA256 = class extends SHA2_32B {
637
+ constructor() {
638
+ super(32, SHA256_IV);
639
+ }
640
+ };
641
+ var K512 = /* @__PURE__ */ (() => split([
642
+ "0x428a2f98d728ae22",
643
+ "0x7137449123ef65cd",
644
+ "0xb5c0fbcfec4d3b2f",
645
+ "0xe9b5dba58189dbbc",
646
+ "0x3956c25bf348b538",
647
+ "0x59f111f1b605d019",
648
+ "0x923f82a4af194f9b",
649
+ "0xab1c5ed5da6d8118",
650
+ "0xd807aa98a3030242",
651
+ "0x12835b0145706fbe",
652
+ "0x243185be4ee4b28c",
653
+ "0x550c7dc3d5ffb4e2",
654
+ "0x72be5d74f27b896f",
655
+ "0x80deb1fe3b1696b1",
656
+ "0x9bdc06a725c71235",
657
+ "0xc19bf174cf692694",
658
+ "0xe49b69c19ef14ad2",
659
+ "0xefbe4786384f25e3",
660
+ "0x0fc19dc68b8cd5b5",
661
+ "0x240ca1cc77ac9c65",
662
+ "0x2de92c6f592b0275",
663
+ "0x4a7484aa6ea6e483",
664
+ "0x5cb0a9dcbd41fbd4",
665
+ "0x76f988da831153b5",
666
+ "0x983e5152ee66dfab",
667
+ "0xa831c66d2db43210",
668
+ "0xb00327c898fb213f",
669
+ "0xbf597fc7beef0ee4",
670
+ "0xc6e00bf33da88fc2",
671
+ "0xd5a79147930aa725",
672
+ "0x06ca6351e003826f",
673
+ "0x142929670a0e6e70",
674
+ "0x27b70a8546d22ffc",
675
+ "0x2e1b21385c26c926",
676
+ "0x4d2c6dfc5ac42aed",
677
+ "0x53380d139d95b3df",
678
+ "0x650a73548baf63de",
679
+ "0x766a0abb3c77b2a8",
680
+ "0x81c2c92e47edaee6",
681
+ "0x92722c851482353b",
682
+ "0xa2bfe8a14cf10364",
683
+ "0xa81a664bbc423001",
684
+ "0xc24b8b70d0f89791",
685
+ "0xc76c51a30654be30",
686
+ "0xd192e819d6ef5218",
687
+ "0xd69906245565a910",
688
+ "0xf40e35855771202a",
689
+ "0x106aa07032bbd1b8",
690
+ "0x19a4c116b8d2d0c8",
691
+ "0x1e376c085141ab53",
692
+ "0x2748774cdf8eeb99",
693
+ "0x34b0bcb5e19b48a8",
694
+ "0x391c0cb3c5c95a63",
695
+ "0x4ed8aa4ae3418acb",
696
+ "0x5b9cca4f7763e373",
697
+ "0x682e6ff3d6b2b8a3",
698
+ "0x748f82ee5defb2fc",
699
+ "0x78a5636f43172f60",
700
+ "0x84c87814a1f0ab72",
701
+ "0x8cc702081a6439ec",
702
+ "0x90befffa23631e28",
703
+ "0xa4506cebde82bde9",
704
+ "0xbef9a3f7b2c67915",
705
+ "0xc67178f2e372532b",
706
+ "0xca273eceea26619c",
707
+ "0xd186b8c721c0c207",
708
+ "0xeada7dd6cde0eb1e",
709
+ "0xf57d4f7fee6ed178",
710
+ "0x06f067aa72176fba",
711
+ "0x0a637dc5a2c898a6",
712
+ "0x113f9804bef90dae",
713
+ "0x1b710b35131c471b",
714
+ "0x28db77f523047d84",
715
+ "0x32caab7b40c72493",
716
+ "0x3c9ebe0a15c9bebc",
717
+ "0x431d67c49c100d4c",
718
+ "0x4cc5d4becb3e42b6",
719
+ "0x597f299cfc657e2a",
720
+ "0x5fcb6fab3ad6faec",
721
+ "0x6c44198c4a475817"
722
+ ].map((n) => BigInt(n))))();
723
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
724
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
725
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
726
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
727
+ var SHA2_64B = class extends HashMD {
728
+ constructor(outputLen, IV) {
729
+ super(128, outputLen, 16, false);
730
+ // We cannot use array here since array allows indexing by variable
731
+ // which means optimizer/compiler cannot use registers.
732
+ // h -- high 32 bits, l -- low 32 bits
733
+ // Numeric initializers matter: starting the fields as `undefined` changes
734
+ // V8's field representation and slows hashing down (measured on sha256).
735
+ __publicField(this, "Ah", 0);
736
+ __publicField(this, "Al", 0);
737
+ __publicField(this, "Bh", 0);
738
+ __publicField(this, "Bl", 0);
739
+ __publicField(this, "Ch", 0);
740
+ __publicField(this, "Cl", 0);
741
+ __publicField(this, "Dh", 0);
742
+ __publicField(this, "Dl", 0);
743
+ __publicField(this, "Eh", 0);
744
+ __publicField(this, "El", 0);
745
+ __publicField(this, "Fh", 0);
746
+ __publicField(this, "Fl", 0);
747
+ __publicField(this, "Gh", 0);
748
+ __publicField(this, "Gl", 0);
749
+ __publicField(this, "Hh", 0);
750
+ __publicField(this, "Hl", 0);
751
+ this.Ah = IV[0] | 0;
752
+ this.Al = IV[1] | 0;
753
+ this.Bh = IV[2] | 0;
754
+ this.Bl = IV[3] | 0;
755
+ this.Ch = IV[4] | 0;
756
+ this.Cl = IV[5] | 0;
757
+ this.Dh = IV[6] | 0;
758
+ this.Dl = IV[7] | 0;
759
+ this.Eh = IV[8] | 0;
760
+ this.El = IV[9] | 0;
761
+ this.Fh = IV[10] | 0;
762
+ this.Fl = IV[11] | 0;
763
+ this.Gh = IV[12] | 0;
764
+ this.Gl = IV[13] | 0;
765
+ this.Hh = IV[14] | 0;
766
+ this.Hl = IV[15] | 0;
767
+ }
768
+ // prettier-ignore
769
+ get() {
770
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
771
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
772
+ }
773
+ // prettier-ignore
774
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
775
+ this.Ah = Ah | 0;
776
+ this.Al = Al | 0;
777
+ this.Bh = Bh | 0;
778
+ this.Bl = Bl | 0;
779
+ this.Ch = Ch | 0;
780
+ this.Cl = Cl | 0;
781
+ this.Dh = Dh | 0;
782
+ this.Dl = Dl | 0;
783
+ this.Eh = Eh | 0;
784
+ this.El = El | 0;
785
+ this.Fh = Fh | 0;
786
+ this.Fl = Fl | 0;
787
+ this.Gh = Gh | 0;
788
+ this.Gl = Gl | 0;
789
+ this.Hh = Hh | 0;
790
+ this.Hl = Hl | 0;
791
+ }
792
+ _cloneInto(to) {
793
+ (to || (to = new this.constructor())).set(...this.get());
794
+ return this._cloneIntoMeta(to);
795
+ }
796
+ process(view, offset) {
797
+ for (let i = 0; i < 16; i++, offset += 4) {
798
+ SHA512_W_H[i] = view.getUint32(offset);
799
+ SHA512_W_L[i] = view.getUint32(offset += 4);
800
+ }
801
+ for (let i = 16; i < 80; i++) {
802
+ const W15h = SHA512_W_H[i - 15] | 0;
803
+ const W15l = SHA512_W_L[i - 15] | 0;
804
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
805
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
806
+ const W2h = SHA512_W_H[i - 2] | 0;
807
+ const W2l = SHA512_W_L[i - 2] | 0;
808
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
809
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
810
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
811
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
812
+ SHA512_W_H[i] = SUMh | 0;
813
+ SHA512_W_L[i] = SUMl | 0;
814
+ }
815
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
816
+ for (let i = 0; i < 80; i++) {
817
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
818
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
819
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
820
+ const CHIl = El & Fl ^ ~El & Gl;
821
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
822
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
823
+ const T1l = T1ll | 0;
824
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
825
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
826
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
827
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
828
+ Hh = Gh | 0;
829
+ Hl = Gl | 0;
830
+ Gh = Fh | 0;
831
+ Gl = Fl | 0;
832
+ Fh = Eh | 0;
833
+ Fl = El | 0;
834
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
835
+ Dh = Ch | 0;
836
+ Dl = Cl | 0;
837
+ Ch = Bh | 0;
838
+ Cl = Bl | 0;
839
+ Bh = Ah | 0;
840
+ Bl = Al | 0;
841
+ const All = add3L(T1l, sigma0l, MAJl);
842
+ Ah = add3H(All, T1h, sigma0h, MAJh);
843
+ Al = All | 0;
844
+ }
845
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
846
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
847
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
848
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
849
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
850
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
851
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
852
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
853
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
854
+ }
855
+ roundClean() {
856
+ clean(SHA512_W_H, SHA512_W_L);
857
+ }
858
+ destroy() {
859
+ this.destroyed = true;
860
+ clean(this.buffer);
861
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
862
+ }
863
+ };
864
+ var _SHA512 = class extends SHA2_64B {
865
+ constructor() {
866
+ super(64, SHA512_IV);
867
+ }
868
+ };
869
+ var sha256 = /* @__PURE__ */ createHasher(
870
+ () => new _SHA256(),
871
+ /* @__PURE__ */ oidNist(1)
872
+ );
873
+ var sha512 = /* @__PURE__ */ createHasher(
874
+ () => new _SHA512(),
875
+ /* @__PURE__ */ oidNist(3)
876
+ );
877
+
878
+ // ../../node_modules/@noble/curves/utils.js
879
+ function aarray(item, title, inner = () => {
880
+ }) {
881
+ if (!Array.isArray(item))
882
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
883
+ for (let i = 0; i < item.length; i++)
884
+ inner(item[i], `${title}[${i}]`);
885
+ return item;
886
+ }
887
+ var abytes2 = (value, length, title) => abytes(value, length, title);
888
+ var anumber2 = anumber;
889
+ function astring(value, title = "") {
890
+ if (typeof value !== "string") {
891
+ const prefix = title && `"${title}" `;
892
+ throw new TypeError(prefix + "expected string, got type=" + typeof value);
893
+ }
894
+ return value;
895
+ }
896
+ function aobject2(value, title = "object") {
897
+ if (value === null || typeof value !== "object" || Array.isArray(value))
898
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
899
+ return value;
900
+ }
901
+ function afunction(value, title) {
902
+ if (typeof value !== "function")
903
+ throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
904
+ return value;
905
+ }
906
+ var bytesToHex2 = bytesToHex;
907
+ var concatBytes2 = (...arrays) => concatBytes(...arrays);
908
+ var hexToBytes2 = (hex) => hexToBytes(hex);
909
+ var isBytes2 = isBytes;
910
+ var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
911
+ var _0n = /* @__PURE__ */ BigInt(0);
912
+ var _1n = /* @__PURE__ */ BigInt(1);
913
+ var atitle2 = (title) => title ? `"${title}" ` : "";
914
+ function abool2(value, title = "") {
915
+ if (typeof value !== "boolean")
916
+ throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
917
+ return value;
918
+ }
919
+ function abignumber(n) {
920
+ if (typeof n === "bigint") {
921
+ if (!isPosBig(n))
922
+ throw new RangeError("positive bigint expected, got " + n);
923
+ } else
924
+ anumber2(n);
925
+ return n;
926
+ }
927
+ function asafenumber(value, title = "") {
928
+ if (typeof value !== "number") {
929
+ const prefix = title && `"${title}" `;
930
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
931
+ }
932
+ if (!Number.isSafeInteger(value)) {
933
+ const prefix = title && `"${title}" `;
934
+ throw new RangeError(prefix + "expected safe integer, got " + value);
935
+ }
936
+ }
937
+ function numberToHexUnpadded(num) {
938
+ const hex = abignumber(num).toString(16);
939
+ return hex.length & 1 ? "0" + hex : hex;
940
+ }
941
+ function hexToNumber(hex) {
942
+ if (typeof hex !== "string")
943
+ throw new TypeError("hex string expected, got " + typeof hex);
944
+ return hex === "" ? _0n : BigInt("0x" + hex);
945
+ }
946
+ function bytesToNumberBE(bytes) {
947
+ return hexToNumber(bytesToHex(bytes));
948
+ }
949
+ function bytesToNumberLE(bytes) {
950
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
951
+ }
952
+ function numberToBytesBE(n, len) {
953
+ anumber(len);
954
+ if (len === 0)
955
+ throw new Error("zero output length is invalid");
956
+ n = abignumber(n);
957
+ const expectedLen = len * 2;
958
+ const hex = n.toString(16);
959
+ if (hex.length > expectedLen)
960
+ throw new RangeError("number is too large");
961
+ return hexToBytes(hex.padStart(expectedLen, "0"));
962
+ }
963
+ function numberToBytesLE(n, len) {
964
+ return numberToBytesBE(n, len).reverse();
965
+ }
966
+ function copyBytes(bytes) {
967
+ return Uint8Array.from(abytes2(bytes));
968
+ }
969
+ function isPosBig(n) {
970
+ return typeof n === "bigint" && _0n <= n;
971
+ }
972
+ function inRange(n, min, max) {
973
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
974
+ }
975
+ function aInRange(title, n, min, max) {
976
+ if (!inRange(n, min, max))
977
+ throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
978
+ }
979
+ function bitLen(n) {
980
+ if (n < _0n)
981
+ throw new Error("expected non-negative bigint, got " + n);
982
+ return n === _0n ? 0 : n.toString(2).length;
983
+ }
984
+ var bitMask = (n) => {
985
+ asafenumber(n, "n");
986
+ return (_1n << BigInt(n)) - _1n;
987
+ };
988
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
989
+ anumber(hashLen, "hashLen");
990
+ anumber(qByteLen, "qByteLen");
991
+ if (typeof hmacFn !== "function")
992
+ throw new TypeError("hmacFn must be a function");
993
+ const u8n = (len) => new Uint8Array(len);
994
+ const NULL = Uint8Array.of();
995
+ const byte0 = Uint8Array.of(0);
996
+ const byte1 = Uint8Array.of(1);
997
+ const _maxDrbgIters = 1e3;
998
+ let v = u8n(hashLen);
999
+ let k = u8n(hashLen);
1000
+ let i = 0;
1001
+ const reset = () => {
1002
+ v.fill(1);
1003
+ k.fill(0);
1004
+ i = 0;
1005
+ };
1006
+ const h = (...msgs) => hmacFn(k, concatBytes2(v, ...msgs));
1007
+ const reseed = (seed = NULL) => {
1008
+ k = h(byte0, seed);
1009
+ v = h();
1010
+ if (seed.length === 0)
1011
+ return;
1012
+ k = h(byte1, seed);
1013
+ v = h();
1014
+ };
1015
+ const gen = () => {
1016
+ if (i++ >= _maxDrbgIters)
1017
+ throw new Error("drbg: tried max amount of iterations");
1018
+ let len = 0;
1019
+ const out = [];
1020
+ while (len < qByteLen) {
1021
+ v = h();
1022
+ const sl = v.slice();
1023
+ out.push(sl);
1024
+ len += v.length;
1025
+ }
1026
+ return concatBytes2(...out);
1027
+ };
1028
+ const genUntil = (seed, pred) => {
1029
+ reset();
1030
+ reseed(seed);
1031
+ let res = void 0;
1032
+ while ((res = pred(gen())) === void 0)
1033
+ reseed();
1034
+ reset();
1035
+ return res;
1036
+ };
1037
+ return genUntil;
1038
+ }
1039
+ function validateObject(object, fields = {}, optFields = {}, title = "object") {
1040
+ aobject2(object, title);
1041
+ aobject2(fields, "fields");
1042
+ aobject2(optFields, "optFields");
1043
+ function checkField(fieldName, expectedType, isOpt) {
1044
+ const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
1045
+ const val = object[fieldName];
1046
+ if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
1047
+ throw new TypeError(`${label} is invalid: expected own property`);
1048
+ }
1049
+ if (isOpt && val === void 0)
1050
+ return;
1051
+ const current = typeof val;
1052
+ if (current !== expectedType || val === null)
1053
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
1054
+ }
1055
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
1056
+ iter(fields, false);
1057
+ iter(optFields, true);
1058
+ }
1059
+
1060
+ // ../../node_modules/@noble/curves/abstract/modular.js
1061
+ var _0n2 = /* @__PURE__ */ BigInt(0);
1062
+ var _1n2 = /* @__PURE__ */ BigInt(1);
1063
+ var _2n = /* @__PURE__ */ BigInt(2);
1064
+ var _3n = /* @__PURE__ */ BigInt(3);
1065
+ var _4n = /* @__PURE__ */ BigInt(4);
1066
+ var _5n = /* @__PURE__ */ BigInt(5);
1067
+ var _7n = /* @__PURE__ */ BigInt(7);
1068
+ var _8n = /* @__PURE__ */ BigInt(8);
1069
+ var _9n = /* @__PURE__ */ BigInt(9);
1070
+ var _15n = /* @__PURE__ */ BigInt(15);
1071
+ var _16n = /* @__PURE__ */ BigInt(16);
1072
+ var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
1073
+ function mod(a, b) {
1074
+ if (b <= _0n2)
1075
+ throw new Error("mod: expected positive modulus, got " + b);
1076
+ const result = a % b;
1077
+ return result >= _0n2 ? result : b + result;
1078
+ }
1079
+ function pow(num, power, modulo) {
1080
+ if (modulo <= _1n2)
1081
+ throw new Error("pow: expected modulus > 1, got " + modulo);
1082
+ if (typeof power !== "bigint")
1083
+ throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
1084
+ if (power < _0n2)
1085
+ throw new Error("invalid exponent, negatives unsupported");
1086
+ if (power === _0n2)
1087
+ return _1n2;
1088
+ if (power === _1n2)
1089
+ return num;
1090
+ let d = num % modulo;
1091
+ if (d < _0n2)
1092
+ d += modulo;
1093
+ if (power < POW_WINDOWED_MIN) {
1094
+ let p2 = _1n2;
1095
+ while (power > _0n2) {
1096
+ if (power & _1n2)
1097
+ p2 = p2 * d % modulo;
1098
+ d = d * d % modulo;
1099
+ power >>= _1n2;
1100
+ }
1101
+ return p2;
1102
+ }
1103
+ const digits = [];
1104
+ while (power > _0n2) {
1105
+ digits.push(Number(power & _15n));
1106
+ power >>= _4n;
1107
+ }
1108
+ const table = new Array(16);
1109
+ table[0] = _1n2;
1110
+ table[1] = d;
1111
+ for (let i = 2; i < 16; i++)
1112
+ table[i] = table[i - 1] * d % modulo;
1113
+ let p = table[digits[digits.length - 1]];
1114
+ for (let w = digits.length - 2; w >= 0; w--) {
1115
+ p = p * p % modulo;
1116
+ p = p * p % modulo;
1117
+ p = p * p % modulo;
1118
+ p = p * p % modulo;
1119
+ const digit = digits[w];
1120
+ if (digit !== 0)
1121
+ p = p * table[digit] % modulo;
1122
+ }
1123
+ return p;
1124
+ }
1125
+ function pow2(x, power, modulo) {
1126
+ if (modulo <= _1n2)
1127
+ throw new Error("pow2: expected modulus > 1, got " + modulo);
1128
+ if (power < _0n2)
1129
+ throw new Error("pow2: expected non-negative exponent, got " + power);
1130
+ let res = x;
1131
+ while (power-- > _0n2) {
1132
+ res *= res;
1133
+ res %= modulo;
1134
+ }
1135
+ return res;
1136
+ }
1137
+ function invert(number, modulo) {
1138
+ if (number === _0n2)
1139
+ throw new Error("invert: expected non-zero number");
1140
+ if (modulo <= _1n2)
1141
+ throw new Error("invert: expected modulus > 1, got " + modulo);
1142
+ let a = mod(number, modulo);
1143
+ let b = modulo;
1144
+ let x = _0n2, u = _1n2;
1145
+ while (a !== _0n2) {
1146
+ const q = b / a;
1147
+ const r = b - a * q;
1148
+ const m = x - u * q;
1149
+ b = a, a = r, x = u, u = m;
1150
+ }
1151
+ const gcd = b;
1152
+ if (gcd !== _1n2)
1153
+ throw new Error("invert: does not exist");
1154
+ return mod(x, modulo);
1155
+ }
1156
+ function invertCt(a, prime) {
1157
+ if (prime <= _1n2)
1158
+ throw new Error("invertCt: expected prime modulus > 1, got " + prime);
1159
+ const an = mod(a, prime);
1160
+ if (an === _0n2)
1161
+ throw new Error("invertCt: expected non-zero number");
1162
+ const inverse = pow(an, prime - _2n, prime);
1163
+ if (mod(an * inverse, prime) !== _1n2)
1164
+ throw new Error("invertCt: does not exist");
1165
+ return inverse;
1166
+ }
1167
+ function assertIsSquare(Fp2, root, n) {
1168
+ const F = Fp2;
1169
+ if (!F.eql(F.sqr(root), n))
1170
+ throw new Error("Cannot find square root");
1171
+ }
1172
+ function aoddModulus(order, fnName) {
1173
+ if ((order & _1n2) === _0n2)
1174
+ throw new Error(fnName + ": expected odd modulus, got " + order);
1175
+ }
1176
+ function sqrt3mod4(Fp2, n) {
1177
+ const F = Fp2;
1178
+ const p1div4 = (F.ORDER + _1n2) / _4n;
1179
+ const root = F.pow(n, p1div4);
1180
+ assertIsSquare(F, root, n);
1181
+ return root;
1182
+ }
1183
+ function sqrt5mod8(Fp2, n) {
1184
+ const F = Fp2;
1185
+ const p5div8 = (F.ORDER - _5n) / _8n;
1186
+ const n2 = F.mul(n, _2n);
1187
+ const v = F.pow(n2, p5div8);
1188
+ const nv = F.mul(n, v);
1189
+ const i = F.mul(F.mul(nv, _2n), v);
1190
+ const root = F.mul(nv, F.sub(i, F.ONE));
1191
+ assertIsSquare(F, root, n);
1192
+ return root;
1193
+ }
1194
+ function sqrt9mod16(P) {
1195
+ const Fp_ = Field(P);
1196
+ const tn = tonelliShanks(P);
1197
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1198
+ const c2 = tn(Fp_, c1);
1199
+ const c3 = tn(Fp_, Fp_.neg(c1));
1200
+ const c4 = (P + _7n) / _16n;
1201
+ return (Fp2, n) => {
1202
+ const F = Fp2;
1203
+ let tv1 = F.pow(n, c4);
1204
+ let tv2 = F.mul(tv1, c1);
1205
+ const tv3 = F.mul(tv1, c2);
1206
+ const tv4 = F.mul(tv1, c3);
1207
+ const e1 = F.eql(F.sqr(tv2), n);
1208
+ const e2 = F.eql(F.sqr(tv3), n);
1209
+ tv1 = F.cmov(tv1, tv2, e1);
1210
+ tv2 = F.cmov(tv4, tv3, e2);
1211
+ const e3 = F.eql(F.sqr(tv2), n);
1212
+ const root = F.cmov(tv1, tv2, e3);
1213
+ assertIsSquare(F, root, n);
1214
+ return root;
1215
+ };
1216
+ }
1217
+ function tonelliShanks(P) {
1218
+ if (P < _3n)
1219
+ throw new Error("sqrt is not defined for small field");
1220
+ aoddModulus(P, "tonelliShanks");
1221
+ let Q = P - _1n2;
1222
+ let S = 0;
1223
+ while (Q % _2n === _0n2) {
1224
+ Q /= _2n;
1225
+ S++;
1226
+ }
1227
+ let Z = _2n;
1228
+ const _Fp = Field(P);
1229
+ while (FpLegendre(_Fp, Z) === 1) {
1230
+ if (Z++ > 1e3)
1231
+ throw new Error("Cannot find square root: probably non-prime P");
1232
+ }
1233
+ if (S === 1)
1234
+ return sqrt3mod4;
1235
+ let cc = _Fp.pow(Z, Q);
1236
+ const Q1div2 = (Q + _1n2) / _2n;
1237
+ return function tonelliSlow(Fp2, n) {
1238
+ const F = Fp2;
1239
+ if (F.is0(n))
1240
+ return n;
1241
+ if (FpLegendre(F, n) !== 1)
1242
+ throw new Error("Cannot find square root");
1243
+ let M = S;
1244
+ let c = F.mul(F.ONE, cc);
1245
+ let t = F.pow(n, Q);
1246
+ let R = F.pow(n, Q1div2);
1247
+ while (!F.eql(t, F.ONE)) {
1248
+ if (F.is0(t))
1249
+ throw new Error("Cannot find square root: probably non-prime P");
1250
+ let i = 1;
1251
+ let t_tmp = F.sqr(t);
1252
+ while (!F.eql(t_tmp, F.ONE)) {
1253
+ i++;
1254
+ t_tmp = F.sqr(t_tmp);
1255
+ if (i === M)
1256
+ throw new Error("Cannot find square root");
1257
+ }
1258
+ const exponent = _1n2 << BigInt(M - i - 1);
1259
+ const b = F.pow(c, exponent);
1260
+ M = i;
1261
+ c = F.sqr(b);
1262
+ t = F.mul(t, c);
1263
+ R = F.mul(R, b);
1264
+ }
1265
+ return R;
1266
+ };
1267
+ }
1268
+ function FpSqrt(P) {
1269
+ aoddModulus(P, "Fp.sqrt");
1270
+ if (P % _4n === _3n)
1271
+ return sqrt3mod4;
1272
+ if (P % _8n === _5n)
1273
+ return sqrt5mod8;
1274
+ if (P % _16n === _9n)
1275
+ return sqrt9mod16(P);
1276
+ return tonelliShanks(P);
1277
+ }
1278
+ var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
1279
+ var FIELD_FIELDS = [
1280
+ "create",
1281
+ "isValid",
1282
+ "is0",
1283
+ "neg",
1284
+ "inv",
1285
+ "sqrt",
1286
+ "sqr",
1287
+ "eql",
1288
+ "add",
1289
+ "sub",
1290
+ "mul",
1291
+ "pow",
1292
+ "div",
1293
+ "addN",
1294
+ "subN",
1295
+ "mulN",
1296
+ "sqrN"
1297
+ ];
1298
+ function validateField(field) {
1299
+ aobject2(field, "field");
1300
+ if (typeof field.ORDER !== "bigint")
1301
+ throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
1302
+ asafenumber(field.BYTES, "BYTES");
1303
+ asafenumber(field.BITS, "BITS");
1304
+ for (const name of FIELD_FIELDS)
1305
+ afunction(field[name], "field." + name);
1306
+ if (field.BYTES < 1 || field.BITS < 1)
1307
+ throw new Error("invalid field: expected BYTES/BITS > 0");
1308
+ if (field.ORDER <= _1n2)
1309
+ throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
1310
+ return field;
1311
+ }
1312
+ function FpInvertBatch(Fp2, nums, passZero = false) {
1313
+ validateField(Fp2);
1314
+ aarray(nums, "nums");
1315
+ abool2(passZero, "passZero");
1316
+ const F = Fp2;
1317
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
1318
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1319
+ if (F.is0(num))
1320
+ return acc;
1321
+ inverted[i] = acc;
1322
+ return F.mul(acc, num);
1323
+ }, F.ONE);
1324
+ const invertedAcc = F.inv(multipliedAcc);
1325
+ nums.reduceRight((acc, num, i) => {
1326
+ if (F.is0(num))
1327
+ return acc;
1328
+ inverted[i] = F.mul(acc, inverted[i]);
1329
+ return F.mul(acc, num);
1330
+ }, invertedAcc);
1331
+ return inverted;
1332
+ }
1333
+ function FpLegendre(Fp2, n) {
1334
+ validateField(Fp2);
1335
+ const F = Fp2;
1336
+ aoddModulus(F.ORDER, "FpLegendre");
1337
+ const p1mod2 = (F.ORDER - _1n2) / _2n;
1338
+ const powered = F.pow(n, p1mod2);
1339
+ const yes = F.eql(powered, F.ONE);
1340
+ const zero = F.eql(powered, F.ZERO);
1341
+ const no = F.eql(powered, F.neg(F.ONE));
1342
+ if (!yes && !zero && !no)
1343
+ throw new Error("invalid Legendre symbol result");
1344
+ return yes ? 1 : zero ? 0 : -1;
1345
+ }
1346
+ function nLength(n, nBitLength) {
1347
+ if (nBitLength !== void 0)
1348
+ anumber2(nBitLength);
1349
+ if (n <= _0n2)
1350
+ throw new Error("invalid n length: expected positive n, got " + n);
1351
+ if (nBitLength !== void 0 && nBitLength < 1)
1352
+ throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
1353
+ const bits = bitLen(n);
1354
+ if (nBitLength !== void 0 && nBitLength < bits)
1355
+ throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
1356
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
1357
+ const nByteLength = Math.ceil(_nBitLength / 8);
1358
+ return { nBitLength: _nBitLength, nByteLength };
1359
+ }
1360
+ var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
1361
+ var _Field = class {
1362
+ constructor(ORDER, opts = {}) {
1363
+ __publicField(this, "ORDER");
1364
+ __publicField(this, "BITS");
1365
+ __publicField(this, "BYTES");
1366
+ __publicField(this, "isLE");
1367
+ __publicField(this, "ZERO", _0n2);
1368
+ __publicField(this, "ONE", _1n2);
1369
+ __publicField(this, "_lengths");
1370
+ __publicField(this, "_mod");
1371
+ if (ORDER <= _1n2)
1372
+ throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
1373
+ let _nbitLength = void 0;
1374
+ this.isLE = false;
1375
+ if (opts != null && typeof opts === "object") {
1376
+ if (typeof opts.BITS === "number")
1377
+ _nbitLength = opts.BITS;
1378
+ if (typeof opts.sqrt === "function")
1379
+ Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
1380
+ if (typeof opts.isLE === "boolean")
1381
+ this.isLE = opts.isLE;
1382
+ if (opts.allowedLengths)
1383
+ this._lengths = Object.freeze(opts.allowedLengths.slice());
1384
+ if (typeof opts.modFromBytes === "boolean")
1385
+ this._mod = opts.modFromBytes;
1386
+ }
1387
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
1388
+ if (nByteLength > 2048)
1389
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1390
+ this.ORDER = ORDER;
1391
+ this.BITS = nBitLength;
1392
+ this.BYTES = nByteLength;
1393
+ Object.freeze(this);
1394
+ }
1395
+ create(num) {
1396
+ return mod(num, this.ORDER);
1397
+ }
1398
+ isValid(num) {
1399
+ if (typeof num !== "bigint")
1400
+ throw new TypeError("invalid field element: expected bigint, got " + typeof num);
1401
+ return _0n2 <= num && num < this.ORDER;
1402
+ }
1403
+ is0(num) {
1404
+ return num === _0n2;
1405
+ }
1406
+ // is valid and invertible
1407
+ isValidNot0(num) {
1408
+ return !this.is0(num) && this.isValid(num);
1409
+ }
1410
+ isOdd(num) {
1411
+ return (num & _1n2) === _1n2;
1412
+ }
1413
+ neg(num) {
1414
+ return mod(-num, this.ORDER);
1415
+ }
1416
+ eql(lhs, rhs) {
1417
+ return lhs === rhs;
1418
+ }
1419
+ sqr(num) {
1420
+ return mod(num * num, this.ORDER);
1421
+ }
1422
+ add(lhs, rhs) {
1423
+ return mod(lhs + rhs, this.ORDER);
1424
+ }
1425
+ sub(lhs, rhs) {
1426
+ return mod(lhs - rhs, this.ORDER);
1427
+ }
1428
+ mul(lhs, rhs) {
1429
+ return mod(lhs * rhs, this.ORDER);
1430
+ }
1431
+ pow(num, power) {
1432
+ return pow(num, power, this.ORDER);
1433
+ }
1434
+ div(lhs, rhs) {
1435
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
1436
+ }
1437
+ // Same as above, but doesn't normalize
1438
+ sqrN(num) {
1439
+ return num * num;
1440
+ }
1441
+ addN(lhs, rhs) {
1442
+ return lhs + rhs;
1443
+ }
1444
+ subN(lhs, rhs) {
1445
+ return lhs - rhs;
1446
+ }
1447
+ mulN(lhs, rhs) {
1448
+ return lhs * rhs;
1449
+ }
1450
+ inv(num) {
1451
+ return invert(num, this.ORDER);
1452
+ }
1453
+ sqrt(num) {
1454
+ let sqrt = FIELD_SQRT.get(this);
1455
+ if (!sqrt)
1456
+ FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
1457
+ return sqrt(this, num);
1458
+ }
1459
+ toBytes(num) {
1460
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1461
+ }
1462
+ fromBytes(bytes, skipValidation = false) {
1463
+ abytes2(bytes);
1464
+ const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
1465
+ if (allowedLengths) {
1466
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1467
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1468
+ }
1469
+ const padded = new Uint8Array(BYTES);
1470
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
1471
+ bytes = padded;
1472
+ }
1473
+ if (bytes.length !== BYTES)
1474
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1475
+ let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1476
+ if (modFromBytes)
1477
+ scalar = mod(scalar, ORDER);
1478
+ if (!skipValidation) {
1479
+ if (!this.isValid(scalar))
1480
+ throw new Error("invalid field element: outside of range 0..ORDER");
1481
+ }
1482
+ return scalar;
1483
+ }
1484
+ // TODO: we don't need it here, move out to separate fn
1485
+ invertBatch(lst) {
1486
+ return FpInvertBatch(this, lst, true);
1487
+ }
1488
+ // We can't move this out because Fp6, Fp12 implement it
1489
+ // and it's unclear what to return in there.
1490
+ cmov(a, b, condition) {
1491
+ abool2(condition, "condition");
1492
+ return condition ? b : a;
1493
+ }
1494
+ };
1495
+ function Field(ORDER, opts = {}) {
1496
+ Object.freeze(_Field.prototype);
1497
+ return new _Field(ORDER, opts);
1498
+ }
1499
+ function getFieldBytesLength(fieldOrder) {
1500
+ if (typeof fieldOrder !== "bigint")
1501
+ throw new Error("field order must be bigint");
1502
+ if (fieldOrder <= _1n2)
1503
+ throw new Error("field order must be greater than 1");
1504
+ const bitLength = bitLen(fieldOrder - _1n2);
1505
+ return Math.ceil(bitLength / 8);
1506
+ }
1507
+ function getMinHashLength(fieldOrder) {
1508
+ const length = getFieldBytesLength(fieldOrder);
1509
+ return length + Math.ceil(length / 2);
1510
+ }
1511
+ function mapHashToField(key, fieldOrder, isLE2 = false) {
1512
+ abytes2(key);
1513
+ const len = key.length;
1514
+ const fieldLen = getFieldBytesLength(fieldOrder);
1515
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
1516
+ if (len < minLen || len > 1024)
1517
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
1518
+ const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
1519
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
1520
+ return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1521
+ }
1522
+
1523
+ // ../../node_modules/@noble/curves/abstract/curve.js
1524
+ var _0n3 = /* @__PURE__ */ BigInt(0);
1525
+ var _1n3 = /* @__PURE__ */ BigInt(1);
1526
+ var _4n2 = /* @__PURE__ */ BigInt(4);
1527
+ var BLIND_BYTES = 16;
1528
+ var BLIND_BITS = 128;
1529
+ var FW_WINDOW = 5;
1530
+ var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
1531
+ function validatePointCons(Point) {
1532
+ const pc = Point;
1533
+ if (typeof pc !== "function")
1534
+ throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
1535
+ afunction(pc.fromAffine, "Point.fromAffine");
1536
+ afunction(pc.fromBytes, "Point.fromBytes");
1537
+ afunction(pc.fromHex, "Point.fromHex");
1538
+ aobject2(pc.BASE, "Point.BASE");
1539
+ aobject2(pc.ZERO, "Point.ZERO");
1540
+ validateField(pc.Fp);
1541
+ validateField(pc.Fn);
1542
+ }
1543
+ function normalizeZ(c, points) {
1544
+ validatePointCons(c);
1545
+ validateMSMPoints(points, c);
1546
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1547
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1548
+ }
1549
+ function validateW(W, bits, min = 1) {
1550
+ if (!Number.isSafeInteger(W) || W < min || W > bits)
1551
+ throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
1552
+ }
1553
+ function validateTableBytes(numPoints, fpBytes) {
1554
+ const bytes = numPoints * (4 * fpBytes + 128);
1555
+ if (bytes > TABLE_BYTES_MAX)
1556
+ throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
1557
+ }
1558
+ function probeRandomBytes(randomBytes3, length) {
1559
+ if (randomBytes3 === void 0)
1560
+ return void 0;
1561
+ afunction(randomBytes3, "randomBytes");
1562
+ try {
1563
+ const probe = randomBytes3(length);
1564
+ if (!isBytes2(probe) || probe.length !== length)
1565
+ return void 0;
1566
+ } catch {
1567
+ return void 0;
1568
+ }
1569
+ return randomBytes3;
1570
+ }
1571
+ function validateMSMPoints(points, c) {
1572
+ aarray(points, "points");
1573
+ points.forEach((p, i) => {
1574
+ if (!(p instanceof c))
1575
+ throw new Error("invalid point at index " + i);
1576
+ });
1577
+ }
1578
+ function validateMSMScalars(scalars, field, maxScalar) {
1579
+ if (!Array.isArray(scalars))
1580
+ throw new Error("array of scalars expected");
1581
+ scalars.forEach((s, i) => {
1582
+ const ok = maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar;
1583
+ if (!ok)
1584
+ throw new Error("invalid scalar at index " + i);
1585
+ });
1586
+ }
1587
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1588
+ function getWindowSize(P) {
1589
+ return pointWindowSizes.get(P) || 1;
1590
+ }
1591
+ function oddMultiples(p, size) {
1592
+ const dbl = p.double();
1593
+ const t = [p];
1594
+ for (let j = 1; j < size; j++)
1595
+ t.push(t[j - 1].add(dbl));
1596
+ return t;
1597
+ }
1598
+ function wnafDigits(n, W) {
1599
+ const size = 2 ** W;
1600
+ const half = size / 2;
1601
+ const mask = BigInt(size - 1);
1602
+ const d = [];
1603
+ while (n > _0n3) {
1604
+ let w = 0;
1605
+ if (n & _1n3) {
1606
+ w = Number(n & mask);
1607
+ if (w >= half)
1608
+ w -= size;
1609
+ n -= BigInt(w);
1610
+ }
1611
+ d.push(w);
1612
+ n >>= _1n3;
1613
+ }
1614
+ return d;
1615
+ }
1616
+ function signedWindowDigits(n, W, windows) {
1617
+ const size = 2 ** W;
1618
+ const half = size / 2;
1619
+ const mask = BigInt(size - 1);
1620
+ const shiftBy = BigInt(W);
1621
+ const d = [];
1622
+ for (let w = 0; w < windows; w++) {
1623
+ let v = Number(n & mask);
1624
+ n >>= shiftBy;
1625
+ if (v > half) {
1626
+ v -= size;
1627
+ n += _1n3;
1628
+ }
1629
+ d.push(v);
1630
+ }
1631
+ if (n !== _0n3)
1632
+ throw new Error("invalid wnaf");
1633
+ return d;
1634
+ }
1635
+ function wnafWalk(zero, tables, digits) {
1636
+ let max = 0;
1637
+ for (const d of digits)
1638
+ max = Math.max(max, d.length);
1639
+ let acc = zero;
1640
+ for (let bit = max - 1; bit >= 0; bit--) {
1641
+ if (bit !== max - 1)
1642
+ acc = acc.double();
1643
+ for (let i = 0; i < digits.length; i++) {
1644
+ const w = digits[i][bit];
1645
+ if (w) {
1646
+ const item = tables[i][Math.abs(w) - 1 >> 1];
1647
+ acc = acc.add(w < 0 ? item.negate() : item);
1648
+ }
1649
+ }
1650
+ }
1651
+ return acc;
1652
+ }
1653
+ var ScalarMultiplier = class {
1654
+ // Parametrized with a given Point class (not individual point)
1655
+ constructor(Point, randomBytes3) {
1656
+ __publicField(this, "Point");
1657
+ __publicField(this, "BASE");
1658
+ __publicField(this, "ZERO");
1659
+ __publicField(this, "randomBytes");
1660
+ __publicField(this, "wnafPrecomputes", /* @__PURE__ */ new WeakMap());
1661
+ __publicField(this, "baseCanBeBlinded");
1662
+ __publicField(this, "bits");
1663
+ validatePointCons(Point);
1664
+ this.randomBytes = probeRandomBytes(randomBytes3, BLIND_BYTES);
1665
+ this.Point = Point;
1666
+ this.BASE = Point.BASE;
1667
+ this.ZERO = Point.ZERO;
1668
+ this.bits = Point.Fn.BITS;
1669
+ }
1670
+ /**
1671
+ * Creates a signed fixed-window wNAF precomputation table: for every window w, the
1672
+ * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
1673
+ * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
1674
+ * window absorbs the final carry of signed-digit recoding.
1675
+ * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
1676
+ * @param point - Point instance
1677
+ * @param W - window size
1678
+ * @param bits - scalar bitlength the table must cover
1679
+ */
1680
+ buildWnafTable(point, W, bits) {
1681
+ const windows = Math.ceil(bits / W) + 1;
1682
+ const half = 2 ** (W - 1);
1683
+ const comp = [];
1684
+ let base = point;
1685
+ for (let w = 0; w < windows; w++) {
1686
+ let acc = base;
1687
+ for (let i = 0; i < half; i++) {
1688
+ comp.push(acc);
1689
+ acc = acc.add(base);
1690
+ }
1691
+ base = comp[comp.length - 1].double();
1692
+ }
1693
+ return { W, bits, windows, comp };
1694
+ }
1695
+ /**
1696
+ * Implements ec multiplication using precomputed signed fixed-window wNAF tables.
1697
+ * Constant-time: fixed window count with one table addition per window — zero digits feed
1698
+ * the fake accumulator — and no doublings; the lookup scans the whole window slice.
1699
+ * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
1700
+ * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
1701
+ * signedWindowDigits throws if `n` exceeds the table.
1702
+ * @returns real and fake (for const-time) points
1703
+ */
1704
+ wnafCachedCT(precomputes, n) {
1705
+ const { W, windows, comp } = precomputes;
1706
+ const half = 2 ** (W - 1);
1707
+ const digits = signedWindowDigits(n, W, windows);
1708
+ let p = this.ZERO;
1709
+ let f = this.BASE;
1710
+ for (let w = 0; w < windows; w++) {
1711
+ const digit = digits[w];
1712
+ const start = w * half;
1713
+ const idx = Math.abs(digit) - 1;
1714
+ let sel = comp[start];
1715
+ for (let i = 1; i < half; i++)
1716
+ sel = i === idx ? comp[start + i] : sel;
1717
+ const neg = sel.negate();
1718
+ if (digit === 0)
1719
+ f = f.add(comp[start]);
1720
+ else
1721
+ p = p.add(digit < 0 ? neg : sel);
1722
+ }
1723
+ return { p, f };
1724
+ }
1725
+ // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
1726
+ // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
1727
+ // incompatible `transform(...)` layouts and expect a separate cache entry.
1728
+ getWnafPrecomputes(W, point, bits, transform) {
1729
+ let entries = this.wnafPrecomputes.get(point);
1730
+ let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
1731
+ if (!comp) {
1732
+ comp = this.buildWnafTable(point, W, bits);
1733
+ if (typeof transform === "function")
1734
+ comp = { ...comp, comp: transform(comp.comp) };
1735
+ if (!entries) {
1736
+ entries = [];
1737
+ this.wnafPrecomputes.set(point, entries);
1738
+ }
1739
+ entries.push(comp);
1740
+ }
1741
+ return comp;
1742
+ }
1743
+ assertPoint(point) {
1744
+ if (!(point instanceof this.Point))
1745
+ throw new TypeError('"point" expected Point instance, got type=' + typeof point);
1746
+ }
1747
+ // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
1748
+ // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
1749
+ // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
1750
+ validateMulInput(point, scalar) {
1751
+ this.assertPoint(point);
1752
+ if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
1753
+ throw new Error("invalid scalar");
1754
+ }
1755
+ // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
1756
+ // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
1757
+ // multiply. `n` must be < 2^bits.
1758
+ runCT(point, n, bits, transform) {
1759
+ const W = getWindowSize(point);
1760
+ if (W === 1)
1761
+ return this.fixedWindowCT(point, n, bits);
1762
+ return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
1763
+ }
1764
+ mulCT(point, scalar, transform) {
1765
+ this.validateMulInput(point, scalar);
1766
+ return this.runCT(point, scalar, this.bits, transform);
1767
+ }
1768
+ mulCTBlinded(point, scalar, transform) {
1769
+ this.validateMulInput(point, scalar);
1770
+ if (this.randomBytes === void 0)
1771
+ throw new Error("randomBytes is required for scalar blinding");
1772
+ const bits = this.Point.Fn.BITS + BLIND_BITS;
1773
+ const blind = this.randomBytes(BLIND_BYTES);
1774
+ if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
1775
+ throw new Error("randomBytes returned invalid byte array");
1776
+ blind[0] = blind[0] & 63 | 128;
1777
+ const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
1778
+ return this.runCT(point, n, bits, transform);
1779
+ }
1780
+ /**
1781
+ * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
1782
+ * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
1783
+ * far cheaper to build for a single use. The point-operation sequence is independent of `n`:
1784
+ * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
1785
+ * every table entry, and one addition (adds the identity when the window digit is 0 — never
1786
+ * skipped).
1787
+ *
1788
+ * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
1789
+ * add), which holds for the Weierstrass/Edwards point types used here. The table is left in
1790
+ * projective form (no normalizeZ): normalizing this small a table costs more than the
1791
+ * mixed-add savings it would buy for a single multiply.
1792
+ * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
1793
+ * (this path needs no fake accumulator — its op-count is already scalar-independent).
1794
+ */
1795
+ fixedWindowCT(point, n, bits) {
1796
+ const W = FW_WINDOW;
1797
+ const size = 1 << W;
1798
+ const mask = bitMask(W);
1799
+ const table = new Array(size);
1800
+ table[0] = this.ZERO;
1801
+ for (let i = 1; i < size; i++)
1802
+ table[i] = table[i - 1].add(point);
1803
+ const windows = Math.ceil(bits / W);
1804
+ let acc = this.ZERO;
1805
+ for (let window = windows - 1; window >= 0; window--) {
1806
+ if (window !== windows - 1)
1807
+ for (let d = 0; d < W; d++)
1808
+ acc = acc.double();
1809
+ const digit = Number(n >> BigInt(window * W) & mask);
1810
+ let sel = table[0];
1811
+ for (let i = 1; i < size; i++)
1812
+ sel = i === digit ? table[i] : sel;
1813
+ acc = acc.add(sel);
1814
+ }
1815
+ return { p: acc, f: acc };
1816
+ }
1817
+ shouldBlind(point, cofactor) {
1818
+ if (this.randomBytes === void 0)
1819
+ return false;
1820
+ if (cofactor === _1n3)
1821
+ return true;
1822
+ if (point !== this.BASE)
1823
+ return false;
1824
+ if (this.baseCanBeBlinded === void 0)
1825
+ this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
1826
+ return this.baseCanBeBlinded;
1827
+ }
1828
+ mulSecret(point, scalar, cofactor, transform) {
1829
+ return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
1830
+ }
1831
+ mulUnsafe(point, scalar, transform) {
1832
+ this.assertPoint(point);
1833
+ if (!isPosBig(scalar))
1834
+ throw new Error("invalid scalar");
1835
+ const W = getWindowSize(point);
1836
+ if (W === 1 || scalar >= this.Point.Fn.ORDER)
1837
+ return mulAddUnsafe(this.Point, [point], [scalar], true);
1838
+ const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
1839
+ return this.wnafCachedCT(precomputes, scalar).p;
1840
+ }
1841
+ // Remembers the window size used for precomputed wNAF multiplication of the given point
1842
+ // and drops any previously built tables. Usually only the base point is precomputed.
1843
+ // W=1 resets the point to the un-precomputed (table-less) paths.
1844
+ // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
1845
+ setWindowSize(point, W) {
1846
+ this.assertPoint(point);
1847
+ validateW(W, this.bits);
1848
+ const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
1849
+ validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
1850
+ pointWindowSizes.set(point, W);
1851
+ this.wnafPrecomputes.delete(point);
1852
+ }
1853
+ // True when a window size is set: tables themselves are built lazily on first multiply.
1854
+ hasWindowSize(point) {
1855
+ return getWindowSize(point) !== 1;
1856
+ }
1857
+ };
1858
+ function mulAddUnsafe(c, points, scalars, allowOversized = false) {
1859
+ validatePointCons(c);
1860
+ validateMSMPoints(points, c);
1861
+ abool2(allowOversized, "allowOversized");
1862
+ validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
1863
+ if (points.length !== scalars.length)
1864
+ throw new Error("arrays of points and scalars must have equal length");
1865
+ const tables = points.map((p) => oddMultiples(p, 4));
1866
+ const digits = scalars.map((n) => wnafDigits(n, 4));
1867
+ return wnafWalk(c.ZERO, tables, digits);
1868
+ }
1869
+ function createField(order, field, isLE2) {
1870
+ if (field) {
1871
+ if (field.ORDER !== order)
1872
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1873
+ validateField(field);
1874
+ return field;
1875
+ } else {
1876
+ return Field(order, { isLE: isLE2 });
1877
+ }
1878
+ }
1879
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1880
+ if (type !== "weierstrass" && type !== "edwards")
1881
+ throw new Error('expected curve type "weierstrass" or "edwards"');
1882
+ if (FpFnLE === void 0)
1883
+ FpFnLE = type === "edwards";
1884
+ if (!CURVE || typeof CURVE !== "object")
1885
+ throw new Error(`expected valid ${type} CURVE object`);
1886
+ validateObject(curveOpts);
1887
+ for (const p of ["p", "n", "h"]) {
1888
+ const val = CURVE[p];
1889
+ if (!(isPosBig(val) && val !== _0n3))
1890
+ throw new Error(`CURVE.${p} must be positive bigint`);
1891
+ }
1892
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1893
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1894
+ const _b = type === "weierstrass" ? "b" : "d";
1895
+ const params = ["Gx", "Gy", "a", _b];
1896
+ for (const p of params) {
1897
+ if (!Fp2.isValid(CURVE[p]))
1898
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1899
+ }
1900
+ CURVE = Object.freeze(Object.assign({}, CURVE));
1901
+ return { CURVE, Fp: Fp2, Fn };
1902
+ }
1903
+ function createKeygen(randomSecretKey, getPublicKey) {
1904
+ return function keygen(seed) {
1905
+ const secretKey = randomSecretKey(seed);
1906
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1907
+ };
1908
+ }
1909
+
1910
+ // ../../node_modules/@noble/hashes/hmac.js
1911
+ var _HMAC = class {
1912
+ constructor(hash, key) {
1913
+ __publicField(this, "oHash");
1914
+ __publicField(this, "iHash");
1915
+ __publicField(this, "blockLen");
1916
+ __publicField(this, "outputLen");
1917
+ __publicField(this, "canXOF", false);
1918
+ __publicField(this, "finished", false);
1919
+ __publicField(this, "destroyed", false);
1920
+ ahash(hash);
1921
+ abytes(key, void 0, "key");
1922
+ this.iHash = hash.create();
1923
+ if (typeof this.iHash.update !== "function")
1924
+ throw new Error("expected Hash instance");
1925
+ this.blockLen = this.iHash.blockLen;
1926
+ this.outputLen = this.iHash.outputLen;
1927
+ const blockLen = this.blockLen;
1928
+ const pad = new Uint8Array(blockLen);
1929
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1930
+ for (let i = 0; i < pad.length; i++)
1931
+ pad[i] ^= 54;
1932
+ this.iHash.update(pad);
1933
+ this.oHash = hash.create();
1934
+ for (let i = 0; i < pad.length; i++)
1935
+ pad[i] ^= 54 ^ 92;
1936
+ this.oHash.update(pad);
1937
+ clean(pad);
1938
+ }
1939
+ update(buf) {
1940
+ aexists(this);
1941
+ this.iHash.update(buf);
1942
+ return this;
1943
+ }
1944
+ digestInto(out) {
1945
+ aexists(this);
1946
+ aoutput(out, this);
1947
+ this.finished = true;
1948
+ const buf = out.subarray(0, this.outputLen);
1949
+ this.iHash.digestInto(buf);
1950
+ this.oHash.update(buf);
1951
+ this.oHash.digestInto(buf);
1952
+ this.destroy();
1953
+ }
1954
+ digest() {
1955
+ const out = new Uint8Array(this.oHash.outputLen);
1956
+ this.digestInto(out);
1957
+ return out;
1958
+ }
1959
+ _cloneInto(to) {
1960
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
1961
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;
1962
+ to = to;
1963
+ to.finished = finished;
1964
+ to.destroyed = destroyed;
1965
+ to.blockLen = blockLen;
1966
+ to.outputLen = outputLen;
1967
+ to.canXOF = canXOF;
1968
+ to.oHash = oHash._cloneInto(to.oHash);
1969
+ to.iHash = iHash._cloneInto(to.iHash);
1970
+ return to;
1971
+ }
1972
+ clone() {
1973
+ return this._cloneInto();
1974
+ }
1975
+ destroy() {
1976
+ this.destroyed = true;
1977
+ this.oHash.destroy();
1978
+ this.iHash.destroy();
1979
+ }
1980
+ };
1981
+ var hmac = /* @__PURE__ */ (() => {
1982
+ const hmac_ = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
1983
+ hmac_.create = (hash, key) => new _HMAC(hash, key);
1984
+ return hmac_;
1985
+ })();
1986
+
1987
+ // ../../node_modules/@noble/curves/abstract/der.js
1988
+ var _0n4 = /* @__PURE__ */ BigInt(0);
1989
+ var DERErr = class extends Error {
1990
+ constructor(m = "") {
1991
+ super(m);
1992
+ }
1993
+ };
1994
+ var _DER = {
1995
+ // asn.1 DER encoding utils
1996
+ Err: DERErr,
1997
+ // Basic building block is TLV (Tag-Length-Value)
1998
+ _tlv: {
1999
+ encode: (tag, data) => {
2000
+ const { Err: E } = _DER;
2001
+ asafenumber(tag, "tag");
2002
+ if (tag < 0 || tag > 255)
2003
+ throw new E("tlv.encode: wrong tag");
2004
+ astring(data, "data");
2005
+ if (data.length & 1)
2006
+ throw new E("tlv.encode: unpadded data");
2007
+ const dataLen = data.length / 2;
2008
+ const len = numberToHexUnpadded(dataLen);
2009
+ if (len.length / 2 & 128)
2010
+ throw new E("tlv.encode: long form length too big");
2011
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
2012
+ const t = numberToHexUnpadded(tag);
2013
+ return t + lenLen + len + data;
2014
+ },
2015
+ // v - value, l - left bytes (unparsed)
2016
+ decode(tag, data) {
2017
+ const { Err: E } = _DER;
2018
+ data = abytes2(data, void 0, "DER data");
2019
+ let pos = 0;
2020
+ if (tag < 0 || tag > 255)
2021
+ throw new E("tlv.decode: wrong tag");
2022
+ if (data.length < 2 || data[pos++] !== tag)
2023
+ throw new E("tlv.decode: wrong tlv");
2024
+ const first = data[pos++];
2025
+ const isLong = !!(first & 128);
2026
+ let length = 0;
2027
+ if (!isLong)
2028
+ length = first;
2029
+ else {
2030
+ const lenLen = first & 127;
2031
+ if (!lenLen)
2032
+ throw new E("tlv.decode(long): indefinite length not supported");
2033
+ if (lenLen > 4)
2034
+ throw new E("tlv.decode(long): byte length is too big");
2035
+ const lengthBytes = data.subarray(pos, pos + lenLen);
2036
+ if (lengthBytes.length !== lenLen)
2037
+ throw new E("tlv.decode: length bytes not complete");
2038
+ if (lengthBytes[0] === 0)
2039
+ throw new E("tlv.decode(long): zero leftmost byte");
2040
+ for (const b of lengthBytes)
2041
+ length = length << 8 | b;
2042
+ pos += lenLen;
2043
+ if (length < 128)
2044
+ throw new E("tlv.decode(long): not minimal encoding");
2045
+ }
2046
+ const v = data.subarray(pos, pos + length);
2047
+ if (v.length !== length)
2048
+ throw new E("tlv.decode: wrong value length");
2049
+ return { v, l: data.subarray(pos + length) };
2050
+ }
2051
+ },
2052
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
2053
+ // since we always use positive integers here. It must always be empty:
2054
+ // - add zero byte if exists
2055
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
2056
+ _int: {
2057
+ encode(num) {
2058
+ const { Err: E } = _DER;
2059
+ abignumber(num);
2060
+ if (num < _0n4)
2061
+ throw new E("integer: negative integers are not allowed");
2062
+ let hex = numberToHexUnpadded(num);
2063
+ if (Number.parseInt(hex[0], 16) & 8)
2064
+ hex = "00" + hex;
2065
+ if (hex.length & 1)
2066
+ throw new E("unexpected DER parsing assertion: unpadded hex");
2067
+ return hex;
2068
+ },
2069
+ decode(data) {
2070
+ const { Err: E } = _DER;
2071
+ if (data.length < 1)
2072
+ throw new E("invalid signature integer: empty");
2073
+ if (data[0] & 128)
2074
+ throw new E("invalid signature integer: negative");
2075
+ if (data.length > 1 && data[0] === 0 && !(data[1] & 128))
2076
+ throw new E("invalid signature integer: unnecessary leading zero");
2077
+ return bytesToNumberBE(data);
2078
+ }
2079
+ },
2080
+ toSig(bytes, maxScalarBytes) {
2081
+ const { Err: E, _int: int, _tlv: tlv } = _DER;
2082
+ if (maxScalarBytes !== void 0) {
2083
+ asafenumber(maxScalarBytes, "maxScalarBytes");
2084
+ if (maxScalarBytes < 1)
2085
+ throw new E("invalid signature: maxScalarBytes must be positive");
2086
+ }
2087
+ const data = abytes2(bytes, void 0, "signature");
2088
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
2089
+ if (seqLeftBytes.length)
2090
+ throw new E("invalid signature: left bytes after parsing");
2091
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
2092
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
2093
+ if (sLeftBytes.length)
2094
+ throw new E("invalid signature: left bytes after parsing");
2095
+ if (maxScalarBytes !== void 0 && (rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes))
2096
+ throw new E("invalid signature: integer too large");
2097
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
2098
+ },
2099
+ hexFromSig(sig) {
2100
+ const { _tlv: tlv, _int: int } = _DER;
2101
+ validateObject(sig, { r: "bigint", s: "bigint" }, {}, "sig");
2102
+ const rs = tlv.encode(2, int.encode(sig.r));
2103
+ const ss = tlv.encode(2, int.encode(sig.s));
2104
+ const seq = rs + ss;
2105
+ return tlv.encode(48, seq);
2106
+ }
2107
+ };
2108
+ var DER = /* @__PURE__ */ (() => {
2109
+ Object.freeze(_DER._tlv);
2110
+ Object.freeze(_DER._int);
2111
+ return Object.freeze(_DER);
2112
+ })();
2113
+
2114
+ // ../../node_modules/@noble/curves/abstract/weierstrass.js
2115
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
2116
+ function _splitEndoScalar(k, basis, n) {
2117
+ aInRange("scalar", k, _0n5, n);
2118
+ const [[a1, b1], [a2, b2]] = basis;
2119
+ const c1 = divNearest(b2 * k, n);
2120
+ const c2 = divNearest(-b1 * k, n);
2121
+ let k1 = k - c1 * a1 - c2 * a2;
2122
+ let k2 = -c1 * b1 - c2 * b2;
2123
+ const k1neg = k1 < _0n5;
2124
+ const k2neg = k2 < _0n5;
2125
+ if (k1neg)
2126
+ k1 = -k1;
2127
+ if (k2neg)
2128
+ k2 = -k2;
2129
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
2130
+ if (k1 < _0n5 || k1 >= MAX_NUM || k2 < _0n5 || k2 >= MAX_NUM) {
2131
+ throw new Error("splitScalar (endomorphism): failed for k");
2132
+ }
2133
+ return { k1neg, k1, k2neg, k2 };
2134
+ }
2135
+ function validateSigFormat(format) {
2136
+ if (!["compact", "recovered", "der"].includes(format))
2137
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
2138
+ return format;
2139
+ }
2140
+ function validateSigOpts(opts, def) {
2141
+ validateObject(opts);
2142
+ const optsn = {};
2143
+ for (let optName of Object.keys(def)) {
2144
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
2145
+ }
2146
+ abool2(optsn.lowS, "lowS");
2147
+ abool2(optsn.prehash, "prehash");
2148
+ if (optsn.format !== void 0)
2149
+ validateSigFormat(optsn.format);
2150
+ return optsn;
2151
+ }
2152
+ var _0n5 = /* @__PURE__ */ BigInt(0);
2153
+ var _1n4 = /* @__PURE__ */ BigInt(1);
2154
+ var _2n2 = /* @__PURE__ */ BigInt(2);
2155
+ var _3n2 = /* @__PURE__ */ BigInt(3);
2156
+ var _4n3 = /* @__PURE__ */ BigInt(4);
2157
+ function weierstrass(params, extraOpts = {}) {
2158
+ const validated = createCurveFields("weierstrass", params, extraOpts);
2159
+ const Fp2 = validated.Fp;
2160
+ const Fn = validated.Fn;
2161
+ let CURVE = validated.CURVE;
2162
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
2163
+ validateObject(extraOpts, {}, {
2164
+ allowInfinityPoint: "boolean",
2165
+ clearCofactor: "function",
2166
+ isTorsionFree: "function",
2167
+ fromBytes: "function",
2168
+ toBytes: "function",
2169
+ endo: "object",
2170
+ randomBytes: "function"
2171
+ });
2172
+ const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes } = extraOpts;
2173
+ const randomBytes3 = extraOpts.randomBytes === void 0 ? randomBytes2 : extraOpts.randomBytes;
2174
+ if (endoOpts) {
2175
+ if (!Fp2.is0(CURVE.a) || typeof endoOpts.beta !== "bigint" || !Array.isArray(endoOpts.basises)) {
2176
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
2177
+ }
2178
+ }
2179
+ const endo = endoOpts ? {
2180
+ beta: endoOpts.beta,
2181
+ basises: endoOpts.basises.map((basis) => [...basis])
2182
+ } : void 0;
2183
+ const lengths = getWLengths(Fp2, Fn);
2184
+ function assertCompressionIsSupported() {
2185
+ if (!Fp2.isOdd)
2186
+ throw new Error("compression is not supported: Field does not have .isOdd()");
2187
+ }
2188
+ function pointToBytes(_c, point, isCompressed) {
2189
+ if (point.is0()) {
2190
+ if (!allowInfinityPoint)
2191
+ throw new Error("bad point: ZERO");
2192
+ return Uint8Array.of(0);
2193
+ }
2194
+ const { x, y } = point.toAffine();
2195
+ const bx = Fp2.toBytes(x);
2196
+ abool2(isCompressed, "isCompressed");
2197
+ if (isCompressed) {
2198
+ assertCompressionIsSupported();
2199
+ const hasEvenY = !Fp2.isOdd(y);
2200
+ return concatBytes2(pprefix(hasEvenY), bx);
2201
+ } else {
2202
+ return concatBytes2(Uint8Array.of(4), bx, Fp2.toBytes(y));
2203
+ }
2204
+ }
2205
+ function pointFromBytes(bytes) {
2206
+ abytes2(bytes, void 0, "Point");
2207
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
2208
+ const length = bytes.length;
2209
+ const head = bytes[0];
2210
+ const tail = bytes.subarray(1);
2211
+ if (allowInfinityPoint && length === 1 && head === 0)
2212
+ return { x: Fp2.ZERO, y: Fp2.ZERO };
2213
+ if (length === comp && (head === 2 || head === 3)) {
2214
+ const x = Fp2.fromBytes(tail);
2215
+ if (!Fp2.isValid(x))
2216
+ throw new Error("bad point: is not on curve, wrong x");
2217
+ const y2 = weierstrassEquation(x);
2218
+ let y;
2219
+ try {
2220
+ y = Fp2.sqrt(y2);
2221
+ } catch (sqrtError) {
2222
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
2223
+ throw new Error("bad point: is not on curve, sqrt error" + err);
2224
+ }
2225
+ assertCompressionIsSupported();
2226
+ const evenY = Fp2.isOdd(y);
2227
+ const evenH = (head & 1) === 1;
2228
+ if (evenH !== evenY)
2229
+ y = Fp2.neg(y);
2230
+ return { x, y };
2231
+ } else if (length === uncomp && head === 4) {
2232
+ const L = Fp2.BYTES;
2233
+ const x = Fp2.fromBytes(tail.subarray(0, L));
2234
+ const y = Fp2.fromBytes(tail.subarray(L, L * 2));
2235
+ if (!isValidXY(x, y))
2236
+ throw new Error("bad point: is not on curve");
2237
+ return { x, y };
2238
+ } else {
2239
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
2240
+ }
2241
+ }
2242
+ const encodePoint = toBytes === void 0 ? pointToBytes : toBytes;
2243
+ const decodePoint = fromBytes === void 0 ? pointFromBytes : fromBytes;
2244
+ const b3 = Fp2.mul(CURVE.b, _3n2);
2245
+ const mulA = Fp2.is0(CURVE.a) ? (_) => Fp2.ZERO : (x) => Fp2.mul(CURVE.a, x);
2246
+ function weierstrassEquation(x) {
2247
+ const x2 = Fp2.sqr(x);
2248
+ const x3 = Fp2.mul(x2, x);
2249
+ return Fp2.add(Fp2.add(x3, Fp2.mul(x, CURVE.a)), CURVE.b);
2250
+ }
2251
+ function isValidXY(x, y) {
2252
+ const left = Fp2.sqr(y);
2253
+ const right = weierstrassEquation(x);
2254
+ return Fp2.eql(left, right);
2255
+ }
2256
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
2257
+ throw new Error("bad curve params: generator point");
2258
+ const _4a3 = Fp2.mul(Fp2.pow(CURVE.a, _3n2), _4n3);
2259
+ const _27b2 = Fp2.mul(Fp2.sqr(CURVE.b), BigInt(27));
2260
+ if (Fp2.is0(Fp2.add(_4a3, _27b2)))
2261
+ throw new Error("bad curve params: a or b");
2262
+ function acoord(title, n, banZero = false) {
2263
+ if (!Fp2.isValid(n) || banZero && Fp2.is0(n))
2264
+ throw new Error(`bad point coordinate ${title}`);
2265
+ return typeof n === "object" && n !== null ? Fp2.create(n) : n;
2266
+ }
2267
+ function aprjpoint(other) {
2268
+ if (!(other instanceof Point))
2269
+ throw new Error("Weierstrass Point expected");
2270
+ }
2271
+ function splitEndoScalarN(k) {
2272
+ if (!endo || !endo.basises)
2273
+ throw new Error("no endo");
2274
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
2275
+ }
2276
+ function pushWnafPair(points, scalars, p, k) {
2277
+ if (!Fn.isValid(k))
2278
+ throw new RangeError("invalid scalar: out of range");
2279
+ if (endo) {
2280
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);
2281
+ const psi = new Point(Fp2.mul(p.X, endo.beta), p.Y, p.Z);
2282
+ points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);
2283
+ scalars.push(k1, k2);
2284
+ } else {
2285
+ points.push(p);
2286
+ scalars.push(k);
2287
+ }
2288
+ }
2289
+ const validityCache = /* @__PURE__ */ new WeakSet();
2290
+ const _Point = class _Point {
2291
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2292
+ constructor(X, Y, Z) {
2293
+ __publicField(this, "X");
2294
+ __publicField(this, "Y");
2295
+ __publicField(this, "Z");
2296
+ this.X = acoord("x", X);
2297
+ this.Y = acoord("y", Y, true);
2298
+ this.Z = acoord("z", Z);
2299
+ Object.freeze(this);
2300
+ }
2301
+ static CURVE() {
2302
+ return CURVE;
2303
+ }
2304
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2305
+ static fromAffine(p) {
2306
+ const { x, y } = p || {};
2307
+ if (!p || !Fp2.isValid(x) || !Fp2.isValid(y))
2308
+ throw new Error("invalid affine point");
2309
+ if (p instanceof _Point)
2310
+ throw new Error("projective point not allowed");
2311
+ if (Fp2.is0(x) && Fp2.is0(y))
2312
+ return _Point.ZERO;
2313
+ return new _Point(x, y, Fp2.ONE);
2314
+ }
2315
+ static fromBytes(bytes) {
2316
+ const P = _Point.fromAffine(decodePoint(abytes2(bytes, void 0, "point")));
2317
+ P.assertValidity();
2318
+ return P;
2319
+ }
2320
+ static fromHex(hex) {
2321
+ return _Point.fromBytes(hexToBytes2(hex));
2322
+ }
2323
+ get x() {
2324
+ return this.toAffine().x;
2325
+ }
2326
+ get y() {
2327
+ return this.toAffine().y;
2328
+ }
2329
+ /**
2330
+ * @param isLazy - true will defer table computation until the first multiplication
2331
+ */
2332
+ precompute(windowSize = 6, isLazy = true) {
2333
+ wnaf.setWindowSize(this, windowSize);
2334
+ if (!isLazy)
2335
+ this.multiply(_3n2);
2336
+ return this;
2337
+ }
2338
+ // TODO: return `this`
2339
+ /** A point on curve is valid if it conforms to equation. */
2340
+ assertValidity() {
2341
+ const p = this;
2342
+ if (p.is0()) {
2343
+ if (allowInfinityPoint && Fp2.is0(p.X) && Fp2.eql(p.Y, Fp2.ONE) && Fp2.is0(p.Z))
2344
+ return;
2345
+ throw new Error("bad point: ZERO");
2346
+ }
2347
+ if (validityCache.has(p))
2348
+ return;
2349
+ const { x, y } = p.toAffine();
2350
+ if (!Fp2.isValid(x) || !Fp2.isValid(y))
2351
+ throw new Error("bad point: x or y not field elements");
2352
+ if (!isValidXY(x, y))
2353
+ throw new Error("bad point: equation left != right");
2354
+ if (!p.isTorsionFree())
2355
+ throw new Error("bad point: not in prime-order subgroup");
2356
+ validityCache.add(p);
2357
+ }
2358
+ hasEvenY() {
2359
+ const { y } = this.toAffine();
2360
+ if (!Fp2.isOdd)
2361
+ throw new Error("Field doesn't support isOdd");
2362
+ return !Fp2.isOdd(y);
2363
+ }
2364
+ /** Compare one point to another. */
2365
+ equals(other) {
2366
+ aprjpoint(other);
2367
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2368
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2369
+ const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
2370
+ const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
2371
+ return U1 && U2;
2372
+ }
2373
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
2374
+ negate() {
2375
+ return new _Point(this.X, Fp2.neg(this.Y), this.Z);
2376
+ }
2377
+ // Renes-Costello-Batina exception-free doubling formula.
2378
+ // There is 30% faster Jacobian formula, but it is not complete.
2379
+ // https://eprint.iacr.org/2015/1060, algorithm 3
2380
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
2381
+ double() {
2382
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2383
+ let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
2384
+ let t0 = Fp2.mul(X1, X1);
2385
+ let t1 = Fp2.mul(Y1, Y1);
2386
+ let t2 = Fp2.mul(Z1, Z1);
2387
+ let t3 = Fp2.mul(X1, Y1);
2388
+ t3 = Fp2.add(t3, t3);
2389
+ Z3 = Fp2.mul(X1, Z1);
2390
+ Z3 = Fp2.add(Z3, Z3);
2391
+ X3 = mulA(Z3);
2392
+ Y3 = Fp2.mul(b3, t2);
2393
+ Y3 = Fp2.add(X3, Y3);
2394
+ X3 = Fp2.sub(t1, Y3);
2395
+ Y3 = Fp2.add(t1, Y3);
2396
+ Y3 = Fp2.mul(X3, Y3);
2397
+ X3 = Fp2.mul(t3, X3);
2398
+ Z3 = Fp2.mul(b3, Z3);
2399
+ t2 = mulA(t2);
2400
+ t3 = Fp2.sub(t0, t2);
2401
+ t3 = mulA(t3);
2402
+ t3 = Fp2.add(t3, Z3);
2403
+ Z3 = Fp2.add(t0, t0);
2404
+ t0 = Fp2.add(Z3, t0);
2405
+ t0 = Fp2.add(t0, t2);
2406
+ t0 = Fp2.mul(t0, t3);
2407
+ Y3 = Fp2.add(Y3, t0);
2408
+ t2 = Fp2.mul(Y1, Z1);
2409
+ t2 = Fp2.add(t2, t2);
2410
+ t0 = Fp2.mul(t2, t3);
2411
+ X3 = Fp2.sub(X3, t0);
2412
+ Z3 = Fp2.mul(t2, t1);
2413
+ Z3 = Fp2.add(Z3, Z3);
2414
+ Z3 = Fp2.add(Z3, Z3);
2415
+ return new _Point(X3, Y3, Z3);
2416
+ }
2417
+ // Renes-Costello-Batina exception-free addition formula.
2418
+ // There is 30% faster Jacobian formula, but it is not complete.
2419
+ // https://eprint.iacr.org/2015/1060, algorithm 1
2420
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2421
+ add(other) {
2422
+ aprjpoint(other);
2423
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2424
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2425
+ let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
2426
+ let t0 = Fp2.mul(X1, X2);
2427
+ let t1 = Fp2.mul(Y1, Y2);
2428
+ let t2 = Fp2.mul(Z1, Z2);
2429
+ let t3 = Fp2.add(X1, Y1);
2430
+ let t4 = Fp2.add(X2, Y2);
2431
+ t3 = Fp2.mul(t3, t4);
2432
+ t4 = Fp2.add(t0, t1);
2433
+ t3 = Fp2.sub(t3, t4);
2434
+ t4 = Fp2.add(X1, Z1);
2435
+ let t5 = Fp2.add(X2, Z2);
2436
+ t4 = Fp2.mul(t4, t5);
2437
+ t5 = Fp2.add(t0, t2);
2438
+ t4 = Fp2.sub(t4, t5);
2439
+ t5 = Fp2.add(Y1, Z1);
2440
+ X3 = Fp2.add(Y2, Z2);
2441
+ t5 = Fp2.mul(t5, X3);
2442
+ X3 = Fp2.add(t1, t2);
2443
+ t5 = Fp2.sub(t5, X3);
2444
+ Z3 = mulA(t4);
2445
+ X3 = Fp2.mul(b3, t2);
2446
+ Z3 = Fp2.add(X3, Z3);
2447
+ X3 = Fp2.sub(t1, Z3);
2448
+ Z3 = Fp2.add(t1, Z3);
2449
+ Y3 = Fp2.mul(X3, Z3);
2450
+ t1 = Fp2.add(t0, t0);
2451
+ t1 = Fp2.add(t1, t0);
2452
+ t2 = mulA(t2);
2453
+ t4 = Fp2.mul(b3, t4);
2454
+ t1 = Fp2.add(t1, t2);
2455
+ t2 = Fp2.sub(t0, t2);
2456
+ t2 = mulA(t2);
2457
+ t4 = Fp2.add(t4, t2);
2458
+ t0 = Fp2.mul(t1, t4);
2459
+ Y3 = Fp2.add(Y3, t0);
2460
+ t0 = Fp2.mul(t5, t4);
2461
+ X3 = Fp2.mul(t3, X3);
2462
+ X3 = Fp2.sub(X3, t0);
2463
+ t0 = Fp2.mul(t3, t1);
2464
+ Z3 = Fp2.mul(t5, Z3);
2465
+ Z3 = Fp2.add(Z3, t0);
2466
+ return new _Point(X3, Y3, Z3);
2467
+ }
2468
+ subtract(other) {
2469
+ aprjpoint(other);
2470
+ return this.add(other.negate());
2471
+ }
2472
+ is0() {
2473
+ return this.equals(_Point.ZERO);
2474
+ }
2475
+ /**
2476
+ * Constant time multiplication.
2477
+ * Uses precomputed tables (signed fixed-window wNAF) when available.
2478
+ * Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.
2479
+ * @param scalar - by which the point would be multiplied
2480
+ * @returns New point
2481
+ */
2482
+ multiply(scalar) {
2483
+ if (!Fn.isValidNot0(scalar))
2484
+ throw new RangeError("invalid scalar: out of range");
2485
+ const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
2486
+ return normalize([p, f])[0];
2487
+ }
2488
+ /**
2489
+ * Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting
2490
+ * when available (two half-width scalars sharing one halved doubling chain).
2491
+ * It's faster, but should only be used when you don't care about
2492
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
2493
+ */
2494
+ multiplyUnsafe(scalar) {
2495
+ const p = this;
2496
+ const sc = scalar;
2497
+ if (!Fn.isValid(sc))
2498
+ throw new RangeError("invalid scalar: out of range");
2499
+ if (sc === _0n5 || p.is0())
2500
+ return _Point.ZERO;
2501
+ if (sc === _1n4)
2502
+ return p;
2503
+ if (wnaf.hasWindowSize(this))
2504
+ return wnaf.mulUnsafe(p, sc, normalize);
2505
+ const points = [];
2506
+ const scalars = [];
2507
+ pushWnafPair(points, scalars, p, sc);
2508
+ return mulAddUnsafe(_Point, points, scalars);
2509
+ }
2510
+ /**
2511
+ * Non-constant-time double-scalar multiplication `a⋅this + b⋅other` (Strauss–Shamir).
2512
+ * Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism
2513
+ * (when available) halves the chain again by splitting each scalar into two half-width
2514
+ * parts. Used by ECDSA verification and public-key recovery for `R = u1⋅G + u2⋅P`.
2515
+ * Only for public scalars.
2516
+ */
2517
+ mulAddUnsafe(a, other, b) {
2518
+ aprjpoint(other);
2519
+ const points = [];
2520
+ const scalars = [];
2521
+ pushWnafPair(points, scalars, this, a);
2522
+ pushWnafPair(points, scalars, other, b);
2523
+ return mulAddUnsafe(_Point, points, scalars);
2524
+ }
2525
+ /**
2526
+ * Converts Projective point to affine (x, y) coordinates.
2527
+ * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
2528
+ * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
2529
+ */
2530
+ toAffine(invertedZ) {
2531
+ const p = this;
2532
+ let iz = invertedZ;
2533
+ if (iz != null && !Fp2.isValid(iz))
2534
+ throw new RangeError('"invertedZ" expected valid field element');
2535
+ const { X, Y, Z } = p;
2536
+ if (Fp2.eql(Z, Fp2.ONE))
2537
+ return { x: X, y: Y };
2538
+ const is0 = p.is0();
2539
+ if (iz == null)
2540
+ iz = is0 ? Fp2.ONE : Fp2.inv(Z);
2541
+ const x = Fp2.mul(X, iz);
2542
+ const y = Fp2.mul(Y, iz);
2543
+ const zz = Fp2.mul(Z, iz);
2544
+ if (is0)
2545
+ return { x: Fp2.ZERO, y: Fp2.ZERO };
2546
+ if (!Fp2.eql(zz, Fp2.ONE))
2547
+ throw new Error("invZ was invalid");
2548
+ return { x, y };
2549
+ }
2550
+ /**
2551
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
2552
+ * Always torsion-free for cofactor=1 curves.
2553
+ */
2554
+ isTorsionFree() {
2555
+ if (cofactor === _1n4)
2556
+ return true;
2557
+ if (isTorsionFree)
2558
+ return isTorsionFree(_Point, this);
2559
+ return wnaf.mulUnsafe(this, CURVE_ORDER).is0();
2560
+ }
2561
+ clearCofactor() {
2562
+ if (cofactor === _1n4)
2563
+ return this;
2564
+ if (clearCofactor)
2565
+ return clearCofactor(_Point, this);
2566
+ return this.multiplyUnsafe(cofactor);
2567
+ }
2568
+ isSmallOrder() {
2569
+ if (cofactor === _1n4)
2570
+ return this.is0();
2571
+ return this.clearCofactor().is0();
2572
+ }
2573
+ toBytes(isCompressed = true) {
2574
+ abool2(isCompressed, "isCompressed");
2575
+ this.assertValidity();
2576
+ return encodePoint(_Point, this, isCompressed);
2577
+ }
2578
+ toHex(isCompressed = true) {
2579
+ return bytesToHex2(this.toBytes(isCompressed));
2580
+ }
2581
+ toString() {
2582
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2583
+ }
2584
+ };
2585
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp2.ONE));
2586
+ __publicField(_Point, "ZERO", new _Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO));
2587
+ __publicField(_Point, "Fp", Fp2);
2588
+ __publicField(_Point, "Fn", Fn);
2589
+ let Point = _Point;
2590
+ const normalize = (points) => normalizeZ(Point, points);
2591
+ const wnaf = new ScalarMultiplier(Point, randomBytes3);
2592
+ if (wnaf.bits >= 6)
2593
+ Point.BASE.precompute(6);
2594
+ Object.freeze(Point.prototype);
2595
+ Object.freeze(Point);
2596
+ return Point;
2597
+ }
2598
+ function pprefix(hasEvenY) {
2599
+ return Uint8Array.of(hasEvenY ? 2 : 3);
2600
+ }
2601
+ function getWLengths(Fp2, Fn) {
2602
+ return {
2603
+ secretKey: Fn.BYTES,
2604
+ publicKey: 1 + Fp2.BYTES,
2605
+ publicKeyUncompressed: 1 + 2 * Fp2.BYTES,
2606
+ publicKeyHasPrefix: true,
2607
+ // Raw compact `(r || s)` signature width; DER and recovered signatures use
2608
+ // different lengths outside this helper.
2609
+ signature: 2 * Fn.BYTES
2610
+ };
2611
+ }
2612
+ function ecdh(Point, ecdhOpts = {}) {
2613
+ validatePointCons(Point);
2614
+ const { Fn } = Point;
2615
+ const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes2 : ecdhOpts.randomBytes;
2616
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), {
2617
+ seed: Math.max(getMinHashLength(Fn.ORDER), 16)
2618
+ });
2619
+ function isValidSecretKey(secretKey) {
2620
+ try {
2621
+ const num = Fn.fromBytes(secretKey);
2622
+ return Fn.isValidNot0(num);
2623
+ } catch (error) {
2624
+ return false;
2625
+ }
2626
+ }
2627
+ function isValidPublicKey(publicKey, isCompressed) {
2628
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
2629
+ try {
2630
+ const l = publicKey.length;
2631
+ if (isCompressed === true && l !== comp)
2632
+ return false;
2633
+ if (isCompressed === false && l !== publicKeyUncompressed)
2634
+ return false;
2635
+ return !Point.fromBytes(publicKey).is0();
2636
+ } catch (error) {
2637
+ return false;
2638
+ }
2639
+ }
2640
+ function randomSecretKey(seed) {
2641
+ seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
2642
+ return mapHashToField(abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
2643
+ }
2644
+ function getPublicKey(secretKey, isCompressed = true) {
2645
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
2646
+ }
2647
+ function isProbPub(item) {
2648
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
2649
+ const allowedLengths = Fn._lengths;
2650
+ if (!isBytes2(item))
2651
+ return void 0;
2652
+ const l = abytes2(item, void 0, "key").length;
2653
+ const isPub = l === publicKey || l === publicKeyUncompressed;
2654
+ const isSec = l === secretKey || !!allowedLengths?.includes(l);
2655
+ if (isPub && isSec)
2656
+ return void 0;
2657
+ return isPub;
2658
+ }
2659
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
2660
+ if (isProbPub(secretKeyA) === true)
2661
+ throw new Error("first arg must be private key");
2662
+ if (isProbPub(publicKeyB) === false)
2663
+ throw new Error("second arg must be public key");
2664
+ const s = Fn.fromBytes(secretKeyA);
2665
+ const b = Point.fromBytes(publicKeyB);
2666
+ if (b.is0())
2667
+ throw new Error("invalid public key: point at infinity");
2668
+ return b.multiply(s).toBytes(isCompressed);
2669
+ }
2670
+ const utils = {
2671
+ isValidSecretKey,
2672
+ isValidPublicKey,
2673
+ randomSecretKey
2674
+ };
2675
+ const keygen = createKeygen(randomSecretKey, getPublicKey);
2676
+ Object.freeze(utils);
2677
+ Object.freeze(lengths);
2678
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
2679
+ }
2680
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
2681
+ validatePointCons(Point);
2682
+ const hash_ = hash;
2683
+ ahash(hash_);
2684
+ validateObject(ecdsaOpts, {}, {
2685
+ hmac: "function",
2686
+ lowS: "boolean",
2687
+ randomBytes: "function",
2688
+ bits2int: "function",
2689
+ bits2int_modN: "function"
2690
+ });
2691
+ const opts = Object.assign({}, ecdsaOpts);
2692
+ const randomBytes3 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
2693
+ const hmac2 = opts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : opts.hmac;
2694
+ const { Fp: Fp2, Fn } = Point;
2695
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
2696
+ const blindLength = getMinHashLength(CURVE_ORDER);
2697
+ const csprng = probeRandomBytes(randomBytes3, blindLength);
2698
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);
2699
+ const defaultSigOpts = {
2700
+ prehash: true,
2701
+ lowS: typeof opts.lowS === "boolean" ? opts.lowS : true,
2702
+ format: "compact",
2703
+ extraEntropy: false
2704
+ };
2705
+ const hasLargeRecoveryLifts = CURVE_ORDER * _2n2 + _1n4 < Fp2.ORDER;
2706
+ function isBiggerThanHalfOrder(number) {
2707
+ const HALF = CURVE_ORDER >> _1n4;
2708
+ return number > HALF;
2709
+ }
2710
+ function validateRS(title, num) {
2711
+ if (!Fn.isValidNot0(num))
2712
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
2713
+ return num;
2714
+ }
2715
+ function assertFieldSignIsSupported() {
2716
+ if (!Fp2.isOdd)
2717
+ throw new Error("Field doesn't support isOdd");
2718
+ }
2719
+ function getRecoveryBit(x, y, r) {
2720
+ assertFieldSignIsSupported();
2721
+ return (x === r ? 0 : 2) | Number(Fp2.isOdd(y));
2722
+ }
2723
+ function assertRecoverableCurve() {
2724
+ if (hasLargeRecoveryLifts)
2725
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
2726
+ }
2727
+ function validateSigLength(bytes, format) {
2728
+ validateSigFormat(format);
2729
+ const size = lengths.signature;
2730
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
2731
+ return abytes2(bytes, sizer);
2732
+ }
2733
+ class Signature {
2734
+ constructor(r, s, recovery) {
2735
+ __publicField(this, "r");
2736
+ __publicField(this, "s");
2737
+ __publicField(this, "recovery");
2738
+ this.r = validateRS("r", r);
2739
+ this.s = validateRS("s", s);
2740
+ if (recovery != null) {
2741
+ assertRecoverableCurve();
2742
+ if (![0, 1, 2, 3].includes(recovery))
2743
+ throw new Error("invalid recovery id");
2744
+ this.recovery = recovery;
2745
+ }
2746
+ Object.freeze(this);
2747
+ }
2748
+ static fromBytes(bytes, format = defaultSigOpts.format) {
2749
+ validateSigLength(bytes, format);
2750
+ let recid;
2751
+ if (format === "der") {
2752
+ if (bytes.length > 2 * Fn.BYTES + 16)
2753
+ throw new DER.Err("invalid signature: DER signature too long");
2754
+ const { r: r2, s: s2 } = DER.toSig(abytes2(bytes), Fn.BYTES + 1);
2755
+ return new Signature(r2, s2);
2756
+ }
2757
+ if (format === "recovered") {
2758
+ recid = bytes[0];
2759
+ format = "compact";
2760
+ bytes = bytes.subarray(1);
2761
+ }
2762
+ const L = lengths.signature / 2;
2763
+ const r = bytes.subarray(0, L);
2764
+ const s = bytes.subarray(L, L * 2);
2765
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
2766
+ }
2767
+ static fromHex(hex, format) {
2768
+ return this.fromBytes(hexToBytes2(hex), format);
2769
+ }
2770
+ assertRecovery() {
2771
+ const { recovery } = this;
2772
+ if (recovery == null)
2773
+ throw new Error("invalid recovery id: must be present");
2774
+ return recovery;
2775
+ }
2776
+ addRecoveryBit(recovery) {
2777
+ return new Signature(this.r, this.s, recovery);
2778
+ }
2779
+ // Unlike the top-level helper below, this method expects a digest that has
2780
+ // already been hashed to the curve's message representative.
2781
+ recoverPublicKey(messageHash) {
2782
+ const { r, s } = this;
2783
+ const recovery = this.assertRecovery();
2784
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
2785
+ if (!Fp2.isValid(radj))
2786
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
2787
+ const x = Fp2.toBytes(radj);
2788
+ const R = Point.fromBytes(concatBytes2(pprefix((recovery & 1) === 0), x));
2789
+ const ir = Fn.inv(radj);
2790
+ const h = bits2int_modN(abytes2(messageHash, void 0, "msgHash"));
2791
+ const u1 = Fn.create(-h * ir);
2792
+ const u2 = Fn.create(s * ir);
2793
+ const Q = Point.BASE.mulAddUnsafe(u1, R, u2);
2794
+ if (Q.is0())
2795
+ throw new Error("invalid recovery: point at infinify");
2796
+ Q.assertValidity();
2797
+ return Q;
2798
+ }
2799
+ // Signatures should be low-s, to prevent malleability.
2800
+ hasHighS() {
2801
+ return isBiggerThanHalfOrder(this.s);
2802
+ }
2803
+ toBytes(format = defaultSigOpts.format) {
2804
+ validateSigFormat(format);
2805
+ if (format === "der")
2806
+ return hexToBytes2(DER.hexFromSig(this));
2807
+ const { r, s } = this;
2808
+ const rb = Fn.toBytes(r);
2809
+ const sb = Fn.toBytes(s);
2810
+ if (format === "recovered") {
2811
+ assertRecoverableCurve();
2812
+ return concatBytes2(Uint8Array.of(this.assertRecovery()), rb, sb);
2813
+ }
2814
+ return concatBytes2(rb, sb);
2815
+ }
2816
+ toHex(format) {
2817
+ return bytesToHex2(this.toBytes(format));
2818
+ }
2819
+ }
2820
+ Object.freeze(Signature.prototype);
2821
+ Object.freeze(Signature);
2822
+ const bits2int = opts.bits2int === void 0 ? function bits2int_def(bytes) {
2823
+ if (bytes.length > 8192)
2824
+ throw new Error("input is too large");
2825
+ const num = bytesToNumberBE(bytes);
2826
+ const delta = bytes.length * 8 - fnBits;
2827
+ return delta > 0 ? num >> BigInt(delta) : num;
2828
+ } : opts.bits2int;
2829
+ const bits2int_modN = opts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
2830
+ return Fn.create(bits2int(bytes));
2831
+ } : opts.bits2int_modN;
2832
+ const ORDER_MASK = bitMask(fnBits);
2833
+ function int2octets(num) {
2834
+ aInRange("num < 2^" + fnBits, num, _0n5, ORDER_MASK);
2835
+ return Fn.toBytes(num);
2836
+ }
2837
+ function validateMsgAndHash(message, prehash) {
2838
+ abytes2(message, void 0, "message");
2839
+ return prehash ? abytes2(hash_(message), void 0, "prehashed message") : message;
2840
+ }
2841
+ function prepSig(message, secretKey, opts2) {
2842
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts2, defaultSigOpts);
2843
+ message = validateMsgAndHash(message, prehash);
2844
+ const h1int = bits2int_modN(message);
2845
+ const d = Fn.fromBytes(secretKey);
2846
+ if (!Fn.isValidNot0(d))
2847
+ throw new Error("invalid private key");
2848
+ const seedArgs = [int2octets(d), int2octets(h1int)];
2849
+ if (extraEntropy != null && extraEntropy !== false) {
2850
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
2851
+ seedArgs.push(abytes2(e, void 0, "extraEntropy"));
2852
+ }
2853
+ const seed = concatBytes2(...seedArgs);
2854
+ const m = h1int;
2855
+ function k2sig(kBytes) {
2856
+ const k = bits2int(kBytes);
2857
+ if (!Fn.isValidNot0(k))
2858
+ return;
2859
+ const q = Point.BASE.multiply(k).toAffine();
2860
+ const r = Fn.create(q.x);
2861
+ if (r === _0n5)
2862
+ return;
2863
+ let s;
2864
+ if (csprng !== void 0) {
2865
+ const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));
2866
+ const ibk = Fn.inv(Fn.mul(b, k));
2867
+ const bm = Fn.mul(b, m);
2868
+ const bd = Fn.mul(b, d);
2869
+ s = Fn.create(ibk * Fn.create(bm + bd * r));
2870
+ } else {
2871
+ const ik = invertCt(k, CURVE_ORDER);
2872
+ s = Fn.create(ik * Fn.create(m + r * d));
2873
+ }
2874
+ if (s === _0n5)
2875
+ return;
2876
+ let recovery = getRecoveryBit(q.x, q.y, r);
2877
+ let normS = s;
2878
+ if (lowS && isBiggerThanHalfOrder(s)) {
2879
+ normS = Fn.neg(s);
2880
+ recovery ^= 1;
2881
+ }
2882
+ return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
2883
+ }
2884
+ return { seed, k2sig };
2885
+ }
2886
+ function sign(message, secretKey, opts2 = {}) {
2887
+ const { seed, k2sig } = prepSig(message, secretKey, opts2);
2888
+ const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac2);
2889
+ const sig = drbg(seed, k2sig);
2890
+ return sig.toBytes(opts2.format);
2891
+ }
2892
+ function verify(signature, message, publicKey, opts2 = {}) {
2893
+ const { lowS, prehash, format } = validateSigOpts(opts2, defaultSigOpts);
2894
+ publicKey = abytes2(publicKey, void 0, "publicKey");
2895
+ message = validateMsgAndHash(message, prehash);
2896
+ if (!isBytes2(signature)) {
2897
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
2898
+ throw new Error("verify expects Uint8Array signature" + end);
2899
+ }
2900
+ validateSigLength(signature, format);
2901
+ try {
2902
+ const sig = Signature.fromBytes(signature, format);
2903
+ const P = Point.fromBytes(publicKey);
2904
+ if (P.is0())
2905
+ return false;
2906
+ if (lowS && sig.hasHighS())
2907
+ return false;
2908
+ const { r, s } = sig;
2909
+ const h = bits2int_modN(message);
2910
+ const is = Fn.inv(s);
2911
+ const u1 = Fn.create(h * is);
2912
+ const u2 = Fn.create(r * is);
2913
+ const R = Point.BASE.mulAddUnsafe(u1, P, u2);
2914
+ if (R.is0())
2915
+ return false;
2916
+ const q = R.toAffine();
2917
+ const v = Fn.create(q.x);
2918
+ if (v !== r)
2919
+ return false;
2920
+ if (format === "recovered" && sig.recovery !== getRecoveryBit(q.x, q.y, r))
2921
+ return false;
2922
+ return true;
2923
+ } catch (e) {
2924
+ return false;
2925
+ }
2926
+ }
2927
+ function recoverPublicKey(signature, message, opts2 = {}) {
2928
+ const { prehash } = validateSigOpts(opts2, defaultSigOpts);
2929
+ message = validateMsgAndHash(message, prehash);
2930
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
2931
+ }
2932
+ return Object.freeze({
2933
+ keygen,
2934
+ getPublicKey,
2935
+ getSharedSecret,
2936
+ utils,
2937
+ lengths,
2938
+ Point,
2939
+ sign,
2940
+ verify,
2941
+ recoverPublicKey,
2942
+ Signature,
2943
+ hash: hash_
2944
+ });
2945
+ }
2946
+
2947
+ // ../../node_modules/@noble/curves/secp256k1.js
2948
+ var secp256k1_CURVE = {
2949
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
2950
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
2951
+ h: BigInt(1),
2952
+ a: BigInt(0),
2953
+ b: BigInt(7),
2954
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
2955
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
2956
+ };
2957
+ var secp256k1_ENDO = {
2958
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
2959
+ basises: [
2960
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
2961
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
2962
+ ]
2963
+ };
2964
+ var _2n3 = /* @__PURE__ */ BigInt(2);
2965
+ function sqrtMod(y) {
2966
+ const P = secp256k1_CURVE.p;
2967
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
2968
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
2969
+ const b2 = y * y * y % P;
2970
+ const b3 = b2 * b2 * y % P;
2971
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
2972
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
2973
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
2974
+ const b22 = pow2(b11, _11n, P) * b11 % P;
2975
+ const b44 = pow2(b22, _22n, P) * b22 % P;
2976
+ const b88 = pow2(b44, _44n, P) * b44 % P;
2977
+ const b176 = pow2(b88, _88n, P) * b88 % P;
2978
+ const b220 = pow2(b176, _44n, P) * b44 % P;
2979
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
2980
+ const t1 = pow2(b223, _23n, P) * b22 % P;
2981
+ const t2 = pow2(t1, _6n, P) * b2 % P;
2982
+ const root = pow2(t2, _2n3, P);
2983
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
2984
+ throw new Error("Cannot find square root");
2985
+ return root;
2986
+ }
2987
+ var Fpk1 = /* @__PURE__ */ Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
2988
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
2989
+ Fp: Fpk1,
2990
+ endo: secp256k1_ENDO
2991
+ });
2992
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
2993
+
2994
+ // ../../node_modules/@noble/curves/abstract/edwards.js
2995
+ var _0n6 = /* @__PURE__ */ BigInt(0);
2996
+ var _1n5 = /* @__PURE__ */ BigInt(1);
2997
+ var _2n4 = /* @__PURE__ */ BigInt(2);
2998
+ var _4n4 = /* @__PURE__ */ BigInt(4);
2999
+ var _8n2 = /* @__PURE__ */ BigInt(8);
3000
+ function isEdValidXY(Fp2, CURVE, x, y) {
3001
+ const x2 = Fp2.sqr(x);
3002
+ const y2 = Fp2.sqr(y);
3003
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
3004
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
3005
+ return Fp2.eql(left, right);
3006
+ }
3007
+ function edwards(params, extraOpts = {}) {
3008
+ validateObject(extraOpts, {}, {}, "extraOpts");
3009
+ const opts = extraOpts;
3010
+ const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
3011
+ const { Fp: Fp2, Fn } = validated;
3012
+ let CURVE = validated.CURVE;
3013
+ const { h: cofactor } = CURVE;
3014
+ if (FpLegendre(Fp2, CURVE.a) !== 1)
3015
+ throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
3016
+ if (FpLegendre(Fp2, CURVE.d) !== -1)
3017
+ throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
3018
+ validateObject(opts, {}, { uvRatio: "function", randomBytes: "function" });
3019
+ const randomBytes3 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
3020
+ const MASK = _2n4 << BigInt(Fp2.BYTES * 8) - _1n5;
3021
+ function isOdd(n) {
3022
+ if (!Fp2.isOdd)
3023
+ throw new Error("Field does not have .isOdd()");
3024
+ return Fp2.isOdd(n);
3025
+ }
3026
+ const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
3027
+ try {
3028
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
3029
+ } catch (e) {
3030
+ return { isValid: false, value: _0n6 };
3031
+ }
3032
+ } : opts.uvRatio;
3033
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
3034
+ throw new Error("bad curve params: generator point");
3035
+ const mulA = Fp2.eql(CURVE.a, Fp2.neg(Fp2.ONE)) ? (x) => Fp2.neg(x) : Fp2.eql(CURVE.a, Fp2.ONE) ? (x) => x : (x) => Fp2.mul(CURVE.a, x);
3036
+ function acoord(title, n, banZero = false) {
3037
+ const min = banZero ? _1n5 : _0n6;
3038
+ aInRange("coordinate " + title, n, min, MASK);
3039
+ return n;
3040
+ }
3041
+ function aedpoint(other) {
3042
+ if (!(other instanceof Point))
3043
+ throw new Error("EdwardsPoint expected");
3044
+ }
3045
+ const _Point = class _Point {
3046
+ constructor(X, Y, Z, T) {
3047
+ __publicField(this, "X");
3048
+ __publicField(this, "Y");
3049
+ __publicField(this, "Z");
3050
+ __publicField(this, "T");
3051
+ this.X = acoord("x", X);
3052
+ this.Y = acoord("y", Y);
3053
+ this.Z = acoord("z", Z, true);
3054
+ this.T = acoord("t", T);
3055
+ Object.freeze(this);
3056
+ }
3057
+ static CURVE() {
3058
+ return CURVE;
3059
+ }
3060
+ /**
3061
+ * Create one extended Edwards point from affine coordinates.
3062
+ * Does NOT validate that the point is on-curve or torsion-free.
3063
+ * Use `.assertValidity()` on adversarial inputs.
3064
+ */
3065
+ static fromAffine(p) {
3066
+ if (p instanceof _Point)
3067
+ throw new Error("extended point not allowed");
3068
+ const { x, y } = p || {};
3069
+ acoord("x", x);
3070
+ acoord("y", y);
3071
+ return new _Point(x, y, Fp2.ONE, Fp2.mul(x, y));
3072
+ }
3073
+ // Uses algo from RFC8032 5.1.3.
3074
+ static fromBytes(bytes, zip215 = false) {
3075
+ const len = Fp2.BYTES;
3076
+ const { a, d } = CURVE;
3077
+ bytes = copyBytes(abytes2(bytes, len, "point"));
3078
+ abool2(zip215, "zip215");
3079
+ const normed = copyBytes(bytes);
3080
+ const lastByte = bytes[len - 1];
3081
+ normed[len - 1] = lastByte & ~128;
3082
+ const y = bytesToNumberLE(normed);
3083
+ const max = zip215 ? MASK : Fp2.ORDER;
3084
+ aInRange("point.y", y, _0n6, max);
3085
+ const y2 = Fp2.sqr(y);
3086
+ const u = Fp2.sub(y2, Fp2.ONE);
3087
+ const v = Fp2.sub(Fp2.mulN(d, y2), a);
3088
+ let { isValid, value: x } = uvRatio2(u, v);
3089
+ if (!isValid)
3090
+ throw new Error("bad point: invalid y coordinate");
3091
+ const isXOdd = isOdd(x);
3092
+ const isLastByteOdd = (lastByte & 128) !== 0;
3093
+ if (!zip215 && Fp2.is0(x) && isLastByteOdd)
3094
+ throw new Error("bad point: x=0 and x_0=1");
3095
+ if (isLastByteOdd !== isXOdd)
3096
+ x = Fp2.neg(x);
3097
+ return _Point.fromAffine({ x, y });
3098
+ }
3099
+ static fromHex(hex, zip215 = false) {
3100
+ return _Point.fromBytes(hexToBytes2(hex), zip215);
3101
+ }
3102
+ get x() {
3103
+ return this.toAffine().x;
3104
+ }
3105
+ get y() {
3106
+ return this.toAffine().y;
3107
+ }
3108
+ precompute(windowSize = 6, isLazy = true) {
3109
+ wnaf.setWindowSize(this, windowSize);
3110
+ if (!isLazy)
3111
+ this.multiply(_2n4);
3112
+ return this;
3113
+ }
3114
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
3115
+ assertValidity() {
3116
+ const p = this;
3117
+ const { a, d } = CURVE;
3118
+ if (p.is0())
3119
+ throw new Error("bad point: ZERO");
3120
+ const { X, Y, Z, T } = p;
3121
+ const X2 = Fp2.sqr(X);
3122
+ const Y2 = Fp2.sqr(Y);
3123
+ const Z2 = Fp2.sqr(Z);
3124
+ const Z4 = Fp2.sqr(Z2);
3125
+ const aX2 = Fp2.mul(X2, a);
3126
+ const left = Fp2.mul(Fp2.add(aX2, Y2), Z2);
3127
+ const right = Fp2.add(Z4, Fp2.mul(d, Fp2.mul(X2, Y2)));
3128
+ if (!Fp2.eql(left, right))
3129
+ throw new Error("bad point: equation left != right (1)");
3130
+ const XY = Fp2.mul(X, Y);
3131
+ const ZT = Fp2.mul(Z, T);
3132
+ if (!Fp2.eql(XY, ZT))
3133
+ throw new Error("bad point: equation left != right (2)");
3134
+ }
3135
+ // Compare one point to another.
3136
+ equals(other) {
3137
+ aedpoint(other);
3138
+ const { X: X1, Y: Y1, Z: Z1 } = this;
3139
+ const { X: X2, Y: Y2, Z: Z2 } = other;
3140
+ const X1Z2 = Fp2.mul(X1, Z2);
3141
+ const X2Z1 = Fp2.mul(X2, Z1);
3142
+ const Y1Z2 = Fp2.mul(Y1, Z2);
3143
+ const Y2Z1 = Fp2.mul(Y2, Z1);
3144
+ return Fp2.eql(X1Z2, X2Z1) && Fp2.eql(Y1Z2, Y2Z1);
3145
+ }
3146
+ is0() {
3147
+ return this.equals(_Point.ZERO);
3148
+ }
3149
+ negate() {
3150
+ return new _Point(Fp2.neg(this.X), this.Y, this.Z, Fp2.neg(this.T));
3151
+ }
3152
+ // Fast algo for doubling Extended Point.
3153
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
3154
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
3155
+ double() {
3156
+ const { X: X1, Y: Y1, Z: Z1 } = this;
3157
+ const A = Fp2.sqr(X1);
3158
+ const B2 = Fp2.sqr(Y1);
3159
+ const C = Fp2.mul(Fp2.sqr(Z1), _2n4);
3160
+ const D = mulA(A);
3161
+ const x1y1 = Fp2.addN(X1, Y1);
3162
+ const E = Fp2.sub(Fp2.subN(Fp2.sqr(x1y1), A), B2);
3163
+ const G = Fp2.addN(D, B2);
3164
+ const F = Fp2.subN(G, C);
3165
+ const H = Fp2.subN(D, B2);
3166
+ const X3 = Fp2.mul(E, F);
3167
+ const Y3 = Fp2.mul(G, H);
3168
+ const T3 = Fp2.mul(E, H);
3169
+ const Z3 = Fp2.mul(F, G);
3170
+ return new _Point(X3, Y3, Z3, T3);
3171
+ }
3172
+ // Fast algo for adding 2 Extended Points.
3173
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
3174
+ // Cost: 9M + 1*a + 1*d + 7add.
3175
+ add(other) {
3176
+ aedpoint(other);
3177
+ const { d } = CURVE;
3178
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
3179
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
3180
+ const A = Fp2.mul(X1, X2);
3181
+ const B2 = Fp2.mul(Y1, Y2);
3182
+ const C = Fp2.mul(Fp2.mulN(T1, d), T2);
3183
+ const D = Fp2.mul(Z1, Z2);
3184
+ const E = Fp2.sub(Fp2.subN(Fp2.mulN(Fp2.addN(X1, Y1), Fp2.addN(X2, Y2)), A), B2);
3185
+ const F = Fp2.subN(D, C);
3186
+ const G = Fp2.addN(D, C);
3187
+ const H = Fp2.sub(B2, mulA(A));
3188
+ const X3 = Fp2.mul(E, F);
3189
+ const Y3 = Fp2.mul(G, H);
3190
+ const T3 = Fp2.mul(E, H);
3191
+ const Z3 = Fp2.mul(F, G);
3192
+ return new _Point(X3, Y3, Z3, T3);
3193
+ }
3194
+ subtract(other) {
3195
+ aedpoint(other);
3196
+ return this.add(other.negate());
3197
+ }
3198
+ // Constant-time multiplication.
3199
+ multiply(scalar) {
3200
+ if (!Fn.isValidNot0(scalar))
3201
+ throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
3202
+ const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
3203
+ return normalize([p, f])[0];
3204
+ }
3205
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
3206
+ // It's faster, but should only be used when you don't care about
3207
+ // an exposed private key e.g. sig verification.
3208
+ // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
3209
+ // n and larger values are rejected instead of being reduced mod n to the identity point.
3210
+ multiplyUnsafe(scalar) {
3211
+ if (!Fn.isValid(scalar))
3212
+ throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
3213
+ if (scalar === _0n6)
3214
+ return _Point.ZERO;
3215
+ if (this.is0() || scalar === _1n5)
3216
+ return this;
3217
+ return wnaf.mulUnsafe(this, scalar, normalize);
3218
+ }
3219
+ // Checks if point is of small order.
3220
+ // If you add something to small order point, you will have "dirty"
3221
+ // point with torsion component.
3222
+ // Clears cofactor and checks if the result is 0.
3223
+ isSmallOrder() {
3224
+ return this.clearCofactor().is0();
3225
+ }
3226
+ // Multiplies point by curve order and checks if the result is 0.
3227
+ // Returns `false` is the point is dirty.
3228
+ isTorsionFree() {
3229
+ return wnaf.mulUnsafe(this, CURVE.n).is0();
3230
+ }
3231
+ // Converts Extended point to default (x, y) coordinates.
3232
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
3233
+ toAffine(invertedZ) {
3234
+ const p = this;
3235
+ let iz = invertedZ;
3236
+ if (iz != null && typeof iz !== "bigint")
3237
+ throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
3238
+ const { X, Y, Z } = p;
3239
+ const is0 = p.is0();
3240
+ if (iz == null)
3241
+ iz = is0 ? Fp2.create(_8n2) : Fp2.inv(Z);
3242
+ const x = Fp2.mul(X, iz);
3243
+ const y = Fp2.mul(Y, iz);
3244
+ const zz = Fp2.mul(Z, iz);
3245
+ if (is0)
3246
+ return { x: Fp2.ZERO, y: Fp2.ONE };
3247
+ if (!Fp2.eql(zz, Fp2.ONE))
3248
+ throw new Error("invZ was invalid");
3249
+ return { x, y };
3250
+ }
3251
+ clearCofactor() {
3252
+ if (cofactor === _1n5)
3253
+ return this;
3254
+ if (cofactor === _2n4)
3255
+ return this.double();
3256
+ if (cofactor === _4n4)
3257
+ return this.double().double();
3258
+ if (cofactor === _8n2)
3259
+ return this.double().double().double();
3260
+ return this.multiplyUnsafe(cofactor);
3261
+ }
3262
+ toBytes() {
3263
+ const { x, y } = this.toAffine();
3264
+ const bytes = Fp2.toBytes(y);
3265
+ bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
3266
+ return bytes;
3267
+ }
3268
+ toHex() {
3269
+ return bytesToHex2(this.toBytes());
3270
+ }
3271
+ toString() {
3272
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
3273
+ }
3274
+ };
3275
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp2.ONE, Fp2.mul(CURVE.Gx, CURVE.Gy)));
3276
+ __publicField(_Point, "ZERO", new _Point(Fp2.ZERO, Fp2.ONE, Fp2.ONE, Fp2.ZERO));
3277
+ __publicField(_Point, "Fp", Fp2);
3278
+ __publicField(_Point, "Fn", Fn);
3279
+ let Point = _Point;
3280
+ const normalize = (points) => normalizeZ(Point, points);
3281
+ const wnaf = new ScalarMultiplier(Point, randomBytes3);
3282
+ if (wnaf.bits >= 6)
3283
+ Point.BASE.precompute(6);
3284
+ Object.freeze(Point.prototype);
3285
+ Object.freeze(Point);
3286
+ return Point;
3287
+ }
3288
+ function eddsa(Point, cHash, eddsaOpts = {}) {
3289
+ validatePointCons(Point);
3290
+ if (typeof cHash !== "function")
3291
+ throw new Error('"hash" function param is required');
3292
+ const hash = cHash;
3293
+ const opts = eddsaOpts;
3294
+ validateObject(opts, {}, {
3295
+ adjustScalarBytes: "function",
3296
+ randomBytes: "function",
3297
+ domain: "function",
3298
+ prehash: "function",
3299
+ zip215: "boolean",
3300
+ mapToCurve: "function",
3301
+ toMontgomery: "function",
3302
+ toMontgomerySecret: "function"
3303
+ });
3304
+ const { prehash } = opts;
3305
+ const { BASE, Fp: Fp2, Fn } = Point;
3306
+ const outputLen = hash.outputLen;
3307
+ const expectedLen = 2 * Fp2.BYTES;
3308
+ if (outputLen !== void 0) {
3309
+ asafenumber(outputLen, "hash.outputLen");
3310
+ if (outputLen !== expectedLen)
3311
+ throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
3312
+ }
3313
+ const randomBytes3 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
3314
+ const toMontgomery2 = opts.toMontgomery;
3315
+ const toMontgomerySecret2 = opts.toMontgomerySecret;
3316
+ const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
3317
+ const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
3318
+ abool2(phflag, "phflag");
3319
+ if (ctx.length || phflag)
3320
+ throw new Error("Contexts/pre-hash are not supported");
3321
+ return data;
3322
+ } : opts.domain;
3323
+ function modN_LE(hash2) {
3324
+ return Fn.create(bytesToNumberLE(hash2));
3325
+ }
3326
+ function getPrivateScalar(key) {
3327
+ const len = lengths.secretKey;
3328
+ abytes2(key, lengths.secretKey, "secretKey");
3329
+ const hashed = abytes2(hash(key), 2 * len, "hashedSecretKey");
3330
+ const head = adjustScalarBytes2(hashed.slice(0, len));
3331
+ const prefix = hashed.slice(len, 2 * len);
3332
+ const scalar = modN_LE(head);
3333
+ return { head, prefix, scalar };
3334
+ }
3335
+ function getExtendedPublicKey(secretKey) {
3336
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
3337
+ const point = BASE.multiply(scalar);
3338
+ const pointBytes = point.toBytes();
3339
+ return { head, prefix, scalar, point, pointBytes };
3340
+ }
3341
+ function getPublicKey(secretKey) {
3342
+ return getExtendedPublicKey(secretKey).pointBytes;
3343
+ }
3344
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
3345
+ const msg = concatBytes2(...msgs);
3346
+ return modN_LE(hash(domain(msg, abytes2(context, void 0, "context"), !!prehash)));
3347
+ }
3348
+ function sign(msg, secretKey, options = {}) {
3349
+ validateObject(options, {}, {}, "options");
3350
+ msg = copyBytes(abytes2(msg, void 0, "message"));
3351
+ if (prehash)
3352
+ msg = prehash(msg);
3353
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
3354
+ const r = hashDomainToScalar(options.context, prefix, msg);
3355
+ const R = BASE.multiply(r).toBytes();
3356
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
3357
+ const s = Fn.create(r + k * scalar);
3358
+ if (!Fn.isValid(s))
3359
+ throw new Error("sign failed: invalid s");
3360
+ const rs = concatBytes2(R, Fn.toBytes(s));
3361
+ return abytes2(rs, lengths.signature, "result");
3362
+ }
3363
+ const verifyOpts = {
3364
+ zip215: opts.zip215
3365
+ };
3366
+ function verify(sig, msg, publicKey, options = verifyOpts) {
3367
+ validateObject(options);
3368
+ const { context } = options;
3369
+ const zip215 = options.zip215 === void 0 ? !!verifyOpts.zip215 : options.zip215;
3370
+ const len = lengths.signature;
3371
+ sig = abytes2(sig, len, "signature");
3372
+ msg = abytes2(msg, void 0, "message");
3373
+ publicKey = abytes2(publicKey, lengths.publicKey, "publicKey");
3374
+ if (zip215 !== void 0)
3375
+ abool2(zip215, "zip215");
3376
+ if (prehash)
3377
+ msg = prehash(msg);
3378
+ const mid = len / 2;
3379
+ const r = sig.subarray(0, mid);
3380
+ const s = bytesToNumberLE(sig.subarray(mid, len));
3381
+ let A, R, SB;
3382
+ try {
3383
+ A = Point.fromBytes(publicKey, zip215);
3384
+ R = Point.fromBytes(r, zip215);
3385
+ SB = BASE.multiplyUnsafe(s);
3386
+ } catch (error) {
3387
+ return false;
3388
+ }
3389
+ if (!zip215 && A.isSmallOrder())
3390
+ return false;
3391
+ const k = hashDomainToScalar(context, r, publicKey, msg);
3392
+ const RkA = R.add(A.multiplyUnsafe(k));
3393
+ return RkA.subtract(SB).clearCofactor().is0();
3394
+ }
3395
+ const _size = Fp2.BYTES;
3396
+ const lengths = {
3397
+ secretKey: _size,
3398
+ publicKey: _size,
3399
+ signature: 2 * _size,
3400
+ seed: _size
3401
+ };
3402
+ function randomSecretKey(seed) {
3403
+ seed = seed === void 0 ? randomBytes3(lengths.seed) : seed;
3404
+ return abytes2(seed, lengths.seed, "seed");
3405
+ }
3406
+ function isValidSecretKey(key) {
3407
+ return isBytes2(key) && key.length === lengths.secretKey;
3408
+ }
3409
+ function isValidPublicKey(key, zip215) {
3410
+ try {
3411
+ return !!Point.fromBytes(key, zip215 === void 0 ? verifyOpts.zip215 : zip215);
3412
+ } catch (error) {
3413
+ return false;
3414
+ }
3415
+ }
3416
+ const utils = {
3417
+ getExtendedPublicKey,
3418
+ randomSecretKey,
3419
+ isValidSecretKey,
3420
+ isValidPublicKey,
3421
+ /** Converts an Edwards public key to a companion Montgomery public key. */
3422
+ toMontgomery(publicKey) {
3423
+ if (toMontgomery2 === void 0)
3424
+ throw new Error("Montgomery conversion is not supported for this curve");
3425
+ return toMontgomery2(Point.fromBytes(publicKey));
3426
+ },
3427
+ toMontgomerySecret(secretKey) {
3428
+ if (toMontgomerySecret2 === void 0)
3429
+ throw new Error("Montgomery conversion is not supported for this curve");
3430
+ return toMontgomerySecret2(secretKey);
3431
+ }
3432
+ };
3433
+ Object.freeze(lengths);
3434
+ Object.freeze(utils);
3435
+ return Object.freeze({
3436
+ keygen: createKeygen(randomSecretKey, getPublicKey),
3437
+ getPublicKey,
3438
+ sign,
3439
+ verify,
3440
+ utils,
3441
+ Point,
3442
+ lengths
3443
+ });
3444
+ }
3445
+
3446
+ // ../../node_modules/@noble/curves/ed25519.js
3447
+ var _1n6 = /* @__PURE__ */ BigInt(1);
3448
+ var _2n5 = /* @__PURE__ */ BigInt(2);
3449
+ var _5n2 = /* @__PURE__ */ BigInt(5);
3450
+ var _8n3 = /* @__PURE__ */ BigInt(8);
3451
+ var ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
3452
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
3453
+ p: ed25519_CURVE_p,
3454
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
3455
+ h: _8n3,
3456
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
3457
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
3458
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
3459
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
3460
+ }))();
3461
+ function ed25519_pow_2_252_3(x) {
3462
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
3463
+ const P = ed25519_CURVE_p;
3464
+ const x2 = x * x % P;
3465
+ const b2 = x2 * x % P;
3466
+ const b4 = pow2(b2, _2n5, P) * b2 % P;
3467
+ const b5 = pow2(b4, _1n6, P) * x % P;
3468
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
3469
+ const b20 = pow2(b10, _10n, P) * b10 % P;
3470
+ const b40 = pow2(b20, _20n, P) * b20 % P;
3471
+ const b80 = pow2(b40, _40n, P) * b40 % P;
3472
+ const b160 = pow2(b80, _80n, P) * b80 % P;
3473
+ const b240 = pow2(b160, _80n, P) * b80 % P;
3474
+ const b250 = pow2(b240, _10n, P) * b10 % P;
3475
+ const pow_p_5_8 = pow2(b250, _2n5, P) * x % P;
3476
+ return { pow_p_5_8, b2 };
3477
+ }
3478
+ function adjustScalarBytes(bytes) {
3479
+ bytes[0] &= 248;
3480
+ bytes[31] &= 127;
3481
+ bytes[31] |= 64;
3482
+ return bytes;
3483
+ }
3484
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
3485
+ function uvRatio(u, v) {
3486
+ const P = ed25519_CURVE_p;
3487
+ const v3 = mod(v * v * v, P);
3488
+ const v7 = mod(v3 * v3 * v, P);
3489
+ const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
3490
+ let x = mod(u * v3 * pow3, P);
3491
+ const vx2 = mod(v * x * x, P);
3492
+ const root1 = x;
3493
+ const root2 = mod(x * ED25519_SQRT_M1, P);
3494
+ const useRoot1 = vx2 === u;
3495
+ const useRoot2 = vx2 === mod(-u, P);
3496
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
3497
+ if (useRoot1)
3498
+ x = root1;
3499
+ if (useRoot2 || noRoot)
3500
+ x = root2;
3501
+ if (isNegativeLE(x, P))
3502
+ x = mod(-x, P);
3503
+ return { isValid: useRoot1 || useRoot2, value: x };
3504
+ }
3505
+ var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
3506
+ var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
3507
+ function toMontgomery(point) {
3508
+ const { y } = point;
3509
+ return Fp.toBytes(Fp.div(_1n6 + y, _1n6 - y));
3510
+ }
3511
+ function toMontgomerySecret(secretKey) {
3512
+ const size = ed25519_Point.Fp.BYTES;
3513
+ abytes(secretKey, size);
3514
+ return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);
3515
+ }
3516
+ function ed(opts) {
3517
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));
3518
+ }
3519
+ var ed25519 = /* @__PURE__ */ ed({});
3520
+
3521
+ // ../../node_modules/@noble/hashes/sha3.js
3522
+ var _0n7 = BigInt(0);
3523
+ var _1n7 = BigInt(1);
3524
+ var _2n6 = BigInt(2);
3525
+ var _7n2 = BigInt(7);
3526
+ var _256n = BigInt(256);
3527
+ var _0x71n = BigInt(113);
3528
+ var SHA3_PI = [];
3529
+ var SHA3_ROTL = [];
3530
+ var _SHA3_IOTA = [];
3531
+ for (let round = 0, R = _1n7, x = 1, y = 0; round < 24; round++) {
3532
+ [x, y] = [y, (2 * x + 3 * y) % 5];
3533
+ SHA3_PI.push(2 * (5 * y + x));
3534
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
3535
+ let t = _0n7;
3536
+ for (let j = 0; j < 7; j++) {
3537
+ R = (R << _1n7 ^ (R >> _7n2) * _0x71n) % _256n;
3538
+ if (R & _2n6)
3539
+ t ^= _1n7 << (_1n7 << BigInt(j)) - _1n7;
3540
+ }
3541
+ _SHA3_IOTA.push(t);
3542
+ }
3543
+ var IOTAS = split(_SHA3_IOTA, true);
3544
+ var SHA3_IOTA_H = IOTAS[0];
3545
+ var SHA3_IOTA_L = IOTAS[1];
3546
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
3547
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
3548
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
3549
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
3550
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
3551
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
3552
+ var B = new Uint32Array(5 * 2);
3553
+ function keccakP(s, rounds = 24) {
3554
+ if (!(s instanceof Uint32Array))
3555
+ throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
3556
+ if (s.length !== 50)
3557
+ throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
3558
+ anumber(rounds, "rounds");
3559
+ if (rounds < 1 || rounds > 24)
3560
+ throw new Error('"rounds" expected integer 1..24');
3561
+ for (let round = 24 - rounds; round < 24; round++) {
3562
+ for (let x = 0; x < 10; x++)
3563
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
3564
+ for (let x = 0; x < 10; x += 2) {
3565
+ const idx1 = (x + 8) % 10;
3566
+ const idx0 = (x + 2) % 10;
3567
+ const B0 = B[idx0];
3568
+ const B1 = B[idx0 + 1];
3569
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
3570
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
3571
+ for (let y = 0; y < 50; y += 10) {
3572
+ s[x + y] ^= Th;
3573
+ s[x + y + 1] ^= Tl;
3574
+ }
3575
+ }
3576
+ let curH = s[2];
3577
+ let curL = s[3];
3578
+ for (let t = 0; t < 24; t++) {
3579
+ const shift = SHA3_ROTL[t];
3580
+ const Th = rotlH(curH, curL, shift);
3581
+ const Tl = rotlL(curH, curL, shift);
3582
+ const PI = SHA3_PI[t];
3583
+ curH = s[PI];
3584
+ curL = s[PI + 1];
3585
+ s[PI] = Th;
3586
+ s[PI + 1] = Tl;
3587
+ }
3588
+ for (let y = 0; y < 50; y += 10) {
3589
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
3590
+ s[y] ^= ~s[y + 2] & s[y + 4];
3591
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
3592
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
3593
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
3594
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
3595
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
3596
+ s[y + 6] ^= ~s[y + 8] & b0;
3597
+ s[y + 7] ^= ~s[y + 9] & b1;
3598
+ s[y + 8] ^= ~b0 & b2;
3599
+ s[y + 9] ^= ~b1 & b3;
3600
+ }
3601
+ s[0] ^= SHA3_IOTA_H[round];
3602
+ s[1] ^= SHA3_IOTA_L[round];
3603
+ }
3604
+ clean(B);
3605
+ }
3606
+ var Keccak = class _Keccak {
3607
+ // NOTE: we accept arguments in bytes instead of bits here.
3608
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
3609
+ __publicField(this, "state");
3610
+ __publicField(this, "pos", 0);
3611
+ __publicField(this, "posOut", 0);
3612
+ __publicField(this, "finished", false);
3613
+ __publicField(this, "state32");
3614
+ __publicField(this, "destroyed", false);
3615
+ __publicField(this, "blockLen");
3616
+ __publicField(this, "suffix");
3617
+ __publicField(this, "outputLen");
3618
+ __publicField(this, "canXOF");
3619
+ __publicField(this, "enableXOF", false);
3620
+ __publicField(this, "rounds");
3621
+ anumber(blockLen, "blockLen");
3622
+ anumber(suffix, "suffix");
3623
+ anumber(rounds, "rounds");
3624
+ abool(enableXOF, "enableXOF");
3625
+ this.blockLen = blockLen;
3626
+ this.suffix = suffix;
3627
+ this.outputLen = outputLen;
3628
+ this.enableXOF = enableXOF;
3629
+ this.canXOF = enableXOF;
3630
+ this.rounds = rounds;
3631
+ anumber(outputLen, "outputLen");
3632
+ if (!(0 < blockLen && blockLen < 200))
3633
+ throw new Error('"blockLen" must be 1..199');
3634
+ this.state = new Uint8Array(200);
3635
+ this.state32 = u32(this.state);
3636
+ }
3637
+ clone() {
3638
+ return this._cloneInto();
3639
+ }
3640
+ keccak() {
3641
+ swap32IfBE(this.state32);
3642
+ keccakP(this.state32, this.rounds);
3643
+ swap32IfBE(this.state32);
3644
+ this.posOut = 0;
3645
+ this.pos = 0;
3646
+ }
3647
+ update(data) {
3648
+ aexists(this);
3649
+ abytes(data);
3650
+ const { blockLen, state, state32 } = this;
3651
+ const len = data.length;
3652
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
3653
+ const blockLen32 = blockLen / 4;
3654
+ const data32 = canUseU32 && len >= blockLen ? u32(data) : void 0;
3655
+ for (let pos = 0; pos < len; ) {
3656
+ if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
3657
+ for (let i = 0, o = pos / 4; i < blockLen32; i++)
3658
+ state32[i] ^= data32[o + i];
3659
+ pos += blockLen;
3660
+ this.pos = blockLen;
3661
+ this.keccak();
3662
+ continue;
3663
+ }
3664
+ const take = Math.min(blockLen - this.pos, len - pos);
3665
+ for (let i = 0; i < take; i++)
3666
+ state[this.pos++] ^= data[pos++];
3667
+ if (this.pos === blockLen)
3668
+ this.keccak();
3669
+ }
3670
+ return this;
3671
+ }
3672
+ finish() {
3673
+ if (this.finished)
3674
+ return;
3675
+ this.finished = true;
3676
+ const { state, suffix, pos, blockLen } = this;
3677
+ state[pos] ^= suffix;
3678
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
3679
+ this.keccak();
3680
+ state[blockLen - 1] ^= 128;
3681
+ this.keccak();
3682
+ }
3683
+ writeInto(out) {
3684
+ aexists(this, false);
3685
+ abytes(out);
3686
+ this.finish();
3687
+ const bufferOut = this.state;
3688
+ const { blockLen } = this;
3689
+ for (let pos = 0, len = out.length; pos < len; ) {
3690
+ if (this.posOut >= blockLen)
3691
+ this.keccak();
3692
+ const take = Math.min(blockLen - this.posOut, len - pos);
3693
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
3694
+ this.posOut += take;
3695
+ pos += take;
3696
+ }
3697
+ return out;
3698
+ }
3699
+ xofInto(out) {
3700
+ if (!this.enableXOF)
3701
+ throw new Error("XOF is not enabled");
3702
+ return this.writeInto(out);
3703
+ }
3704
+ xof(bytes) {
3705
+ anumber(bytes);
3706
+ return this.xofInto(new Uint8Array(bytes));
3707
+ }
3708
+ digestInto(out) {
3709
+ aoutput(out, this);
3710
+ if (this.finished)
3711
+ throw new Error("digest() was already called");
3712
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
3713
+ this.destroy();
3714
+ }
3715
+ digest() {
3716
+ const out = new Uint8Array(this.outputLen);
3717
+ this.digestInto(out);
3718
+ return out;
3719
+ }
3720
+ destroy() {
3721
+ this.destroyed = true;
3722
+ clean(this.state);
3723
+ }
3724
+ _cloneInto(to) {
3725
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
3726
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
3727
+ to.blockLen = blockLen;
3728
+ to.state32.set(this.state32);
3729
+ to.pos = this.pos;
3730
+ to.posOut = this.posOut;
3731
+ to.finished = this.finished;
3732
+ to.rounds = rounds;
3733
+ to.suffix = suffix;
3734
+ to.outputLen = outputLen;
3735
+ to.enableXOF = enableXOF;
3736
+ to.canXOF = this.canXOF;
3737
+ to.destroyed = this.destroyed;
3738
+ return to;
3739
+ }
3740
+ };
3741
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
3742
+ var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
3743
+
3744
+ // src/wallet-proof-verify.js
3745
+ var enc = new TextEncoder();
3746
+ function hexBytes(hex) {
3747
+ const h = String(hex).replace(/^0x/i, "");
3748
+ if (!/^(?:[0-9a-fA-F]{2})*$/.test(h))
3749
+ throw new Error("not hex");
3750
+ const out = new Uint8Array(h.length / 2);
3751
+ for (let i = 0; i < out.length; i++)
3752
+ out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
3753
+ return out;
3754
+ }
3755
+ var toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
3756
+ function eip191Hash(message) {
3757
+ const body = enc.encode(message);
3758
+ const prefix = enc.encode(`Ethereum Signed Message:
3759
+ ${body.length}`);
3760
+ const all = new Uint8Array(prefix.length + body.length);
3761
+ all.set(prefix);
3762
+ all.set(body, prefix.length);
3763
+ return keccak_256(all);
3764
+ }
3765
+ function recoverEthAddress(message, signature) {
3766
+ const sig = hexBytes(signature);
3767
+ if (sig.length !== 65)
3768
+ throw new Error("signature must be 65 bytes");
3769
+ let v = sig[64];
3770
+ if (v >= 27)
3771
+ v -= 27;
3772
+ if (v !== 0 && v !== 1)
3773
+ throw new Error("bad recovery byte");
3774
+ const pub = secp256k1.Signature.fromBytes(sig.slice(0, 64), "compact").addRecoveryBit(v).recoverPublicKey(eip191Hash(message)).toBytes(false);
3775
+ return "0x" + toHex(keccak_256(pub.slice(1)).slice(-20));
3776
+ }
3777
+ function checkSignature(chain, address, message, signature) {
3778
+ if (chain === "eth")
3779
+ return recoverEthAddress(message, signature) === address.toLowerCase();
3780
+ const sig = base58Decode(signature);
3781
+ const pub = base58Decode(address);
3782
+ if (sig.length !== 64 || pub.length !== 32)
3783
+ return false;
3784
+ return ed25519.verify(sig, enc.encode(message), pub);
3785
+ }
3786
+ function verifyWalletProof({ chain, address, userid, proof, maxAgeMs, now = Date.now() }) {
3787
+ try {
3788
+ if (!WALLET_CHAINS.includes(chain))
3789
+ return { ok: false, error: "unknown chain" };
3790
+ const p = proof && typeof proof === "object" && "message" in proof ? proof : decodeWalletProof(proof);
3791
+ if (!p)
3792
+ return { ok: false, error: "no proof" };
3793
+ const f = parseWalletProofMessage(p.message);
3794
+ if (!f)
3795
+ return { ok: false, error: "proof message is not in the expected form" };
3796
+ if (f.chain !== chain)
3797
+ return { ok: false, error: "proof is for another chain" };
3798
+ if (f.userid !== userid)
3799
+ return { ok: false, error: "proof names another Beagle identity" };
3800
+ const same = chain === "eth" ? f.address.toLowerCase() === String(address).toLowerCase() : f.address === address;
3801
+ if (!same)
3802
+ return { ok: false, error: "proof names another address" };
3803
+ const t = Date.parse(f.issued);
3804
+ if (t > now + 5 * 6e4)
3805
+ return { ok: false, error: "proof is dated in the future" };
3806
+ if (maxAgeMs != null && now - t > maxAgeMs)
3807
+ return { ok: false, error: "proof is too old" };
3808
+ if (!checkSignature(chain, address, p.message, p.signature))
3809
+ return { ok: false, error: "wallet signature does not match the address" };
3810
+ return { ok: true, issued: f.issued };
3811
+ } catch (e) {
3812
+ return { ok: false, error: "bad wallet signature: " + String(e && e.message || e) };
3813
+ }
3814
+ }
3815
+ function verifyRecordWallet(record, chain) {
3816
+ const address = record && record.addresses && record.addresses[COIN_TYPE[chain]];
3817
+ if (!address)
3818
+ return { ok: false, error: "no address bound" };
3819
+ const userid = record.texts && record.texts.carrierUserId || record.owner;
3820
+ const r = verifyWalletProof({ chain, address, userid, proof: record.texts && record.texts[PROOF_KEY[chain]] });
3821
+ if (r.ok)
3822
+ return { ok: true, address, via: "proof", issued: r.issued };
3823
+ const owner = String(record.owner || "");
3824
+ if (owner && (chain === "eth" ? owner.toLowerCase() === address.toLowerCase() : owner === address)) {
3825
+ return { ok: true, address, via: "owner" };
3826
+ }
3827
+ return r;
3828
+ }
3829
+ var BIND_MAX_AGE_MS = 10 * 6e4;
3830
+ function applyWalletBind(record, { chain, address, proof, userid, now = Date.now() }) {
3831
+ if (!WALLET_CHAINS.includes(chain))
3832
+ return { ok: false, status: 400, error: "invalid chain or address" };
3833
+ const addr = typeof address === "string" ? address.trim() : "";
3834
+ if (addr && !isWalletAddress(chain, addr))
3835
+ return { ok: false, status: 400, error: "invalid chain or address" };
3836
+ const coin = COIN_TYPE[chain], key = PROOF_KEY[chain];
3837
+ const addresses = { ...record && record.addresses || {} };
3838
+ const texts = { ...record && record.texts || {} };
3839
+ if (!addr) {
3840
+ delete addresses[coin];
3841
+ delete texts[key];
3842
+ return { ok: true, addresses, texts };
3843
+ }
3844
+ addresses[coin] = addr;
3845
+ if (proof) {
3846
+ const p = typeof proof === "string" ? decodeWalletProof(proof) : proof;
3847
+ const v = verifyWalletProof({ chain, address: addr, userid, proof: p, maxAgeMs: BIND_MAX_AGE_MS, now });
3848
+ if (!v.ok)
3849
+ return { ok: false, status: 400, error: v.error };
3850
+ texts[key] = encodeWalletProof({ message: p.message, signature: p.signature });
3851
+ } else if (!verifyWalletProof({ chain, address: addr, userid, proof: texts[key], now }).ok) {
3852
+ delete texts[key];
3853
+ }
3854
+ return { ok: true, addresses, texts };
3855
+ }
3856
+ export {
3857
+ BIND_MAX_AGE_MS,
3858
+ COIN_TYPE,
3859
+ PROOF_KEY,
3860
+ WALLET_CHAINS,
3861
+ WALLET_PROOF_VERSION,
3862
+ applyWalletBind,
3863
+ base58Decode,
3864
+ base58Encode,
3865
+ decodeWalletProof,
3866
+ eip191Hash,
3867
+ encodeWalletProof,
3868
+ isWalletAddress,
3869
+ parseWalletProofMessage,
3870
+ proofTime,
3871
+ recoverEthAddress,
3872
+ signEthProof,
3873
+ signSolProof,
3874
+ verifyRecordWallet,
3875
+ verifyWalletProof,
3876
+ walletProofMessage
3877
+ };
3878
+ /*! Bundled license information:
3879
+
3880
+ @noble/curves/utils.js:
3881
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3882
+
3883
+ @noble/curves/abstract/modular.js:
3884
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3885
+
3886
+ @noble/curves/abstract/curve.js:
3887
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3888
+
3889
+ @noble/curves/abstract/der.js:
3890
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3891
+
3892
+ @noble/curves/abstract/weierstrass.js:
3893
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3894
+
3895
+ @noble/curves/secp256k1.js:
3896
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3897
+
3898
+ @noble/curves/abstract/edwards.js:
3899
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3900
+
3901
+ @noble/curves/ed25519.js:
3902
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3903
+ */