@ghostlytools/cli 1.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.
Files changed (57) hide show
  1. package/README.md +405 -0
  2. package/SKILL.md +282 -0
  3. package/dist/assets/argon2id-088uQfnH.js +645 -0
  4. package/dist/assets/argon2id-088uQfnH.js.map +1 -0
  5. package/dist/assets/bark_ffi_wasm_bg-Bxru_BVW.wasm +0 -0
  6. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js +6 -0
  7. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -0
  8. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js +6 -0
  9. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -0
  10. package/dist/assets/bitcoindevkit_bg-CRkZTSbO.wasm +0 -0
  11. package/dist/assets/breez_sdk_spark_wasm_bg.wasm +0 -0
  12. package/dist/assets/endpoint-h3cqRyRz.js +185 -0
  13. package/dist/assets/endpoint-h3cqRyRz.js.map +1 -0
  14. package/dist/assets/fedimintWorker.mjs +95 -0
  15. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js +6 -0
  16. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js.map +1 -0
  17. package/dist/assets/fedimint_client_wasm_bg-DeFtkIv6.wasm +0 -0
  18. package/dist/assets/fileBytes-ByS16quP.js +154 -0
  19. package/dist/assets/fileBytes-ByS16quP.js.map +1 -0
  20. package/dist/assets/fileBytesIdb-COzoilo9.js +230 -0
  21. package/dist/assets/fileBytesIdb-COzoilo9.js.map +1 -0
  22. package/dist/assets/fileBytesOpfs-B27wAMUh.js +145 -0
  23. package/dist/assets/fileBytesOpfs-B27wAMUh.js.map +1 -0
  24. package/dist/assets/ghostly_iroh_web-CPa_YEfb.js +1154 -0
  25. package/dist/assets/ghostly_iroh_web-CPa_YEfb.js.map +1 -0
  26. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  27. package/dist/assets/hyperdhtRelay-BKsFpPjr.js +342 -0
  28. package/dist/assets/hyperdhtRelay-BKsFpPjr.js.map +1 -0
  29. package/dist/assets/legacy_ciphers-JJOu0JXL.js +5185 -0
  30. package/dist/assets/legacy_ciphers-JJOu0JXL.js.map +1 -0
  31. package/dist/assets/mainline-DOncVbJN.js +176 -0
  32. package/dist/assets/mainline-DOncVbJN.js.map +1 -0
  33. package/dist/assets/nacl-fast-CDhNCYHs.js +1512 -0
  34. package/dist/assets/nacl-fast-CDhNCYHs.js.map +1 -0
  35. package/dist/assets/noble_curves-DDWn5AH0.js +2978 -0
  36. package/dist/assets/noble_curves-DDWn5AH0.js.map +1 -0
  37. package/dist/assets/noble_hashes-B7AZyFyS.js +427 -0
  38. package/dist/assets/noble_hashes-B7AZyFyS.js.map +1 -0
  39. package/dist/assets/openpgp-BBFr-zHQ.js +16573 -0
  40. package/dist/assets/openpgp-BBFr-zHQ.js.map +1 -0
  41. package/dist/assets/server-5T5l8hfy.js +28293 -0
  42. package/dist/assets/server-5T5l8hfy.js.map +1 -0
  43. package/dist/assets/sha512-BYId-G-T.js +1034 -0
  44. package/dist/assets/sha512-BYId-G-T.js.map +1 -0
  45. package/dist/assets/src-DptDr2et.js +20971 -0
  46. package/dist/assets/src-DptDr2et.js.map +1 -0
  47. package/dist/assets/storage-Bya5b2Xt.js +1648 -0
  48. package/dist/assets/storage-Bya5b2Xt.js.map +1 -0
  49. package/dist/assets/tree-store-N362nuzZ.js +1031 -0
  50. package/dist/assets/tree-store-N362nuzZ.js.map +1 -0
  51. package/dist/assets/unbzip2-stream-B1C-JX9L.js +681 -0
  52. package/dist/assets/unbzip2-stream-B1C-JX9L.js.map +1 -0
  53. package/dist/assets/web-OUQl4Q7L.js +3802 -0
  54. package/dist/assets/web-OUQl4Q7L.js.map +1 -0
  55. package/dist/ghostly.mjs +17087 -0
  56. package/dist/ghostly.mjs.map +1 -0
  57. package/package.json +76 -0
