@capxul/mcp 2.8.0 → 3.0.0

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,2343 @@
1
+ import * as nc from "node:crypto";
2
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/cryptoNode.js
3
+ /**
4
+ * Internal webcrypto alias.
5
+ * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.
6
+ * Falls back to Node.js built-in crypto for Node.js <=v14.
7
+ * See utils.ts for details.
8
+ * @module
9
+ */
10
+ const crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
11
+ //#endregion
12
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
13
+ /**
14
+ * Utilities for hex, bytes, CSPRNG.
15
+ * @module
16
+ */
17
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
18
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
19
+ function isBytes$1(a) {
20
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
21
+ }
22
+ /** Asserts something is positive integer. */
23
+ function anumber(n) {
24
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n);
25
+ }
26
+ /** Asserts something is Uint8Array. */
27
+ function abytes$1(b, ...lengths) {
28
+ if (!isBytes$1(b)) throw new Error("Uint8Array expected");
29
+ if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
30
+ }
31
+ /** Asserts something is hash */
32
+ function ahash(h) {
33
+ if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher");
34
+ anumber(h.outputLen);
35
+ anumber(h.blockLen);
36
+ }
37
+ /** Asserts a hash instance has not been destroyed / finished */
38
+ function aexists(instance, checkFinished = true) {
39
+ if (instance.destroyed) throw new Error("Hash instance has been destroyed");
40
+ if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
41
+ }
42
+ /** Asserts output is properly-sized byte array */
43
+ function aoutput(out, instance) {
44
+ abytes$1(out);
45
+ const min = instance.outputLen;
46
+ if (out.length < min) throw new Error("digestInto() expects output buffer of length at least " + min);
47
+ }
48
+ /** Cast u8 / u16 / u32 to u32. */
49
+ function u32(arr) {
50
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
51
+ }
52
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
53
+ function clean(...arrays) {
54
+ for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
55
+ }
56
+ /** Create DataView of an array for easy byte-level manipulation. */
57
+ function createView(arr) {
58
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
59
+ }
60
+ /** The rotate right (circular right shift) operation for uint32 */
61
+ function rotr(word, shift) {
62
+ return word << 32 - shift | word >>> shift;
63
+ }
64
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
65
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
66
+ /** The byte swap operation for uint32 */
67
+ function byteSwap(word) {
68
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
69
+ }
70
+ /** In place byte swap for Uint32Array */
71
+ function byteSwap32(arr) {
72
+ for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]);
73
+ return arr;
74
+ }
75
+ const swap32IfBE = isLE ? (u) => u : byteSwap32;
76
+ /**
77
+ * Converts string to bytes using UTF8 encoding.
78
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
79
+ */
80
+ function utf8ToBytes(str) {
81
+ if (typeof str !== "string") throw new Error("string expected");
82
+ return new Uint8Array(new TextEncoder().encode(str));
83
+ }
84
+ /**
85
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
86
+ * Warning: when Uint8Array is passed, it would NOT get copied.
87
+ * Keep in mind for future mutable operations.
88
+ */
89
+ function toBytes(data) {
90
+ if (typeof data === "string") data = utf8ToBytes(data);
91
+ abytes$1(data);
92
+ return data;
93
+ }
94
+ /** Copies several Uint8Arrays into one. */
95
+ function concatBytes$1(...arrays) {
96
+ let sum = 0;
97
+ for (let i = 0; i < arrays.length; i++) {
98
+ const a = arrays[i];
99
+ abytes$1(a);
100
+ sum += a.length;
101
+ }
102
+ const res = new Uint8Array(sum);
103
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
104
+ const a = arrays[i];
105
+ res.set(a, pad);
106
+ pad += a.length;
107
+ }
108
+ return res;
109
+ }
110
+ /** For runtime check if class implements interface */
111
+ var Hash = class {};
112
+ /** Wraps hash function, creating an interface on top of it */
113
+ function createHasher(hashCons) {
114
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
115
+ const tmp = hashCons();
116
+ hashC.outputLen = tmp.outputLen;
117
+ hashC.blockLen = tmp.blockLen;
118
+ hashC.create = () => hashCons();
119
+ return hashC;
120
+ }
121
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
122
+ function randomBytes(bytesLength = 32) {
123
+ if (crypto && typeof crypto.getRandomValues === "function") return crypto.getRandomValues(new Uint8Array(bytesLength));
124
+ if (crypto && typeof crypto.randomBytes === "function") return Uint8Array.from(crypto.randomBytes(bytesLength));
125
+ throw new Error("crypto.getRandomValues must be defined");
126
+ }
127
+ //#endregion
128
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
129
+ /**
130
+ * Internal Merkle-Damgard hash utils.
131
+ * @module
132
+ */
133
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
134
+ function setBigUint64(view, byteOffset, value, isLE) {
135
+ if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE);
136
+ const _32n = BigInt(32);
137
+ const _u32_max = BigInt(4294967295);
138
+ const wh = Number(value >> _32n & _u32_max);
139
+ const wl = Number(value & _u32_max);
140
+ const h = isLE ? 4 : 0;
141
+ const l = isLE ? 0 : 4;
142
+ view.setUint32(byteOffset + h, wh, isLE);
143
+ view.setUint32(byteOffset + l, wl, isLE);
144
+ }
145
+ /** Choice: a ? b : c */
146
+ function Chi(a, b, c) {
147
+ return a & b ^ ~a & c;
148
+ }
149
+ /** Majority function, true if any two inputs is true. */
150
+ function Maj(a, b, c) {
151
+ return a & b ^ a & c ^ b & c;
152
+ }
153
+ /**
154
+ * Merkle-Damgard hash construction base class.
155
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
156
+ */
157
+ var HashMD = class extends Hash {
158
+ constructor(blockLen, outputLen, padOffset, isLE) {
159
+ super();
160
+ this.finished = false;
161
+ this.length = 0;
162
+ this.pos = 0;
163
+ this.destroyed = false;
164
+ this.blockLen = blockLen;
165
+ this.outputLen = outputLen;
166
+ this.padOffset = padOffset;
167
+ this.isLE = isLE;
168
+ this.buffer = new Uint8Array(blockLen);
169
+ this.view = createView(this.buffer);
170
+ }
171
+ update(data) {
172
+ aexists(this);
173
+ data = toBytes(data);
174
+ abytes$1(data);
175
+ const { view, buffer, blockLen } = this;
176
+ const len = data.length;
177
+ for (let pos = 0; pos < len;) {
178
+ const take = Math.min(blockLen - this.pos, len - pos);
179
+ if (take === blockLen) {
180
+ const dataView = createView(data);
181
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
182
+ continue;
183
+ }
184
+ buffer.set(data.subarray(pos, pos + take), this.pos);
185
+ this.pos += take;
186
+ pos += take;
187
+ if (this.pos === blockLen) {
188
+ this.process(view, 0);
189
+ this.pos = 0;
190
+ }
191
+ }
192
+ this.length += data.length;
193
+ this.roundClean();
194
+ return this;
195
+ }
196
+ digestInto(out) {
197
+ aexists(this);
198
+ aoutput(out, this);
199
+ this.finished = true;
200
+ const { buffer, view, blockLen, isLE } = this;
201
+ let { pos } = this;
202
+ buffer[pos++] = 128;
203
+ clean(this.buffer.subarray(pos));
204
+ if (this.padOffset > blockLen - pos) {
205
+ this.process(view, 0);
206
+ pos = 0;
207
+ }
208
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
209
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
210
+ this.process(view, 0);
211
+ const oview = createView(out);
212
+ const len = this.outputLen;
213
+ if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit");
214
+ const outLen = len / 4;
215
+ const state = this.get();
216
+ if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
217
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
218
+ }
219
+ digest() {
220
+ const { buffer, outputLen } = this;
221
+ this.digestInto(buffer);
222
+ const res = buffer.slice(0, outputLen);
223
+ this.destroy();
224
+ return res;
225
+ }
226
+ _cloneInto(to) {
227
+ to || (to = new this.constructor());
228
+ to.set(...this.get());
229
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
230
+ to.destroyed = destroyed;
231
+ to.finished = finished;
232
+ to.length = length;
233
+ to.pos = pos;
234
+ if (length % blockLen) to.buffer.set(buffer);
235
+ return to;
236
+ }
237
+ clone() {
238
+ return this._cloneInto();
239
+ }
240
+ };
241
+ /**
242
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
243
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
244
+ */
245
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
246
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
247
+ 1779033703,
248
+ 3144134277,
249
+ 1013904242,
250
+ 2773480762,
251
+ 1359893119,
252
+ 2600822924,
253
+ 528734635,
254
+ 1541459225
255
+ ]);
256
+ //#endregion
257
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
258
+ /**
259
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
260
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
261
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
262
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
263
+ * @module
264
+ */
265
+ /**
266
+ * Round constants:
267
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
268
+ */
269
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
270
+ 1116352408,
271
+ 1899447441,
272
+ 3049323471,
273
+ 3921009573,
274
+ 961987163,
275
+ 1508970993,
276
+ 2453635748,
277
+ 2870763221,
278
+ 3624381080,
279
+ 310598401,
280
+ 607225278,
281
+ 1426881987,
282
+ 1925078388,
283
+ 2162078206,
284
+ 2614888103,
285
+ 3248222580,
286
+ 3835390401,
287
+ 4022224774,
288
+ 264347078,
289
+ 604807628,
290
+ 770255983,
291
+ 1249150122,
292
+ 1555081692,
293
+ 1996064986,
294
+ 2554220882,
295
+ 2821834349,
296
+ 2952996808,
297
+ 3210313671,
298
+ 3336571891,
299
+ 3584528711,
300
+ 113926993,
301
+ 338241895,
302
+ 666307205,
303
+ 773529912,
304
+ 1294757372,
305
+ 1396182291,
306
+ 1695183700,
307
+ 1986661051,
308
+ 2177026350,
309
+ 2456956037,
310
+ 2730485921,
311
+ 2820302411,
312
+ 3259730800,
313
+ 3345764771,
314
+ 3516065817,
315
+ 3600352804,
316
+ 4094571909,
317
+ 275423344,
318
+ 430227734,
319
+ 506948616,
320
+ 659060556,
321
+ 883997877,
322
+ 958139571,
323
+ 1322822218,
324
+ 1537002063,
325
+ 1747873779,
326
+ 1955562222,
327
+ 2024104815,
328
+ 2227730452,
329
+ 2361852424,
330
+ 2428436474,
331
+ 2756734187,
332
+ 3204031479,
333
+ 3329325298
334
+ ]);
335
+ /** Reusable temporary buffer. "W" comes straight from spec. */
336
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
337
+ var SHA256 = class extends HashMD {
338
+ constructor(outputLen = 32) {
339
+ super(64, outputLen, 8, false);
340
+ this.A = SHA256_IV[0] | 0;
341
+ this.B = SHA256_IV[1] | 0;
342
+ this.C = SHA256_IV[2] | 0;
343
+ this.D = SHA256_IV[3] | 0;
344
+ this.E = SHA256_IV[4] | 0;
345
+ this.F = SHA256_IV[5] | 0;
346
+ this.G = SHA256_IV[6] | 0;
347
+ this.H = SHA256_IV[7] | 0;
348
+ }
349
+ get() {
350
+ const { A, B, C, D, E, F, G, H } = this;
351
+ return [
352
+ A,
353
+ B,
354
+ C,
355
+ D,
356
+ E,
357
+ F,
358
+ G,
359
+ H
360
+ ];
361
+ }
362
+ set(A, B, C, D, E, F, G, H) {
363
+ this.A = A | 0;
364
+ this.B = B | 0;
365
+ this.C = C | 0;
366
+ this.D = D | 0;
367
+ this.E = E | 0;
368
+ this.F = F | 0;
369
+ this.G = G | 0;
370
+ this.H = H | 0;
371
+ }
372
+ process(view, offset) {
373
+ for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
374
+ for (let i = 16; i < 64; i++) {
375
+ const W15 = SHA256_W[i - 15];
376
+ const W2 = SHA256_W[i - 2];
377
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
378
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
379
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
380
+ }
381
+ let { A, B, C, D, E, F, G, H } = this;
382
+ for (let i = 0; i < 64; i++) {
383
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
384
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
385
+ const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
386
+ H = G;
387
+ G = F;
388
+ F = E;
389
+ E = D + T1 | 0;
390
+ D = C;
391
+ C = B;
392
+ B = A;
393
+ A = T1 + T2 | 0;
394
+ }
395
+ A = A + this.A | 0;
396
+ B = B + this.B | 0;
397
+ C = C + this.C | 0;
398
+ D = D + this.D | 0;
399
+ E = E + this.E | 0;
400
+ F = F + this.F | 0;
401
+ G = G + this.G | 0;
402
+ H = H + this.H | 0;
403
+ this.set(A, B, C, D, E, F, G, H);
404
+ }
405
+ roundClean() {
406
+ clean(SHA256_W);
407
+ }
408
+ destroy() {
409
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
410
+ clean(this.buffer);
411
+ }
412
+ };
413
+ /**
414
+ * SHA2-256 hash function from RFC 4634.
415
+ *
416
+ * It is the fastest JS hash, even faster than Blake3.
417
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
418
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
419
+ */
420
+ const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
421
+ //#endregion
422
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/utils.js
423
+ /**
424
+ * Hex, bytes and number utilities.
425
+ * @module
426
+ */
427
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
428
+ const _0n$4 = /* @__PURE__ */ BigInt(0);
429
+ const _1n$4 = /* @__PURE__ */ BigInt(1);
430
+ function isBytes(a) {
431
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
432
+ }
433
+ function abytes(item) {
434
+ if (!isBytes(item)) throw new Error("Uint8Array expected");
435
+ }
436
+ function abool(title, value) {
437
+ if (typeof value !== "boolean") throw new Error(title + " boolean expected, got " + value);
438
+ }
439
+ function numberToHexUnpadded(num) {
440
+ const hex = num.toString(16);
441
+ return hex.length & 1 ? "0" + hex : hex;
442
+ }
443
+ function hexToNumber(hex) {
444
+ if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
445
+ return hex === "" ? _0n$4 : BigInt("0x" + hex);
446
+ }
447
+ const hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
448
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
449
+ /**
450
+ * Convert byte array to hex string. Uses built-in function, when available.
451
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
452
+ */
453
+ function bytesToHex(bytes) {
454
+ abytes(bytes);
455
+ if (hasHexBuiltin) return bytes.toHex();
456
+ let hex = "";
457
+ for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
458
+ return hex;
459
+ }
460
+ const asciis = {
461
+ _0: 48,
462
+ _9: 57,
463
+ A: 65,
464
+ F: 70,
465
+ a: 97,
466
+ f: 102
467
+ };
468
+ function asciiToBase16(ch) {
469
+ if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0;
470
+ if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10);
471
+ if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10);
472
+ }
473
+ /**
474
+ * Convert hex string to byte array. Uses built-in function, when available.
475
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
476
+ */
477
+ function hexToBytes(hex) {
478
+ if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
479
+ if (hasHexBuiltin) return Uint8Array.fromHex(hex);
480
+ const hl = hex.length;
481
+ const al = hl / 2;
482
+ if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl);
483
+ const array = new Uint8Array(al);
484
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
485
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
486
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
487
+ if (n1 === void 0 || n2 === void 0) {
488
+ const char = hex[hi] + hex[hi + 1];
489
+ throw new Error("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
490
+ }
491
+ array[ai] = n1 * 16 + n2;
492
+ }
493
+ return array;
494
+ }
495
+ function bytesToNumberBE(bytes) {
496
+ return hexToNumber(bytesToHex(bytes));
497
+ }
498
+ function bytesToNumberLE(bytes) {
499
+ abytes(bytes);
500
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
501
+ }
502
+ function numberToBytesBE(n, len) {
503
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
504
+ }
505
+ function numberToBytesLE(n, len) {
506
+ return numberToBytesBE(n, len).reverse();
507
+ }
508
+ /**
509
+ * Takes hex string or Uint8Array, converts to Uint8Array.
510
+ * Validates output length.
511
+ * Will throw error for other types.
512
+ * @param title descriptive title for an error e.g. 'private key'
513
+ * @param hex hex string or Uint8Array
514
+ * @param expectedLength optional, will compare to result array's length
515
+ * @returns
516
+ */
517
+ function ensureBytes(title, hex, expectedLength) {
518
+ let res;
519
+ if (typeof hex === "string") try {
520
+ res = hexToBytes(hex);
521
+ } catch (e) {
522
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
523
+ }
524
+ else if (isBytes(hex)) res = Uint8Array.from(hex);
525
+ else throw new Error(title + " must be hex string or Uint8Array");
526
+ const len = res.length;
527
+ if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(title + " of length " + expectedLength + " expected, got " + len);
528
+ return res;
529
+ }
530
+ /**
531
+ * Copies several Uint8Arrays into one.
532
+ */
533
+ function concatBytes(...arrays) {
534
+ let sum = 0;
535
+ for (let i = 0; i < arrays.length; i++) {
536
+ const a = arrays[i];
537
+ abytes(a);
538
+ sum += a.length;
539
+ }
540
+ const res = new Uint8Array(sum);
541
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
542
+ const a = arrays[i];
543
+ res.set(a, pad);
544
+ pad += a.length;
545
+ }
546
+ return res;
547
+ }
548
+ const isPosBig = (n) => typeof n === "bigint" && _0n$4 <= n;
549
+ function inRange(n, min, max) {
550
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
551
+ }
552
+ /**
553
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
554
+ * @example
555
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
556
+ */
557
+ function aInRange(title, n, min, max) {
558
+ if (!inRange(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
559
+ }
560
+ /**
561
+ * Calculates amount of bits in a bigint.
562
+ * Same as `n.toString(2).length`
563
+ * TODO: merge with nLength in modular
564
+ */
565
+ function bitLen(n) {
566
+ let len;
567
+ for (len = 0; n > _0n$4; n >>= _1n$4, len += 1);
568
+ return len;
569
+ }
570
+ /**
571
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
572
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
573
+ */
574
+ const bitMask = (n) => (_1n$4 << BigInt(n)) - _1n$4;
575
+ const u8n = (len) => new Uint8Array(len);
576
+ const u8fr = (arr) => Uint8Array.from(arr);
577
+ /**
578
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
579
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
580
+ * @example
581
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
582
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
583
+ */
584
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
585
+ if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number");
586
+ if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number");
587
+ if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function");
588
+ let v = u8n(hashLen);
589
+ let k = u8n(hashLen);
590
+ let i = 0;
591
+ const reset = () => {
592
+ v.fill(1);
593
+ k.fill(0);
594
+ i = 0;
595
+ };
596
+ const h = (...b) => hmacFn(k, v, ...b);
597
+ const reseed = (seed = u8n(0)) => {
598
+ k = h(u8fr([0]), seed);
599
+ v = h();
600
+ if (seed.length === 0) return;
601
+ k = h(u8fr([1]), seed);
602
+ v = h();
603
+ };
604
+ const gen = () => {
605
+ if (i++ >= 1e3) throw new Error("drbg: tried 1000 values");
606
+ let len = 0;
607
+ const out = [];
608
+ while (len < qByteLen) {
609
+ v = h();
610
+ const sl = v.slice();
611
+ out.push(sl);
612
+ len += v.length;
613
+ }
614
+ return concatBytes(...out);
615
+ };
616
+ const genUntil = (seed, pred) => {
617
+ reset();
618
+ reseed(seed);
619
+ let res = void 0;
620
+ while (!(res = pred(gen()))) reseed();
621
+ reset();
622
+ return res;
623
+ };
624
+ return genUntil;
625
+ }
626
+ const validatorFns = {
627
+ bigint: (val) => typeof val === "bigint",
628
+ function: (val) => typeof val === "function",
629
+ boolean: (val) => typeof val === "boolean",
630
+ string: (val) => typeof val === "string",
631
+ stringOrUint8Array: (val) => typeof val === "string" || isBytes(val),
632
+ isSafeInteger: (val) => Number.isSafeInteger(val),
633
+ array: (val) => Array.isArray(val),
634
+ field: (val, object) => object.Fp.isValid(val),
635
+ hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
636
+ };
637
+ function validateObject(object, validators, optValidators = {}) {
638
+ const checkField = (fieldName, type, isOptional) => {
639
+ const checkVal = validatorFns[type];
640
+ if (typeof checkVal !== "function") throw new Error("invalid validator function");
641
+ const val = object[fieldName];
642
+ if (isOptional && val === void 0) return;
643
+ if (!checkVal(val, object)) throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
644
+ };
645
+ for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type, false);
646
+ for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type, true);
647
+ return object;
648
+ }
649
+ /**
650
+ * Memoizes (caches) computation result.
651
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
652
+ */
653
+ function memoized(fn) {
654
+ const map = /* @__PURE__ */ new WeakMap();
655
+ return (arg, ...args) => {
656
+ const val = map.get(arg);
657
+ if (val !== void 0) return val;
658
+ const computed = fn(arg, ...args);
659
+ map.set(arg, computed);
660
+ return computed;
661
+ };
662
+ }
663
+ //#endregion
664
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
665
+ /**
666
+ * HMAC: RFC2104 message authentication code.
667
+ * @module
668
+ */
669
+ var HMAC = class extends Hash {
670
+ constructor(hash, _key) {
671
+ super();
672
+ this.finished = false;
673
+ this.destroyed = false;
674
+ ahash(hash);
675
+ const key = toBytes(_key);
676
+ this.iHash = hash.create();
677
+ if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
678
+ this.blockLen = this.iHash.blockLen;
679
+ this.outputLen = this.iHash.outputLen;
680
+ const blockLen = this.blockLen;
681
+ const pad = new Uint8Array(blockLen);
682
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
683
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
684
+ this.iHash.update(pad);
685
+ this.oHash = hash.create();
686
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
687
+ this.oHash.update(pad);
688
+ clean(pad);
689
+ }
690
+ update(buf) {
691
+ aexists(this);
692
+ this.iHash.update(buf);
693
+ return this;
694
+ }
695
+ digestInto(out) {
696
+ aexists(this);
697
+ abytes$1(out, this.outputLen);
698
+ this.finished = true;
699
+ this.iHash.digestInto(out);
700
+ this.oHash.update(out);
701
+ this.oHash.digestInto(out);
702
+ this.destroy();
703
+ }
704
+ digest() {
705
+ const out = new Uint8Array(this.oHash.outputLen);
706
+ this.digestInto(out);
707
+ return out;
708
+ }
709
+ _cloneInto(to) {
710
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
711
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
712
+ to = to;
713
+ to.finished = finished;
714
+ to.destroyed = destroyed;
715
+ to.blockLen = blockLen;
716
+ to.outputLen = outputLen;
717
+ to.oHash = oHash._cloneInto(to.oHash);
718
+ to.iHash = iHash._cloneInto(to.iHash);
719
+ return to;
720
+ }
721
+ clone() {
722
+ return this._cloneInto();
723
+ }
724
+ destroy() {
725
+ this.destroyed = true;
726
+ this.oHash.destroy();
727
+ this.iHash.destroy();
728
+ }
729
+ };
730
+ /**
731
+ * HMAC: RFC2104 message authentication code.
732
+ * @param hash - function that would be used e.g. sha256
733
+ * @param key - message key
734
+ * @param message - message data
735
+ * @example
736
+ * import { hmac } from '@noble/hashes/hmac';
737
+ * import { sha256 } from '@noble/hashes/sha2';
738
+ * const mac1 = hmac(sha256, 'key', 'message');
739
+ */
740
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
741
+ hmac.create = (hash, key) => new HMAC(hash, key);
742
+ //#endregion
743
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/modular.js
744
+ /**
745
+ * Utils for modular division and finite fields.
746
+ * A finite field over 11 is integer number operations `mod 11`.
747
+ * There is no division: it is replaced by modular multiplicative inverse.
748
+ * @module
749
+ */
750
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
751
+ const _0n$3 = BigInt(0);
752
+ const _1n$3 = BigInt(1);
753
+ const _2n$1 = /* @__PURE__ */ BigInt(2);
754
+ const _3n$1 = /* @__PURE__ */ BigInt(3);
755
+ const _4n$1 = /* @__PURE__ */ BigInt(4);
756
+ const _5n = /* @__PURE__ */ BigInt(5);
757
+ const _8n = /* @__PURE__ */ BigInt(8);
758
+ function mod(a, b) {
759
+ const result = a % b;
760
+ return result >= _0n$3 ? result : b + result;
761
+ }
762
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
763
+ function pow2(x, power, modulo) {
764
+ let res = x;
765
+ while (power-- > _0n$3) {
766
+ res *= res;
767
+ res %= modulo;
768
+ }
769
+ return res;
770
+ }
771
+ /**
772
+ * Inverses number over modulo.
773
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
774
+ */
775
+ function invert(number, modulo) {
776
+ if (number === _0n$3) throw new Error("invert: expected non-zero number");
777
+ if (modulo <= _0n$3) throw new Error("invert: expected positive modulus, got " + modulo);
778
+ let a = mod(number, modulo);
779
+ let b = modulo;
780
+ let x = _0n$3, y = _1n$3, u = _1n$3, v = _0n$3;
781
+ while (a !== _0n$3) {
782
+ const q = b / a;
783
+ const r = b % a;
784
+ const m = x - u * q;
785
+ const n = y - v * q;
786
+ b = a, a = r, x = u, y = v, u = m, v = n;
787
+ }
788
+ if (b !== _1n$3) throw new Error("invert: does not exist");
789
+ return mod(x, modulo);
790
+ }
791
+ function sqrt3mod4(Fp, n) {
792
+ const p1div4 = (Fp.ORDER + _1n$3) / _4n$1;
793
+ const root = Fp.pow(n, p1div4);
794
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
795
+ return root;
796
+ }
797
+ function sqrt5mod8(Fp, n) {
798
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
799
+ const n2 = Fp.mul(n, _2n$1);
800
+ const v = Fp.pow(n2, p5div8);
801
+ const nv = Fp.mul(n, v);
802
+ const i = Fp.mul(Fp.mul(nv, _2n$1), v);
803
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
804
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
805
+ return root;
806
+ }
807
+ /**
808
+ * Tonelli-Shanks square root search algorithm.
809
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
810
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
811
+ * @param P field order
812
+ * @returns function that takes field Fp (created from P) and number n
813
+ */
814
+ function tonelliShanks(P) {
815
+ if (P < BigInt(3)) throw new Error("sqrt is not defined for small field");
816
+ let Q = P - _1n$3;
817
+ let S = 0;
818
+ while (Q % _2n$1 === _0n$3) {
819
+ Q /= _2n$1;
820
+ S++;
821
+ }
822
+ let Z = _2n$1;
823
+ const _Fp = Field(P);
824
+ while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
825
+ if (S === 1) return sqrt3mod4;
826
+ let cc = _Fp.pow(Z, Q);
827
+ const Q1div2 = (Q + _1n$3) / _2n$1;
828
+ return function tonelliSlow(Fp, n) {
829
+ if (Fp.is0(n)) return n;
830
+ if (FpLegendre(Fp, n) !== 1) throw new Error("Cannot find square root");
831
+ let M = S;
832
+ let c = Fp.mul(Fp.ONE, cc);
833
+ let t = Fp.pow(n, Q);
834
+ let R = Fp.pow(n, Q1div2);
835
+ while (!Fp.eql(t, Fp.ONE)) {
836
+ if (Fp.is0(t)) return Fp.ZERO;
837
+ let i = 1;
838
+ let t_tmp = Fp.sqr(t);
839
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
840
+ i++;
841
+ t_tmp = Fp.sqr(t_tmp);
842
+ if (i === M) throw new Error("Cannot find square root");
843
+ }
844
+ const exponent = _1n$3 << BigInt(M - i - 1);
845
+ const b = Fp.pow(c, exponent);
846
+ M = i;
847
+ c = Fp.sqr(b);
848
+ t = Fp.mul(t, c);
849
+ R = Fp.mul(R, b);
850
+ }
851
+ return R;
852
+ };
853
+ }
854
+ /**
855
+ * Square root for a finite field. Will try optimized versions first:
856
+ *
857
+ * 1. P ≡ 3 (mod 4)
858
+ * 2. P ≡ 5 (mod 8)
859
+ * 3. Tonelli-Shanks algorithm
860
+ *
861
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
862
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
863
+ */
864
+ function FpSqrt(P) {
865
+ if (P % _4n$1 === _3n$1) return sqrt3mod4;
866
+ if (P % _8n === _5n) return sqrt5mod8;
867
+ return tonelliShanks(P);
868
+ }
869
+ const FIELD_FIELDS = [
870
+ "create",
871
+ "isValid",
872
+ "is0",
873
+ "neg",
874
+ "inv",
875
+ "sqrt",
876
+ "sqr",
877
+ "eql",
878
+ "add",
879
+ "sub",
880
+ "mul",
881
+ "pow",
882
+ "div",
883
+ "addN",
884
+ "subN",
885
+ "mulN",
886
+ "sqrN"
887
+ ];
888
+ function validateField(field) {
889
+ return validateObject(field, FIELD_FIELDS.reduce((map, val) => {
890
+ map[val] = "function";
891
+ return map;
892
+ }, {
893
+ ORDER: "bigint",
894
+ MASK: "bigint",
895
+ BYTES: "isSafeInteger",
896
+ BITS: "isSafeInteger"
897
+ }));
898
+ }
899
+ /**
900
+ * Same as `pow` but for Fp: non-constant-time.
901
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
902
+ */
903
+ function FpPow(Fp, num, power) {
904
+ if (power < _0n$3) throw new Error("invalid exponent, negatives unsupported");
905
+ if (power === _0n$3) return Fp.ONE;
906
+ if (power === _1n$3) return num;
907
+ let p = Fp.ONE;
908
+ let d = num;
909
+ while (power > _0n$3) {
910
+ if (power & _1n$3) p = Fp.mul(p, d);
911
+ d = Fp.sqr(d);
912
+ power >>= _1n$3;
913
+ }
914
+ return p;
915
+ }
916
+ /**
917
+ * Efficiently invert an array of Field elements.
918
+ * Exception-free. Will return `undefined` for 0 elements.
919
+ * @param passZero map 0 to 0 (instead of undefined)
920
+ */
921
+ function FpInvertBatch(Fp, nums, passZero = false) {
922
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
923
+ const multipliedAcc = nums.reduce((acc, num, i) => {
924
+ if (Fp.is0(num)) return acc;
925
+ inverted[i] = acc;
926
+ return Fp.mul(acc, num);
927
+ }, Fp.ONE);
928
+ const invertedAcc = Fp.inv(multipliedAcc);
929
+ nums.reduceRight((acc, num, i) => {
930
+ if (Fp.is0(num)) return acc;
931
+ inverted[i] = Fp.mul(acc, inverted[i]);
932
+ return Fp.mul(acc, num);
933
+ }, invertedAcc);
934
+ return inverted;
935
+ }
936
+ /**
937
+ * Legendre symbol.
938
+ * Legendre constant is used to calculate Legendre symbol (a | p)
939
+ * which denotes the value of a^((p-1)/2) (mod p).
940
+ *
941
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
942
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
943
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
944
+ */
945
+ function FpLegendre(Fp, n) {
946
+ const p1mod2 = (Fp.ORDER - _1n$3) / _2n$1;
947
+ const powered = Fp.pow(n, p1mod2);
948
+ const yes = Fp.eql(powered, Fp.ONE);
949
+ const zero = Fp.eql(powered, Fp.ZERO);
950
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
951
+ if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
952
+ return yes ? 1 : zero ? 0 : -1;
953
+ }
954
+ function nLength(n, nBitLength) {
955
+ if (nBitLength !== void 0) anumber(nBitLength);
956
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
957
+ return {
958
+ nBitLength: _nBitLength,
959
+ nByteLength: Math.ceil(_nBitLength / 8)
960
+ };
961
+ }
962
+ /**
963
+ * Initializes a finite field over prime.
964
+ * Major performance optimizations:
965
+ * * a) denormalized operations like mulN instead of mul
966
+ * * b) same object shape: never add or remove keys
967
+ * * c) Object.freeze
968
+ * Fragile: always run a benchmark on a change.
969
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
970
+ * it is caller responsibility to check this.
971
+ * This is low-level code, please make sure you know what you're doing.
972
+ * @param ORDER prime positive bigint
973
+ * @param bitLen how many bits the field consumes
974
+ * @param isLE (def: false) if encoding / decoding should be in little-endian
975
+ * @param redef optional faster redefinitions of sqrt and other methods
976
+ */
977
+ function Field(ORDER, bitLen, isLE = false, redef = {}) {
978
+ if (ORDER <= _0n$3) throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
979
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
980
+ if (BYTES > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
981
+ let sqrtP;
982
+ const f = Object.freeze({
983
+ ORDER,
984
+ isLE,
985
+ BITS,
986
+ BYTES,
987
+ MASK: bitMask(BITS),
988
+ ZERO: _0n$3,
989
+ ONE: _1n$3,
990
+ create: (num) => mod(num, ORDER),
991
+ isValid: (num) => {
992
+ if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num);
993
+ return _0n$3 <= num && num < ORDER;
994
+ },
995
+ is0: (num) => num === _0n$3,
996
+ isOdd: (num) => (num & _1n$3) === _1n$3,
997
+ neg: (num) => mod(-num, ORDER),
998
+ eql: (lhs, rhs) => lhs === rhs,
999
+ sqr: (num) => mod(num * num, ORDER),
1000
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
1001
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
1002
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
1003
+ pow: (num, power) => FpPow(f, num, power),
1004
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
1005
+ sqrN: (num) => num * num,
1006
+ addN: (lhs, rhs) => lhs + rhs,
1007
+ subN: (lhs, rhs) => lhs - rhs,
1008
+ mulN: (lhs, rhs) => lhs * rhs,
1009
+ inv: (num) => invert(num, ORDER),
1010
+ sqrt: redef.sqrt || ((n) => {
1011
+ if (!sqrtP) sqrtP = FpSqrt(ORDER);
1012
+ return sqrtP(f, n);
1013
+ }),
1014
+ toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
1015
+ fromBytes: (bytes) => {
1016
+ if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1017
+ return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1018
+ },
1019
+ invertBatch: (lst) => FpInvertBatch(f, lst),
1020
+ cmov: (a, b, c) => c ? b : a
1021
+ });
1022
+ return Object.freeze(f);
1023
+ }
1024
+ /**
1025
+ * Returns total number of bytes consumed by the field element.
1026
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
1027
+ * @param fieldOrder number of field elements, usually CURVE.n
1028
+ * @returns byte length of field
1029
+ */
1030
+ function getFieldBytesLength(fieldOrder) {
1031
+ if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
1032
+ const bitLength = fieldOrder.toString(2).length;
1033
+ return Math.ceil(bitLength / 8);
1034
+ }
1035
+ /**
1036
+ * Returns minimal amount of bytes that can be safely reduced
1037
+ * by field order.
1038
+ * Should be 2^-128 for 128-bit curve such as P256.
1039
+ * @param fieldOrder number of field elements, usually CURVE.n
1040
+ * @returns byte length of target hash
1041
+ */
1042
+ function getMinHashLength(fieldOrder) {
1043
+ const length = getFieldBytesLength(fieldOrder);
1044
+ return length + Math.ceil(length / 2);
1045
+ }
1046
+ /**
1047
+ * "Constant-time" private key generation utility.
1048
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
1049
+ * and convert them into private scalar, with the modulo bias being negligible.
1050
+ * Needs at least 48 bytes of input for 32-byte private key.
1051
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
1052
+ * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
1053
+ * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
1054
+ * @param hash hash output from SHA3 or a similar function
1055
+ * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
1056
+ * @param isLE interpret hash bytes as LE num
1057
+ * @returns valid private scalar
1058
+ */
1059
+ function mapHashToField(key, fieldOrder, isLE = false) {
1060
+ const len = key.length;
1061
+ const fieldLen = getFieldBytesLength(fieldOrder);
1062
+ const minLen = getMinHashLength(fieldOrder);
1063
+ if (len < 16 || len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
1064
+ const reduced = mod(isLE ? bytesToNumberLE(key) : bytesToNumberBE(key), fieldOrder - _1n$3) + _1n$3;
1065
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1066
+ }
1067
+ //#endregion
1068
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/curve.js
1069
+ /**
1070
+ * Methods for elliptic curve multiplication by scalars.
1071
+ * Contains wNAF, pippenger
1072
+ * @module
1073
+ */
1074
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1075
+ const _0n$2 = BigInt(0);
1076
+ const _1n$2 = BigInt(1);
1077
+ function constTimeNegate(condition, item) {
1078
+ const neg = item.negate();
1079
+ return condition ? neg : item;
1080
+ }
1081
+ function validateW(W, bits) {
1082
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1083
+ }
1084
+ function calcWOpts(W, scalarBits) {
1085
+ validateW(W, scalarBits);
1086
+ const windows = Math.ceil(scalarBits / W) + 1;
1087
+ const windowSize = 2 ** (W - 1);
1088
+ const maxNumber = 2 ** W;
1089
+ return {
1090
+ windows,
1091
+ windowSize,
1092
+ mask: bitMask(W),
1093
+ maxNumber,
1094
+ shiftBy: BigInt(W)
1095
+ };
1096
+ }
1097
+ function calcOffsets(n, window, wOpts) {
1098
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1099
+ let wbits = Number(n & mask);
1100
+ let nextN = n >> shiftBy;
1101
+ if (wbits > windowSize) {
1102
+ wbits -= maxNumber;
1103
+ nextN += _1n$2;
1104
+ }
1105
+ const offsetStart = window * windowSize;
1106
+ const offset = offsetStart + Math.abs(wbits) - 1;
1107
+ const isZero = wbits === 0;
1108
+ const isNeg = wbits < 0;
1109
+ const isNegF = window % 2 !== 0;
1110
+ return {
1111
+ nextN,
1112
+ offset,
1113
+ isZero,
1114
+ isNeg,
1115
+ isNegF,
1116
+ offsetF: offsetStart
1117
+ };
1118
+ }
1119
+ function validateMSMPoints(points, c) {
1120
+ if (!Array.isArray(points)) throw new Error("array expected");
1121
+ points.forEach((p, i) => {
1122
+ if (!(p instanceof c)) throw new Error("invalid point at index " + i);
1123
+ });
1124
+ }
1125
+ function validateMSMScalars(scalars, field) {
1126
+ if (!Array.isArray(scalars)) throw new Error("array of scalars expected");
1127
+ scalars.forEach((s, i) => {
1128
+ if (!field.isValid(s)) throw new Error("invalid scalar at index " + i);
1129
+ });
1130
+ }
1131
+ const pointPrecomputes = /* @__PURE__ */ new WeakMap();
1132
+ const pointWindowSizes = /* @__PURE__ */ new WeakMap();
1133
+ function getW(P) {
1134
+ return pointWindowSizes.get(P) || 1;
1135
+ }
1136
+ /**
1137
+ * Elliptic curve multiplication of Point by scalar. Fragile.
1138
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
1139
+ * Creates precomputation tables for fast multiplication:
1140
+ * - private scalar is split by fixed size windows of W bits
1141
+ * - every window point is collected from window's table & added to accumulator
1142
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
1143
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1144
+ * - +1 window is neccessary for wNAF
1145
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1146
+ *
1147
+ * @todo Research returning 2d JS array of windows, instead of a single window.
1148
+ * This would allow windows to be in different memory locations
1149
+ */
1150
+ function wNAF(c, bits) {
1151
+ return {
1152
+ constTimeNegate,
1153
+ hasPrecomputes(elm) {
1154
+ return getW(elm) !== 1;
1155
+ },
1156
+ unsafeLadder(elm, n, p = c.ZERO) {
1157
+ let d = elm;
1158
+ while (n > _0n$2) {
1159
+ if (n & _1n$2) p = p.add(d);
1160
+ d = d.double();
1161
+ n >>= _1n$2;
1162
+ }
1163
+ return p;
1164
+ },
1165
+ /**
1166
+ * Creates a wNAF precomputation window. Used for caching.
1167
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1168
+ * Number of precomputed points depends on the curve size:
1169
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1170
+ * - 𝑊 is the window size
1171
+ * - 𝑛 is the bitlength of the curve order.
1172
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1173
+ * @param elm Point instance
1174
+ * @param W window size
1175
+ * @returns precomputed point tables flattened to a single array
1176
+ */
1177
+ precomputeWindow(elm, W) {
1178
+ const { windows, windowSize } = calcWOpts(W, bits);
1179
+ const points = [];
1180
+ let p = elm;
1181
+ let base = p;
1182
+ for (let window = 0; window < windows; window++) {
1183
+ base = p;
1184
+ points.push(base);
1185
+ for (let i = 1; i < windowSize; i++) {
1186
+ base = base.add(p);
1187
+ points.push(base);
1188
+ }
1189
+ p = base.double();
1190
+ }
1191
+ return points;
1192
+ },
1193
+ /**
1194
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1195
+ * @param W window size
1196
+ * @param precomputes precomputed tables
1197
+ * @param n scalar (we don't check here, but should be less than curve order)
1198
+ * @returns real and fake (for const-time) points
1199
+ */
1200
+ wNAF(W, precomputes, n) {
1201
+ let p = c.ZERO;
1202
+ let f = c.BASE;
1203
+ const wo = calcWOpts(W, bits);
1204
+ for (let window = 0; window < wo.windows; window++) {
1205
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1206
+ n = nextN;
1207
+ if (isZero) f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
1208
+ else p = p.add(constTimeNegate(isNeg, precomputes[offset]));
1209
+ }
1210
+ return {
1211
+ p,
1212
+ f
1213
+ };
1214
+ },
1215
+ /**
1216
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1217
+ * @param W window size
1218
+ * @param precomputes precomputed tables
1219
+ * @param n scalar (we don't check here, but should be less than curve order)
1220
+ * @param acc accumulator point to add result of multiplication
1221
+ * @returns point
1222
+ */
1223
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
1224
+ const wo = calcWOpts(W, bits);
1225
+ for (let window = 0; window < wo.windows; window++) {
1226
+ if (n === _0n$2) break;
1227
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1228
+ n = nextN;
1229
+ if (isZero) continue;
1230
+ else {
1231
+ const item = precomputes[offset];
1232
+ acc = acc.add(isNeg ? item.negate() : item);
1233
+ }
1234
+ }
1235
+ return acc;
1236
+ },
1237
+ getPrecomputes(W, P, transform) {
1238
+ let comp = pointPrecomputes.get(P);
1239
+ if (!comp) {
1240
+ comp = this.precomputeWindow(P, W);
1241
+ if (W !== 1) pointPrecomputes.set(P, transform(comp));
1242
+ }
1243
+ return comp;
1244
+ },
1245
+ wNAFCached(P, n, transform) {
1246
+ const W = getW(P);
1247
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
1248
+ },
1249
+ wNAFCachedUnsafe(P, n, transform, prev) {
1250
+ const W = getW(P);
1251
+ if (W === 1) return this.unsafeLadder(P, n, prev);
1252
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
1253
+ },
1254
+ setWindowSize(P, W) {
1255
+ validateW(W, bits);
1256
+ pointWindowSizes.set(P, W);
1257
+ pointPrecomputes.delete(P);
1258
+ }
1259
+ };
1260
+ }
1261
+ /**
1262
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
1263
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
1264
+ * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
1265
+ * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
1266
+ * @param c Curve Point constructor
1267
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
1268
+ * @param points array of L curve points
1269
+ * @param scalars array of L scalars (aka private keys / bigints)
1270
+ */
1271
+ function pippenger(c, fieldN, points, scalars) {
1272
+ validateMSMPoints(points, c);
1273
+ validateMSMScalars(scalars, fieldN);
1274
+ const plength = points.length;
1275
+ const slength = scalars.length;
1276
+ if (plength !== slength) throw new Error("arrays of points and scalars must have equal length");
1277
+ const zero = c.ZERO;
1278
+ const wbits = bitLen(BigInt(plength));
1279
+ let windowSize = 1;
1280
+ if (wbits > 12) windowSize = wbits - 3;
1281
+ else if (wbits > 4) windowSize = wbits - 2;
1282
+ else if (wbits > 0) windowSize = 2;
1283
+ const MASK = bitMask(windowSize);
1284
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
1285
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
1286
+ let sum = zero;
1287
+ for (let i = lastBits; i >= 0; i -= windowSize) {
1288
+ buckets.fill(zero);
1289
+ for (let j = 0; j < slength; j++) {
1290
+ const scalar = scalars[j];
1291
+ const wbits = Number(scalar >> BigInt(i) & MASK);
1292
+ buckets[wbits] = buckets[wbits].add(points[j]);
1293
+ }
1294
+ let resI = zero;
1295
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
1296
+ sumI = sumI.add(buckets[j]);
1297
+ resI = resI.add(sumI);
1298
+ }
1299
+ sum = sum.add(resI);
1300
+ if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();
1301
+ }
1302
+ return sum;
1303
+ }
1304
+ function validateBasic(curve) {
1305
+ validateField(curve.Fp);
1306
+ validateObject(curve, {
1307
+ n: "bigint",
1308
+ h: "bigint",
1309
+ Gx: "field",
1310
+ Gy: "field"
1311
+ }, {
1312
+ nBitLength: "isSafeInteger",
1313
+ nByteLength: "isSafeInteger"
1314
+ });
1315
+ return Object.freeze({
1316
+ ...nLength(curve.n, curve.nBitLength),
1317
+ ...curve,
1318
+ p: curve.Fp.ORDER
1319
+ });
1320
+ }
1321
+ //#endregion
1322
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/weierstrass.js
1323
+ /**
1324
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
1325
+ *
1326
+ * ### Parameters
1327
+ *
1328
+ * To initialize a weierstrass curve, one needs to pass following params:
1329
+ *
1330
+ * * a: formula param
1331
+ * * b: formula param
1332
+ * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field
1333
+ * * n: order of prime subgroup a.k.a total amount of valid curve points
1334
+ * * Gx: Base point (x, y) aka generator point. Gx = x coordinate
1335
+ * * Gy: ...y coordinate
1336
+ * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
1337
+ * * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
1338
+ *
1339
+ * ### Design rationale for types
1340
+ *
1341
+ * * Interaction between classes from different curves should fail:
1342
+ * `k256.Point.BASE.add(p256.Point.BASE)`
1343
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
1344
+ * * Different calls of `curve()` would return different classes -
1345
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
1346
+ * it won't affect others
1347
+ *
1348
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
1349
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
1350
+ * unique type for every function call.
1351
+ *
1352
+ * We can use generic types via some param, like curve opts, but that would:
1353
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
1354
+ * which is hard to debug.
1355
+ * 2. Params can be generic and we can't enforce them to be constant value:
1356
+ * if somebody creates curve from non-constant params,
1357
+ * it would be allowed to interact with other curves with non-constant params
1358
+ *
1359
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
1360
+ * @module
1361
+ */
1362
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1363
+ function validateSigVerOpts(opts) {
1364
+ if (opts.lowS !== void 0) abool("lowS", opts.lowS);
1365
+ if (opts.prehash !== void 0) abool("prehash", opts.prehash);
1366
+ }
1367
+ function validatePointOpts(curve) {
1368
+ const opts = validateBasic(curve);
1369
+ validateObject(opts, {
1370
+ a: "field",
1371
+ b: "field"
1372
+ }, {
1373
+ allowInfinityPoint: "boolean",
1374
+ allowedPrivateKeyLengths: "array",
1375
+ clearCofactor: "function",
1376
+ fromBytes: "function",
1377
+ isTorsionFree: "function",
1378
+ toBytes: "function",
1379
+ wrapPrivateKey: "boolean"
1380
+ });
1381
+ const { endo, Fp, a } = opts;
1382
+ if (endo) {
1383
+ if (!Fp.eql(a, Fp.ZERO)) throw new Error("invalid endo: CURVE.a must be 0");
1384
+ if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") throw new Error("invalid endo: expected \"beta\": bigint and \"splitScalar\": function");
1385
+ }
1386
+ return Object.freeze({ ...opts });
1387
+ }
1388
+ var DERErr = class extends Error {
1389
+ constructor(m = "") {
1390
+ super(m);
1391
+ }
1392
+ };
1393
+ /**
1394
+ * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
1395
+ *
1396
+ * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
1397
+ *
1398
+ * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
1399
+ */
1400
+ const DER = {
1401
+ Err: DERErr,
1402
+ _tlv: {
1403
+ encode: (tag, data) => {
1404
+ const { Err: E } = DER;
1405
+ if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
1406
+ if (data.length & 1) throw new E("tlv.encode: unpadded data");
1407
+ const dataLen = data.length / 2;
1408
+ const len = numberToHexUnpadded(dataLen);
1409
+ if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big");
1410
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
1411
+ return numberToHexUnpadded(tag) + lenLen + len + data;
1412
+ },
1413
+ decode(tag, data) {
1414
+ const { Err: E } = DER;
1415
+ let pos = 0;
1416
+ if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
1417
+ if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv");
1418
+ const first = data[pos++];
1419
+ const isLong = !!(first & 128);
1420
+ let length = 0;
1421
+ if (!isLong) length = first;
1422
+ else {
1423
+ const lenLen = first & 127;
1424
+ if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported");
1425
+ if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big");
1426
+ const lengthBytes = data.subarray(pos, pos + lenLen);
1427
+ if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete");
1428
+ if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte");
1429
+ for (const b of lengthBytes) length = length << 8 | b;
1430
+ pos += lenLen;
1431
+ if (length < 128) throw new E("tlv.decode(long): not minimal encoding");
1432
+ }
1433
+ const v = data.subarray(pos, pos + length);
1434
+ if (v.length !== length) throw new E("tlv.decode: wrong value length");
1435
+ return {
1436
+ v,
1437
+ l: data.subarray(pos + length)
1438
+ };
1439
+ }
1440
+ },
1441
+ _int: {
1442
+ encode(num) {
1443
+ const { Err: E } = DER;
1444
+ if (num < _0n$1) throw new E("integer: negative integers are not allowed");
1445
+ let hex = numberToHexUnpadded(num);
1446
+ if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex;
1447
+ if (hex.length & 1) throw new E("unexpected DER parsing assertion: unpadded hex");
1448
+ return hex;
1449
+ },
1450
+ decode(data) {
1451
+ const { Err: E } = DER;
1452
+ if (data[0] & 128) throw new E("invalid signature integer: negative");
1453
+ if (data[0] === 0 && !(data[1] & 128)) throw new E("invalid signature integer: unnecessary leading zero");
1454
+ return bytesToNumberBE(data);
1455
+ }
1456
+ },
1457
+ toSig(hex) {
1458
+ const { Err: E, _int: int, _tlv: tlv } = DER;
1459
+ const data = ensureBytes("signature", hex);
1460
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
1461
+ if (seqLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
1462
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
1463
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
1464
+ if (sLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
1465
+ return {
1466
+ r: int.decode(rBytes),
1467
+ s: int.decode(sBytes)
1468
+ };
1469
+ },
1470
+ hexFromSig(sig) {
1471
+ const { _tlv: tlv, _int: int } = DER;
1472
+ const seq = tlv.encode(2, int.encode(sig.r)) + tlv.encode(2, int.encode(sig.s));
1473
+ return tlv.encode(48, seq);
1474
+ }
1475
+ };
1476
+ function numToSizedHex(num, size) {
1477
+ return bytesToHex(numberToBytesBE(num, size));
1478
+ }
1479
+ const _0n$1 = BigInt(0);
1480
+ const _1n$1 = BigInt(1);
1481
+ const _3n = BigInt(3);
1482
+ const _4n = BigInt(4);
1483
+ function weierstrassPoints(opts) {
1484
+ const CURVE = validatePointOpts(opts);
1485
+ const { Fp } = CURVE;
1486
+ const Fn = Field(CURVE.n, CURVE.nBitLength);
1487
+ const toBytes = CURVE.toBytes || ((_c, point, _isCompressed) => {
1488
+ const a = point.toAffine();
1489
+ return concatBytes(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
1490
+ });
1491
+ const fromBytes = CURVE.fromBytes || ((bytes) => {
1492
+ const tail = bytes.subarray(1);
1493
+ return {
1494
+ x: Fp.fromBytes(tail.subarray(0, Fp.BYTES)),
1495
+ y: Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES))
1496
+ };
1497
+ });
1498
+ /**
1499
+ * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
1500
+ * @returns y²
1501
+ */
1502
+ function weierstrassEquation(x) {
1503
+ const { a, b } = CURVE;
1504
+ const x2 = Fp.sqr(x);
1505
+ const x3 = Fp.mul(x2, x);
1506
+ return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
1507
+ }
1508
+ function isValidXY(x, y) {
1509
+ const left = Fp.sqr(y);
1510
+ const right = weierstrassEquation(x);
1511
+ return Fp.eql(left, right);
1512
+ }
1513
+ if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
1514
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
1515
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
1516
+ if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error("bad curve params: a or b");
1517
+ function isWithinCurveOrder(num) {
1518
+ return inRange(num, _1n$1, CURVE.n);
1519
+ }
1520
+ function normPrivateKeyToScalar(key) {
1521
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
1522
+ if (lengths && typeof key !== "bigint") {
1523
+ if (isBytes(key)) key = bytesToHex(key);
1524
+ if (typeof key !== "string" || !lengths.includes(key.length)) throw new Error("invalid private key");
1525
+ key = key.padStart(nByteLength * 2, "0");
1526
+ }
1527
+ let num;
1528
+ try {
1529
+ num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
1530
+ } catch (error) {
1531
+ throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
1532
+ }
1533
+ if (wrapPrivateKey) num = mod(num, N);
1534
+ aInRange("private key", num, _1n$1, N);
1535
+ return num;
1536
+ }
1537
+ function aprjpoint(other) {
1538
+ if (!(other instanceof Point)) throw new Error("ProjectivePoint expected");
1539
+ }
1540
+ const toAffineMemo = memoized((p, iz) => {
1541
+ const { px: x, py: y, pz: z } = p;
1542
+ if (Fp.eql(z, Fp.ONE)) return {
1543
+ x,
1544
+ y
1545
+ };
1546
+ const is0 = p.is0();
1547
+ if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);
1548
+ const ax = Fp.mul(x, iz);
1549
+ const ay = Fp.mul(y, iz);
1550
+ const zz = Fp.mul(z, iz);
1551
+ if (is0) return {
1552
+ x: Fp.ZERO,
1553
+ y: Fp.ZERO
1554
+ };
1555
+ if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
1556
+ return {
1557
+ x: ax,
1558
+ y: ay
1559
+ };
1560
+ });
1561
+ const assertValidMemo = memoized((p) => {
1562
+ if (p.is0()) {
1563
+ if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return;
1564
+ throw new Error("bad point: ZERO");
1565
+ }
1566
+ const { x, y } = p.toAffine();
1567
+ if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not FE");
1568
+ if (!isValidXY(x, y)) throw new Error("bad point: equation left != right");
1569
+ if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup");
1570
+ return true;
1571
+ });
1572
+ /**
1573
+ * Projective Point works in 3d / projective (homogeneous) coordinates: (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
1574
+ * Default Point works in 2d / affine coordinates: (x, y)
1575
+ * We're doing calculations in projective, because its operations don't require costly inversion.
1576
+ */
1577
+ class Point {
1578
+ constructor(px, py, pz) {
1579
+ if (px == null || !Fp.isValid(px)) throw new Error("x required");
1580
+ if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error("y required");
1581
+ if (pz == null || !Fp.isValid(pz)) throw new Error("z required");
1582
+ this.px = px;
1583
+ this.py = py;
1584
+ this.pz = pz;
1585
+ Object.freeze(this);
1586
+ }
1587
+ static fromAffine(p) {
1588
+ const { x, y } = p || {};
1589
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point");
1590
+ if (p instanceof Point) throw new Error("projective point not allowed");
1591
+ const is0 = (i) => Fp.eql(i, Fp.ZERO);
1592
+ if (is0(x) && is0(y)) return Point.ZERO;
1593
+ return new Point(x, y, Fp.ONE);
1594
+ }
1595
+ get x() {
1596
+ return this.toAffine().x;
1597
+ }
1598
+ get y() {
1599
+ return this.toAffine().y;
1600
+ }
1601
+ /**
1602
+ * Takes a bunch of Projective Points but executes only one
1603
+ * inversion on all of them. Inversion is very slow operation,
1604
+ * so this improves performance massively.
1605
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
1606
+ */
1607
+ static normalizeZ(points) {
1608
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
1609
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1610
+ }
1611
+ /**
1612
+ * Converts hash string or Uint8Array to Point.
1613
+ * @param hex short/long ECDSA hex
1614
+ */
1615
+ static fromHex(hex) {
1616
+ const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
1617
+ P.assertValidity();
1618
+ return P;
1619
+ }
1620
+ static fromPrivateKey(privateKey) {
1621
+ return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
1622
+ }
1623
+ static msm(points, scalars) {
1624
+ return pippenger(Point, Fn, points, scalars);
1625
+ }
1626
+ _setWindowSize(windowSize) {
1627
+ wnaf.setWindowSize(this, windowSize);
1628
+ }
1629
+ assertValidity() {
1630
+ assertValidMemo(this);
1631
+ }
1632
+ hasEvenY() {
1633
+ const { y } = this.toAffine();
1634
+ if (Fp.isOdd) return !Fp.isOdd(y);
1635
+ throw new Error("Field doesn't support isOdd");
1636
+ }
1637
+ /**
1638
+ * Compare one point to another.
1639
+ */
1640
+ equals(other) {
1641
+ aprjpoint(other);
1642
+ const { px: X1, py: Y1, pz: Z1 } = this;
1643
+ const { px: X2, py: Y2, pz: Z2 } = other;
1644
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1645
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1646
+ return U1 && U2;
1647
+ }
1648
+ /**
1649
+ * Flips point to one corresponding to (x, -y) in Affine coordinates.
1650
+ */
1651
+ negate() {
1652
+ return new Point(this.px, Fp.neg(this.py), this.pz);
1653
+ }
1654
+ double() {
1655
+ const { a, b } = CURVE;
1656
+ const b3 = Fp.mul(b, _3n);
1657
+ const { px: X1, py: Y1, pz: Z1 } = this;
1658
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1659
+ let t0 = Fp.mul(X1, X1);
1660
+ let t1 = Fp.mul(Y1, Y1);
1661
+ let t2 = Fp.mul(Z1, Z1);
1662
+ let t3 = Fp.mul(X1, Y1);
1663
+ t3 = Fp.add(t3, t3);
1664
+ Z3 = Fp.mul(X1, Z1);
1665
+ Z3 = Fp.add(Z3, Z3);
1666
+ X3 = Fp.mul(a, Z3);
1667
+ Y3 = Fp.mul(b3, t2);
1668
+ Y3 = Fp.add(X3, Y3);
1669
+ X3 = Fp.sub(t1, Y3);
1670
+ Y3 = Fp.add(t1, Y3);
1671
+ Y3 = Fp.mul(X3, Y3);
1672
+ X3 = Fp.mul(t3, X3);
1673
+ Z3 = Fp.mul(b3, Z3);
1674
+ t2 = Fp.mul(a, t2);
1675
+ t3 = Fp.sub(t0, t2);
1676
+ t3 = Fp.mul(a, t3);
1677
+ t3 = Fp.add(t3, Z3);
1678
+ Z3 = Fp.add(t0, t0);
1679
+ t0 = Fp.add(Z3, t0);
1680
+ t0 = Fp.add(t0, t2);
1681
+ t0 = Fp.mul(t0, t3);
1682
+ Y3 = Fp.add(Y3, t0);
1683
+ t2 = Fp.mul(Y1, Z1);
1684
+ t2 = Fp.add(t2, t2);
1685
+ t0 = Fp.mul(t2, t3);
1686
+ X3 = Fp.sub(X3, t0);
1687
+ Z3 = Fp.mul(t2, t1);
1688
+ Z3 = Fp.add(Z3, Z3);
1689
+ Z3 = Fp.add(Z3, Z3);
1690
+ return new Point(X3, Y3, Z3);
1691
+ }
1692
+ add(other) {
1693
+ aprjpoint(other);
1694
+ const { px: X1, py: Y1, pz: Z1 } = this;
1695
+ const { px: X2, py: Y2, pz: Z2 } = other;
1696
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1697
+ const a = CURVE.a;
1698
+ const b3 = Fp.mul(CURVE.b, _3n);
1699
+ let t0 = Fp.mul(X1, X2);
1700
+ let t1 = Fp.mul(Y1, Y2);
1701
+ let t2 = Fp.mul(Z1, Z2);
1702
+ let t3 = Fp.add(X1, Y1);
1703
+ let t4 = Fp.add(X2, Y2);
1704
+ t3 = Fp.mul(t3, t4);
1705
+ t4 = Fp.add(t0, t1);
1706
+ t3 = Fp.sub(t3, t4);
1707
+ t4 = Fp.add(X1, Z1);
1708
+ let t5 = Fp.add(X2, Z2);
1709
+ t4 = Fp.mul(t4, t5);
1710
+ t5 = Fp.add(t0, t2);
1711
+ t4 = Fp.sub(t4, t5);
1712
+ t5 = Fp.add(Y1, Z1);
1713
+ X3 = Fp.add(Y2, Z2);
1714
+ t5 = Fp.mul(t5, X3);
1715
+ X3 = Fp.add(t1, t2);
1716
+ t5 = Fp.sub(t5, X3);
1717
+ Z3 = Fp.mul(a, t4);
1718
+ X3 = Fp.mul(b3, t2);
1719
+ Z3 = Fp.add(X3, Z3);
1720
+ X3 = Fp.sub(t1, Z3);
1721
+ Z3 = Fp.add(t1, Z3);
1722
+ Y3 = Fp.mul(X3, Z3);
1723
+ t1 = Fp.add(t0, t0);
1724
+ t1 = Fp.add(t1, t0);
1725
+ t2 = Fp.mul(a, t2);
1726
+ t4 = Fp.mul(b3, t4);
1727
+ t1 = Fp.add(t1, t2);
1728
+ t2 = Fp.sub(t0, t2);
1729
+ t2 = Fp.mul(a, t2);
1730
+ t4 = Fp.add(t4, t2);
1731
+ t0 = Fp.mul(t1, t4);
1732
+ Y3 = Fp.add(Y3, t0);
1733
+ t0 = Fp.mul(t5, t4);
1734
+ X3 = Fp.mul(t3, X3);
1735
+ X3 = Fp.sub(X3, t0);
1736
+ t0 = Fp.mul(t3, t1);
1737
+ Z3 = Fp.mul(t5, Z3);
1738
+ Z3 = Fp.add(Z3, t0);
1739
+ return new Point(X3, Y3, Z3);
1740
+ }
1741
+ subtract(other) {
1742
+ return this.add(other.negate());
1743
+ }
1744
+ is0() {
1745
+ return this.equals(Point.ZERO);
1746
+ }
1747
+ wNAF(n) {
1748
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
1749
+ }
1750
+ /**
1751
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
1752
+ * It's faster, but should only be used when you don't care about
1753
+ * an exposed private key e.g. sig verification, which works over *public* keys.
1754
+ */
1755
+ multiplyUnsafe(sc) {
1756
+ const { endo, n: N } = CURVE;
1757
+ aInRange("scalar", sc, _0n$1, N);
1758
+ const I = Point.ZERO;
1759
+ if (sc === _0n$1) return I;
1760
+ if (this.is0() || sc === _1n$1) return this;
1761
+ if (!endo || wnaf.hasPrecomputes(this)) return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
1762
+ /** See docs for {@link EndomorphismOpts} */
1763
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
1764
+ let k1p = I;
1765
+ let k2p = I;
1766
+ let d = this;
1767
+ while (k1 > _0n$1 || k2 > _0n$1) {
1768
+ if (k1 & _1n$1) k1p = k1p.add(d);
1769
+ if (k2 & _1n$1) k2p = k2p.add(d);
1770
+ d = d.double();
1771
+ k1 >>= _1n$1;
1772
+ k2 >>= _1n$1;
1773
+ }
1774
+ if (k1neg) k1p = k1p.negate();
1775
+ if (k2neg) k2p = k2p.negate();
1776
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
1777
+ return k1p.add(k2p);
1778
+ }
1779
+ /**
1780
+ * Constant time multiplication.
1781
+ * Uses wNAF method. Windowed method may be 10% faster,
1782
+ * but takes 2x longer to generate and consumes 2x memory.
1783
+ * Uses precomputes when available.
1784
+ * Uses endomorphism for Koblitz curves.
1785
+ * @param scalar by which the point would be multiplied
1786
+ * @returns New point
1787
+ */
1788
+ multiply(scalar) {
1789
+ const { endo, n: N } = CURVE;
1790
+ aInRange("scalar", scalar, _1n$1, N);
1791
+ let point, fake;
1792
+ /** See docs for {@link EndomorphismOpts} */
1793
+ if (endo) {
1794
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
1795
+ let { p: k1p, f: f1p } = this.wNAF(k1);
1796
+ let { p: k2p, f: f2p } = this.wNAF(k2);
1797
+ k1p = wnaf.constTimeNegate(k1neg, k1p);
1798
+ k2p = wnaf.constTimeNegate(k2neg, k2p);
1799
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
1800
+ point = k1p.add(k2p);
1801
+ fake = f1p.add(f2p);
1802
+ } else {
1803
+ const { p, f } = this.wNAF(scalar);
1804
+ point = p;
1805
+ fake = f;
1806
+ }
1807
+ return Point.normalizeZ([point, fake])[0];
1808
+ }
1809
+ /**
1810
+ * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
1811
+ * Not using Strauss-Shamir trick: precomputation tables are faster.
1812
+ * The trick could be useful if both P and Q are not G (not in our case).
1813
+ * @returns non-zero affine point
1814
+ */
1815
+ multiplyAndAddUnsafe(Q, a, b) {
1816
+ const G = Point.BASE;
1817
+ const mul = (P, a) => a === _0n$1 || a === _1n$1 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a);
1818
+ const sum = mul(this, a).add(mul(Q, b));
1819
+ return sum.is0() ? void 0 : sum;
1820
+ }
1821
+ toAffine(iz) {
1822
+ return toAffineMemo(this, iz);
1823
+ }
1824
+ isTorsionFree() {
1825
+ const { h: cofactor, isTorsionFree } = CURVE;
1826
+ if (cofactor === _1n$1) return true;
1827
+ if (isTorsionFree) return isTorsionFree(Point, this);
1828
+ throw new Error("isTorsionFree() has not been declared for the elliptic curve");
1829
+ }
1830
+ clearCofactor() {
1831
+ const { h: cofactor, clearCofactor } = CURVE;
1832
+ if (cofactor === _1n$1) return this;
1833
+ if (clearCofactor) return clearCofactor(Point, this);
1834
+ return this.multiplyUnsafe(CURVE.h);
1835
+ }
1836
+ toRawBytes(isCompressed = true) {
1837
+ abool("isCompressed", isCompressed);
1838
+ this.assertValidity();
1839
+ return toBytes(Point, this, isCompressed);
1840
+ }
1841
+ toHex(isCompressed = true) {
1842
+ abool("isCompressed", isCompressed);
1843
+ return bytesToHex(this.toRawBytes(isCompressed));
1844
+ }
1845
+ }
1846
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1847
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1848
+ const { endo, nBitLength } = CURVE;
1849
+ const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);
1850
+ return {
1851
+ CURVE,
1852
+ ProjectivePoint: Point,
1853
+ normPrivateKeyToScalar,
1854
+ weierstrassEquation,
1855
+ isWithinCurveOrder
1856
+ };
1857
+ }
1858
+ function validateOpts(curve) {
1859
+ const opts = validateBasic(curve);
1860
+ validateObject(opts, {
1861
+ hash: "hash",
1862
+ hmac: "function",
1863
+ randomBytes: "function"
1864
+ }, {
1865
+ bits2int: "function",
1866
+ bits2int_modN: "function",
1867
+ lowS: "boolean"
1868
+ });
1869
+ return Object.freeze({
1870
+ lowS: true,
1871
+ ...opts
1872
+ });
1873
+ }
1874
+ /**
1875
+ * Creates short weierstrass curve and ECDSA signature methods for it.
1876
+ * @example
1877
+ * import { Field } from '@noble/curves/abstract/modular';
1878
+ * // Before that, define BigInt-s: a, b, p, n, Gx, Gy
1879
+ * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })
1880
+ */
1881
+ function weierstrass(curveDef) {
1882
+ const CURVE = validateOpts(curveDef);
1883
+ const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
1884
+ const compressedLen = Fp.BYTES + 1;
1885
+ const uncompressedLen = 2 * Fp.BYTES + 1;
1886
+ function modN(a) {
1887
+ return mod(a, CURVE_ORDER);
1888
+ }
1889
+ function invN(a) {
1890
+ return invert(a, CURVE_ORDER);
1891
+ }
1892
+ const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
1893
+ ...CURVE,
1894
+ toBytes(_c, point, isCompressed) {
1895
+ const a = point.toAffine();
1896
+ const x = Fp.toBytes(a.x);
1897
+ const cat = concatBytes;
1898
+ abool("isCompressed", isCompressed);
1899
+ if (isCompressed) return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
1900
+ else return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
1901
+ },
1902
+ fromBytes(bytes) {
1903
+ const len = bytes.length;
1904
+ const head = bytes[0];
1905
+ const tail = bytes.subarray(1);
1906
+ if (len === compressedLen && (head === 2 || head === 3)) {
1907
+ const x = bytesToNumberBE(tail);
1908
+ if (!inRange(x, _1n$1, Fp.ORDER)) throw new Error("Point is not on curve");
1909
+ const y2 = weierstrassEquation(x);
1910
+ let y;
1911
+ try {
1912
+ y = Fp.sqrt(y2);
1913
+ } catch (sqrtError) {
1914
+ const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1915
+ throw new Error("Point is not on curve" + suffix);
1916
+ }
1917
+ const isYOdd = (y & _1n$1) === _1n$1;
1918
+ if ((head & 1) === 1 !== isYOdd) y = Fp.neg(y);
1919
+ return {
1920
+ x,
1921
+ y
1922
+ };
1923
+ } else if (len === uncompressedLen && head === 4) return {
1924
+ x: Fp.fromBytes(tail.subarray(0, Fp.BYTES)),
1925
+ y: Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES))
1926
+ };
1927
+ else {
1928
+ const cl = compressedLen;
1929
+ const ul = uncompressedLen;
1930
+ throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
1931
+ }
1932
+ }
1933
+ });
1934
+ function isBiggerThanHalfOrder(number) {
1935
+ return number > CURVE_ORDER >> _1n$1;
1936
+ }
1937
+ function normalizeS(s) {
1938
+ return isBiggerThanHalfOrder(s) ? modN(-s) : s;
1939
+ }
1940
+ const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
1941
+ /**
1942
+ * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
1943
+ */
1944
+ class Signature {
1945
+ constructor(r, s, recovery) {
1946
+ aInRange("r", r, _1n$1, CURVE_ORDER);
1947
+ aInRange("s", s, _1n$1, CURVE_ORDER);
1948
+ this.r = r;
1949
+ this.s = s;
1950
+ if (recovery != null) this.recovery = recovery;
1951
+ Object.freeze(this);
1952
+ }
1953
+ static fromCompact(hex) {
1954
+ const l = nByteLength;
1955
+ hex = ensureBytes("compactSignature", hex, l * 2);
1956
+ return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
1957
+ }
1958
+ static fromDER(hex) {
1959
+ const { r, s } = DER.toSig(ensureBytes("DER", hex));
1960
+ return new Signature(r, s);
1961
+ }
1962
+ /**
1963
+ * @todo remove
1964
+ * @deprecated
1965
+ */
1966
+ assertValidity() {}
1967
+ addRecoveryBit(recovery) {
1968
+ return new Signature(this.r, this.s, recovery);
1969
+ }
1970
+ recoverPublicKey(msgHash) {
1971
+ const { r, s, recovery: rec } = this;
1972
+ const h = bits2int_modN(ensureBytes("msgHash", msgHash));
1973
+ if (rec == null || ![
1974
+ 0,
1975
+ 1,
1976
+ 2,
1977
+ 3
1978
+ ].includes(rec)) throw new Error("recovery id invalid");
1979
+ const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
1980
+ if (radj >= Fp.ORDER) throw new Error("recovery id 2 or 3 invalid");
1981
+ const prefix = (rec & 1) === 0 ? "02" : "03";
1982
+ const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));
1983
+ const ir = invN(radj);
1984
+ const u1 = modN(-h * ir);
1985
+ const u2 = modN(s * ir);
1986
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
1987
+ if (!Q) throw new Error("point at infinify");
1988
+ Q.assertValidity();
1989
+ return Q;
1990
+ }
1991
+ hasHighS() {
1992
+ return isBiggerThanHalfOrder(this.s);
1993
+ }
1994
+ normalizeS() {
1995
+ return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
1996
+ }
1997
+ toDERRawBytes() {
1998
+ return hexToBytes(this.toDERHex());
1999
+ }
2000
+ toDERHex() {
2001
+ return DER.hexFromSig(this);
2002
+ }
2003
+ toCompactRawBytes() {
2004
+ return hexToBytes(this.toCompactHex());
2005
+ }
2006
+ toCompactHex() {
2007
+ const l = nByteLength;
2008
+ return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);
2009
+ }
2010
+ }
2011
+ const utils = {
2012
+ isValidPrivateKey(privateKey) {
2013
+ try {
2014
+ normPrivateKeyToScalar(privateKey);
2015
+ return true;
2016
+ } catch (error) {
2017
+ return false;
2018
+ }
2019
+ },
2020
+ normPrivateKeyToScalar,
2021
+ /**
2022
+ * Produces cryptographically secure private key from random of size
2023
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
2024
+ */
2025
+ randomPrivateKey: () => {
2026
+ const length = getMinHashLength(CURVE.n);
2027
+ return mapHashToField(CURVE.randomBytes(length), CURVE.n);
2028
+ },
2029
+ /**
2030
+ * Creates precompute table for an arbitrary EC point. Makes point "cached".
2031
+ * Allows to massively speed-up `point.multiply(scalar)`.
2032
+ * @returns cached point
2033
+ * @example
2034
+ * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
2035
+ * fast.multiply(privKey); // much faster ECDH now
2036
+ */
2037
+ precompute(windowSize = 8, point = Point.BASE) {
2038
+ point._setWindowSize(windowSize);
2039
+ point.multiply(BigInt(3));
2040
+ return point;
2041
+ }
2042
+ };
2043
+ /**
2044
+ * Computes public key for a private key. Checks for validity of the private key.
2045
+ * @param privateKey private key
2046
+ * @param isCompressed whether to return compact (default), or full key
2047
+ * @returns Public key, full when isCompressed=false; short when isCompressed=true
2048
+ */
2049
+ function getPublicKey(privateKey, isCompressed = true) {
2050
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
2051
+ }
2052
+ /**
2053
+ * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
2054
+ */
2055
+ function isProbPub(item) {
2056
+ if (typeof item === "bigint") return false;
2057
+ if (item instanceof Point) return true;
2058
+ const len = ensureBytes("key", item).length;
2059
+ const fpl = Fp.BYTES;
2060
+ const compLen = fpl + 1;
2061
+ const uncompLen = 2 * fpl + 1;
2062
+ if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) return;
2063
+ else return len === compLen || len === uncompLen;
2064
+ }
2065
+ /**
2066
+ * ECDH (Elliptic Curve Diffie Hellman).
2067
+ * Computes shared public key from private key and public key.
2068
+ * Checks: 1) private key validity 2) shared key is on-curve.
2069
+ * Does NOT hash the result.
2070
+ * @param privateA private key
2071
+ * @param publicB different public key
2072
+ * @param isCompressed whether to return compact (default), or full key
2073
+ * @returns shared public key
2074
+ */
2075
+ function getSharedSecret(privateA, publicB, isCompressed = true) {
2076
+ if (isProbPub(privateA) === true) throw new Error("first arg must be private key");
2077
+ if (isProbPub(publicB) === false) throw new Error("second arg must be public key");
2078
+ return Point.fromHex(publicB).multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
2079
+ }
2080
+ const bits2int = CURVE.bits2int || function(bytes) {
2081
+ if (bytes.length > 8192) throw new Error("input is too large");
2082
+ const num = bytesToNumberBE(bytes);
2083
+ const delta = bytes.length * 8 - nBitLength;
2084
+ return delta > 0 ? num >> BigInt(delta) : num;
2085
+ };
2086
+ const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
2087
+ return modN(bits2int(bytes));
2088
+ };
2089
+ const ORDER_MASK = bitMask(nBitLength);
2090
+ /**
2091
+ * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
2092
+ */
2093
+ function int2octets(num) {
2094
+ aInRange("num < 2^" + nBitLength, num, _0n$1, ORDER_MASK);
2095
+ return numberToBytesBE(num, nByteLength);
2096
+ }
2097
+ function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
2098
+ if (["recovered", "canonical"].some((k) => k in opts)) throw new Error("sign() legacy options not supported");
2099
+ const { hash, randomBytes } = CURVE;
2100
+ let { lowS, prehash, extraEntropy: ent } = opts;
2101
+ if (lowS == null) lowS = true;
2102
+ msgHash = ensureBytes("msgHash", msgHash);
2103
+ validateSigVerOpts(opts);
2104
+ if (prehash) msgHash = ensureBytes("prehashed msgHash", hash(msgHash));
2105
+ const h1int = bits2int_modN(msgHash);
2106
+ const d = normPrivateKeyToScalar(privateKey);
2107
+ const seedArgs = [int2octets(d), int2octets(h1int)];
2108
+ if (ent != null && ent !== false) {
2109
+ const e = ent === true ? randomBytes(Fp.BYTES) : ent;
2110
+ seedArgs.push(ensureBytes("extraEntropy", e));
2111
+ }
2112
+ const seed = concatBytes(...seedArgs);
2113
+ const m = h1int;
2114
+ function k2sig(kBytes) {
2115
+ const k = bits2int(kBytes);
2116
+ if (!isWithinCurveOrder(k)) return;
2117
+ const ik = invN(k);
2118
+ const q = Point.BASE.multiply(k).toAffine();
2119
+ const r = modN(q.x);
2120
+ if (r === _0n$1) return;
2121
+ const s = modN(ik * modN(m + r * d));
2122
+ if (s === _0n$1) return;
2123
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$1);
2124
+ let normS = s;
2125
+ if (lowS && isBiggerThanHalfOrder(s)) {
2126
+ normS = normalizeS(s);
2127
+ recovery ^= 1;
2128
+ }
2129
+ return new Signature(r, normS, recovery);
2130
+ }
2131
+ return {
2132
+ seed,
2133
+ k2sig
2134
+ };
2135
+ }
2136
+ const defaultSigOpts = {
2137
+ lowS: CURVE.lowS,
2138
+ prehash: false
2139
+ };
2140
+ const defaultVerOpts = {
2141
+ lowS: CURVE.lowS,
2142
+ prehash: false
2143
+ };
2144
+ /**
2145
+ * Signs message hash with a private key.
2146
+ * ```
2147
+ * sign(m, d, k) where
2148
+ * (x, y) = G × k
2149
+ * r = x mod n
2150
+ * s = (m + dr)/k mod n
2151
+ * ```
2152
+ * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.
2153
+ * @param privKey private key
2154
+ * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.
2155
+ * @returns signature with recovery param
2156
+ */
2157
+ function sign(msgHash, privKey, opts = defaultSigOpts) {
2158
+ const { seed, k2sig } = prepSig(msgHash, privKey, opts);
2159
+ const C = CURVE;
2160
+ return createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac)(seed, k2sig);
2161
+ }
2162
+ Point.BASE._setWindowSize(8);
2163
+ /**
2164
+ * Verifies a signature against message hash and public key.
2165
+ * Rejects lowS signatures by default: to override,
2166
+ * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
2167
+ *
2168
+ * ```
2169
+ * verify(r, s, h, P) where
2170
+ * U1 = hs^-1 mod n
2171
+ * U2 = rs^-1 mod n
2172
+ * R = U1⋅G - U2⋅P
2173
+ * mod(R.x, n) == r
2174
+ * ```
2175
+ */
2176
+ function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
2177
+ const sg = signature;
2178
+ msgHash = ensureBytes("msgHash", msgHash);
2179
+ publicKey = ensureBytes("publicKey", publicKey);
2180
+ const { lowS, prehash, format } = opts;
2181
+ validateSigVerOpts(opts);
2182
+ if ("strict" in opts) throw new Error("options.strict was renamed to lowS");
2183
+ if (format !== void 0 && format !== "compact" && format !== "der") throw new Error("format must be compact or der");
2184
+ const isHex = typeof sg === "string" || isBytes(sg);
2185
+ const isObj = !isHex && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
2186
+ if (!isHex && !isObj) throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
2187
+ let _sig = void 0;
2188
+ let P;
2189
+ try {
2190
+ if (isObj) _sig = new Signature(sg.r, sg.s);
2191
+ if (isHex) {
2192
+ try {
2193
+ if (format !== "compact") _sig = Signature.fromDER(sg);
2194
+ } catch (derError) {
2195
+ if (!(derError instanceof DER.Err)) throw derError;
2196
+ }
2197
+ if (!_sig && format !== "der") _sig = Signature.fromCompact(sg);
2198
+ }
2199
+ P = Point.fromHex(publicKey);
2200
+ } catch (error) {
2201
+ return false;
2202
+ }
2203
+ if (!_sig) return false;
2204
+ if (lowS && _sig.hasHighS()) return false;
2205
+ if (prehash) msgHash = CURVE.hash(msgHash);
2206
+ const { r, s } = _sig;
2207
+ const h = bits2int_modN(msgHash);
2208
+ const is = invN(s);
2209
+ const u1 = modN(h * is);
2210
+ const u2 = modN(r * is);
2211
+ const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
2212
+ if (!R) return false;
2213
+ return modN(R.x) === r;
2214
+ }
2215
+ return {
2216
+ CURVE,
2217
+ getPublicKey,
2218
+ getSharedSecret,
2219
+ sign,
2220
+ verify,
2221
+ ProjectivePoint: Point,
2222
+ Signature,
2223
+ utils
2224
+ };
2225
+ }
2226
+ //#endregion
2227
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/_shortw_utils.js
2228
+ /**
2229
+ * Utilities for short weierstrass curves, combined with noble-hashes.
2230
+ * @module
2231
+ */
2232
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2233
+ /** connects noble-curves to noble-hashes */
2234
+ function getHash(hash) {
2235
+ return {
2236
+ hash,
2237
+ hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)),
2238
+ randomBytes
2239
+ };
2240
+ }
2241
+ function createCurve(curveDef, defHash) {
2242
+ const create = (hash) => weierstrass({
2243
+ ...curveDef,
2244
+ ...getHash(hash)
2245
+ });
2246
+ return {
2247
+ ...create(defHash),
2248
+ create
2249
+ };
2250
+ }
2251
+ //#endregion
2252
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/secp256k1.js
2253
+ /**
2254
+ * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
2255
+ *
2256
+ * Seems to be rigid (not backdoored)
2257
+ * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
2258
+ *
2259
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
2260
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
2261
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
2262
+ * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
2263
+ * @module
2264
+ */
2265
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2266
+ const secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
2267
+ const secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
2268
+ const _0n = BigInt(0);
2269
+ const _1n = BigInt(1);
2270
+ const _2n = BigInt(2);
2271
+ const divNearest = (a, b) => (a + b / _2n) / b;
2272
+ /**
2273
+ * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
2274
+ * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
2275
+ */
2276
+ function sqrtMod(y) {
2277
+ const P = secp256k1P;
2278
+ const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
2279
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
2280
+ const b2 = y * y * y % P;
2281
+ const b3 = b2 * b2 * y % P;
2282
+ const b11 = pow2(pow2(pow2(b3, _3n, P) * b3 % P, _3n, P) * b3 % P, _2n, P) * b2 % P;
2283
+ const b22 = pow2(b11, _11n, P) * b11 % P;
2284
+ const b44 = pow2(b22, _22n, P) * b22 % P;
2285
+ const b88 = pow2(b44, _44n, P) * b44 % P;
2286
+ const root = pow2(pow2(pow2(pow2(pow2(pow2(b88, _88n, P) * b88 % P, _44n, P) * b44 % P, _3n, P) * b3 % P, _23n, P) * b22 % P, _6n, P) * b2 % P, _2n, P);
2287
+ if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error("Cannot find square root");
2288
+ return root;
2289
+ }
2290
+ const Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod });
2291
+ /**
2292
+ * secp256k1 curve, ECDSA and ECDH methods.
2293
+ *
2294
+ * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
2295
+ *
2296
+ * @example
2297
+ * ```js
2298
+ * import { secp256k1 } from '@noble/curves/secp256k1';
2299
+ * const priv = secp256k1.utils.randomPrivateKey();
2300
+ * const pub = secp256k1.getPublicKey(priv);
2301
+ * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
2302
+ * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
2303
+ * const isValid = secp256k1.verify(sig, msg, pub) === true;
2304
+ * ```
2305
+ */
2306
+ const secp256k1 = createCurve({
2307
+ a: _0n,
2308
+ b: BigInt(7),
2309
+ Fp: Fpk1,
2310
+ n: secp256k1N,
2311
+ Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
2312
+ Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
2313
+ h: BigInt(1),
2314
+ lowS: true,
2315
+ endo: {
2316
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
2317
+ splitScalar: (k) => {
2318
+ const n = secp256k1N;
2319
+ const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
2320
+ const b1 = -_1n * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
2321
+ const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
2322
+ const b2 = a1;
2323
+ const POW_2_128 = BigInt("0x100000000000000000000000000000000");
2324
+ const c1 = divNearest(b2 * k, n);
2325
+ const c2 = divNearest(-b1 * k, n);
2326
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
2327
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
2328
+ const k1neg = k1 > POW_2_128;
2329
+ const k2neg = k2 > POW_2_128;
2330
+ if (k1neg) k1 = n - k1;
2331
+ if (k2neg) k2 = n - k2;
2332
+ if (k1 > POW_2_128 || k2 > POW_2_128) throw new Error("splitScalar: Endomorphism failed, k=" + k);
2333
+ return {
2334
+ k1neg,
2335
+ k1,
2336
+ k2neg,
2337
+ k2
2338
+ };
2339
+ }
2340
+ }
2341
+ }, sha256);
2342
+ //#endregion
2343
+ export { aexists as a, clean as c, toBytes as d, u32 as f, abytes$1 as i, createHasher as l, sha256 as n, anumber as o, Hash as r, aoutput as s, secp256k1 as t, swap32IfBE as u };