@tangle-network/sandbox 0.60.2 → 0.60.6

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