@@ -0,0 +1,2978 @@
1
+ import { D as toBytes, E as shake256, T as sha512$1, a as abytes, b as sha384, c as anumber, d as concatBytes, f as createHasher, h as randomBytes, l as bytesToHex, m as isBytes, n as Hash, o as aexists, p as hexToBytes, s as ahash, u as clean, v as sha256, w as sha512, x as sha384$1, y as sha256$1 } from "./sha512-BYId-G-T.js";
2
+ //#region ../../node_modules/openpgp/dist/lightweight/noble_curves.mjs
3
+ /*! OpenPGP.js v6.3.2 - 2026-09-24 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
4
+ /**
5
+ * Hex, bytes and number utilities.
6
+ * @module
7
+ */
8
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
9
+ var _0n$5 = /* @__PURE__ */ BigInt(0);
10
+ var _1n$6 = /* @__PURE__ */ BigInt(1);
11
+ function _abool2(value, title = "") {
12
+ if (typeof value !== "boolean") {
13
+ const prefix = title && `"${title}"`;
14
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
15
+ }
16
+ return value;
17
+ }
18
+ /** Asserts something is Uint8Array. */
19
+ function _abytes2(value, length, title = "") {
20
+ const bytes = isBytes(value);
21
+ const len = value?.length;
22
+ const needsLen = length !== void 0;
23
+ if (!bytes || needsLen && len !== length) {
24
+ const prefix = title && `"${title}" `;
25
+ const ofLen = needsLen ? ` of length ${length}` : "";
26
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
27
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
28
+ }
29
+ return value;
30
+ }
31
+ function numberToHexUnpadded(num) {
32
+ const hex = num.toString(16);
33
+ return hex.length & 1 ? "0" + hex : hex;
34
+ }
35
+ function hexToNumber(hex) {
36
+ if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
37
+ return hex === "" ? _0n$5 : BigInt("0x" + hex);
38
+ }
39
+ function bytesToNumberBE(bytes) {
40
+ return hexToNumber(bytesToHex(bytes));
41
+ }
42
+ function bytesToNumberLE(bytes) {
43
+ abytes(bytes);
44
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
45
+ }
46
+ function numberToBytesBE(n, len) {
47
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
48
+ }
49
+ function numberToBytesLE(n, len) {
50
+ return numberToBytesBE(n, len).reverse();
51
+ }
52
+ /**
53
+ * Takes hex string or Uint8Array, converts to Uint8Array.
54
+ * Validates output length.
55
+ * Will throw error for other types.
56
+ * @param title descriptive title for an error e.g. 'secret key'
57
+ * @param hex hex string or Uint8Array
58
+ * @param expectedLength optional, will compare to result array's length
59
+ * @returns
60
+ */
61
+ function ensureBytes(title, hex, expectedLength) {
62
+ let res;
63
+ if (typeof hex === "string") try {
64
+ res = hexToBytes(hex);
65
+ } catch (e) {
66
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
67
+ }
68
+ else if (isBytes(hex)) res = Uint8Array.from(hex);
69
+ else throw new Error(title + " must be hex string or Uint8Array");
70
+ const len = res.length;
71
+ if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(title + " of length " + expectedLength + " expected, got " + len);
72
+ return res;
73
+ }
74
+ /**
75
+ * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
76
+ * and Buffer#slice creates mutable copy. Never use Buffers!
77
+ */
78
+ function copyBytes(bytes) {
79
+ return Uint8Array.from(bytes);
80
+ }
81
+ /**
82
+ * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
83
+ * Should be safe to use for things expected to be ASCII.
84
+ * Returns exact same result as utf8ToBytes for ASCII or throws.
85
+ */
86
+ function asciiToBytes(ascii) {
87
+ return Uint8Array.from(ascii, (c, i) => {
88
+ const charCode = c.charCodeAt(0);
89
+ if (c.length !== 1 || charCode > 127) throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
90
+ return charCode;
91
+ });
92
+ }
93
+ /**
94
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
95
+ */
96
+ /**
97
+ * Converts bytes to string using UTF8 encoding.
98
+ * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
99
+ */
100
+ var isPosBig = (n) => typeof n === "bigint" && _0n$5 <= n;
101
+ function inRange(n, min, max) {
102
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
103
+ }
104
+ /**
105
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
106
+ * @example
107
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
108
+ */
109
+ function aInRange(title, n, min, max) {
110
+ if (!inRange(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
111
+ }
112
+ /**
113
+ * Calculates amount of bits in a bigint.
114
+ * Same as `n.toString(2).length`
115
+ * TODO: merge with nLength in modular
116
+ */
117
+ function bitLen(n) {
118
+ let len = 0;
119
+ for (; n > _0n$5; n >>= _1n$6, len += 1);
120
+ return len;
121
+ }
122
+ /**
123
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
124
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
125
+ */
126
+ var bitMask = (n) => (_1n$6 << BigInt(n)) - _1n$6;
127
+ /**
128
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
129
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
130
+ * @example
131
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
132
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
133
+ */
134
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
135
+ if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number");
136
+ if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number");
137
+ if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function");
138
+ const u8n = (len) => new Uint8Array(len);
139
+ const u8of = (byte) => Uint8Array.of(byte);
140
+ let v = u8n(hashLen);
141
+ let k = u8n(hashLen);
142
+ let i = 0;
143
+ const reset = () => {
144
+ v.fill(1);
145
+ k.fill(0);
146
+ i = 0;
147
+ };
148
+ const h = (...b) => hmacFn(k, v, ...b);
149
+ const reseed = (seed = u8n(0)) => {
150
+ k = h(u8of(0), seed);
151
+ v = h();
152
+ if (seed.length === 0) return;
153
+ k = h(u8of(1), seed);
154
+ v = h();
155
+ };
156
+ const gen = () => {
157
+ if (i++ >= 1e3) throw new Error("drbg: tried 1000 values");
158
+ let len = 0;
159
+ const out = [];
160
+ while (len < qByteLen) {
161
+ v = h();
162
+ const sl = v.slice();
163
+ out.push(sl);
164
+ len += v.length;
165
+ }
166
+ return concatBytes(...out);
167
+ };
168
+ const genUntil = (seed, pred) => {
169
+ reset();
170
+ reseed(seed);
171
+ let res = void 0;
172
+ while (!(res = pred(gen()))) reseed();
173
+ reset();
174
+ return res;
175
+ };
176
+ return genUntil;
177
+ }
178
+ function _validateObject(object, fields, optFields = {}) {
179
+ if (!object || typeof object !== "object") throw new Error("expected valid options object");
180
+ function checkField(fieldName, expectedType, isOpt) {
181
+ const val = object[fieldName];
182
+ if (isOpt && val === void 0) return;
183
+ const current = typeof val;
184
+ if (current !== expectedType || val === null) throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
185
+ }
186
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
187
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
188
+ }
189
+ /**
190
+ * Memoizes (caches) computation result.
191
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
192
+ */
193
+ function memoized(fn) {
194
+ const map = /* @__PURE__ */ new WeakMap();
195
+ return (arg, ...args) => {
196
+ const val = map.get(arg);
197
+ if (val !== void 0) return val;
198
+ const computed = fn(arg, ...args);
199
+ map.set(arg, computed);
200
+ return computed;
201
+ };
202
+ }
203
+ /**
204
+ * Utils for modular division and fields.
205
+ * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
206
+ * There is no division: it is replaced by modular multiplicative inverse.
207
+ * @module
208
+ */
209
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
210
+ var _0n$4 = BigInt(0);
211
+ var _1n$5 = BigInt(1);
212
+ var _2n$5 = /* @__PURE__ */ BigInt(2);
213
+ var _3n$2 = /* @__PURE__ */ BigInt(3);
214
+ var _4n$1 = /* @__PURE__ */ BigInt(4);
215
+ var _5n = /* @__PURE__ */ BigInt(5);
216
+ var _7n = /* @__PURE__ */ BigInt(7);
217
+ var _8n$1 = /* @__PURE__ */ BigInt(8);
218
+ var _9n = /* @__PURE__ */ BigInt(9);
219
+ var _16n = /* @__PURE__ */ BigInt(16);
220
+ function mod(a, b) {
221
+ const result = a % b;
222
+ return result >= _0n$4 ? result : b + result;
223
+ }
224
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
225
+ function pow2(x, power, modulo) {
226
+ let res = x;
227
+ while (power-- > _0n$4) {
228
+ res *= res;
229
+ res %= modulo;
230
+ }
231
+ return res;
232
+ }
233
+ /**
234
+ * Inverses number over modulo.
235
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
236
+ */
237
+ function invert(number, modulo) {
238
+ if (number === _0n$4) throw new Error("invert: expected non-zero number");
239
+ if (modulo <= _0n$4) throw new Error("invert: expected positive modulus, got " + modulo);
240
+ let a = mod(number, modulo);
241
+ let b = modulo;
242
+ let x = _0n$4, u = _1n$5;
243
+ while (a !== _0n$4) {
244
+ const q = b / a;
245
+ const r = b % a;
246
+ const m = x - u * q;
247
+ b = a, a = r, x = u, u = m;
248
+ }
249
+ if (b !== _1n$5) throw new Error("invert: does not exist");
250
+ return mod(x, modulo);
251
+ }
252
+ function assertIsSquare(Fp, root, n) {
253
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
254
+ }
255
+ function sqrt3mod4(Fp, n) {
256
+ const p1div4 = (Fp.ORDER + _1n$5) / _4n$1;
257
+ const root = Fp.pow(n, p1div4);
258
+ assertIsSquare(Fp, root, n);
259
+ return root;
260
+ }
261
+ function sqrt5mod8(Fp, n) {
262
+ const p5div8 = (Fp.ORDER - _5n) / _8n$1;
263
+ const n2 = Fp.mul(n, _2n$5);
264
+ const v = Fp.pow(n2, p5div8);
265
+ const nv = Fp.mul(n, v);
266
+ const i = Fp.mul(Fp.mul(nv, _2n$5), v);
267
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
268
+ assertIsSquare(Fp, root, n);
269
+ return root;
270
+ }
271
+ function sqrt9mod16(P) {
272
+ const Fp_ = Field(P);
273
+ const tn = tonelliShanks(P);
274
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
275
+ const c2 = tn(Fp_, c1);
276
+ const c3 = tn(Fp_, Fp_.neg(c1));
277
+ const c4 = (P + _7n) / _16n;
278
+ return (Fp, n) => {
279
+ let tv1 = Fp.pow(n, c4);
280
+ let tv2 = Fp.mul(tv1, c1);
281
+ const tv3 = Fp.mul(tv1, c2);
282
+ const tv4 = Fp.mul(tv1, c3);
283
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
284
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
285
+ tv1 = Fp.cmov(tv1, tv2, e1);
286
+ tv2 = Fp.cmov(tv4, tv3, e2);
287
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
288
+ const root = Fp.cmov(tv1, tv2, e3);
289
+ assertIsSquare(Fp, root, n);
290
+ return root;
291
+ };
292
+ }
293
+ /**
294
+ * Tonelli-Shanks square root search algorithm.
295
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
296
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
297
+ * @param P field order
298
+ * @returns function that takes field Fp (created from P) and number n
299
+ */
300
+ function tonelliShanks(P) {
301
+ if (P < _3n$2) throw new Error("sqrt is not defined for small field");
302
+ let Q = P - _1n$5;
303
+ let S = 0;
304
+ while (Q % _2n$5 === _0n$4) {
305
+ Q /= _2n$5;
306
+ S++;
307
+ }
308
+ let Z = _2n$5;
309
+ const _Fp = Field(P);
310
+ while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
311
+ if (S === 1) return sqrt3mod4;
312
+ let cc = _Fp.pow(Z, Q);
313
+ const Q1div2 = (Q + _1n$5) / _2n$5;
314
+ return function tonelliSlow(Fp, n) {
315
+ if (Fp.is0(n)) return n;
316
+ if (FpLegendre(Fp, n) !== 1) throw new Error("Cannot find square root");
317
+ let M = S;
318
+ let c = Fp.mul(Fp.ONE, cc);
319
+ let t = Fp.pow(n, Q);
320
+ let R = Fp.pow(n, Q1div2);
321
+ while (!Fp.eql(t, Fp.ONE)) {
322
+ if (Fp.is0(t)) return Fp.ZERO;
323
+ let i = 1;
324
+ let t_tmp = Fp.sqr(t);
325
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
326
+ i++;
327
+ t_tmp = Fp.sqr(t_tmp);
328
+ if (i === M) throw new Error("Cannot find square root");
329
+ }
330
+ const exponent = _1n$5 << BigInt(M - i - 1);
331
+ const b = Fp.pow(c, exponent);
332
+ M = i;
333
+ c = Fp.sqr(b);
334
+ t = Fp.mul(t, c);
335
+ R = Fp.mul(R, b);
336
+ }
337
+ return R;
338
+ };
339
+ }
340
+ /**
341
+ * Square root for a finite field. Will try optimized versions first:
342
+ *
343
+ * 1. P ≡ 3 (mod 4)
344
+ * 2. P ≡ 5 (mod 8)
345
+ * 3. P ≡ 9 (mod 16)
346
+ * 4. Tonelli-Shanks algorithm
347
+ *
348
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
349
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
350
+ */
351
+ function FpSqrt(P) {
352
+ if (P % _4n$1 === _3n$2) return sqrt3mod4;
353
+ if (P % _8n$1 === _5n) return sqrt5mod8;
354
+ if (P % _16n === _9n) return sqrt9mod16(P);
355
+ return tonelliShanks(P);
356
+ }
357
+ var FIELD_FIELDS = [
358
+ "create",
359
+ "isValid",
360
+ "is0",
361
+ "neg",
362
+ "inv",
363
+ "sqrt",
364
+ "sqr",
365
+ "eql",
366
+ "add",
367
+ "sub",
368
+ "mul",
369
+ "pow",
370
+ "div",
371
+ "addN",
372
+ "subN",
373
+ "mulN",
374
+ "sqrN"
375
+ ];
376
+ function validateField(field) {
377
+ _validateObject(field, FIELD_FIELDS.reduce((map, val) => {
378
+ map[val] = "function";
379
+ return map;
380
+ }, {
381
+ ORDER: "bigint",
382
+ MASK: "bigint",
383
+ BYTES: "number",
384
+ BITS: "number"
385
+ }));
386
+ return field;
387
+ }
388
+ /**
389
+ * Same as `pow` but for Fp: non-constant-time.
390
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
391
+ */
392
+ function FpPow(Fp, num, power) {
393
+ if (power < _0n$4) throw new Error("invalid exponent, negatives unsupported");
394
+ if (power === _0n$4) return Fp.ONE;
395
+ if (power === _1n$5) return num;
396
+ let p = Fp.ONE;
397
+ let d = num;
398
+ while (power > _0n$4) {
399
+ if (power & _1n$5) p = Fp.mul(p, d);
400
+ d = Fp.sqr(d);
401
+ power >>= _1n$5;
402
+ }
403
+ return p;
404
+ }
405
+ /**
406
+ * Efficiently invert an array of Field elements.
407
+ * Exception-free. Will return `undefined` for 0 elements.
408
+ * @param passZero map 0 to 0 (instead of undefined)
409
+ */
410
+ function FpInvertBatch(Fp, nums, passZero = false) {
411
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
412
+ const multipliedAcc = nums.reduce((acc, num, i) => {
413
+ if (Fp.is0(num)) return acc;
414
+ inverted[i] = acc;
415
+ return Fp.mul(acc, num);
416
+ }, Fp.ONE);
417
+ const invertedAcc = Fp.inv(multipliedAcc);
418
+ nums.reduceRight((acc, num, i) => {
419
+ if (Fp.is0(num)) return acc;
420
+ inverted[i] = Fp.mul(acc, inverted[i]);
421
+ return Fp.mul(acc, num);
422
+ }, invertedAcc);
423
+ return inverted;
424
+ }
425
+ /**
426
+ * Legendre symbol.
427
+ * Legendre constant is used to calculate Legendre symbol (a | p)
428
+ * which denotes the value of a^((p-1)/2) (mod p).
429
+ *
430
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
431
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
432
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
433
+ */
434
+ function FpLegendre(Fp, n) {
435
+ const p1mod2 = (Fp.ORDER - _1n$5) / _2n$5;
436
+ const powered = Fp.pow(n, p1mod2);
437
+ const yes = Fp.eql(powered, Fp.ONE);
438
+ const zero = Fp.eql(powered, Fp.ZERO);
439
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
440
+ if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
441
+ return yes ? 1 : zero ? 0 : -1;
442
+ }
443
+ function nLength(n, nBitLength) {
444
+ if (nBitLength !== void 0) anumber(nBitLength);
445
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
446
+ return {
447
+ nBitLength: _nBitLength,
448
+ nByteLength: Math.ceil(_nBitLength / 8)
449
+ };
450
+ }
451
+ /**
452
+ * Creates a finite field. Major performance optimizations:
453
+ * * 1. Denormalized operations like mulN instead of mul.
454
+ * * 2. Identical object shape: never add or remove keys.
455
+ * * 3. `Object.freeze`.
456
+ * Fragile: always run a benchmark on a change.
457
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
458
+ * it is caller responsibility to check this.
459
+ * This is low-level code, please make sure you know what you're doing.
460
+ *
461
+ * Note about field properties:
462
+ * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
463
+ * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
464
+ *
465
+ * @param ORDER field order, probably prime, or could be composite
466
+ * @param bitLen how many bits the field consumes
467
+ * @param isLE (default: false) if encoding / decoding should be in little-endian
468
+ * @param redef optional faster redefinitions of sqrt and other methods
469
+ */
470
+ function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
471
+ if (ORDER <= _0n$4) throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
472
+ let _nbitLength = void 0;
473
+ let _sqrt = void 0;
474
+ let modFromBytes = false;
475
+ let allowedLengths = void 0;
476
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
477
+ if (opts.sqrt || isLE) throw new Error("cannot specify opts in two arguments");
478
+ const _opts = bitLenOrOpts;
479
+ if (_opts.BITS) _nbitLength = _opts.BITS;
480
+ if (_opts.sqrt) _sqrt = _opts.sqrt;
481
+ if (typeof _opts.isLE === "boolean") isLE = _opts.isLE;
482
+ if (typeof _opts.modFromBytes === "boolean") modFromBytes = _opts.modFromBytes;
483
+ allowedLengths = _opts.allowedLengths;
484
+ } else {
485
+ if (typeof bitLenOrOpts === "number") _nbitLength = bitLenOrOpts;
486
+ if (opts.sqrt) _sqrt = opts.sqrt;
487
+ }
488
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
489
+ if (BYTES > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
490
+ let sqrtP;
491
+ const f = Object.freeze({
492
+ ORDER,
493
+ isLE,
494
+ BITS,
495
+ BYTES,
496
+ MASK: bitMask(BITS),
497
+ ZERO: _0n$4,
498
+ ONE: _1n$5,
499
+ allowedLengths,
500
+ create: (num) => mod(num, ORDER),
501
+ isValid: (num) => {
502
+ if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num);
503
+ return _0n$4 <= num && num < ORDER;
504
+ },
505
+ is0: (num) => num === _0n$4,
506
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
507
+ isOdd: (num) => (num & _1n$5) === _1n$5,
508
+ neg: (num) => mod(-num, ORDER),
509
+ eql: (lhs, rhs) => lhs === rhs,
510
+ sqr: (num) => mod(num * num, ORDER),
511
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
512
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
513
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
514
+ pow: (num, power) => FpPow(f, num, power),
515
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
516
+ sqrN: (num) => num * num,
517
+ addN: (lhs, rhs) => lhs + rhs,
518
+ subN: (lhs, rhs) => lhs - rhs,
519
+ mulN: (lhs, rhs) => lhs * rhs,
520
+ inv: (num) => invert(num, ORDER),
521
+ sqrt: _sqrt || ((n) => {
522
+ if (!sqrtP) sqrtP = FpSqrt(ORDER);
523
+ return sqrtP(f, n);
524
+ }),
525
+ toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
526
+ fromBytes: (bytes, skipValidation = true) => {
527
+ if (allowedLengths) {
528
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
529
+ const padded = new Uint8Array(BYTES);
530
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
531
+ bytes = padded;
532
+ }
533
+ if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
534
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
535
+ if (modFromBytes) scalar = mod(scalar, ORDER);
536
+ if (!skipValidation) {
537
+ if (!f.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER");
538
+ }
539
+ return scalar;
540
+ },
541
+ invertBatch: (lst) => FpInvertBatch(f, lst),
542
+ cmov: (a, b, c) => c ? b : a
543
+ });
544
+ return Object.freeze(f);
545
+ }
546
+ /**
547
+ * Returns total number of bytes consumed by the field element.
548
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
549
+ * @param fieldOrder number of field elements, usually CURVE.n
550
+ * @returns byte length of field
551
+ */
552
+ function getFieldBytesLength(fieldOrder) {
553
+ if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
554
+ const bitLength = fieldOrder.toString(2).length;
555
+ return Math.ceil(bitLength / 8);
556
+ }
557
+ /**
558
+ * Returns minimal amount of bytes that can be safely reduced
559
+ * by field order.
560
+ * Should be 2^-128 for 128-bit curve such as P256.
561
+ * @param fieldOrder number of field elements, usually CURVE.n
562
+ * @returns byte length of target hash
563
+ */
564
+ function getMinHashLength(fieldOrder) {
565
+ const length = getFieldBytesLength(fieldOrder);
566
+ return length + Math.ceil(length / 2);
567
+ }
568
+ /**
569
+ * "Constant-time" private key generation utility.
570
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
571
+ * and convert them into private scalar, with the modulo bias being negligible.
572
+ * Needs at least 48 bytes of input for 32-byte private key.
573
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
574
+ * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
575
+ * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
576
+ * @param hash hash output from SHA3 or a similar function
577
+ * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
578
+ * @param isLE interpret hash bytes as LE num
579
+ * @returns valid private scalar
580
+ */
581
+ function mapHashToField(key, fieldOrder, isLE = false) {
582
+ const len = key.length;
583
+ const fieldLen = getFieldBytesLength(fieldOrder);
584
+ const minLen = getMinHashLength(fieldOrder);
585
+ if (len < 16 || len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
586
+ const reduced = mod(isLE ? bytesToNumberLE(key) : bytesToNumberBE(key), fieldOrder - _1n$5) + _1n$5;
587
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
588
+ }
589
+ /**
590
+ * HMAC: RFC2104 message authentication code.
591
+ * @module
592
+ */
593
+ var HMAC = class extends Hash {
594
+ constructor(hash, _key) {
595
+ super();
596
+ this.finished = false;
597
+ this.destroyed = false;
598
+ ahash(hash);
599
+ const key = toBytes(_key);
600
+ this.iHash = hash.create();
601
+ if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
602
+ this.blockLen = this.iHash.blockLen;
603
+ this.outputLen = this.iHash.outputLen;
604
+ const blockLen = this.blockLen;
605
+ const pad = new Uint8Array(blockLen);
606
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
607
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
608
+ this.iHash.update(pad);
609
+ this.oHash = hash.create();
610
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
611
+ this.oHash.update(pad);
612
+ clean(pad);
613
+ }
614
+ update(buf) {
615
+ aexists(this);
616
+ this.iHash.update(buf);
617
+ return this;
618
+ }
619
+ digestInto(out) {
620
+ aexists(this);
621
+ abytes(out, this.outputLen);
622
+ this.finished = true;
623
+ this.iHash.digestInto(out);
624
+ this.oHash.update(out);
625
+ this.oHash.digestInto(out);
626
+ this.destroy();
627
+ }
628
+ digest() {
629
+ const out = new Uint8Array(this.oHash.outputLen);
630
+ this.digestInto(out);
631
+ return out;
632
+ }
633
+ _cloneInto(to) {
634
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
635
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
636
+ to = to;
637
+ to.finished = finished;
638
+ to.destroyed = destroyed;
639
+ to.blockLen = blockLen;
640
+ to.outputLen = outputLen;
641
+ to.oHash = oHash._cloneInto(to.oHash);
642
+ to.iHash = iHash._cloneInto(to.iHash);
643
+ return to;
644
+ }
645
+ clone() {
646
+ return this._cloneInto();
647
+ }
648
+ destroy() {
649
+ this.destroyed = true;
650
+ this.oHash.destroy();
651
+ this.iHash.destroy();
652
+ }
653
+ };
654
+ /**
655
+ * HMAC: RFC2104 message authentication code.
656
+ * @param hash - function that would be used e.g. sha256
657
+ * @param key - message key
658
+ * @param message - message data
659
+ * @example
660
+ * import { hmac } from '@noble/hashes/hmac';
661
+ * import { sha256 } from '@noble/hashes/sha2';
662
+ * const mac1 = hmac(sha256, 'key', 'message');
663
+ */
664
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
665
+ hmac.create = (hash, key) => new HMAC(hash, key);
666
+ /**
667
+ * Methods for elliptic curve multiplication by scalars.
668
+ * Contains wNAF, pippenger.
669
+ * @module
670
+ */
671
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
672
+ var _0n$3 = BigInt(0);
673
+ var _1n$4 = BigInt(1);
674
+ function negateCt(condition, item) {
675
+ const neg = item.negate();
676
+ return condition ? neg : item;
677
+ }
678
+ /**
679
+ * Takes a bunch of Projective Points but executes only one
680
+ * inversion on all of them. Inversion is very slow operation,
681
+ * so this improves performance massively.
682
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
683
+ */
684
+ function normalizeZ(c, points) {
685
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
686
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
687
+ }
688
+ function validateW(W, bits) {
689
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
690
+ }
691
+ function calcWOpts(W, scalarBits) {
692
+ validateW(W, scalarBits);
693
+ const windows = Math.ceil(scalarBits / W) + 1;
694
+ const windowSize = 2 ** (W - 1);
695
+ const maxNumber = 2 ** W;
696
+ return {
697
+ windows,
698
+ windowSize,
699
+ mask: bitMask(W),
700
+ maxNumber,
701
+ shiftBy: BigInt(W)
702
+ };
703
+ }
704
+ function calcOffsets(n, window, wOpts) {
705
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
706
+ let wbits = Number(n & mask);
707
+ let nextN = n >> shiftBy;
708
+ if (wbits > windowSize) {
709
+ wbits -= maxNumber;
710
+ nextN += _1n$4;
711
+ }
712
+ const offsetStart = window * windowSize;
713
+ const offset = offsetStart + Math.abs(wbits) - 1;
714
+ const isZero = wbits === 0;
715
+ const isNeg = wbits < 0;
716
+ const isNegF = window % 2 !== 0;
717
+ return {
718
+ nextN,
719
+ offset,
720
+ isZero,
721
+ isNeg,
722
+ isNegF,
723
+ offsetF: offsetStart
724
+ };
725
+ }
726
+ function validateMSMPoints(points, c) {
727
+ if (!Array.isArray(points)) throw new Error("array expected");
728
+ points.forEach((p, i) => {
729
+ if (!(p instanceof c)) throw new Error("invalid point at index " + i);
730
+ });
731
+ }
732
+ function validateMSMScalars(scalars, field) {
733
+ if (!Array.isArray(scalars)) throw new Error("array of scalars expected");
734
+ scalars.forEach((s, i) => {
735
+ if (!field.isValid(s)) throw new Error("invalid scalar at index " + i);
736
+ });
737
+ }
738
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
739
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
740
+ function getW(P) {
741
+ return pointWindowSizes.get(P) || 1;
742
+ }
743
+ function assert0(n) {
744
+ if (n !== _0n$3) throw new Error("invalid wNAF");
745
+ }
746
+ /**
747
+ * Elliptic curve multiplication of Point by scalar. Fragile.
748
+ * Table generation takes **30MB of ram and 10ms on high-end CPU**,
749
+ * but may take much longer on slow devices. Actual generation will happen on
750
+ * first call of `multiply()`. By default, `BASE` point is precomputed.
751
+ *
752
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
753
+ * Creates precomputation tables for fast multiplication:
754
+ * - private scalar is split by fixed size windows of W bits
755
+ * - every window point is collected from window's table & added to accumulator
756
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
757
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
758
+ * - +1 window is neccessary for wNAF
759
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
760
+ *
761
+ * @todo Research returning 2d JS array of windows, instead of a single window.
762
+ * This would allow windows to be in different memory locations
763
+ */
764
+ var wNAF = class {
765
+ constructor(Point, bits) {
766
+ this.BASE = Point.BASE;
767
+ this.ZERO = Point.ZERO;
768
+ this.Fn = Point.Fn;
769
+ this.bits = bits;
770
+ }
771
+ _unsafeLadder(elm, n, p = this.ZERO) {
772
+ let d = elm;
773
+ while (n > _0n$3) {
774
+ if (n & _1n$4) p = p.add(d);
775
+ d = d.double();
776
+ n >>= _1n$4;
777
+ }
778
+ return p;
779
+ }
780
+ /**
781
+ * Creates a wNAF precomputation window. Used for caching.
782
+ * Default window size is set by `utils.precompute()` and is equal to 8.
783
+ * Number of precomputed points depends on the curve size:
784
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
785
+ * - 𝑊 is the window size
786
+ * - 𝑛 is the bitlength of the curve order.
787
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
788
+ * @param point Point instance
789
+ * @param W window size
790
+ * @returns precomputed point tables flattened to a single array
791
+ */
792
+ precomputeWindow(point, W) {
793
+ const { windows, windowSize } = calcWOpts(W, this.bits);
794
+ const points = [];
795
+ let p = point;
796
+ let base = p;
797
+ for (let window = 0; window < windows; window++) {
798
+ base = p;
799
+ points.push(base);
800
+ for (let i = 1; i < windowSize; i++) {
801
+ base = base.add(p);
802
+ points.push(base);
803
+ }
804
+ p = base.double();
805
+ }
806
+ return points;
807
+ }
808
+ /**
809
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
810
+ * More compact implementation:
811
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
812
+ * @returns real and fake (for const-time) points
813
+ */
814
+ wNAF(W, precomputes, n) {
815
+ if (!this.Fn.isValid(n)) throw new Error("invalid scalar");
816
+ let p = this.ZERO;
817
+ let f = this.BASE;
818
+ const wo = calcWOpts(W, this.bits);
819
+ for (let window = 0; window < wo.windows; window++) {
820
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
821
+ n = nextN;
822
+ if (isZero) f = f.add(negateCt(isNegF, precomputes[offsetF]));
823
+ else p = p.add(negateCt(isNeg, precomputes[offset]));
824
+ }
825
+ assert0(n);
826
+ return {
827
+ p,
828
+ f
829
+ };
830
+ }
831
+ /**
832
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
833
+ * @param acc accumulator point to add result of multiplication
834
+ * @returns point
835
+ */
836
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
837
+ const wo = calcWOpts(W, this.bits);
838
+ for (let window = 0; window < wo.windows; window++) {
839
+ if (n === _0n$3) break;
840
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
841
+ n = nextN;
842
+ if (isZero) continue;
843
+ else {
844
+ const item = precomputes[offset];
845
+ acc = acc.add(isNeg ? item.negate() : item);
846
+ }
847
+ }
848
+ assert0(n);
849
+ return acc;
850
+ }
851
+ getPrecomputes(W, point, transform) {
852
+ let comp = pointPrecomputes.get(point);
853
+ if (!comp) {
854
+ comp = this.precomputeWindow(point, W);
855
+ if (W !== 1) {
856
+ if (typeof transform === "function") comp = transform(comp);
857
+ pointPrecomputes.set(point, comp);
858
+ }
859
+ }
860
+ return comp;
861
+ }
862
+ cached(point, scalar, transform) {
863
+ const W = getW(point);
864
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
865
+ }
866
+ unsafe(point, scalar, transform, prev) {
867
+ const W = getW(point);
868
+ if (W === 1) return this._unsafeLadder(point, scalar, prev);
869
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
870
+ }
871
+ createCache(P, W) {
872
+ validateW(W, this.bits);
873
+ pointWindowSizes.set(P, W);
874
+ pointPrecomputes.delete(P);
875
+ }
876
+ hasCache(elm) {
877
+ return getW(elm) !== 1;
878
+ }
879
+ };
880
+ /**
881
+ * Endomorphism-specific multiplication for Koblitz curves.
882
+ * Cost: 128 dbl, 0-256 adds.
883
+ */
884
+ function mulEndoUnsafe(Point, point, k1, k2) {
885
+ let acc = point;
886
+ let p1 = Point.ZERO;
887
+ let p2 = Point.ZERO;
888
+ while (k1 > _0n$3 || k2 > _0n$3) {
889
+ if (k1 & _1n$4) p1 = p1.add(acc);
890
+ if (k2 & _1n$4) p2 = p2.add(acc);
891
+ acc = acc.double();
892
+ k1 >>= _1n$4;
893
+ k2 >>= _1n$4;
894
+ }
895
+ return {
896
+ p1,
897
+ p2
898
+ };
899
+ }
900
+ /**
901
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
902
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
903
+ * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
904
+ * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
905
+ * @param c Curve Point constructor
906
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
907
+ * @param points array of L curve points
908
+ * @param scalars array of L scalars (aka secret keys / bigints)
909
+ */
910
+ function pippenger(c, fieldN, points, scalars) {
911
+ validateMSMPoints(points, c);
912
+ validateMSMScalars(scalars, fieldN);
913
+ const plength = points.length;
914
+ const slength = scalars.length;
915
+ if (plength !== slength) throw new Error("arrays of points and scalars must have equal length");
916
+ const zero = c.ZERO;
917
+ const wbits = bitLen(BigInt(plength));
918
+ let windowSize = 1;
919
+ if (wbits > 12) windowSize = wbits - 3;
920
+ else if (wbits > 4) windowSize = wbits - 2;
921
+ else if (wbits > 0) windowSize = 2;
922
+ const MASK = bitMask(windowSize);
923
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
924
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
925
+ let sum = zero;
926
+ for (let i = lastBits; i >= 0; i -= windowSize) {
927
+ buckets.fill(zero);
928
+ for (let j = 0; j < slength; j++) {
929
+ const scalar = scalars[j];
930
+ const wbits = Number(scalar >> BigInt(i) & MASK);
931
+ buckets[wbits] = buckets[wbits].add(points[j]);
932
+ }
933
+ let resI = zero;
934
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
935
+ sumI = sumI.add(buckets[j]);
936
+ resI = resI.add(sumI);
937
+ }
938
+ sum = sum.add(resI);
939
+ if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();
940
+ }
941
+ return sum;
942
+ }
943
+ function createField(order, field, isLE) {
944
+ if (field) {
945
+ if (field.ORDER !== order) throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
946
+ validateField(field);
947
+ return field;
948
+ } else return Field(order, { isLE });
949
+ }
950
+ /** Validates CURVE opts and creates fields */
951
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
952
+ if (FpFnLE === void 0) FpFnLE = type === "edwards";
953
+ if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`);
954
+ for (const p of [
955
+ "p",
956
+ "n",
957
+ "h"
958
+ ]) {
959
+ const val = CURVE[p];
960
+ if (!(typeof val === "bigint" && val > _0n$3)) throw new Error(`CURVE.${p} must be positive bigint`);
961
+ }
962
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
963
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
964
+ const params = [
965
+ "Gx",
966
+ "Gy",
967
+ "a",
968
+ type === "weierstrass" ? "b" : "d"
969
+ ];
970
+ for (const p of params) if (!Fp.isValid(CURVE[p])) throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
971
+ CURVE = Object.freeze(Object.assign({}, CURVE));
972
+ return {
973
+ CURVE,
974
+ Fp,
975
+ Fn
976
+ };
977
+ }
978
+ /**
979
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
980
+ *
981
+ * ### Design rationale for types
982
+ *
983
+ * * Interaction between classes from different curves should fail:
984
+ * `k256.Point.BASE.add(p256.Point.BASE)`
985
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
986
+ * * Different calls of `curve()` would return different classes -
987
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
988
+ * it won't affect others
989
+ *
990
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
991
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
992
+ * unique type for every function call.
993
+ *
994
+ * We can use generic types via some param, like curve opts, but that would:
995
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
996
+ * which is hard to debug.
997
+ * 2. Params can be generic and we can't enforce them to be constant value:
998
+ * if somebody creates curve from non-constant params,
999
+ * it would be allowed to interact with other curves with non-constant params
1000
+ *
1001
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
1002
+ * @module
1003
+ */
1004
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1005
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$4) / den;
1006
+ /**
1007
+ * Splits scalar for GLV endomorphism.
1008
+ */
1009
+ function _splitEndoScalar(k, basis, n) {
1010
+ const [[a1, b1], [a2, b2]] = basis;
1011
+ const c1 = divNearest(b2 * k, n);
1012
+ const c2 = divNearest(-b1 * k, n);
1013
+ let k1 = k - c1 * a1 - c2 * a2;
1014
+ let k2 = -c1 * b1 - c2 * b2;
1015
+ const k1neg = k1 < _0n$2;
1016
+ const k2neg = k2 < _0n$2;
1017
+ if (k1neg) k1 = -k1;
1018
+ if (k2neg) k2 = -k2;
1019
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n$3;
1020
+ if (k1 < _0n$2 || k1 >= MAX_NUM || k2 < _0n$2 || k2 >= MAX_NUM) throw new Error("splitScalar (endomorphism): failed, k=" + k);
1021
+ return {
1022
+ k1neg,
1023
+ k1,
1024
+ k2neg,
1025
+ k2
1026
+ };
1027
+ }
1028
+ function validateSigFormat(format) {
1029
+ if (![
1030
+ "compact",
1031
+ "recovered",
1032
+ "der"
1033
+ ].includes(format)) throw new Error("Signature format must be \"compact\", \"recovered\", or \"der\"");
1034
+ return format;
1035
+ }
1036
+ function validateSigOpts(opts, def) {
1037
+ const optsn = {};
1038
+ for (let optName of Object.keys(def)) optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
1039
+ _abool2(optsn.lowS, "lowS");
1040
+ _abool2(optsn.prehash, "prehash");
1041
+ if (optsn.format !== void 0) validateSigFormat(optsn.format);
1042
+ return optsn;
1043
+ }
1044
+ var DERErr = class extends Error {
1045
+ constructor(m = "") {
1046
+ super(m);
1047
+ }
1048
+ };
1049
+ /**
1050
+ * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
1051
+ *
1052
+ * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
1053
+ *
1054
+ * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
1055
+ */
1056
+ var DER = {
1057
+ Err: DERErr,
1058
+ _tlv: {
1059
+ encode: (tag, data) => {
1060
+ const { Err: E } = DER;
1061
+ if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
1062
+ if (data.length & 1) throw new E("tlv.encode: unpadded data");
1063
+ const dataLen = data.length / 2;
1064
+ const len = numberToHexUnpadded(dataLen);
1065
+ if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big");
1066
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
1067
+ return numberToHexUnpadded(tag) + lenLen + len + data;
1068
+ },
1069
+ decode(tag, data) {
1070
+ const { Err: E } = DER;
1071
+ let pos = 0;
1072
+ if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
1073
+ if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv");
1074
+ const first = data[pos++];
1075
+ const isLong = !!(first & 128);
1076
+ let length = 0;
1077
+ if (!isLong) length = first;
1078
+ else {
1079
+ const lenLen = first & 127;
1080
+ if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported");
1081
+ if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big");
1082
+ const lengthBytes = data.subarray(pos, pos + lenLen);
1083
+ if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete");
1084
+ if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte");
1085
+ for (const b of lengthBytes) length = length << 8 | b;
1086
+ pos += lenLen;
1087
+ if (length < 128) throw new E("tlv.decode(long): not minimal encoding");
1088
+ }
1089
+ const v = data.subarray(pos, pos + length);
1090
+ if (v.length !== length) throw new E("tlv.decode: wrong value length");
1091
+ return {
1092
+ v,
1093
+ l: data.subarray(pos + length)
1094
+ };
1095
+ }
1096
+ },
1097
+ _int: {
1098
+ encode(num) {
1099
+ const { Err: E } = DER;
1100
+ if (num < _0n$2) throw new E("integer: negative integers are not allowed");
1101
+ let hex = numberToHexUnpadded(num);
1102
+ if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex;
1103
+ if (hex.length & 1) throw new E("unexpected DER parsing assertion: unpadded hex");
1104
+ return hex;
1105
+ },
1106
+ decode(data) {
1107
+ const { Err: E } = DER;
1108
+ if (data[0] & 128) throw new E("invalid signature integer: negative");
1109
+ if (data[0] === 0 && !(data[1] & 128)) throw new E("invalid signature integer: unnecessary leading zero");
1110
+ return bytesToNumberBE(data);
1111
+ }
1112
+ },
1113
+ toSig(hex) {
1114
+ const { Err: E, _int: int, _tlv: tlv } = DER;
1115
+ const data = ensureBytes("signature", hex);
1116
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
1117
+ if (seqLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
1118
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
1119
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
1120
+ if (sLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
1121
+ return {
1122
+ r: int.decode(rBytes),
1123
+ s: int.decode(sBytes)
1124
+ };
1125
+ },
1126
+ hexFromSig(sig) {
1127
+ const { _tlv: tlv, _int: int } = DER;
1128
+ const seq = tlv.encode(2, int.encode(sig.r)) + tlv.encode(2, int.encode(sig.s));
1129
+ return tlv.encode(48, seq);
1130
+ }
1131
+ };
1132
+ var _0n$2 = BigInt(0);
1133
+ var _1n$3 = BigInt(1);
1134
+ var _2n$4 = BigInt(2);
1135
+ var _3n$1 = BigInt(3);
1136
+ var _4n = BigInt(4);
1137
+ function _normFnElement(Fn, key) {
1138
+ const { BYTES: expected } = Fn;
1139
+ let num;
1140
+ if (typeof key === "bigint") num = key;
1141
+ else {
1142
+ let bytes = ensureBytes("private key", key);
1143
+ try {
1144
+ num = Fn.fromBytes(bytes);
1145
+ } catch (error) {
1146
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
1147
+ }
1148
+ }
1149
+ if (!Fn.isValidNot0(num)) throw new Error("invalid private key: out of range [1..N-1]");
1150
+ return num;
1151
+ }
1152
+ /**
1153
+ * Creates weierstrass Point constructor, based on specified curve options.
1154
+ *
1155
+ * @example
1156
+ ```js
1157
+ const opts = {
1158
+ p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
1159
+ n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
1160
+ h: BigInt(1),
1161
+ a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
1162
+ b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
1163
+ Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
1164
+ Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
1165
+ };
1166
+ const p256_Point = weierstrass(opts);
1167
+ ```
1168
+ */
1169
+ function weierstrassN(params, extraOpts = {}) {
1170
+ const validated = _createCurveFields("weierstrass", params, extraOpts);
1171
+ const { Fp, Fn } = validated;
1172
+ let CURVE = validated.CURVE;
1173
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
1174
+ _validateObject(extraOpts, {}, {
1175
+ allowInfinityPoint: "boolean",
1176
+ clearCofactor: "function",
1177
+ isTorsionFree: "function",
1178
+ fromBytes: "function",
1179
+ toBytes: "function",
1180
+ endo: "object",
1181
+ wrapPrivateKey: "boolean"
1182
+ });
1183
+ const { endo } = extraOpts;
1184
+ if (endo) {
1185
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) throw new Error("invalid endo: expected \"beta\": bigint and \"basises\": array");
1186
+ }
1187
+ const lengths = getWLengths(Fp, Fn);
1188
+ function assertCompressionIsSupported() {
1189
+ if (!Fp.isOdd) throw new Error("compression is not supported: Field does not have .isOdd()");
1190
+ }
1191
+ function pointToBytes(_c, point, isCompressed) {
1192
+ const { x, y } = point.toAffine();
1193
+ const bx = Fp.toBytes(x);
1194
+ _abool2(isCompressed, "isCompressed");
1195
+ if (isCompressed) {
1196
+ assertCompressionIsSupported();
1197
+ const hasEvenY = !Fp.isOdd(y);
1198
+ return concatBytes(pprefix(hasEvenY), bx);
1199
+ } else return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
1200
+ }
1201
+ function pointFromBytes(bytes) {
1202
+ _abytes2(bytes, void 0, "Point");
1203
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
1204
+ const length = bytes.length;
1205
+ const head = bytes[0];
1206
+ const tail = bytes.subarray(1);
1207
+ if (length === comp && (head === 2 || head === 3)) {
1208
+ const x = Fp.fromBytes(tail);
1209
+ if (!Fp.isValid(x)) throw new Error("bad point: is not on curve, wrong x");
1210
+ const y2 = weierstrassEquation(x);
1211
+ let y;
1212
+ try {
1213
+ y = Fp.sqrt(y2);
1214
+ } catch (sqrtError) {
1215
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1216
+ throw new Error("bad point: is not on curve, sqrt error" + err);
1217
+ }
1218
+ assertCompressionIsSupported();
1219
+ const isYOdd = Fp.isOdd(y);
1220
+ if ((head & 1) === 1 !== isYOdd) y = Fp.neg(y);
1221
+ return {
1222
+ x,
1223
+ y
1224
+ };
1225
+ } else if (length === uncomp && head === 4) {
1226
+ const L = Fp.BYTES;
1227
+ const x = Fp.fromBytes(tail.subarray(0, L));
1228
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
1229
+ if (!isValidXY(x, y)) throw new Error("bad point: is not on curve");
1230
+ return {
1231
+ x,
1232
+ y
1233
+ };
1234
+ } else throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
1235
+ }
1236
+ const encodePoint = extraOpts.toBytes || pointToBytes;
1237
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
1238
+ function weierstrassEquation(x) {
1239
+ const x2 = Fp.sqr(x);
1240
+ const x3 = Fp.mul(x2, x);
1241
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
1242
+ }
1243
+ /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
1244
+ function isValidXY(x, y) {
1245
+ const left = Fp.sqr(y);
1246
+ const right = weierstrassEquation(x);
1247
+ return Fp.eql(left, right);
1248
+ }
1249
+ if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
1250
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n$1), _4n);
1251
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
1252
+ if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error("bad curve params: a or b");
1253
+ /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
1254
+ function acoord(title, n, banZero = false) {
1255
+ if (!Fp.isValid(n) || banZero && Fp.is0(n)) throw new Error(`bad point coordinate ${title}`);
1256
+ return n;
1257
+ }
1258
+ function aprjpoint(other) {
1259
+ if (!(other instanceof Point)) throw new Error("ProjectivePoint expected");
1260
+ }
1261
+ function splitEndoScalarN(k) {
1262
+ if (!endo || !endo.basises) throw new Error("no endo");
1263
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
1264
+ }
1265
+ const toAffineMemo = memoized((p, iz) => {
1266
+ const { X, Y, Z } = p;
1267
+ if (Fp.eql(Z, Fp.ONE)) return {
1268
+ x: X,
1269
+ y: Y
1270
+ };
1271
+ const is0 = p.is0();
1272
+ if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);
1273
+ const x = Fp.mul(X, iz);
1274
+ const y = Fp.mul(Y, iz);
1275
+ const zz = Fp.mul(Z, iz);
1276
+ if (is0) return {
1277
+ x: Fp.ZERO,
1278
+ y: Fp.ZERO
1279
+ };
1280
+ if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
1281
+ return {
1282
+ x,
1283
+ y
1284
+ };
1285
+ });
1286
+ const assertValidMemo = memoized((p) => {
1287
+ if (p.is0()) {
1288
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) return;
1289
+ throw new Error("bad point: ZERO");
1290
+ }
1291
+ const { x, y } = p.toAffine();
1292
+ if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not field elements");
1293
+ if (!isValidXY(x, y)) throw new Error("bad point: equation left != right");
1294
+ if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup");
1295
+ return true;
1296
+ });
1297
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
1298
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
1299
+ k1p = negateCt(k1neg, k1p);
1300
+ k2p = negateCt(k2neg, k2p);
1301
+ return k1p.add(k2p);
1302
+ }
1303
+ /**
1304
+ * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
1305
+ * Default Point works in 2d / affine coordinates: (x, y).
1306
+ * We're doing calculations in projective, because its operations don't require costly inversion.
1307
+ */
1308
+ class Point {
1309
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1310
+ constructor(X, Y, Z) {
1311
+ this.X = acoord("x", X);
1312
+ this.Y = acoord("y", Y, true);
1313
+ this.Z = acoord("z", Z);
1314
+ Object.freeze(this);
1315
+ }
1316
+ static CURVE() {
1317
+ return CURVE;
1318
+ }
1319
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1320
+ static fromAffine(p) {
1321
+ const { x, y } = p || {};
1322
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point");
1323
+ if (p instanceof Point) throw new Error("projective point not allowed");
1324
+ if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;
1325
+ return new Point(x, y, Fp.ONE);
1326
+ }
1327
+ static fromBytes(bytes) {
1328
+ const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
1329
+ P.assertValidity();
1330
+ return P;
1331
+ }
1332
+ static fromHex(hex) {
1333
+ return Point.fromBytes(ensureBytes("pointHex", hex));
1334
+ }
1335
+ get x() {
1336
+ return this.toAffine().x;
1337
+ }
1338
+ get y() {
1339
+ return this.toAffine().y;
1340
+ }
1341
+ /**
1342
+ *
1343
+ * @param windowSize
1344
+ * @param isLazy true will defer table computation until the first multiplication
1345
+ * @returns
1346
+ */
1347
+ precompute(windowSize = 8, isLazy = true) {
1348
+ wnaf.createCache(this, windowSize);
1349
+ if (!isLazy) this.multiply(_3n$1);
1350
+ return this;
1351
+ }
1352
+ /** A point on curve is valid if it conforms to equation. */
1353
+ assertValidity() {
1354
+ assertValidMemo(this);
1355
+ }
1356
+ hasEvenY() {
1357
+ const { y } = this.toAffine();
1358
+ if (!Fp.isOdd) throw new Error("Field doesn't support isOdd");
1359
+ return !Fp.isOdd(y);
1360
+ }
1361
+ /** Compare one point to another. */
1362
+ equals(other) {
1363
+ aprjpoint(other);
1364
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1365
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1366
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1367
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1368
+ return U1 && U2;
1369
+ }
1370
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
1371
+ negate() {
1372
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
1373
+ }
1374
+ double() {
1375
+ const { a, b } = CURVE;
1376
+ const b3 = Fp.mul(b, _3n$1);
1377
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1378
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1379
+ let t0 = Fp.mul(X1, X1);
1380
+ let t1 = Fp.mul(Y1, Y1);
1381
+ let t2 = Fp.mul(Z1, Z1);
1382
+ let t3 = Fp.mul(X1, Y1);
1383
+ t3 = Fp.add(t3, t3);
1384
+ Z3 = Fp.mul(X1, Z1);
1385
+ Z3 = Fp.add(Z3, Z3);
1386
+ X3 = Fp.mul(a, Z3);
1387
+ Y3 = Fp.mul(b3, t2);
1388
+ Y3 = Fp.add(X3, Y3);
1389
+ X3 = Fp.sub(t1, Y3);
1390
+ Y3 = Fp.add(t1, Y3);
1391
+ Y3 = Fp.mul(X3, Y3);
1392
+ X3 = Fp.mul(t3, X3);
1393
+ Z3 = Fp.mul(b3, Z3);
1394
+ t2 = Fp.mul(a, t2);
1395
+ t3 = Fp.sub(t0, t2);
1396
+ t3 = Fp.mul(a, t3);
1397
+ t3 = Fp.add(t3, Z3);
1398
+ Z3 = Fp.add(t0, t0);
1399
+ t0 = Fp.add(Z3, t0);
1400
+ t0 = Fp.add(t0, t2);
1401
+ t0 = Fp.mul(t0, t3);
1402
+ Y3 = Fp.add(Y3, t0);
1403
+ t2 = Fp.mul(Y1, Z1);
1404
+ t2 = Fp.add(t2, t2);
1405
+ t0 = Fp.mul(t2, t3);
1406
+ X3 = Fp.sub(X3, t0);
1407
+ Z3 = Fp.mul(t2, t1);
1408
+ Z3 = Fp.add(Z3, Z3);
1409
+ Z3 = Fp.add(Z3, Z3);
1410
+ return new Point(X3, Y3, Z3);
1411
+ }
1412
+ add(other) {
1413
+ aprjpoint(other);
1414
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1415
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1416
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1417
+ const a = CURVE.a;
1418
+ const b3 = Fp.mul(CURVE.b, _3n$1);
1419
+ let t0 = Fp.mul(X1, X2);
1420
+ let t1 = Fp.mul(Y1, Y2);
1421
+ let t2 = Fp.mul(Z1, Z2);
1422
+ let t3 = Fp.add(X1, Y1);
1423
+ let t4 = Fp.add(X2, Y2);
1424
+ t3 = Fp.mul(t3, t4);
1425
+ t4 = Fp.add(t0, t1);
1426
+ t3 = Fp.sub(t3, t4);
1427
+ t4 = Fp.add(X1, Z1);
1428
+ let t5 = Fp.add(X2, Z2);
1429
+ t4 = Fp.mul(t4, t5);
1430
+ t5 = Fp.add(t0, t2);
1431
+ t4 = Fp.sub(t4, t5);
1432
+ t5 = Fp.add(Y1, Z1);
1433
+ X3 = Fp.add(Y2, Z2);
1434
+ t5 = Fp.mul(t5, X3);
1435
+ X3 = Fp.add(t1, t2);
1436
+ t5 = Fp.sub(t5, X3);
1437
+ Z3 = Fp.mul(a, t4);
1438
+ X3 = Fp.mul(b3, t2);
1439
+ Z3 = Fp.add(X3, Z3);
1440
+ X3 = Fp.sub(t1, Z3);
1441
+ Z3 = Fp.add(t1, Z3);
1442
+ Y3 = Fp.mul(X3, Z3);
1443
+ t1 = Fp.add(t0, t0);
1444
+ t1 = Fp.add(t1, t0);
1445
+ t2 = Fp.mul(a, t2);
1446
+ t4 = Fp.mul(b3, t4);
1447
+ t1 = Fp.add(t1, t2);
1448
+ t2 = Fp.sub(t0, t2);
1449
+ t2 = Fp.mul(a, t2);
1450
+ t4 = Fp.add(t4, t2);
1451
+ t0 = Fp.mul(t1, t4);
1452
+ Y3 = Fp.add(Y3, t0);
1453
+ t0 = Fp.mul(t5, t4);
1454
+ X3 = Fp.mul(t3, X3);
1455
+ X3 = Fp.sub(X3, t0);
1456
+ t0 = Fp.mul(t3, t1);
1457
+ Z3 = Fp.mul(t5, Z3);
1458
+ Z3 = Fp.add(Z3, t0);
1459
+ return new Point(X3, Y3, Z3);
1460
+ }
1461
+ subtract(other) {
1462
+ return this.add(other.negate());
1463
+ }
1464
+ is0() {
1465
+ return this.equals(Point.ZERO);
1466
+ }
1467
+ /**
1468
+ * Constant time multiplication.
1469
+ * Uses wNAF method. Windowed method may be 10% faster,
1470
+ * but takes 2x longer to generate and consumes 2x memory.
1471
+ * Uses precomputes when available.
1472
+ * Uses endomorphism for Koblitz curves.
1473
+ * @param scalar by which the point would be multiplied
1474
+ * @returns New point
1475
+ */
1476
+ multiply(scalar) {
1477
+ const { endo } = extraOpts;
1478
+ if (!Fn.isValidNot0(scalar)) throw new Error("invalid scalar: out of range");
1479
+ let point, fake;
1480
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
1481
+ /** See docs for {@link EndomorphismOpts} */
1482
+ if (endo) {
1483
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
1484
+ const { p: k1p, f: k1f } = mul(k1);
1485
+ const { p: k2p, f: k2f } = mul(k2);
1486
+ fake = k1f.add(k2f);
1487
+ point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
1488
+ } else {
1489
+ const { p, f } = mul(scalar);
1490
+ point = p;
1491
+ fake = f;
1492
+ }
1493
+ return normalizeZ(Point, [point, fake])[0];
1494
+ }
1495
+ /**
1496
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
1497
+ * It's faster, but should only be used when you don't care about
1498
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
1499
+ */
1500
+ multiplyUnsafe(sc) {
1501
+ const { endo } = extraOpts;
1502
+ const p = this;
1503
+ if (!Fn.isValid(sc)) throw new Error("invalid scalar: out of range");
1504
+ if (sc === _0n$2 || p.is0()) return Point.ZERO;
1505
+ if (sc === _1n$3) return p;
1506
+ if (wnaf.hasCache(this)) return this.multiply(sc);
1507
+ if (endo) {
1508
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
1509
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
1510
+ return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
1511
+ } else return wnaf.unsafe(p, sc);
1512
+ }
1513
+ multiplyAndAddUnsafe(Q, a, b) {
1514
+ const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
1515
+ return sum.is0() ? void 0 : sum;
1516
+ }
1517
+ /**
1518
+ * Converts Projective point to affine (x, y) coordinates.
1519
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
1520
+ */
1521
+ toAffine(invertedZ) {
1522
+ return toAffineMemo(this, invertedZ);
1523
+ }
1524
+ /**
1525
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
1526
+ * Always torsion-free for cofactor=1 curves.
1527
+ */
1528
+ isTorsionFree() {
1529
+ const { isTorsionFree } = extraOpts;
1530
+ if (cofactor === _1n$3) return true;
1531
+ if (isTorsionFree) return isTorsionFree(Point, this);
1532
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
1533
+ }
1534
+ clearCofactor() {
1535
+ const { clearCofactor } = extraOpts;
1536
+ if (cofactor === _1n$3) return this;
1537
+ if (clearCofactor) return clearCofactor(Point, this);
1538
+ return this.multiplyUnsafe(cofactor);
1539
+ }
1540
+ isSmallOrder() {
1541
+ return this.multiplyUnsafe(cofactor).is0();
1542
+ }
1543
+ toBytes(isCompressed = true) {
1544
+ _abool2(isCompressed, "isCompressed");
1545
+ this.assertValidity();
1546
+ return encodePoint(Point, this, isCompressed);
1547
+ }
1548
+ toHex(isCompressed = true) {
1549
+ return bytesToHex(this.toBytes(isCompressed));
1550
+ }
1551
+ toString() {
1552
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1553
+ }
1554
+ get px() {
1555
+ return this.X;
1556
+ }
1557
+ get py() {
1558
+ return this.X;
1559
+ }
1560
+ get pz() {
1561
+ return this.Z;
1562
+ }
1563
+ toRawBytes(isCompressed = true) {
1564
+ return this.toBytes(isCompressed);
1565
+ }
1566
+ _setWindowSize(windowSize) {
1567
+ this.precompute(windowSize);
1568
+ }
1569
+ static normalizeZ(points) {
1570
+ return normalizeZ(Point, points);
1571
+ }
1572
+ static msm(points, scalars) {
1573
+ return pippenger(Point, Fn, points, scalars);
1574
+ }
1575
+ static fromPrivateKey(privateKey) {
1576
+ return Point.BASE.multiply(_normFnElement(Fn, privateKey));
1577
+ }
1578
+ }
1579
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1580
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1581
+ Point.Fp = Fp;
1582
+ Point.Fn = Fn;
1583
+ const bits = Fn.BITS;
1584
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
1585
+ Point.BASE.precompute(8);
1586
+ return Point;
1587
+ }
1588
+ function pprefix(hasEvenY) {
1589
+ return Uint8Array.of(hasEvenY ? 2 : 3);
1590
+ }
1591
+ function getWLengths(Fp, Fn) {
1592
+ return {
1593
+ secretKey: Fn.BYTES,
1594
+ publicKey: 1 + Fp.BYTES,
1595
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
1596
+ publicKeyHasPrefix: true,
1597
+ signature: 2 * Fn.BYTES
1598
+ };
1599
+ }
1600
+ /**
1601
+ * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
1602
+ * This helper ensures no signature functionality is present. Less code, smaller bundle size.
1603
+ */
1604
+ function ecdh(Point, ecdhOpts = {}) {
1605
+ const { Fn } = Point;
1606
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
1607
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
1608
+ function isValidSecretKey(secretKey) {
1609
+ try {
1610
+ return !!_normFnElement(Fn, secretKey);
1611
+ } catch (error) {
1612
+ return false;
1613
+ }
1614
+ }
1615
+ function isValidPublicKey(publicKey, isCompressed) {
1616
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
1617
+ try {
1618
+ const l = publicKey.length;
1619
+ if (isCompressed === true && l !== comp) return false;
1620
+ if (isCompressed === false && l !== publicKeyUncompressed) return false;
1621
+ return !!Point.fromBytes(publicKey);
1622
+ } catch (error) {
1623
+ return false;
1624
+ }
1625
+ }
1626
+ /**
1627
+ * Produces cryptographically secure secret key from random of size
1628
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
1629
+ */
1630
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
1631
+ return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
1632
+ }
1633
+ /**
1634
+ * Computes public key for a secret key. Checks for validity of the secret key.
1635
+ * @param isCompressed whether to return compact (default), or full key
1636
+ * @returns Public key, full when isCompressed=false; short when isCompressed=true
1637
+ */
1638
+ function getPublicKey(secretKey, isCompressed = true) {
1639
+ return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
1640
+ }
1641
+ function keygen(seed) {
1642
+ const secretKey = randomSecretKey(seed);
1643
+ return {
1644
+ secretKey,
1645
+ publicKey: getPublicKey(secretKey)
1646
+ };
1647
+ }
1648
+ /**
1649
+ * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
1650
+ */
1651
+ function isProbPub(item) {
1652
+ if (typeof item === "bigint") return false;
1653
+ if (item instanceof Point) return true;
1654
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
1655
+ if (Fn.allowedLengths || secretKey === publicKey) return void 0;
1656
+ const l = ensureBytes("key", item).length;
1657
+ return l === publicKey || l === publicKeyUncompressed;
1658
+ }
1659
+ /**
1660
+ * ECDH (Elliptic Curve Diffie Hellman).
1661
+ * Computes shared public key from secret key A and public key B.
1662
+ * Checks: 1) secret key validity 2) shared key is on-curve.
1663
+ * Does NOT hash the result.
1664
+ * @param isCompressed whether to return compact (default), or full key
1665
+ * @returns shared public key
1666
+ */
1667
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
1668
+ if (isProbPub(secretKeyA) === true) throw new Error("first arg must be private key");
1669
+ if (isProbPub(publicKeyB) === false) throw new Error("second arg must be public key");
1670
+ const s = _normFnElement(Fn, secretKeyA);
1671
+ return Point.fromHex(publicKeyB).multiply(s).toBytes(isCompressed);
1672
+ }
1673
+ return Object.freeze({
1674
+ getPublicKey,
1675
+ getSharedSecret,
1676
+ keygen,
1677
+ Point,
1678
+ utils: {
1679
+ isValidSecretKey,
1680
+ isValidPublicKey,
1681
+ randomSecretKey,
1682
+ isValidPrivateKey: isValidSecretKey,
1683
+ randomPrivateKey: randomSecretKey,
1684
+ normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
1685
+ precompute(windowSize = 8, point = Point.BASE) {
1686
+ return point.precompute(windowSize, false);
1687
+ }
1688
+ },
1689
+ lengths
1690
+ });
1691
+ }
1692
+ /**
1693
+ * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
1694
+ * We need `hash` for 2 features:
1695
+ * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
1696
+ * 2. k generation in `sign`, using HMAC-drbg(hash)
1697
+ *
1698
+ * ECDSAOpts are only rarely needed.
1699
+ *
1700
+ * @example
1701
+ * ```js
1702
+ * const p256_Point = weierstrass(...);
1703
+ * const p256_sha256 = ecdsa(p256_Point, sha256);
1704
+ * const p256_sha224 = ecdsa(p256_Point, sha224);
1705
+ * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
1706
+ * ```
1707
+ */
1708
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
1709
+ ahash(hash);
1710
+ _validateObject(ecdsaOpts, {}, {
1711
+ hmac: "function",
1712
+ lowS: "boolean",
1713
+ randomBytes: "function",
1714
+ bits2int: "function",
1715
+ bits2int_modN: "function"
1716
+ });
1717
+ const randomBytes$1 = ecdsaOpts.randomBytes || randomBytes;
1718
+ const hmac$1 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
1719
+ const { Fp, Fn } = Point;
1720
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
1721
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
1722
+ const defaultSigOpts = {
1723
+ prehash: false,
1724
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
1725
+ format: void 0,
1726
+ extraEntropy: false
1727
+ };
1728
+ const defaultSigOpts_format = "compact";
1729
+ function isBiggerThanHalfOrder(number) {
1730
+ return number > CURVE_ORDER >> _1n$3;
1731
+ }
1732
+ function validateRS(title, num) {
1733
+ if (!Fn.isValidNot0(num)) throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
1734
+ return num;
1735
+ }
1736
+ function validateSigLength(bytes, format) {
1737
+ validateSigFormat(format);
1738
+ const size = lengths.signature;
1739
+ return _abytes2(bytes, format === "compact" ? size : format === "recovered" ? size + 1 : void 0, `${format} signature`);
1740
+ }
1741
+ /**
1742
+ * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
1743
+ */
1744
+ class Signature {
1745
+ constructor(r, s, recovery) {
1746
+ this.r = validateRS("r", r);
1747
+ this.s = validateRS("s", s);
1748
+ if (recovery != null) this.recovery = recovery;
1749
+ Object.freeze(this);
1750
+ }
1751
+ static fromBytes(bytes, format = defaultSigOpts_format) {
1752
+ validateSigLength(bytes, format);
1753
+ let recid;
1754
+ if (format === "der") {
1755
+ const { r, s } = DER.toSig(_abytes2(bytes));
1756
+ return new Signature(r, s);
1757
+ }
1758
+ if (format === "recovered") {
1759
+ recid = bytes[0];
1760
+ format = "compact";
1761
+ bytes = bytes.subarray(1);
1762
+ }
1763
+ const L = Fn.BYTES;
1764
+ const r = bytes.subarray(0, L);
1765
+ const s = bytes.subarray(L, L * 2);
1766
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
1767
+ }
1768
+ static fromHex(hex, format) {
1769
+ return this.fromBytes(hexToBytes(hex), format);
1770
+ }
1771
+ addRecoveryBit(recovery) {
1772
+ return new Signature(this.r, this.s, recovery);
1773
+ }
1774
+ recoverPublicKey(messageHash) {
1775
+ const FIELD_ORDER = Fp.ORDER;
1776
+ const { r, s, recovery: rec } = this;
1777
+ if (rec == null || ![
1778
+ 0,
1779
+ 1,
1780
+ 2,
1781
+ 3
1782
+ ].includes(rec)) throw new Error("recovery id invalid");
1783
+ if (CURVE_ORDER * _2n$4 < FIELD_ORDER && rec > 1) throw new Error("recovery id is ambiguous for h>1 curve");
1784
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
1785
+ if (!Fp.isValid(radj)) throw new Error("recovery id 2 or 3 invalid");
1786
+ const x = Fp.toBytes(radj);
1787
+ const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
1788
+ const ir = Fn.inv(radj);
1789
+ const h = bits2int_modN(ensureBytes("msgHash", messageHash));
1790
+ const u1 = Fn.create(-h * ir);
1791
+ const u2 = Fn.create(s * ir);
1792
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
1793
+ if (Q.is0()) throw new Error("point at infinify");
1794
+ Q.assertValidity();
1795
+ return Q;
1796
+ }
1797
+ hasHighS() {
1798
+ return isBiggerThanHalfOrder(this.s);
1799
+ }
1800
+ toBytes(format = defaultSigOpts_format) {
1801
+ validateSigFormat(format);
1802
+ if (format === "der") return hexToBytes(DER.hexFromSig(this));
1803
+ const r = Fn.toBytes(this.r);
1804
+ const s = Fn.toBytes(this.s);
1805
+ if (format === "recovered") {
1806
+ if (this.recovery == null) throw new Error("recovery bit must be present");
1807
+ return concatBytes(Uint8Array.of(this.recovery), r, s);
1808
+ }
1809
+ return concatBytes(r, s);
1810
+ }
1811
+ toHex(format) {
1812
+ return bytesToHex(this.toBytes(format));
1813
+ }
1814
+ assertValidity() {}
1815
+ static fromCompact(hex) {
1816
+ return Signature.fromBytes(ensureBytes("sig", hex), "compact");
1817
+ }
1818
+ static fromDER(hex) {
1819
+ return Signature.fromBytes(ensureBytes("sig", hex), "der");
1820
+ }
1821
+ normalizeS() {
1822
+ return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
1823
+ }
1824
+ toDERRawBytes() {
1825
+ return this.toBytes("der");
1826
+ }
1827
+ toDERHex() {
1828
+ return bytesToHex(this.toBytes("der"));
1829
+ }
1830
+ toCompactRawBytes() {
1831
+ return this.toBytes("compact");
1832
+ }
1833
+ toCompactHex() {
1834
+ return bytesToHex(this.toBytes("compact"));
1835
+ }
1836
+ }
1837
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
1838
+ if (bytes.length > 8192) throw new Error("input is too large");
1839
+ const num = bytesToNumberBE(bytes);
1840
+ const delta = bytes.length * 8 - fnBits;
1841
+ return delta > 0 ? num >> BigInt(delta) : num;
1842
+ };
1843
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
1844
+ return Fn.create(bits2int(bytes));
1845
+ };
1846
+ const ORDER_MASK = bitMask(fnBits);
1847
+ /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
1848
+ function int2octets(num) {
1849
+ aInRange("num < 2^" + fnBits, num, _0n$2, ORDER_MASK);
1850
+ return Fn.toBytes(num);
1851
+ }
1852
+ function validateMsgAndHash(message, prehash) {
1853
+ _abytes2(message, void 0, "message");
1854
+ return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
1855
+ }
1856
+ /**
1857
+ * Steps A, D of RFC6979 3.2.
1858
+ * Creates RFC6979 seed; converts msg/privKey to numbers.
1859
+ * Used only in sign, not in verify.
1860
+ *
1861
+ * Warning: we cannot assume here that message has same amount of bytes as curve order,
1862
+ * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
1863
+ */
1864
+ function prepSig(message, privateKey, opts) {
1865
+ if (["recovered", "canonical"].some((k) => k in opts)) throw new Error("sign() legacy options not supported");
1866
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
1867
+ message = validateMsgAndHash(message, prehash);
1868
+ const h1int = bits2int_modN(message);
1869
+ const d = _normFnElement(Fn, privateKey);
1870
+ const seedArgs = [int2octets(d), int2octets(h1int)];
1871
+ if (extraEntropy != null && extraEntropy !== false) {
1872
+ const e = extraEntropy === true ? randomBytes$1(lengths.secretKey) : extraEntropy;
1873
+ seedArgs.push(ensureBytes("extraEntropy", e));
1874
+ }
1875
+ const seed = concatBytes(...seedArgs);
1876
+ const m = h1int;
1877
+ function k2sig(kBytes) {
1878
+ const k = bits2int(kBytes);
1879
+ if (!Fn.isValidNot0(k)) return;
1880
+ const ik = Fn.inv(k);
1881
+ const q = Point.BASE.multiply(k).toAffine();
1882
+ const r = Fn.create(q.x);
1883
+ if (r === _0n$2) return;
1884
+ const s = Fn.create(ik * Fn.create(m + r * d));
1885
+ if (s === _0n$2) return;
1886
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$3);
1887
+ let normS = s;
1888
+ if (lowS && isBiggerThanHalfOrder(s)) {
1889
+ normS = Fn.neg(s);
1890
+ recovery ^= 1;
1891
+ }
1892
+ return new Signature(r, normS, recovery);
1893
+ }
1894
+ return {
1895
+ seed,
1896
+ k2sig
1897
+ };
1898
+ }
1899
+ /**
1900
+ * Signs message hash with a secret key.
1901
+ *
1902
+ * ```
1903
+ * sign(m, d) where
1904
+ * k = rfc6979_hmac_drbg(m, d)
1905
+ * (x, y) = G × k
1906
+ * r = x mod n
1907
+ * s = (m + dr) / k mod n
1908
+ * ```
1909
+ */
1910
+ function sign(message, secretKey, opts = {}) {
1911
+ message = ensureBytes("message", message);
1912
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
1913
+ return createHmacDrbg(hash.outputLen, Fn.BYTES, hmac$1)(seed, k2sig);
1914
+ }
1915
+ function tryParsingSig(sg) {
1916
+ let sig = void 0;
1917
+ const isHex = typeof sg === "string" || isBytes(sg);
1918
+ const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
1919
+ if (!isHex && !isObj) throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
1920
+ if (isObj) sig = new Signature(sg.r, sg.s);
1921
+ else if (isHex) {
1922
+ try {
1923
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
1924
+ } catch (derError) {
1925
+ if (!(derError instanceof DER.Err)) throw derError;
1926
+ }
1927
+ if (!sig) try {
1928
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
1929
+ } catch (error) {
1930
+ return false;
1931
+ }
1932
+ }
1933
+ if (!sig) return false;
1934
+ return sig;
1935
+ }
1936
+ /**
1937
+ * Verifies a signature against message and public key.
1938
+ * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
1939
+ * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
1940
+ *
1941
+ * ```
1942
+ * verify(r, s, h, P) where
1943
+ * u1 = hs^-1 mod n
1944
+ * u2 = rs^-1 mod n
1945
+ * R = u1⋅G + u2⋅P
1946
+ * mod(R.x, n) == r
1947
+ * ```
1948
+ */
1949
+ function verify(signature, message, publicKey, opts = {}) {
1950
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
1951
+ publicKey = ensureBytes("publicKey", publicKey);
1952
+ message = validateMsgAndHash(ensureBytes("message", message), prehash);
1953
+ if ("strict" in opts) throw new Error("options.strict was renamed to lowS");
1954
+ const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
1955
+ if (sig === false) return false;
1956
+ try {
1957
+ const P = Point.fromBytes(publicKey);
1958
+ if (lowS && sig.hasHighS()) return false;
1959
+ const { r, s } = sig;
1960
+ const h = bits2int_modN(message);
1961
+ const is = Fn.inv(s);
1962
+ const u1 = Fn.create(h * is);
1963
+ const u2 = Fn.create(r * is);
1964
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
1965
+ if (R.is0()) return false;
1966
+ return Fn.create(R.x) === r;
1967
+ } catch (e) {
1968
+ return false;
1969
+ }
1970
+ }
1971
+ function recoverPublicKey(signature, message, opts = {}) {
1972
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
1973
+ message = validateMsgAndHash(message, prehash);
1974
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
1975
+ }
1976
+ return Object.freeze({
1977
+ keygen,
1978
+ getPublicKey,
1979
+ getSharedSecret,
1980
+ utils,
1981
+ lengths,
1982
+ Point,
1983
+ sign,
1984
+ verify,
1985
+ recoverPublicKey,
1986
+ Signature,
1987
+ hash
1988
+ });
1989
+ }
1990
+ function _weierstrass_legacy_opts_to_new(c) {
1991
+ const CURVE = {
1992
+ a: c.a,
1993
+ b: c.b,
1994
+ p: c.Fp.ORDER,
1995
+ n: c.n,
1996
+ h: c.h,
1997
+ Gx: c.Gx,
1998
+ Gy: c.Gy
1999
+ };
2000
+ const Fp = c.Fp;
2001
+ let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
2002
+ return {
2003
+ CURVE,
2004
+ curveOpts: {
2005
+ Fp,
2006
+ Fn: Field(CURVE.n, {
2007
+ BITS: c.nBitLength,
2008
+ allowedLengths,
2009
+ modFromBytes: c.wrapPrivateKey
2010
+ }),
2011
+ allowInfinityPoint: c.allowInfinityPoint,
2012
+ endo: c.endo,
2013
+ isTorsionFree: c.isTorsionFree,
2014
+ clearCofactor: c.clearCofactor,
2015
+ fromBytes: c.fromBytes,
2016
+ toBytes: c.toBytes
2017
+ }
2018
+ };
2019
+ }
2020
+ function _ecdsa_legacy_opts_to_new(c) {
2021
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
2022
+ const ecdsaOpts = {
2023
+ hmac: c.hmac,
2024
+ randomBytes: c.randomBytes,
2025
+ lowS: c.lowS,
2026
+ bits2int: c.bits2int,
2027
+ bits2int_modN: c.bits2int_modN
2028
+ };
2029
+ return {
2030
+ CURVE,
2031
+ curveOpts,
2032
+ hash: c.hash,
2033
+ ecdsaOpts
2034
+ };
2035
+ }
2036
+ function _ecdsa_new_output_to_legacy(c, _ecdsa) {
2037
+ const Point = _ecdsa.Point;
2038
+ return Object.assign({}, _ecdsa, {
2039
+ ProjectivePoint: Point,
2040
+ CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
2041
+ });
2042
+ }
2043
+ function weierstrass(c) {
2044
+ const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
2045
+ return _ecdsa_new_output_to_legacy(c, ecdsa(weierstrassN(CURVE, curveOpts), hash, ecdsaOpts));
2046
+ }
2047
+ /**
2048
+ * Utilities for short weierstrass curves, combined with noble-hashes.
2049
+ * @module
2050
+ */
2051
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2052
+ /** @deprecated use new `weierstrass()` and `ecdsa()` methods */
2053
+ function createCurve(curveDef, defHash) {
2054
+ const create = (hash) => weierstrass({
2055
+ ...curveDef,
2056
+ hash
2057
+ });
2058
+ return {
2059
+ ...create(defHash),
2060
+ create
2061
+ };
2062
+ }
2063
+ /**
2064
+ * Internal module for NIST P256, P384, P521 curves.
2065
+ * Do not use for now.
2066
+ * @module
2067
+ */
2068
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2069
+ var p256_CURVE = {
2070
+ p: BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),
2071
+ n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),
2072
+ h: BigInt(1),
2073
+ a: BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),
2074
+ b: BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),
2075
+ Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
2076
+ Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")
2077
+ };
2078
+ var p384_CURVE = {
2079
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),
2080
+ n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),
2081
+ h: BigInt(1),
2082
+ a: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),
2083
+ b: BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),
2084
+ Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),
2085
+ Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")
2086
+ };
2087
+ var p521_CURVE = {
2088
+ p: BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
2089
+ n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),
2090
+ h: BigInt(1),
2091
+ a: BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),
2092
+ b: BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),
2093
+ Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),
2094
+ Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")
2095
+ };
2096
+ var Fp256 = Field(p256_CURVE.p);
2097
+ var Fp384 = Field(p384_CURVE.p);
2098
+ var Fp521 = Field(p521_CURVE.p);
2099
+ /** NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. */
2100
+ var p256$1 = createCurve({
2101
+ ...p256_CURVE,
2102
+ Fp: Fp256,
2103
+ lowS: false
2104
+ }, sha256$1);
2105
+ /** NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. */
2106
+ var p384$1 = createCurve({
2107
+ ...p384_CURVE,
2108
+ Fp: Fp384,
2109
+ lowS: false
2110
+ }, sha384$1);
2111
+ /** NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. */
2112
+ var p521$1 = createCurve({
2113
+ ...p521_CURVE,
2114
+ Fp: Fp521,
2115
+ lowS: false,
2116
+ allowedPrivateKeyLengths: [
2117
+ 130,
2118
+ 131,
2119
+ 132
2120
+ ]
2121
+ }, sha512$1);
2122
+ /**
2123
+ * NIST secp256r1 aka p256.
2124
+ * @module
2125
+ */
2126
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2127
+ /** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */
2128
+ var p256 = p256$1;
2129
+ /**
2130
+ * NIST secp384r1 aka p384.
2131
+ * @module
2132
+ */
2133
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2134
+ /** @deprecated use `import { p384 } from '@noble/curves/nist.js';` */
2135
+ var p384 = p384$1;
2136
+ /**
2137
+ * NIST secp521r1 aka p521.
2138
+ * @module
2139
+ */
2140
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2141
+ /** @deprecated use `import { p521 } from '@noble/curves/nist.js';` */
2142
+ var p521 = p521$1;
2143
+ /**
2144
+ * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
2145
+ * For design rationale of types / exports, see weierstrass module documentation.
2146
+ * Untwisted Edwards curves exist, but they aren't used in real-world protocols.
2147
+ * @module
2148
+ */
2149
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2150
+ var _0n$1 = BigInt(0);
2151
+ var _1n$2 = BigInt(1);
2152
+ var _2n$3 = BigInt(2);
2153
+ var _8n = BigInt(8);
2154
+ function isEdValidXY(Fp, CURVE, x, y) {
2155
+ const x2 = Fp.sqr(x);
2156
+ const y2 = Fp.sqr(y);
2157
+ const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
2158
+ const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
2159
+ return Fp.eql(left, right);
2160
+ }
2161
+ function edwards(params, extraOpts = {}) {
2162
+ const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
2163
+ const { Fp, Fn } = validated;
2164
+ let CURVE = validated.CURVE;
2165
+ const { h: cofactor } = CURVE;
2166
+ _validateObject(extraOpts, {}, { uvRatio: "function" });
2167
+ const MASK = _2n$3 << BigInt(Fn.BYTES * 8) - _1n$2;
2168
+ const modP = (n) => Fp.create(n);
2169
+ const uvRatio = extraOpts.uvRatio || ((u, v) => {
2170
+ try {
2171
+ return {
2172
+ isValid: true,
2173
+ value: Fp.sqrt(Fp.div(u, v))
2174
+ };
2175
+ } catch (e) {
2176
+ return {
2177
+ isValid: false,
2178
+ value: _0n$1
2179
+ };
2180
+ }
2181
+ });
2182
+ if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
2183
+ /**
2184
+ * Asserts coordinate is valid: 0 <= n < MASK.
2185
+ * Coordinates >= Fp.ORDER are allowed for zip215.
2186
+ */
2187
+ function acoord(title, n, banZero = false) {
2188
+ const min = banZero ? _1n$2 : _0n$1;
2189
+ aInRange("coordinate " + title, n, min, MASK);
2190
+ return n;
2191
+ }
2192
+ function aextpoint(other) {
2193
+ if (!(other instanceof Point)) throw new Error("ExtendedPoint expected");
2194
+ }
2195
+ const toAffineMemo = memoized((p, iz) => {
2196
+ const { X, Y, Z } = p;
2197
+ const is0 = p.is0();
2198
+ if (iz == null) iz = is0 ? _8n : Fp.inv(Z);
2199
+ const x = modP(X * iz);
2200
+ const y = modP(Y * iz);
2201
+ const zz = Fp.mul(Z, iz);
2202
+ if (is0) return {
2203
+ x: _0n$1,
2204
+ y: _1n$2
2205
+ };
2206
+ if (zz !== _1n$2) throw new Error("invZ was invalid");
2207
+ return {
2208
+ x,
2209
+ y
2210
+ };
2211
+ });
2212
+ const assertValidMemo = memoized((p) => {
2213
+ const { a, d } = CURVE;
2214
+ if (p.is0()) throw new Error("bad point: ZERO");
2215
+ const { X, Y, Z, T } = p;
2216
+ const X2 = modP(X * X);
2217
+ const Y2 = modP(Y * Y);
2218
+ const Z2 = modP(Z * Z);
2219
+ const Z4 = modP(Z2 * Z2);
2220
+ const aX2 = modP(X2 * a);
2221
+ if (modP(Z2 * modP(aX2 + Y2)) !== modP(Z4 + modP(d * modP(X2 * Y2)))) throw new Error("bad point: equation left != right (1)");
2222
+ if (modP(X * Y) !== modP(Z * T)) throw new Error("bad point: equation left != right (2)");
2223
+ return true;
2224
+ });
2225
+ class Point {
2226
+ constructor(X, Y, Z, T) {
2227
+ this.X = acoord("x", X);
2228
+ this.Y = acoord("y", Y);
2229
+ this.Z = acoord("z", Z, true);
2230
+ this.T = acoord("t", T);
2231
+ Object.freeze(this);
2232
+ }
2233
+ static CURVE() {
2234
+ return CURVE;
2235
+ }
2236
+ static fromAffine(p) {
2237
+ if (p instanceof Point) throw new Error("extended point not allowed");
2238
+ const { x, y } = p || {};
2239
+ acoord("x", x);
2240
+ acoord("y", y);
2241
+ return new Point(x, y, _1n$2, modP(x * y));
2242
+ }
2243
+ static fromBytes(bytes, zip215 = false) {
2244
+ const len = Fp.BYTES;
2245
+ const { a, d } = CURVE;
2246
+ bytes = copyBytes(_abytes2(bytes, len, "point"));
2247
+ _abool2(zip215, "zip215");
2248
+ const normed = copyBytes(bytes);
2249
+ const lastByte = bytes[len - 1];
2250
+ normed[len - 1] = lastByte & -129;
2251
+ const y = bytesToNumberLE(normed);
2252
+ aInRange("point.y", y, _0n$1, zip215 ? MASK : Fp.ORDER);
2253
+ const y2 = modP(y * y);
2254
+ const u = modP(y2 - _1n$2);
2255
+ const v = modP(d * y2 - a);
2256
+ let { isValid, value: x } = uvRatio(u, v);
2257
+ if (!isValid) throw new Error("bad point: invalid y coordinate");
2258
+ const isXOdd = (x & _1n$2) === _1n$2;
2259
+ const isLastByteOdd = (lastByte & 128) !== 0;
2260
+ if (!zip215 && x === _0n$1 && isLastByteOdd) throw new Error("bad point: x=0 and x_0=1");
2261
+ if (isLastByteOdd !== isXOdd) x = modP(-x);
2262
+ return Point.fromAffine({
2263
+ x,
2264
+ y
2265
+ });
2266
+ }
2267
+ static fromHex(bytes, zip215 = false) {
2268
+ return Point.fromBytes(ensureBytes("point", bytes), zip215);
2269
+ }
2270
+ get x() {
2271
+ return this.toAffine().x;
2272
+ }
2273
+ get y() {
2274
+ return this.toAffine().y;
2275
+ }
2276
+ precompute(windowSize = 8, isLazy = true) {
2277
+ wnaf.createCache(this, windowSize);
2278
+ if (!isLazy) this.multiply(_2n$3);
2279
+ return this;
2280
+ }
2281
+ assertValidity() {
2282
+ assertValidMemo(this);
2283
+ }
2284
+ equals(other) {
2285
+ aextpoint(other);
2286
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2287
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2288
+ const X1Z2 = modP(X1 * Z2);
2289
+ const X2Z1 = modP(X2 * Z1);
2290
+ const Y1Z2 = modP(Y1 * Z2);
2291
+ const Y2Z1 = modP(Y2 * Z1);
2292
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
2293
+ }
2294
+ is0() {
2295
+ return this.equals(Point.ZERO);
2296
+ }
2297
+ negate() {
2298
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
2299
+ }
2300
+ double() {
2301
+ const { a } = CURVE;
2302
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2303
+ const A = modP(X1 * X1);
2304
+ const B = modP(Y1 * Y1);
2305
+ const C = modP(_2n$3 * modP(Z1 * Z1));
2306
+ const D = modP(a * A);
2307
+ const x1y1 = X1 + Y1;
2308
+ const E = modP(modP(x1y1 * x1y1) - A - B);
2309
+ const G = D + B;
2310
+ const F = G - C;
2311
+ const H = D - B;
2312
+ const X3 = modP(E * F);
2313
+ const Y3 = modP(G * H);
2314
+ const T3 = modP(E * H);
2315
+ const Z3 = modP(F * G);
2316
+ return new Point(X3, Y3, Z3, T3);
2317
+ }
2318
+ add(other) {
2319
+ aextpoint(other);
2320
+ const { a, d } = CURVE;
2321
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
2322
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
2323
+ const A = modP(X1 * X2);
2324
+ const B = modP(Y1 * Y2);
2325
+ const C = modP(T1 * d * T2);
2326
+ const D = modP(Z1 * Z2);
2327
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
2328
+ const F = D - C;
2329
+ const G = D + C;
2330
+ const H = modP(B - a * A);
2331
+ const X3 = modP(E * F);
2332
+ const Y3 = modP(G * H);
2333
+ const T3 = modP(E * H);
2334
+ const Z3 = modP(F * G);
2335
+ return new Point(X3, Y3, Z3, T3);
2336
+ }
2337
+ subtract(other) {
2338
+ return this.add(other.negate());
2339
+ }
2340
+ multiply(scalar) {
2341
+ if (!Fn.isValidNot0(scalar)) throw new Error("invalid scalar: expected 1 <= sc < curve.n");
2342
+ const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));
2343
+ return normalizeZ(Point, [p, f])[0];
2344
+ }
2345
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
2346
+ if (!Fn.isValid(scalar)) throw new Error("invalid scalar: expected 0 <= sc < curve.n");
2347
+ if (scalar === _0n$1) return Point.ZERO;
2348
+ if (this.is0() || scalar === _1n$2) return this;
2349
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
2350
+ }
2351
+ isSmallOrder() {
2352
+ return this.multiplyUnsafe(cofactor).is0();
2353
+ }
2354
+ isTorsionFree() {
2355
+ return wnaf.unsafe(this, CURVE.n).is0();
2356
+ }
2357
+ toAffine(invertedZ) {
2358
+ return toAffineMemo(this, invertedZ);
2359
+ }
2360
+ clearCofactor() {
2361
+ if (cofactor === _1n$2) return this;
2362
+ return this.multiplyUnsafe(cofactor);
2363
+ }
2364
+ toBytes() {
2365
+ const { x, y } = this.toAffine();
2366
+ const bytes = Fp.toBytes(y);
2367
+ bytes[bytes.length - 1] |= x & _1n$2 ? 128 : 0;
2368
+ return bytes;
2369
+ }
2370
+ toHex() {
2371
+ return bytesToHex(this.toBytes());
2372
+ }
2373
+ toString() {
2374
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2375
+ }
2376
+ get ex() {
2377
+ return this.X;
2378
+ }
2379
+ get ey() {
2380
+ return this.Y;
2381
+ }
2382
+ get ez() {
2383
+ return this.Z;
2384
+ }
2385
+ get et() {
2386
+ return this.T;
2387
+ }
2388
+ static normalizeZ(points) {
2389
+ return normalizeZ(Point, points);
2390
+ }
2391
+ static msm(points, scalars) {
2392
+ return pippenger(Point, Fn, points, scalars);
2393
+ }
2394
+ _setWindowSize(windowSize) {
2395
+ this.precompute(windowSize);
2396
+ }
2397
+ toRawBytes() {
2398
+ return this.toBytes();
2399
+ }
2400
+ }
2401
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$2, modP(CURVE.Gx * CURVE.Gy));
2402
+ Point.ZERO = new Point(_0n$1, _1n$2, _1n$2, _0n$1);
2403
+ Point.Fp = Fp;
2404
+ Point.Fn = Fn;
2405
+ const wnaf = new wNAF(Point, Fn.BITS);
2406
+ Point.BASE.precompute(8);
2407
+ return Point;
2408
+ }
2409
+ /**
2410
+ * Initializes EdDSA signatures over given Edwards curve.
2411
+ */
2412
+ function eddsa(Point, cHash, eddsaOpts = {}) {
2413
+ if (typeof cHash !== "function") throw new Error("\"hash\" function param is required");
2414
+ _validateObject(eddsaOpts, {}, {
2415
+ adjustScalarBytes: "function",
2416
+ randomBytes: "function",
2417
+ domain: "function",
2418
+ prehash: "function",
2419
+ mapToCurve: "function"
2420
+ });
2421
+ const { prehash } = eddsaOpts;
2422
+ const { BASE, Fp, Fn } = Point;
2423
+ const randomBytes$1 = eddsaOpts.randomBytes || randomBytes;
2424
+ const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
2425
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
2426
+ _abool2(phflag, "phflag");
2427
+ if (ctx.length || phflag) throw new Error("Contexts/pre-hash are not supported");
2428
+ return data;
2429
+ });
2430
+ function modN_LE(hash) {
2431
+ return Fn.create(bytesToNumberLE(hash));
2432
+ }
2433
+ function getPrivateScalar(key) {
2434
+ const len = lengths.secretKey;
2435
+ key = ensureBytes("private key", key, len);
2436
+ const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
2437
+ const head = adjustScalarBytes(hashed.slice(0, len));
2438
+ return {
2439
+ head,
2440
+ prefix: hashed.slice(len, 2 * len),
2441
+ scalar: modN_LE(head)
2442
+ };
2443
+ }
2444
+ /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */
2445
+ function getExtendedPublicKey(secretKey) {
2446
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
2447
+ const point = BASE.multiply(scalar);
2448
+ return {
2449
+ head,
2450
+ prefix,
2451
+ scalar,
2452
+ point,
2453
+ pointBytes: point.toBytes()
2454
+ };
2455
+ }
2456
+ /** Calculates EdDSA pub key. RFC8032 5.1.5. */
2457
+ function getPublicKey(secretKey) {
2458
+ return getExtendedPublicKey(secretKey).pointBytes;
2459
+ }
2460
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
2461
+ const msg = concatBytes(...msgs);
2462
+ return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
2463
+ }
2464
+ /** Signs message with privateKey. RFC8032 5.1.6 */
2465
+ function sign(msg, secretKey, options = {}) {
2466
+ msg = ensureBytes("message", msg);
2467
+ if (prehash) msg = prehash(msg);
2468
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
2469
+ const r = hashDomainToScalar(options.context, prefix, msg);
2470
+ const R = BASE.multiply(r).toBytes();
2471
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
2472
+ const s = Fn.create(r + k * scalar);
2473
+ if (!Fn.isValid(s)) throw new Error("sign failed: invalid s");
2474
+ return _abytes2(concatBytes(R, Fn.toBytes(s)), lengths.signature, "result");
2475
+ }
2476
+ const verifyOpts = { zip215: true };
2477
+ /**
2478
+ * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
2479
+ * An extended group equation is checked.
2480
+ */
2481
+ function verify(sig, msg, publicKey, options = verifyOpts) {
2482
+ const { context, zip215 } = options;
2483
+ const len = lengths.signature;
2484
+ sig = ensureBytes("signature", sig, len);
2485
+ msg = ensureBytes("message", msg);
2486
+ publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
2487
+ if (zip215 !== void 0) _abool2(zip215, "zip215");
2488
+ if (prehash) msg = prehash(msg);
2489
+ const mid = len / 2;
2490
+ const r = sig.subarray(0, mid);
2491
+ const s = bytesToNumberLE(sig.subarray(mid, len));
2492
+ let A, R, SB;
2493
+ try {
2494
+ A = Point.fromBytes(publicKey, zip215);
2495
+ R = Point.fromBytes(r, zip215);
2496
+ SB = BASE.multiplyUnsafe(s);
2497
+ } catch (error) {
2498
+ return false;
2499
+ }
2500
+ if (!zip215 && A.isSmallOrder()) return false;
2501
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
2502
+ return R.add(A.multiplyUnsafe(k)).subtract(SB).clearCofactor().is0();
2503
+ }
2504
+ const _size = Fp.BYTES;
2505
+ const lengths = {
2506
+ secretKey: _size,
2507
+ publicKey: _size,
2508
+ signature: 2 * _size,
2509
+ seed: _size
2510
+ };
2511
+ function randomSecretKey(seed = randomBytes$1(lengths.seed)) {
2512
+ return _abytes2(seed, lengths.seed, "seed");
2513
+ }
2514
+ function keygen(seed) {
2515
+ const secretKey = utils.randomSecretKey(seed);
2516
+ return {
2517
+ secretKey,
2518
+ publicKey: getPublicKey(secretKey)
2519
+ };
2520
+ }
2521
+ function isValidSecretKey(key) {
2522
+ return isBytes(key) && key.length === Fn.BYTES;
2523
+ }
2524
+ function isValidPublicKey(key, zip215) {
2525
+ try {
2526
+ return !!Point.fromBytes(key, zip215);
2527
+ } catch (error) {
2528
+ return false;
2529
+ }
2530
+ }
2531
+ const utils = {
2532
+ getExtendedPublicKey,
2533
+ randomSecretKey,
2534
+ isValidSecretKey,
2535
+ isValidPublicKey,
2536
+ /**
2537
+ * Converts ed public key to x public key. Uses formula:
2538
+ * - ed25519:
2539
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
2540
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
2541
+ * - ed448:
2542
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
2543
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
2544
+ */
2545
+ toMontgomery(publicKey) {
2546
+ const { y } = Point.fromBytes(publicKey);
2547
+ const size = lengths.publicKey;
2548
+ const is25519 = size === 32;
2549
+ if (!is25519 && size !== 57) throw new Error("only defined for 25519 and 448");
2550
+ const u = is25519 ? Fp.div(_1n$2 + y, _1n$2 - y) : Fp.div(y - _1n$2, y + _1n$2);
2551
+ return Fp.toBytes(u);
2552
+ },
2553
+ toMontgomerySecret(secretKey) {
2554
+ const size = lengths.secretKey;
2555
+ _abytes2(secretKey, size);
2556
+ const hashed = cHash(secretKey.subarray(0, size));
2557
+ return adjustScalarBytes(hashed).subarray(0, size);
2558
+ },
2559
+ /** @deprecated */
2560
+ randomPrivateKey: randomSecretKey,
2561
+ /** @deprecated */
2562
+ precompute(windowSize = 8, point = Point.BASE) {
2563
+ return point.precompute(windowSize, false);
2564
+ }
2565
+ };
2566
+ return Object.freeze({
2567
+ keygen,
2568
+ getPublicKey,
2569
+ sign,
2570
+ verify,
2571
+ utils,
2572
+ Point,
2573
+ lengths
2574
+ });
2575
+ }
2576
+ function _eddsa_legacy_opts_to_new(c) {
2577
+ const CURVE = {
2578
+ a: c.a,
2579
+ d: c.d,
2580
+ p: c.Fp.ORDER,
2581
+ n: c.n,
2582
+ h: c.h,
2583
+ Gx: c.Gx,
2584
+ Gy: c.Gy
2585
+ };
2586
+ const curveOpts = {
2587
+ Fp: c.Fp,
2588
+ Fn: Field(CURVE.n, c.nBitLength, true),
2589
+ uvRatio: c.uvRatio
2590
+ };
2591
+ const eddsaOpts = {
2592
+ randomBytes: c.randomBytes,
2593
+ adjustScalarBytes: c.adjustScalarBytes,
2594
+ domain: c.domain,
2595
+ prehash: c.prehash,
2596
+ mapToCurve: c.mapToCurve
2597
+ };
2598
+ return {
2599
+ CURVE,
2600
+ curveOpts,
2601
+ hash: c.hash,
2602
+ eddsaOpts
2603
+ };
2604
+ }
2605
+ function _eddsa_new_output_to_legacy(c, eddsa) {
2606
+ const Point = eddsa.Point;
2607
+ return Object.assign({}, eddsa, {
2608
+ ExtendedPoint: Point,
2609
+ CURVE: c,
2610
+ nBitLength: Point.Fn.BITS,
2611
+ nByteLength: Point.Fn.BYTES
2612
+ });
2613
+ }
2614
+ function twistedEdwards(c) {
2615
+ const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
2616
+ return _eddsa_new_output_to_legacy(c, eddsa(edwards(CURVE, curveOpts), hash, eddsaOpts));
2617
+ }
2618
+ /**
2619
+ * Montgomery curve methods. It's not really whole montgomery curve,
2620
+ * just bunch of very specific methods for X25519 / X448 from
2621
+ * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)
2622
+ * @module
2623
+ */
2624
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2625
+ var _0n = BigInt(0);
2626
+ var _1n$1 = BigInt(1);
2627
+ var _2n$2 = BigInt(2);
2628
+ function validateOpts(curve) {
2629
+ _validateObject(curve, {
2630
+ adjustScalarBytes: "function",
2631
+ powPminus2: "function"
2632
+ });
2633
+ return Object.freeze({ ...curve });
2634
+ }
2635
+ function montgomery(curveDef) {
2636
+ const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = validateOpts(curveDef);
2637
+ const is25519 = type === "x25519";
2638
+ if (!is25519 && type !== "x448") throw new Error("invalid type");
2639
+ const randomBytes_ = rand || randomBytes;
2640
+ const montgomeryBits = is25519 ? 255 : 448;
2641
+ const fieldLen = is25519 ? 32 : 56;
2642
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
2643
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
2644
+ const minScalar = is25519 ? _2n$2 ** BigInt(254) : _2n$2 ** BigInt(447);
2645
+ const maxScalar = minScalar + (is25519 ? BigInt(8) * _2n$2 ** BigInt(251) - _1n$1 : BigInt(4) * _2n$2 ** BigInt(445) - _1n$1) + _1n$1;
2646
+ const modP = (n) => mod(n, P);
2647
+ const GuBytes = encodeU(Gu);
2648
+ function encodeU(u) {
2649
+ return numberToBytesLE(modP(u), fieldLen);
2650
+ }
2651
+ function decodeU(u) {
2652
+ const _u = ensureBytes("u coordinate", u, fieldLen);
2653
+ if (is25519) _u[31] &= 127;
2654
+ return modP(bytesToNumberLE(_u));
2655
+ }
2656
+ function decodeScalar(scalar) {
2657
+ return bytesToNumberLE(adjustScalarBytes(ensureBytes("scalar", scalar, fieldLen)));
2658
+ }
2659
+ function scalarMult(scalar, u) {
2660
+ const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
2661
+ if (pu === _0n) throw new Error("invalid private or public key received");
2662
+ return encodeU(pu);
2663
+ }
2664
+ function scalarMultBase(scalar) {
2665
+ return scalarMult(scalar, GuBytes);
2666
+ }
2667
+ function cswap(swap, x_2, x_3) {
2668
+ const dummy = modP(swap * (x_2 - x_3));
2669
+ x_2 = modP(x_2 - dummy);
2670
+ x_3 = modP(x_3 + dummy);
2671
+ return {
2672
+ x_2,
2673
+ x_3
2674
+ };
2675
+ }
2676
+ /**
2677
+ * Montgomery x-only multiplication ladder.
2678
+ * @param pointU u coordinate (x) on Montgomery Curve 25519
2679
+ * @param scalar by which the point would be multiplied
2680
+ * @returns new Point on Montgomery curve
2681
+ */
2682
+ function montgomeryLadder(u, scalar) {
2683
+ aInRange("u", u, _0n, P);
2684
+ aInRange("scalar", scalar, minScalar, maxScalar);
2685
+ const k = scalar;
2686
+ const x_1 = u;
2687
+ let x_2 = _1n$1;
2688
+ let z_2 = _0n;
2689
+ let x_3 = u;
2690
+ let z_3 = _1n$1;
2691
+ let swap = _0n;
2692
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
2693
+ const k_t = k >> t & _1n$1;
2694
+ swap ^= k_t;
2695
+ ({x_2, x_3} = cswap(swap, x_2, x_3));
2696
+ ({x_2: z_2, x_3: z_3} = cswap(swap, z_2, z_3));
2697
+ swap = k_t;
2698
+ const A = x_2 + z_2;
2699
+ const AA = modP(A * A);
2700
+ const B = x_2 - z_2;
2701
+ const BB = modP(B * B);
2702
+ const E = AA - BB;
2703
+ const C = x_3 + z_3;
2704
+ const D = x_3 - z_3;
2705
+ const DA = modP(D * A);
2706
+ const CB = modP(C * B);
2707
+ const dacb = DA + CB;
2708
+ const da_cb = DA - CB;
2709
+ x_3 = modP(dacb * dacb);
2710
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
2711
+ x_2 = modP(AA * BB);
2712
+ z_2 = modP(E * (AA + modP(a24 * E)));
2713
+ }
2714
+ ({x_2, x_3} = cswap(swap, x_2, x_3));
2715
+ ({x_2: z_2, x_3: z_3} = cswap(swap, z_2, z_3));
2716
+ const z2 = powPminus2(z_2);
2717
+ return modP(x_2 * z2);
2718
+ }
2719
+ const lengths = {
2720
+ secretKey: fieldLen,
2721
+ publicKey: fieldLen,
2722
+ seed: fieldLen
2723
+ };
2724
+ const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
2725
+ abytes(seed, lengths.seed);
2726
+ return seed;
2727
+ };
2728
+ function keygen(seed) {
2729
+ const secretKey = randomSecretKey(seed);
2730
+ return {
2731
+ secretKey,
2732
+ publicKey: scalarMultBase(secretKey)
2733
+ };
2734
+ }
2735
+ return {
2736
+ keygen,
2737
+ getSharedSecret: (secretKey, publicKey) => scalarMult(secretKey, publicKey),
2738
+ getPublicKey: (secretKey) => scalarMultBase(secretKey),
2739
+ scalarMult,
2740
+ scalarMultBase,
2741
+ utils: {
2742
+ randomSecretKey,
2743
+ randomPrivateKey: randomSecretKey
2744
+ },
2745
+ GuBytes: GuBytes.slice(),
2746
+ lengths
2747
+ };
2748
+ }
2749
+ /**
2750
+ * Edwards448 (not Ed448-Goldilocks) curve with following addons:
2751
+ * - X448 ECDH
2752
+ * - Decaf cofactor elimination
2753
+ * - Elligator hash-to-group / point indistinguishability
2754
+ * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2
2755
+ * @module
2756
+ */
2757
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2758
+ var ed448_CURVE = {
2759
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
2760
+ n: BigInt("0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3"),
2761
+ h: BigInt(4),
2762
+ a: BigInt(1),
2763
+ d: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffff6756"),
2764
+ Gx: BigInt("0x4f1970c66bed0ded221d15a622bf36da9e146570470f1767ea6de324a3d3a46412ae1af72ab66511433b80e18b00938e2626a82bc70cc05e"),
2765
+ Gy: BigInt("0x693f46716eb6bc248876203756c9c7624bea73736ca3984087789c1e05a0c2d73ad3ff1ce67c39c4fdbd132c4ed7c8ad9808795bf230fa14")
2766
+ };
2767
+ var E448_CURVE = Object.assign({}, ed448_CURVE, {
2768
+ d: BigInt("0xd78b4bdc7f0daf19f24f38c29373a2ccad46157242a50f37809b1da3412a12e79ccc9c81264cfe9ad080997058fb61c4243cc32dbaa156b9"),
2769
+ Gx: BigInt("0x79a70b2b70400553ae7c9df416c792c61128751ac92969240c25a07d728bdc93e21f7787ed6972249de732f38496cd11698713093e9c04fc"),
2770
+ Gy: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000000000000000000000000000000000000000000000000001")
2771
+ });
2772
+ var shake256_114 = /* @__PURE__ */ createHasher(() => shake256.create({ dkLen: 114 }));
2773
+ var _1n = BigInt(1);
2774
+ var _2n$1 = BigInt(2);
2775
+ var _3n = BigInt(3);
2776
+ var _11n = BigInt(11);
2777
+ var _22n = BigInt(22);
2778
+ var _44n = BigInt(44);
2779
+ var _88n = BigInt(88);
2780
+ var _223n = BigInt(223);
2781
+ function ed448_pow_Pminus3div4(x) {
2782
+ const P = ed448_CURVE.p;
2783
+ const b2 = x * x * x % P;
2784
+ const b3 = b2 * b2 * x % P;
2785
+ const b11 = pow2(pow2(pow2(b3, _3n, P) * b3 % P, _3n, P) * b3 % P, _2n$1, P) * b2 % P;
2786
+ const b22 = pow2(b11, _11n, P) * b11 % P;
2787
+ const b44 = pow2(b22, _22n, P) * b22 % P;
2788
+ const b88 = pow2(b44, _44n, P) * b44 % P;
2789
+ const b222 = pow2(pow2(pow2(b88, _88n, P) * b88 % P, _44n, P) * b44 % P, _2n$1, P) * b2 % P;
2790
+ return pow2(pow2(b222, _1n, P) * x % P, _223n, P) * b222 % P;
2791
+ }
2792
+ function adjustScalarBytes(bytes) {
2793
+ bytes[0] &= 252;
2794
+ bytes[55] |= 128;
2795
+ bytes[56] = 0;
2796
+ return bytes;
2797
+ }
2798
+ function uvRatio(u, v) {
2799
+ const P = ed448_CURVE.p;
2800
+ const u2v = mod(u * u * v, P);
2801
+ const u3v = mod(u2v * u, P);
2802
+ const x = mod(u3v * ed448_pow_Pminus3div4(mod(u3v * u2v * v, P)), P);
2803
+ return {
2804
+ isValid: mod(mod(x * x, P) * v, P) === u,
2805
+ value: x
2806
+ };
2807
+ }
2808
+ var Fp$3 = /* @__PURE__ */ (() => Field(ed448_CURVE.p, {
2809
+ BITS: 456,
2810
+ isLE: true
2811
+ }))();
2812
+ var Fn = /* @__PURE__ */ (() => Field(ed448_CURVE.n, {
2813
+ BITS: 456,
2814
+ isLE: true
2815
+ }))();
2816
+ function dom4(data, ctx, phflag) {
2817
+ if (ctx.length > 255) throw new Error("context must be smaller than 255, got: " + ctx.length);
2818
+ return concatBytes(asciiToBytes("SigEd448"), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
2819
+ }
2820
+ /**
2821
+ * ed448 EdDSA curve and methods.
2822
+ * @example
2823
+ * import { ed448 } from '@noble/curves/ed448';
2824
+ * const { secretKey, publicKey } = ed448.keygen();
2825
+ * const msg = new TextEncoder().encode('hello');
2826
+ * const sig = ed448.sign(msg, secretKey);
2827
+ * const isValid = ed448.verify(sig, msg, publicKey);
2828
+ */
2829
+ var ed448 = twistedEdwards(/* @__PURE__ */ (() => ({
2830
+ ...ed448_CURVE,
2831
+ Fp: Fp$3,
2832
+ Fn,
2833
+ nBitLength: Fn.BITS,
2834
+ hash: shake256_114,
2835
+ adjustScalarBytes,
2836
+ domain: dom4,
2837
+ uvRatio
2838
+ }))());
2839
+ /**
2840
+ * E448 curve, defined by NIST.
2841
+ * E448 != edwards448 used in ed448.
2842
+ * E448 is birationally equivalent to edwards448.
2843
+ */
2844
+ edwards(E448_CURVE);
2845
+ /**
2846
+ * ECDH using curve448 aka x448.
2847
+ * x448 has 56-byte keys as per RFC 7748, while
2848
+ * ed448 has 57-byte keys as per RFC 8032.
2849
+ */
2850
+ var x448 = /* @__PURE__ */ (() => {
2851
+ const P = ed448_CURVE.p;
2852
+ return montgomery({
2853
+ P,
2854
+ type: "x448",
2855
+ powPminus2: (x) => {
2856
+ return mod(pow2(ed448_pow_Pminus3div4(x), _2n$1, P) * x, P);
2857
+ },
2858
+ adjustScalarBytes
2859
+ });
2860
+ })();
2861
+ /**
2862
+ * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
2863
+ *
2864
+ * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
2865
+ * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
2866
+ * @module
2867
+ */
2868
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2869
+ var secp256k1_CURVE = {
2870
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
2871
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
2872
+ h: BigInt(1),
2873
+ a: BigInt(0),
2874
+ b: BigInt(7),
2875
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
2876
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
2877
+ };
2878
+ var secp256k1_ENDO = {
2879
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
2880
+ basises: [[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")], [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]
2881
+ };
2882
+ var _2n = /* @__PURE__ */ BigInt(2);
2883
+ /**
2884
+ * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
2885
+ * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
2886
+ */
2887
+ function sqrtMod(y) {
2888
+ const P = secp256k1_CURVE.p;
2889
+ const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
2890
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
2891
+ const b2 = y * y * y % P;
2892
+ const b3 = b2 * b2 * y % P;
2893
+ const b11 = pow2(pow2(pow2(b3, _3n, P) * b3 % P, _3n, P) * b3 % P, _2n, P) * b2 % P;
2894
+ const b22 = pow2(b11, _11n, P) * b11 % P;
2895
+ const b44 = pow2(b22, _22n, P) * b22 % P;
2896
+ const b88 = pow2(b44, _44n, P) * b44 % P;
2897
+ 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);
2898
+ if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error("Cannot find square root");
2899
+ return root;
2900
+ }
2901
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
2902
+ /**
2903
+ * secp256k1 curve, ECDSA and ECDH methods.
2904
+ *
2905
+ * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
2906
+ *
2907
+ * @example
2908
+ * ```js
2909
+ * import { secp256k1 } from '@noble/curves/secp256k1';
2910
+ * const { secretKey, publicKey } = secp256k1.keygen();
2911
+ * const msg = new TextEncoder().encode('hello');
2912
+ * const sig = secp256k1.sign(msg, secretKey);
2913
+ * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
2914
+ * ```
2915
+ */
2916
+ var secp256k1 = createCurve({
2917
+ ...secp256k1_CURVE,
2918
+ Fp: Fpk1,
2919
+ lowS: true,
2920
+ endo: secp256k1_ENDO
2921
+ }, sha256$1);
2922
+ /** @access private */
2923
+ var Fp$2 = Field(BigInt("0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377"));
2924
+ var brainpoolP256r1 = createCurve({
2925
+ a: Fp$2.create(BigInt("0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9")),
2926
+ b: BigInt("0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6"),
2927
+ Fp: Fp$2,
2928
+ n: BigInt("0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7"),
2929
+ Gx: BigInt("0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262"),
2930
+ Gy: BigInt("0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997"),
2931
+ h: BigInt(1),
2932
+ lowS: false
2933
+ }, sha256);
2934
+ /** @access private */
2935
+ var Fp$1 = Field(BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53"));
2936
+ var brainpoolP384r1 = createCurve({
2937
+ a: Fp$1.create(BigInt("0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826")),
2938
+ b: BigInt("0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11"),
2939
+ Fp: Fp$1,
2940
+ n: BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565"),
2941
+ Gx: BigInt("0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e"),
2942
+ Gy: BigInt("0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315"),
2943
+ h: BigInt(1),
2944
+ lowS: false
2945
+ }, sha384);
2946
+ /** @access private */
2947
+ var Fp = Field(BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3"));
2948
+ var brainpoolP512r1 = createCurve({
2949
+ a: Fp.create(BigInt("0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca")),
2950
+ b: BigInt("0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723"),
2951
+ Fp,
2952
+ n: BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069"),
2953
+ Gx: BigInt("0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822"),
2954
+ Gy: BigInt("0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892"),
2955
+ h: BigInt(1),
2956
+ lowS: false
2957
+ }, sha512);
2958
+ /**
2959
+ * @access private
2960
+ * This file is needed to dynamic import the noble-curves.
2961
+ * Separate dynamic imports are not convenient as they result in too many chunks,
2962
+ * which share a lot of code anyway.
2963
+ */
2964
+ var nobleCurves = new Map(Object.entries({
2965
+ nistP256: p256,
2966
+ nistP384: p384,
2967
+ nistP521: p521,
2968
+ brainpoolP256r1,
2969
+ brainpoolP384r1,
2970
+ brainpoolP512r1,
2971
+ secp256k1,
2972
+ x448,
2973
+ ed448
2974
+ }));
2975
+ //#endregion
2976
+ export { nobleCurves };
2977
+
2978
+ //# sourceMappingURL=noble_curves-DDWn5AH0.js.map