@happyvertical/smrt-profiles 0.37.2 → 0.37.4

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 (61) hide show
  1. package/dist/chunks/ApiKey-3DlNEc91.js +145 -0
  2. package/dist/chunks/ApiKey-3DlNEc91.js.map +1 -0
  3. package/dist/chunks/ApiKeyCollection-PwVs0qDb.js +83 -0
  4. package/dist/chunks/ApiKeyCollection-PwVs0qDb.js.map +1 -0
  5. package/dist/chunks/AuditLogCollection-CnIYU0aK.js +191 -0
  6. package/dist/chunks/AuditLogCollection-CnIYU0aK.js.map +1 -0
  7. package/dist/chunks/NostrIdentityCollection-CG6HGf6c.js +3267 -0
  8. package/dist/chunks/NostrIdentityCollection-CG6HGf6c.js.map +1 -0
  9. package/dist/chunks/OidcIdentityCollection-DiLneB7J.js +158 -0
  10. package/dist/chunks/OidcIdentityCollection-DiLneB7J.js.map +1 -0
  11. package/dist/chunks/ProfileAssetCollection-BY2Wbem3.js +93 -0
  12. package/dist/chunks/ProfileAssetCollection-BY2Wbem3.js.map +1 -0
  13. package/dist/chunks/ProfileCollection-DlhdOnDr.js +641 -0
  14. package/dist/chunks/ProfileCollection-DlhdOnDr.js.map +1 -0
  15. package/dist/chunks/ProfileMetadataCollection-CGcO4Iw_.js +105 -0
  16. package/dist/chunks/ProfileMetadataCollection-CGcO4Iw_.js.map +1 -0
  17. package/dist/chunks/ProfileMetafieldCollection-C8TX9HvN.js +142 -0
  18. package/dist/chunks/ProfileMetafieldCollection-C8TX9HvN.js.map +1 -0
  19. package/dist/chunks/ProfileRelationshipCollection-JnskbZTd.js +159 -0
  20. package/dist/chunks/ProfileRelationshipCollection-JnskbZTd.js.map +1 -0
  21. package/dist/chunks/ProfileRelationshipTermCollection-UopP7sja.js +105 -0
  22. package/dist/chunks/ProfileRelationshipTermCollection-UopP7sja.js.map +1 -0
  23. package/dist/chunks/ProfileRelationshipType-OMBn5cWR.js +98 -0
  24. package/dist/chunks/ProfileRelationshipType-OMBn5cWR.js.map +1 -0
  25. package/dist/chunks/ProfileRelationshipTypeCollection-CQu08kxF.js +54 -0
  26. package/dist/chunks/ProfileRelationshipTypeCollection-CQu08kxF.js.map +1 -0
  27. package/dist/index.js +690 -69
  28. package/dist/index.js.map +1 -1
  29. package/dist/manifest.json +2 -2
  30. package/dist/smrt-knowledge.json +9 -9
  31. package/dist/types.js +0 -2
  32. package/dist/utils.js +18 -36
  33. package/dist/utils.js.map +1 -1
  34. package/package.json +16 -16
  35. package/dist/chunks/ApiKey-B2LKEaP8.js +0 -143
  36. package/dist/chunks/ApiKey-B2LKEaP8.js.map +0 -1
  37. package/dist/chunks/ApiKeyCollection-B6Op817e.js +0 -91
  38. package/dist/chunks/ApiKeyCollection-B6Op817e.js.map +0 -1
  39. package/dist/chunks/AuditLogCollection-BYqCj0uE.js +0 -195
  40. package/dist/chunks/AuditLogCollection-BYqCj0uE.js.map +0 -1
  41. package/dist/chunks/NostrIdentityCollection-DadQBHWy.js +0 -3065
  42. package/dist/chunks/NostrIdentityCollection-DadQBHWy.js.map +0 -1
  43. package/dist/chunks/ProfileAssetCollection-CUM5QfuJ.js +0 -122
  44. package/dist/chunks/ProfileAssetCollection-CUM5QfuJ.js.map +0 -1
  45. package/dist/chunks/ProfileCollection-M2PK8bp-.js +0 -800
  46. package/dist/chunks/ProfileCollection-M2PK8bp-.js.map +0 -1
  47. package/dist/chunks/ProfileMetadataCollection-DEhmljMY.js +0 -120
  48. package/dist/chunks/ProfileMetadataCollection-DEhmljMY.js.map +0 -1
  49. package/dist/chunks/ProfileMetafieldCollection-DMKhSHXX.js +0 -184
  50. package/dist/chunks/ProfileMetafieldCollection-DMKhSHXX.js.map +0 -1
  51. package/dist/chunks/ProfileRelationshipCollection-_TsY7MHL.js +0 -189
  52. package/dist/chunks/ProfileRelationshipCollection-_TsY7MHL.js.map +0 -1
  53. package/dist/chunks/ProfileRelationshipTermCollection-CXem_qT-.js +0 -117
  54. package/dist/chunks/ProfileRelationshipTermCollection-CXem_qT-.js.map +0 -1
  55. package/dist/chunks/ProfileRelationshipType-BXBLldea.js +0 -103
  56. package/dist/chunks/ProfileRelationshipType-BXBLldea.js.map +0 -1
  57. package/dist/chunks/ProfileRelationshipTypeCollection-CF8YvLTV.js +0 -48
  58. package/dist/chunks/ProfileRelationshipTypeCollection-CF8YvLTV.js.map +0 -1
  59. package/dist/chunks/index-B9lXQy7N.js +0 -1029
  60. package/dist/chunks/index-B9lXQy7N.js.map +0 -1
  61. package/dist/types.js.map +0 -1
@@ -0,0 +1,3267 @@
1
+ import { SmrtCollection, SmrtObject, foreignKey, smrt } from "@happyvertical/smrt-core";
2
+ import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from "node:crypto";
3
+ //#region \0rolldown/runtime.js
4
+ var __defProp$1 = Object.defineProperty;
5
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
6
+ var __exportAll = (all, no_symbols) => {
7
+ let target = {};
8
+ for (var name in all) __defProp$1(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ if (!no_symbols) __defProp$1(target, Symbol.toStringTag, { value: "Module" });
13
+ return target;
14
+ };
15
+ //#endregion
16
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/crypto.js
17
+ var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
18
+ //#endregion
19
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
20
+ /**
21
+ * Utilities for hex, bytes, CSPRNG.
22
+ * @module
23
+ */
24
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
25
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
26
+ function isBytes(a) {
27
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
28
+ }
29
+ /** Asserts something is positive integer. */
30
+ function anumber(n) {
31
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n);
32
+ }
33
+ /** Asserts something is Uint8Array. */
34
+ function abytes(b, ...lengths) {
35
+ if (!isBytes(b)) throw new Error("Uint8Array expected");
36
+ if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
37
+ }
38
+ /** Asserts something is hash */
39
+ function ahash(h) {
40
+ if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher");
41
+ anumber(h.outputLen);
42
+ anumber(h.blockLen);
43
+ }
44
+ /** Asserts a hash instance has not been destroyed / finished */
45
+ function aexists(instance, checkFinished = true) {
46
+ if (instance.destroyed) throw new Error("Hash instance has been destroyed");
47
+ if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
48
+ }
49
+ /** Asserts output is properly-sized byte array */
50
+ function aoutput(out, instance) {
51
+ abytes(out);
52
+ const min = instance.outputLen;
53
+ if (out.length < min) throw new Error("digestInto() expects output buffer of length at least " + min);
54
+ }
55
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
56
+ function clean(...arrays) {
57
+ for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
58
+ }
59
+ /** Create DataView of an array for easy byte-level manipulation. */
60
+ function createView(arr) {
61
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
62
+ }
63
+ /** The rotate right (circular right shift) operation for uint32 */
64
+ function rotr(word, shift) {
65
+ return word << 32 - shift | word >>> shift;
66
+ }
67
+ var hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
68
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
69
+ /**
70
+ * Convert byte array to hex string. Uses built-in function, when available.
71
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
72
+ */
73
+ function bytesToHex(bytes) {
74
+ abytes(bytes);
75
+ if (hasHexBuiltin) return bytes.toHex();
76
+ let hex = "";
77
+ for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
78
+ return hex;
79
+ }
80
+ var asciis = {
81
+ _0: 48,
82
+ _9: 57,
83
+ A: 65,
84
+ F: 70,
85
+ a: 97,
86
+ f: 102
87
+ };
88
+ function asciiToBase16(ch) {
89
+ if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0;
90
+ if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10);
91
+ if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10);
92
+ }
93
+ /**
94
+ * Convert hex string to byte array. Uses built-in function, when available.
95
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
96
+ */
97
+ function hexToBytes(hex) {
98
+ if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
99
+ if (hasHexBuiltin) return Uint8Array.fromHex(hex);
100
+ const hl = hex.length;
101
+ const al = hl / 2;
102
+ if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl);
103
+ const array = new Uint8Array(al);
104
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
105
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
106
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
107
+ if (n1 === void 0 || n2 === void 0) {
108
+ const char = hex[hi] + hex[hi + 1];
109
+ throw new Error("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
110
+ }
111
+ array[ai] = n1 * 16 + n2;
112
+ }
113
+ return array;
114
+ }
115
+ /**
116
+ * Converts string to bytes using UTF8 encoding.
117
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
118
+ */
119
+ function utf8ToBytes(str) {
120
+ if (typeof str !== "string") throw new Error("string expected");
121
+ return new Uint8Array(new TextEncoder().encode(str));
122
+ }
123
+ /**
124
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
125
+ * Warning: when Uint8Array is passed, it would NOT get copied.
126
+ * Keep in mind for future mutable operations.
127
+ */
128
+ function toBytes(data) {
129
+ if (typeof data === "string") data = utf8ToBytes(data);
130
+ abytes(data);
131
+ return data;
132
+ }
133
+ /** Copies several Uint8Arrays into one. */
134
+ function concatBytes(...arrays) {
135
+ let sum = 0;
136
+ for (let i = 0; i < arrays.length; i++) {
137
+ const a = arrays[i];
138
+ abytes(a);
139
+ sum += a.length;
140
+ }
141
+ const res = new Uint8Array(sum);
142
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
143
+ const a = arrays[i];
144
+ res.set(a, pad);
145
+ pad += a.length;
146
+ }
147
+ return res;
148
+ }
149
+ /** For runtime check if class implements interface */
150
+ var Hash = class {};
151
+ /** Wraps hash function, creating an interface on top of it */
152
+ function createHasher(hashCons) {
153
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
154
+ const tmp = hashCons();
155
+ hashC.outputLen = tmp.outputLen;
156
+ hashC.blockLen = tmp.blockLen;
157
+ hashC.create = () => hashCons();
158
+ return hashC;
159
+ }
160
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
161
+ function randomBytes$1(bytesLength = 32) {
162
+ if (crypto && typeof crypto.getRandomValues === "function") return crypto.getRandomValues(new Uint8Array(bytesLength));
163
+ if (crypto && typeof crypto.randomBytes === "function") return Uint8Array.from(crypto.randomBytes(bytesLength));
164
+ throw new Error("crypto.getRandomValues must be defined");
165
+ }
166
+ //#endregion
167
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
168
+ /**
169
+ * Internal Merkle-Damgard hash utils.
170
+ * @module
171
+ */
172
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
173
+ function setBigUint64(view, byteOffset, value, isLE) {
174
+ if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE);
175
+ const _32n = BigInt(32);
176
+ const _u32_max = BigInt(4294967295);
177
+ const wh = Number(value >> _32n & _u32_max);
178
+ const wl = Number(value & _u32_max);
179
+ const h = isLE ? 4 : 0;
180
+ const l = isLE ? 0 : 4;
181
+ view.setUint32(byteOffset + h, wh, isLE);
182
+ view.setUint32(byteOffset + l, wl, isLE);
183
+ }
184
+ /** Choice: a ? b : c */
185
+ function Chi(a, b, c) {
186
+ return a & b ^ ~a & c;
187
+ }
188
+ /** Majority function, true if any two inputs is true. */
189
+ function Maj(a, b, c) {
190
+ return a & b ^ a & c ^ b & c;
191
+ }
192
+ /**
193
+ * Merkle-Damgard hash construction base class.
194
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
195
+ */
196
+ var HashMD = class extends Hash {
197
+ constructor(blockLen, outputLen, padOffset, isLE) {
198
+ super();
199
+ this.finished = false;
200
+ this.length = 0;
201
+ this.pos = 0;
202
+ this.destroyed = false;
203
+ this.blockLen = blockLen;
204
+ this.outputLen = outputLen;
205
+ this.padOffset = padOffset;
206
+ this.isLE = isLE;
207
+ this.buffer = new Uint8Array(blockLen);
208
+ this.view = createView(this.buffer);
209
+ }
210
+ update(data) {
211
+ aexists(this);
212
+ data = toBytes(data);
213
+ abytes(data);
214
+ const { view, buffer, blockLen } = this;
215
+ const len = data.length;
216
+ for (let pos = 0; pos < len;) {
217
+ const take = Math.min(blockLen - this.pos, len - pos);
218
+ if (take === blockLen) {
219
+ const dataView = createView(data);
220
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
221
+ continue;
222
+ }
223
+ buffer.set(data.subarray(pos, pos + take), this.pos);
224
+ this.pos += take;
225
+ pos += take;
226
+ if (this.pos === blockLen) {
227
+ this.process(view, 0);
228
+ this.pos = 0;
229
+ }
230
+ }
231
+ this.length += data.length;
232
+ this.roundClean();
233
+ return this;
234
+ }
235
+ digestInto(out) {
236
+ aexists(this);
237
+ aoutput(out, this);
238
+ this.finished = true;
239
+ const { buffer, view, blockLen, isLE } = this;
240
+ let { pos } = this;
241
+ buffer[pos++] = 128;
242
+ clean(this.buffer.subarray(pos));
243
+ if (this.padOffset > blockLen - pos) {
244
+ this.process(view, 0);
245
+ pos = 0;
246
+ }
247
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
248
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
249
+ this.process(view, 0);
250
+ const oview = createView(out);
251
+ const len = this.outputLen;
252
+ if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit");
253
+ const outLen = len / 4;
254
+ const state = this.get();
255
+ if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
256
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
257
+ }
258
+ digest() {
259
+ const { buffer, outputLen } = this;
260
+ this.digestInto(buffer);
261
+ const res = buffer.slice(0, outputLen);
262
+ this.destroy();
263
+ return res;
264
+ }
265
+ _cloneInto(to) {
266
+ to || (to = new this.constructor());
267
+ to.set(...this.get());
268
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
269
+ to.destroyed = destroyed;
270
+ to.finished = finished;
271
+ to.length = length;
272
+ to.pos = pos;
273
+ if (length % blockLen) to.buffer.set(buffer);
274
+ return to;
275
+ }
276
+ clone() {
277
+ return this._cloneInto();
278
+ }
279
+ };
280
+ /**
281
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
282
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
283
+ */
284
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
285
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
286
+ 1779033703,
287
+ 3144134277,
288
+ 1013904242,
289
+ 2773480762,
290
+ 1359893119,
291
+ 2600822924,
292
+ 528734635,
293
+ 1541459225
294
+ ]);
295
+ //#endregion
296
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
297
+ /**
298
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
299
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
300
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
301
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
302
+ * @module
303
+ */
304
+ /**
305
+ * Round constants:
306
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
307
+ */
308
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
309
+ 1116352408,
310
+ 1899447441,
311
+ 3049323471,
312
+ 3921009573,
313
+ 961987163,
314
+ 1508970993,
315
+ 2453635748,
316
+ 2870763221,
317
+ 3624381080,
318
+ 310598401,
319
+ 607225278,
320
+ 1426881987,
321
+ 1925078388,
322
+ 2162078206,
323
+ 2614888103,
324
+ 3248222580,
325
+ 3835390401,
326
+ 4022224774,
327
+ 264347078,
328
+ 604807628,
329
+ 770255983,
330
+ 1249150122,
331
+ 1555081692,
332
+ 1996064986,
333
+ 2554220882,
334
+ 2821834349,
335
+ 2952996808,
336
+ 3210313671,
337
+ 3336571891,
338
+ 3584528711,
339
+ 113926993,
340
+ 338241895,
341
+ 666307205,
342
+ 773529912,
343
+ 1294757372,
344
+ 1396182291,
345
+ 1695183700,
346
+ 1986661051,
347
+ 2177026350,
348
+ 2456956037,
349
+ 2730485921,
350
+ 2820302411,
351
+ 3259730800,
352
+ 3345764771,
353
+ 3516065817,
354
+ 3600352804,
355
+ 4094571909,
356
+ 275423344,
357
+ 430227734,
358
+ 506948616,
359
+ 659060556,
360
+ 883997877,
361
+ 958139571,
362
+ 1322822218,
363
+ 1537002063,
364
+ 1747873779,
365
+ 1955562222,
366
+ 2024104815,
367
+ 2227730452,
368
+ 2361852424,
369
+ 2428436474,
370
+ 2756734187,
371
+ 3204031479,
372
+ 3329325298
373
+ ]);
374
+ /** Reusable temporary buffer. "W" comes straight from spec. */
375
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
376
+ var SHA256 = class extends HashMD {
377
+ constructor(outputLen = 32) {
378
+ super(64, outputLen, 8, false);
379
+ this.A = SHA256_IV[0] | 0;
380
+ this.B = SHA256_IV[1] | 0;
381
+ this.C = SHA256_IV[2] | 0;
382
+ this.D = SHA256_IV[3] | 0;
383
+ this.E = SHA256_IV[4] | 0;
384
+ this.F = SHA256_IV[5] | 0;
385
+ this.G = SHA256_IV[6] | 0;
386
+ this.H = SHA256_IV[7] | 0;
387
+ }
388
+ get() {
389
+ const { A, B, C, D, E, F, G, H } = this;
390
+ return [
391
+ A,
392
+ B,
393
+ C,
394
+ D,
395
+ E,
396
+ F,
397
+ G,
398
+ H
399
+ ];
400
+ }
401
+ set(A, B, C, D, E, F, G, H) {
402
+ this.A = A | 0;
403
+ this.B = B | 0;
404
+ this.C = C | 0;
405
+ this.D = D | 0;
406
+ this.E = E | 0;
407
+ this.F = F | 0;
408
+ this.G = G | 0;
409
+ this.H = H | 0;
410
+ }
411
+ process(view, offset) {
412
+ for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
413
+ for (let i = 16; i < 64; i++) {
414
+ const W15 = SHA256_W[i - 15];
415
+ const W2 = SHA256_W[i - 2];
416
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
417
+ SHA256_W[i] = (rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10) + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
418
+ }
419
+ let { A, B, C, D, E, F, G, H } = this;
420
+ for (let i = 0; i < 64; i++) {
421
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
422
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
423
+ const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
424
+ H = G;
425
+ G = F;
426
+ F = E;
427
+ E = D + T1 | 0;
428
+ D = C;
429
+ C = B;
430
+ B = A;
431
+ A = T1 + T2 | 0;
432
+ }
433
+ A = A + this.A | 0;
434
+ B = B + this.B | 0;
435
+ C = C + this.C | 0;
436
+ D = D + this.D | 0;
437
+ E = E + this.E | 0;
438
+ F = F + this.F | 0;
439
+ G = G + this.G | 0;
440
+ H = H + this.H | 0;
441
+ this.set(A, B, C, D, E, F, G, H);
442
+ }
443
+ roundClean() {
444
+ clean(SHA256_W);
445
+ }
446
+ destroy() {
447
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
448
+ clean(this.buffer);
449
+ }
450
+ };
451
+ /**
452
+ * SHA2-256 hash function from RFC 4634.
453
+ *
454
+ * It is the fastest JS hash, even faster than Blake3.
455
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
456
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
457
+ */
458
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
459
+ //#endregion
460
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
461
+ /**
462
+ * HMAC: RFC2104 message authentication code.
463
+ * @module
464
+ */
465
+ var HMAC = class extends Hash {
466
+ constructor(hash, _key) {
467
+ super();
468
+ this.finished = false;
469
+ this.destroyed = false;
470
+ ahash(hash);
471
+ const key = toBytes(_key);
472
+ this.iHash = hash.create();
473
+ if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
474
+ this.blockLen = this.iHash.blockLen;
475
+ this.outputLen = this.iHash.outputLen;
476
+ const blockLen = this.blockLen;
477
+ const pad = new Uint8Array(blockLen);
478
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
479
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
480
+ this.iHash.update(pad);
481
+ this.oHash = hash.create();
482
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
483
+ this.oHash.update(pad);
484
+ clean(pad);
485
+ }
486
+ update(buf) {
487
+ aexists(this);
488
+ this.iHash.update(buf);
489
+ return this;
490
+ }
491
+ digestInto(out) {
492
+ aexists(this);
493
+ abytes(out, this.outputLen);
494
+ this.finished = true;
495
+ this.iHash.digestInto(out);
496
+ this.oHash.update(out);
497
+ this.oHash.digestInto(out);
498
+ this.destroy();
499
+ }
500
+ digest() {
501
+ const out = new Uint8Array(this.oHash.outputLen);
502
+ this.digestInto(out);
503
+ return out;
504
+ }
505
+ _cloneInto(to) {
506
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
507
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
508
+ to = to;
509
+ to.finished = finished;
510
+ to.destroyed = destroyed;
511
+ to.blockLen = blockLen;
512
+ to.outputLen = outputLen;
513
+ to.oHash = oHash._cloneInto(to.oHash);
514
+ to.iHash = iHash._cloneInto(to.iHash);
515
+ return to;
516
+ }
517
+ clone() {
518
+ return this._cloneInto();
519
+ }
520
+ destroy() {
521
+ this.destroyed = true;
522
+ this.oHash.destroy();
523
+ this.iHash.destroy();
524
+ }
525
+ };
526
+ /**
527
+ * HMAC: RFC2104 message authentication code.
528
+ * @param hash - function that would be used e.g. sha256
529
+ * @param key - message key
530
+ * @param message - message data
531
+ * @example
532
+ * import { hmac } from '@noble/hashes/hmac';
533
+ * import { sha256 } from '@noble/hashes/sha2';
534
+ * const mac1 = hmac(sha256, 'key', 'message');
535
+ */
536
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
537
+ hmac.create = (hash, key) => new HMAC(hash, key);
538
+ //#endregion
539
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js
540
+ /**
541
+ * Hex, bytes and number utilities.
542
+ * @module
543
+ */
544
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
545
+ var _0n$4 = /* @__PURE__ */ BigInt(0);
546
+ var _1n$4 = /* @__PURE__ */ BigInt(1);
547
+ function _abool2(value, title = "") {
548
+ if (typeof value !== "boolean") {
549
+ const prefix = title && `"${title}"`;
550
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
551
+ }
552
+ return value;
553
+ }
554
+ /** Asserts something is Uint8Array. */
555
+ function _abytes2(value, length, title = "") {
556
+ const bytes = isBytes(value);
557
+ const len = value?.length;
558
+ const needsLen = length !== void 0;
559
+ if (!bytes || needsLen && len !== length) {
560
+ const prefix = title && `"${title}" `;
561
+ const ofLen = needsLen ? ` of length ${length}` : "";
562
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
563
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
564
+ }
565
+ return value;
566
+ }
567
+ function numberToHexUnpadded(num) {
568
+ const hex = num.toString(16);
569
+ return hex.length & 1 ? "0" + hex : hex;
570
+ }
571
+ function hexToNumber(hex) {
572
+ if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
573
+ return hex === "" ? _0n$4 : BigInt("0x" + hex);
574
+ }
575
+ function bytesToNumberBE(bytes) {
576
+ return hexToNumber(bytesToHex(bytes));
577
+ }
578
+ function bytesToNumberLE(bytes) {
579
+ abytes(bytes);
580
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
581
+ }
582
+ function numberToBytesBE(n, len) {
583
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
584
+ }
585
+ function numberToBytesLE(n, len) {
586
+ return numberToBytesBE(n, len).reverse();
587
+ }
588
+ /**
589
+ * Takes hex string or Uint8Array, converts to Uint8Array.
590
+ * Validates output length.
591
+ * Will throw error for other types.
592
+ * @param title descriptive title for an error e.g. 'secret key'
593
+ * @param hex hex string or Uint8Array
594
+ * @param expectedLength optional, will compare to result array's length
595
+ * @returns
596
+ */
597
+ function ensureBytes(title, hex, expectedLength) {
598
+ let res;
599
+ if (typeof hex === "string") try {
600
+ res = hexToBytes(hex);
601
+ } catch (e) {
602
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
603
+ }
604
+ else if (isBytes(hex)) res = Uint8Array.from(hex);
605
+ else throw new Error(title + " must be hex string or Uint8Array");
606
+ const len = res.length;
607
+ if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(title + " of length " + expectedLength + " expected, got " + len);
608
+ return res;
609
+ }
610
+ /**
611
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
612
+ */
613
+ /**
614
+ * Converts bytes to string using UTF8 encoding.
615
+ * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
616
+ */
617
+ var isPosBig = (n) => typeof n === "bigint" && _0n$4 <= n;
618
+ function inRange(n, min, max) {
619
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
620
+ }
621
+ /**
622
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
623
+ * @example
624
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
625
+ */
626
+ function aInRange(title, n, min, max) {
627
+ if (!inRange(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
628
+ }
629
+ /**
630
+ * Calculates amount of bits in a bigint.
631
+ * Same as `n.toString(2).length`
632
+ * TODO: merge with nLength in modular
633
+ */
634
+ function bitLen(n) {
635
+ let len;
636
+ for (len = 0; n > _0n$4; n >>= _1n$4, len += 1);
637
+ return len;
638
+ }
639
+ /**
640
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
641
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
642
+ */
643
+ var bitMask = (n) => (_1n$4 << BigInt(n)) - _1n$4;
644
+ /**
645
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
646
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
647
+ * @example
648
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
649
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
650
+ */
651
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
652
+ if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number");
653
+ if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number");
654
+ if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function");
655
+ const u8n = (len) => new Uint8Array(len);
656
+ const u8of = (byte) => Uint8Array.of(byte);
657
+ let v = u8n(hashLen);
658
+ let k = u8n(hashLen);
659
+ let i = 0;
660
+ const reset = () => {
661
+ v.fill(1);
662
+ k.fill(0);
663
+ i = 0;
664
+ };
665
+ const h = (...b) => hmacFn(k, v, ...b);
666
+ const reseed = (seed = u8n(0)) => {
667
+ k = h(u8of(0), seed);
668
+ v = h();
669
+ if (seed.length === 0) return;
670
+ k = h(u8of(1), seed);
671
+ v = h();
672
+ };
673
+ const gen = () => {
674
+ if (i++ >= 1e3) throw new Error("drbg: tried 1000 values");
675
+ let len = 0;
676
+ const out = [];
677
+ while (len < qByteLen) {
678
+ v = h();
679
+ const sl = v.slice();
680
+ out.push(sl);
681
+ len += v.length;
682
+ }
683
+ return concatBytes(...out);
684
+ };
685
+ const genUntil = (seed, pred) => {
686
+ reset();
687
+ reseed(seed);
688
+ let res = void 0;
689
+ while (!(res = pred(gen()))) reseed();
690
+ reset();
691
+ return res;
692
+ };
693
+ return genUntil;
694
+ }
695
+ function _validateObject(object, fields, optFields = {}) {
696
+ if (!object || typeof object !== "object") throw new Error("expected valid options object");
697
+ function checkField(fieldName, expectedType, isOpt) {
698
+ const val = object[fieldName];
699
+ if (isOpt && val === void 0) return;
700
+ const current = typeof val;
701
+ if (current !== expectedType || val === null) throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
702
+ }
703
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
704
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
705
+ }
706
+ /**
707
+ * Memoizes (caches) computation result.
708
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
709
+ */
710
+ function memoized(fn) {
711
+ const map = /* @__PURE__ */ new WeakMap();
712
+ return (arg, ...args) => {
713
+ const val = map.get(arg);
714
+ if (val !== void 0) return val;
715
+ const computed = fn(arg, ...args);
716
+ map.set(arg, computed);
717
+ return computed;
718
+ };
719
+ }
720
+ //#endregion
721
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js
722
+ /**
723
+ * Utils for modular division and fields.
724
+ * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
725
+ * There is no division: it is replaced by modular multiplicative inverse.
726
+ * @module
727
+ */
728
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
729
+ var _0n$3 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
730
+ var _4n$1 = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
731
+ var _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
732
+ function mod(a, b) {
733
+ const result = a % b;
734
+ return result >= _0n$3 ? result : b + result;
735
+ }
736
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
737
+ function pow2(x, power, modulo) {
738
+ let res = x;
739
+ while (power-- > _0n$3) {
740
+ res *= res;
741
+ res %= modulo;
742
+ }
743
+ return res;
744
+ }
745
+ /**
746
+ * Inverses number over modulo.
747
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
748
+ */
749
+ function invert(number, modulo) {
750
+ if (number === _0n$3) throw new Error("invert: expected non-zero number");
751
+ if (modulo <= _0n$3) throw new Error("invert: expected positive modulus, got " + modulo);
752
+ let a = mod(number, modulo);
753
+ let b = modulo;
754
+ let x = _0n$3, y = _1n$3, u = _1n$3, v = _0n$3;
755
+ while (a !== _0n$3) {
756
+ const q = b / a;
757
+ const r = b % a;
758
+ const m = x - u * q;
759
+ const n = y - v * q;
760
+ b = a, a = r, x = u, y = v, u = m, v = n;
761
+ }
762
+ if (b !== _1n$3) throw new Error("invert: does not exist");
763
+ return mod(x, modulo);
764
+ }
765
+ function assertIsSquare(Fp, root, n) {
766
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
767
+ }
768
+ function sqrt3mod4(Fp, n) {
769
+ const p1div4 = (Fp.ORDER + _1n$3) / _4n$1;
770
+ const root = Fp.pow(n, p1div4);
771
+ assertIsSquare(Fp, root, n);
772
+ return root;
773
+ }
774
+ function sqrt5mod8(Fp, n) {
775
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
776
+ const n2 = Fp.mul(n, _2n$2);
777
+ const v = Fp.pow(n2, p5div8);
778
+ const nv = Fp.mul(n, v);
779
+ const i = Fp.mul(Fp.mul(nv, _2n$2), v);
780
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
781
+ assertIsSquare(Fp, root, n);
782
+ return root;
783
+ }
784
+ function sqrt9mod16(P) {
785
+ const Fp_ = Field(P);
786
+ const tn = tonelliShanks(P);
787
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
788
+ const c2 = tn(Fp_, c1);
789
+ const c3 = tn(Fp_, Fp_.neg(c1));
790
+ const c4 = (P + _7n) / _16n;
791
+ return (Fp, n) => {
792
+ let tv1 = Fp.pow(n, c4);
793
+ let tv2 = Fp.mul(tv1, c1);
794
+ const tv3 = Fp.mul(tv1, c2);
795
+ const tv4 = Fp.mul(tv1, c3);
796
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
797
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
798
+ tv1 = Fp.cmov(tv1, tv2, e1);
799
+ tv2 = Fp.cmov(tv4, tv3, e2);
800
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
801
+ const root = Fp.cmov(tv1, tv2, e3);
802
+ assertIsSquare(Fp, root, n);
803
+ return root;
804
+ };
805
+ }
806
+ /**
807
+ * Tonelli-Shanks square root search algorithm.
808
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
809
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
810
+ * @param P field order
811
+ * @returns function that takes field Fp (created from P) and number n
812
+ */
813
+ function tonelliShanks(P) {
814
+ if (P < _3n$1) throw new Error("sqrt is not defined for small field");
815
+ let Q = P - _1n$3;
816
+ let S = 0;
817
+ while (Q % _2n$2 === _0n$3) {
818
+ Q /= _2n$2;
819
+ S++;
820
+ }
821
+ let Z = _2n$2;
822
+ const _Fp = Field(P);
823
+ while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
824
+ if (S === 1) return sqrt3mod4;
825
+ let cc = _Fp.pow(Z, Q);
826
+ const Q1div2 = (Q + _1n$3) / _2n$2;
827
+ return function tonelliSlow(Fp, n) {
828
+ if (Fp.is0(n)) return n;
829
+ if (FpLegendre(Fp, n) !== 1) throw new Error("Cannot find square root");
830
+ let M = S;
831
+ let c = Fp.mul(Fp.ONE, cc);
832
+ let t = Fp.pow(n, Q);
833
+ let R = Fp.pow(n, Q1div2);
834
+ while (!Fp.eql(t, Fp.ONE)) {
835
+ if (Fp.is0(t)) return Fp.ZERO;
836
+ let i = 1;
837
+ let t_tmp = Fp.sqr(t);
838
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
839
+ i++;
840
+ t_tmp = Fp.sqr(t_tmp);
841
+ if (i === M) throw new Error("Cannot find square root");
842
+ }
843
+ const exponent = _1n$3 << BigInt(M - i - 1);
844
+ const b = Fp.pow(c, exponent);
845
+ M = i;
846
+ c = Fp.sqr(b);
847
+ t = Fp.mul(t, c);
848
+ R = Fp.mul(R, b);
849
+ }
850
+ return R;
851
+ };
852
+ }
853
+ /**
854
+ * Square root for a finite field. Will try optimized versions first:
855
+ *
856
+ * 1. P ≡ 3 (mod 4)
857
+ * 2. P ≡ 5 (mod 8)
858
+ * 3. P ≡ 9 (mod 16)
859
+ * 4. Tonelli-Shanks algorithm
860
+ *
861
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
862
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
863
+ */
864
+ function FpSqrt(P) {
865
+ if (P % _4n$1 === _3n$1) return sqrt3mod4;
866
+ if (P % _8n === _5n) return sqrt5mod8;
867
+ if (P % _16n === _9n) return sqrt9mod16(P);
868
+ return tonelliShanks(P);
869
+ }
870
+ var FIELD_FIELDS = [
871
+ "create",
872
+ "isValid",
873
+ "is0",
874
+ "neg",
875
+ "inv",
876
+ "sqrt",
877
+ "sqr",
878
+ "eql",
879
+ "add",
880
+ "sub",
881
+ "mul",
882
+ "pow",
883
+ "div",
884
+ "addN",
885
+ "subN",
886
+ "mulN",
887
+ "sqrN"
888
+ ];
889
+ function validateField(field) {
890
+ _validateObject(field, FIELD_FIELDS.reduce((map, val) => {
891
+ map[val] = "function";
892
+ return map;
893
+ }, {
894
+ ORDER: "bigint",
895
+ MASK: "bigint",
896
+ BYTES: "number",
897
+ BITS: "number"
898
+ }));
899
+ return field;
900
+ }
901
+ /**
902
+ * Same as `pow` but for Fp: non-constant-time.
903
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
904
+ */
905
+ function FpPow(Fp, num, power) {
906
+ if (power < _0n$3) throw new Error("invalid exponent, negatives unsupported");
907
+ if (power === _0n$3) return Fp.ONE;
908
+ if (power === _1n$3) return num;
909
+ let p = Fp.ONE;
910
+ let d = num;
911
+ while (power > _0n$3) {
912
+ if (power & _1n$3) p = Fp.mul(p, d);
913
+ d = Fp.sqr(d);
914
+ power >>= _1n$3;
915
+ }
916
+ return p;
917
+ }
918
+ /**
919
+ * Efficiently invert an array of Field elements.
920
+ * Exception-free. Will return `undefined` for 0 elements.
921
+ * @param passZero map 0 to 0 (instead of undefined)
922
+ */
923
+ function FpInvertBatch(Fp, nums, passZero = false) {
924
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
925
+ const multipliedAcc = nums.reduce((acc, num, i) => {
926
+ if (Fp.is0(num)) return acc;
927
+ inverted[i] = acc;
928
+ return Fp.mul(acc, num);
929
+ }, Fp.ONE);
930
+ const invertedAcc = Fp.inv(multipliedAcc);
931
+ nums.reduceRight((acc, num, i) => {
932
+ if (Fp.is0(num)) return acc;
933
+ inverted[i] = Fp.mul(acc, inverted[i]);
934
+ return Fp.mul(acc, num);
935
+ }, invertedAcc);
936
+ return inverted;
937
+ }
938
+ /**
939
+ * Legendre symbol.
940
+ * Legendre constant is used to calculate Legendre symbol (a | p)
941
+ * which denotes the value of a^((p-1)/2) (mod p).
942
+ *
943
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
944
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
945
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
946
+ */
947
+ function FpLegendre(Fp, n) {
948
+ const p1mod2 = (Fp.ORDER - _1n$3) / _2n$2;
949
+ const powered = Fp.pow(n, p1mod2);
950
+ const yes = Fp.eql(powered, Fp.ONE);
951
+ const zero = Fp.eql(powered, Fp.ZERO);
952
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
953
+ if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
954
+ return yes ? 1 : zero ? 0 : -1;
955
+ }
956
+ function nLength(n, nBitLength) {
957
+ if (nBitLength !== void 0) anumber(nBitLength);
958
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
959
+ return {
960
+ nBitLength: _nBitLength,
961
+ nByteLength: Math.ceil(_nBitLength / 8)
962
+ };
963
+ }
964
+ /**
965
+ * Creates a finite field. Major performance optimizations:
966
+ * * 1. Denormalized operations like mulN instead of mul.
967
+ * * 2. Identical object shape: never add or remove keys.
968
+ * * 3. `Object.freeze`.
969
+ * Fragile: always run a benchmark on a change.
970
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
971
+ * it is caller responsibility to check this.
972
+ * This is low-level code, please make sure you know what you're doing.
973
+ *
974
+ * Note about field properties:
975
+ * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
976
+ * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
977
+ *
978
+ * @param ORDER field order, probably prime, or could be composite
979
+ * @param bitLen how many bits the field consumes
980
+ * @param isLE (default: false) if encoding / decoding should be in little-endian
981
+ * @param redef optional faster redefinitions of sqrt and other methods
982
+ */
983
+ function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
984
+ if (ORDER <= _0n$3) throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
985
+ let _nbitLength = void 0;
986
+ let _sqrt = void 0;
987
+ let modFromBytes = false;
988
+ let allowedLengths = void 0;
989
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
990
+ if (opts.sqrt || isLE) throw new Error("cannot specify opts in two arguments");
991
+ const _opts = bitLenOrOpts;
992
+ if (_opts.BITS) _nbitLength = _opts.BITS;
993
+ if (_opts.sqrt) _sqrt = _opts.sqrt;
994
+ if (typeof _opts.isLE === "boolean") isLE = _opts.isLE;
995
+ if (typeof _opts.modFromBytes === "boolean") modFromBytes = _opts.modFromBytes;
996
+ allowedLengths = _opts.allowedLengths;
997
+ } else {
998
+ if (typeof bitLenOrOpts === "number") _nbitLength = bitLenOrOpts;
999
+ if (opts.sqrt) _sqrt = opts.sqrt;
1000
+ }
1001
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
1002
+ if (BYTES > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1003
+ let sqrtP;
1004
+ const f = Object.freeze({
1005
+ ORDER,
1006
+ isLE,
1007
+ BITS,
1008
+ BYTES,
1009
+ MASK: bitMask(BITS),
1010
+ ZERO: _0n$3,
1011
+ ONE: _1n$3,
1012
+ allowedLengths,
1013
+ create: (num) => mod(num, ORDER),
1014
+ isValid: (num) => {
1015
+ if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num);
1016
+ return _0n$3 <= num && num < ORDER;
1017
+ },
1018
+ is0: (num) => num === _0n$3,
1019
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
1020
+ isOdd: (num) => (num & _1n$3) === _1n$3,
1021
+ neg: (num) => mod(-num, ORDER),
1022
+ eql: (lhs, rhs) => lhs === rhs,
1023
+ sqr: (num) => mod(num * num, ORDER),
1024
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
1025
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
1026
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
1027
+ pow: (num, power) => FpPow(f, num, power),
1028
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
1029
+ sqrN: (num) => num * num,
1030
+ addN: (lhs, rhs) => lhs + rhs,
1031
+ subN: (lhs, rhs) => lhs - rhs,
1032
+ mulN: (lhs, rhs) => lhs * rhs,
1033
+ inv: (num) => invert(num, ORDER),
1034
+ sqrt: _sqrt || ((n) => {
1035
+ if (!sqrtP) sqrtP = FpSqrt(ORDER);
1036
+ return sqrtP(f, n);
1037
+ }),
1038
+ toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
1039
+ fromBytes: (bytes, skipValidation = true) => {
1040
+ if (allowedLengths) {
1041
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1042
+ const padded = new Uint8Array(BYTES);
1043
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
1044
+ bytes = padded;
1045
+ }
1046
+ if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1047
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1048
+ if (modFromBytes) scalar = mod(scalar, ORDER);
1049
+ if (!skipValidation) {
1050
+ if (!f.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER");
1051
+ }
1052
+ return scalar;
1053
+ },
1054
+ invertBatch: (lst) => FpInvertBatch(f, lst),
1055
+ cmov: (a, b, c) => c ? b : a
1056
+ });
1057
+ return Object.freeze(f);
1058
+ }
1059
+ /**
1060
+ * Returns total number of bytes consumed by the field element.
1061
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
1062
+ * @param fieldOrder number of field elements, usually CURVE.n
1063
+ * @returns byte length of field
1064
+ */
1065
+ function getFieldBytesLength(fieldOrder) {
1066
+ if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
1067
+ const bitLength = fieldOrder.toString(2).length;
1068
+ return Math.ceil(bitLength / 8);
1069
+ }
1070
+ /**
1071
+ * Returns minimal amount of bytes that can be safely reduced
1072
+ * by field order.
1073
+ * Should be 2^-128 for 128-bit curve such as P256.
1074
+ * @param fieldOrder number of field elements, usually CURVE.n
1075
+ * @returns byte length of target hash
1076
+ */
1077
+ function getMinHashLength(fieldOrder) {
1078
+ const length = getFieldBytesLength(fieldOrder);
1079
+ return length + Math.ceil(length / 2);
1080
+ }
1081
+ /**
1082
+ * "Constant-time" private key generation utility.
1083
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
1084
+ * and convert them into private scalar, with the modulo bias being negligible.
1085
+ * Needs at least 48 bytes of input for 32-byte private key.
1086
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
1087
+ * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
1088
+ * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
1089
+ * @param hash hash output from SHA3 or a similar function
1090
+ * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
1091
+ * @param isLE interpret hash bytes as LE num
1092
+ * @returns valid private scalar
1093
+ */
1094
+ function mapHashToField(key, fieldOrder, isLE = false) {
1095
+ const len = key.length;
1096
+ const fieldLen = getFieldBytesLength(fieldOrder);
1097
+ const minLen = getMinHashLength(fieldOrder);
1098
+ if (len < 16 || len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
1099
+ const reduced = mod(isLE ? bytesToNumberLE(key) : bytesToNumberBE(key), fieldOrder - _1n$3) + _1n$3;
1100
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1101
+ }
1102
+ //#endregion
1103
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js
1104
+ /**
1105
+ * Methods for elliptic curve multiplication by scalars.
1106
+ * Contains wNAF, pippenger.
1107
+ * @module
1108
+ */
1109
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1110
+ var _0n$2 = BigInt(0);
1111
+ var _1n$2 = BigInt(1);
1112
+ function negateCt(condition, item) {
1113
+ const neg = item.negate();
1114
+ return condition ? neg : item;
1115
+ }
1116
+ /**
1117
+ * Takes a bunch of Projective Points but executes only one
1118
+ * inversion on all of them. Inversion is very slow operation,
1119
+ * so this improves performance massively.
1120
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
1121
+ */
1122
+ function normalizeZ(c, points) {
1123
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1124
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1125
+ }
1126
+ function validateW(W, bits) {
1127
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1128
+ }
1129
+ function calcWOpts(W, scalarBits) {
1130
+ validateW(W, scalarBits);
1131
+ const windows = Math.ceil(scalarBits / W) + 1;
1132
+ const windowSize = 2 ** (W - 1);
1133
+ const maxNumber = 2 ** W;
1134
+ return {
1135
+ windows,
1136
+ windowSize,
1137
+ mask: bitMask(W),
1138
+ maxNumber,
1139
+ shiftBy: BigInt(W)
1140
+ };
1141
+ }
1142
+ function calcOffsets(n, window, wOpts) {
1143
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1144
+ let wbits = Number(n & mask);
1145
+ let nextN = n >> shiftBy;
1146
+ if (wbits > windowSize) {
1147
+ wbits -= maxNumber;
1148
+ nextN += _1n$2;
1149
+ }
1150
+ const offsetStart = window * windowSize;
1151
+ const offset = offsetStart + Math.abs(wbits) - 1;
1152
+ const isZero = wbits === 0;
1153
+ const isNeg = wbits < 0;
1154
+ const isNegF = window % 2 !== 0;
1155
+ return {
1156
+ nextN,
1157
+ offset,
1158
+ isZero,
1159
+ isNeg,
1160
+ isNegF,
1161
+ offsetF: offsetStart
1162
+ };
1163
+ }
1164
+ function validateMSMPoints(points, c) {
1165
+ if (!Array.isArray(points)) throw new Error("array expected");
1166
+ points.forEach((p, i) => {
1167
+ if (!(p instanceof c)) throw new Error("invalid point at index " + i);
1168
+ });
1169
+ }
1170
+ function validateMSMScalars(scalars, field) {
1171
+ if (!Array.isArray(scalars)) throw new Error("array of scalars expected");
1172
+ scalars.forEach((s, i) => {
1173
+ if (!field.isValid(s)) throw new Error("invalid scalar at index " + i);
1174
+ });
1175
+ }
1176
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1177
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1178
+ function getW(P) {
1179
+ return pointWindowSizes.get(P) || 1;
1180
+ }
1181
+ function assert0(n) {
1182
+ if (n !== _0n$2) throw new Error("invalid wNAF");
1183
+ }
1184
+ /**
1185
+ * Elliptic curve multiplication of Point by scalar. Fragile.
1186
+ * Table generation takes **30MB of ram and 10ms on high-end CPU**,
1187
+ * but may take much longer on slow devices. Actual generation will happen on
1188
+ * first call of `multiply()`. By default, `BASE` point is precomputed.
1189
+ *
1190
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
1191
+ * Creates precomputation tables for fast multiplication:
1192
+ * - private scalar is split by fixed size windows of W bits
1193
+ * - every window point is collected from window's table & added to accumulator
1194
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
1195
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1196
+ * - +1 window is neccessary for wNAF
1197
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1198
+ *
1199
+ * @todo Research returning 2d JS array of windows, instead of a single window.
1200
+ * This would allow windows to be in different memory locations
1201
+ */
1202
+ var wNAF = class {
1203
+ constructor(Point, bits) {
1204
+ this.BASE = Point.BASE;
1205
+ this.ZERO = Point.ZERO;
1206
+ this.Fn = Point.Fn;
1207
+ this.bits = bits;
1208
+ }
1209
+ _unsafeLadder(elm, n, p = this.ZERO) {
1210
+ let d = elm;
1211
+ while (n > _0n$2) {
1212
+ if (n & _1n$2) p = p.add(d);
1213
+ d = d.double();
1214
+ n >>= _1n$2;
1215
+ }
1216
+ return p;
1217
+ }
1218
+ /**
1219
+ * Creates a wNAF precomputation window. Used for caching.
1220
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1221
+ * Number of precomputed points depends on the curve size:
1222
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1223
+ * - 𝑊 is the window size
1224
+ * - 𝑛 is the bitlength of the curve order.
1225
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1226
+ * @param point Point instance
1227
+ * @param W window size
1228
+ * @returns precomputed point tables flattened to a single array
1229
+ */
1230
+ precomputeWindow(point, W) {
1231
+ const { windows, windowSize } = calcWOpts(W, this.bits);
1232
+ const points = [];
1233
+ let p = point;
1234
+ let base = p;
1235
+ for (let window = 0; window < windows; window++) {
1236
+ base = p;
1237
+ points.push(base);
1238
+ for (let i = 1; i < windowSize; i++) {
1239
+ base = base.add(p);
1240
+ points.push(base);
1241
+ }
1242
+ p = base.double();
1243
+ }
1244
+ return points;
1245
+ }
1246
+ /**
1247
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1248
+ * More compact implementation:
1249
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1250
+ * @returns real and fake (for const-time) points
1251
+ */
1252
+ wNAF(W, precomputes, n) {
1253
+ if (!this.Fn.isValid(n)) throw new Error("invalid scalar");
1254
+ let p = this.ZERO;
1255
+ let f = this.BASE;
1256
+ const wo = calcWOpts(W, this.bits);
1257
+ for (let window = 0; window < wo.windows; window++) {
1258
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1259
+ n = nextN;
1260
+ if (isZero) f = f.add(negateCt(isNegF, precomputes[offsetF]));
1261
+ else p = p.add(negateCt(isNeg, precomputes[offset]));
1262
+ }
1263
+ assert0(n);
1264
+ return {
1265
+ p,
1266
+ f
1267
+ };
1268
+ }
1269
+ /**
1270
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1271
+ * @param acc accumulator point to add result of multiplication
1272
+ * @returns point
1273
+ */
1274
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1275
+ const wo = calcWOpts(W, this.bits);
1276
+ for (let window = 0; window < wo.windows; window++) {
1277
+ if (n === _0n$2) break;
1278
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1279
+ n = nextN;
1280
+ if (isZero) continue;
1281
+ else {
1282
+ const item = precomputes[offset];
1283
+ acc = acc.add(isNeg ? item.negate() : item);
1284
+ }
1285
+ }
1286
+ assert0(n);
1287
+ return acc;
1288
+ }
1289
+ getPrecomputes(W, point, transform) {
1290
+ let comp = pointPrecomputes.get(point);
1291
+ if (!comp) {
1292
+ comp = this.precomputeWindow(point, W);
1293
+ if (W !== 1) {
1294
+ if (typeof transform === "function") comp = transform(comp);
1295
+ pointPrecomputes.set(point, comp);
1296
+ }
1297
+ }
1298
+ return comp;
1299
+ }
1300
+ cached(point, scalar, transform) {
1301
+ const W = getW(point);
1302
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1303
+ }
1304
+ unsafe(point, scalar, transform, prev) {
1305
+ const W = getW(point);
1306
+ if (W === 1) return this._unsafeLadder(point, scalar, prev);
1307
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1308
+ }
1309
+ createCache(P, W) {
1310
+ validateW(W, this.bits);
1311
+ pointWindowSizes.set(P, W);
1312
+ pointPrecomputes.delete(P);
1313
+ }
1314
+ hasCache(elm) {
1315
+ return getW(elm) !== 1;
1316
+ }
1317
+ };
1318
+ /**
1319
+ * Endomorphism-specific multiplication for Koblitz curves.
1320
+ * Cost: 128 dbl, 0-256 adds.
1321
+ */
1322
+ function mulEndoUnsafe(Point, point, k1, k2) {
1323
+ let acc = point;
1324
+ let p1 = Point.ZERO;
1325
+ let p2 = Point.ZERO;
1326
+ while (k1 > _0n$2 || k2 > _0n$2) {
1327
+ if (k1 & _1n$2) p1 = p1.add(acc);
1328
+ if (k2 & _1n$2) p2 = p2.add(acc);
1329
+ acc = acc.double();
1330
+ k1 >>= _1n$2;
1331
+ k2 >>= _1n$2;
1332
+ }
1333
+ return {
1334
+ p1,
1335
+ p2
1336
+ };
1337
+ }
1338
+ /**
1339
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
1340
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
1341
+ * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
1342
+ * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
1343
+ * @param c Curve Point constructor
1344
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
1345
+ * @param points array of L curve points
1346
+ * @param scalars array of L scalars (aka secret keys / bigints)
1347
+ */
1348
+ function pippenger(c, fieldN, points, scalars) {
1349
+ validateMSMPoints(points, c);
1350
+ validateMSMScalars(scalars, fieldN);
1351
+ const plength = points.length;
1352
+ const slength = scalars.length;
1353
+ if (plength !== slength) throw new Error("arrays of points and scalars must have equal length");
1354
+ const zero = c.ZERO;
1355
+ const wbits = bitLen(BigInt(plength));
1356
+ let windowSize = 1;
1357
+ if (wbits > 12) windowSize = wbits - 3;
1358
+ else if (wbits > 4) windowSize = wbits - 2;
1359
+ else if (wbits > 0) windowSize = 2;
1360
+ const MASK = bitMask(windowSize);
1361
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
1362
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
1363
+ let sum = zero;
1364
+ for (let i = lastBits; i >= 0; i -= windowSize) {
1365
+ buckets.fill(zero);
1366
+ for (let j = 0; j < slength; j++) {
1367
+ const scalar = scalars[j];
1368
+ const wbits = Number(scalar >> BigInt(i) & MASK);
1369
+ buckets[wbits] = buckets[wbits].add(points[j]);
1370
+ }
1371
+ let resI = zero;
1372
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
1373
+ sumI = sumI.add(buckets[j]);
1374
+ resI = resI.add(sumI);
1375
+ }
1376
+ sum = sum.add(resI);
1377
+ if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();
1378
+ }
1379
+ return sum;
1380
+ }
1381
+ function createField(order, field, isLE) {
1382
+ if (field) {
1383
+ if (field.ORDER !== order) throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1384
+ validateField(field);
1385
+ return field;
1386
+ } else return Field(order, { isLE });
1387
+ }
1388
+ /** Validates CURVE opts and creates fields */
1389
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1390
+ if (FpFnLE === void 0) FpFnLE = type === "edwards";
1391
+ if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`);
1392
+ for (const p of [
1393
+ "p",
1394
+ "n",
1395
+ "h"
1396
+ ]) {
1397
+ const val = CURVE[p];
1398
+ if (!(typeof val === "bigint" && val > _0n$2)) throw new Error(`CURVE.${p} must be positive bigint`);
1399
+ }
1400
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1401
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1402
+ const params = [
1403
+ "Gx",
1404
+ "Gy",
1405
+ "a",
1406
+ type === "weierstrass" ? "b" : "d"
1407
+ ];
1408
+ for (const p of params) if (!Fp.isValid(CURVE[p])) throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1409
+ CURVE = Object.freeze(Object.assign({}, CURVE));
1410
+ return {
1411
+ CURVE,
1412
+ Fp,
1413
+ Fn
1414
+ };
1415
+ }
1416
+ //#endregion
1417
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/weierstrass.js
1418
+ /**
1419
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
1420
+ *
1421
+ * ### Design rationale for types
1422
+ *
1423
+ * * Interaction between classes from different curves should fail:
1424
+ * `k256.Point.BASE.add(p256.Point.BASE)`
1425
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
1426
+ * * Different calls of `curve()` would return different classes -
1427
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
1428
+ * it won't affect others
1429
+ *
1430
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
1431
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
1432
+ * unique type for every function call.
1433
+ *
1434
+ * We can use generic types via some param, like curve opts, but that would:
1435
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
1436
+ * which is hard to debug.
1437
+ * 2. Params can be generic and we can't enforce them to be constant value:
1438
+ * if somebody creates curve from non-constant params,
1439
+ * it would be allowed to interact with other curves with non-constant params
1440
+ *
1441
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
1442
+ * @module
1443
+ */
1444
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1445
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$1) / den;
1446
+ /**
1447
+ * Splits scalar for GLV endomorphism.
1448
+ */
1449
+ function _splitEndoScalar(k, basis, n) {
1450
+ const [[a1, b1], [a2, b2]] = basis;
1451
+ const c1 = divNearest(b2 * k, n);
1452
+ const c2 = divNearest(-b1 * k, n);
1453
+ let k1 = k - c1 * a1 - c2 * a2;
1454
+ let k2 = -c1 * b1 - c2 * b2;
1455
+ const k1neg = k1 < _0n$1;
1456
+ const k2neg = k2 < _0n$1;
1457
+ if (k1neg) k1 = -k1;
1458
+ if (k2neg) k2 = -k2;
1459
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n$1;
1460
+ if (k1 < _0n$1 || k1 >= MAX_NUM || k2 < _0n$1 || k2 >= MAX_NUM) throw new Error("splitScalar (endomorphism): failed, k=" + k);
1461
+ return {
1462
+ k1neg,
1463
+ k1,
1464
+ k2neg,
1465
+ k2
1466
+ };
1467
+ }
1468
+ function validateSigFormat(format) {
1469
+ if (![
1470
+ "compact",
1471
+ "recovered",
1472
+ "der"
1473
+ ].includes(format)) throw new Error("Signature format must be \"compact\", \"recovered\", or \"der\"");
1474
+ return format;
1475
+ }
1476
+ function validateSigOpts(opts, def) {
1477
+ const optsn = {};
1478
+ for (let optName of Object.keys(def)) optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
1479
+ _abool2(optsn.lowS, "lowS");
1480
+ _abool2(optsn.prehash, "prehash");
1481
+ if (optsn.format !== void 0) validateSigFormat(optsn.format);
1482
+ return optsn;
1483
+ }
1484
+ var DERErr = class extends Error {
1485
+ constructor(m = "") {
1486
+ super(m);
1487
+ }
1488
+ };
1489
+ /**
1490
+ * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
1491
+ *
1492
+ * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
1493
+ *
1494
+ * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
1495
+ */
1496
+ var DER = {
1497
+ Err: DERErr,
1498
+ _tlv: {
1499
+ encode: (tag, data) => {
1500
+ const { Err: E } = DER;
1501
+ if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
1502
+ if (data.length & 1) throw new E("tlv.encode: unpadded data");
1503
+ const dataLen = data.length / 2;
1504
+ const len = numberToHexUnpadded(dataLen);
1505
+ if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big");
1506
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
1507
+ return numberToHexUnpadded(tag) + lenLen + len + data;
1508
+ },
1509
+ decode(tag, data) {
1510
+ const { Err: E } = DER;
1511
+ let pos = 0;
1512
+ if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
1513
+ if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv");
1514
+ const first = data[pos++];
1515
+ const isLong = !!(first & 128);
1516
+ let length = 0;
1517
+ if (!isLong) length = first;
1518
+ else {
1519
+ const lenLen = first & 127;
1520
+ if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported");
1521
+ if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big");
1522
+ const lengthBytes = data.subarray(pos, pos + lenLen);
1523
+ if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete");
1524
+ if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte");
1525
+ for (const b of lengthBytes) length = length << 8 | b;
1526
+ pos += lenLen;
1527
+ if (length < 128) throw new E("tlv.decode(long): not minimal encoding");
1528
+ }
1529
+ const v = data.subarray(pos, pos + length);
1530
+ if (v.length !== length) throw new E("tlv.decode: wrong value length");
1531
+ return {
1532
+ v,
1533
+ l: data.subarray(pos + length)
1534
+ };
1535
+ }
1536
+ },
1537
+ _int: {
1538
+ encode(num) {
1539
+ const { Err: E } = DER;
1540
+ if (num < _0n$1) throw new E("integer: negative integers are not allowed");
1541
+ let hex = numberToHexUnpadded(num);
1542
+ if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex;
1543
+ if (hex.length & 1) throw new E("unexpected DER parsing assertion: unpadded hex");
1544
+ return hex;
1545
+ },
1546
+ decode(data) {
1547
+ const { Err: E } = DER;
1548
+ if (data[0] & 128) throw new E("invalid signature integer: negative");
1549
+ if (data[0] === 0 && !(data[1] & 128)) throw new E("invalid signature integer: unnecessary leading zero");
1550
+ return bytesToNumberBE(data);
1551
+ }
1552
+ },
1553
+ toSig(hex) {
1554
+ const { Err: E, _int: int, _tlv: tlv } = DER;
1555
+ const data = ensureBytes("signature", hex);
1556
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
1557
+ if (seqLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
1558
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
1559
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
1560
+ if (sLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
1561
+ return {
1562
+ r: int.decode(rBytes),
1563
+ s: int.decode(sBytes)
1564
+ };
1565
+ },
1566
+ hexFromSig(sig) {
1567
+ const { _tlv: tlv, _int: int } = DER;
1568
+ const seq = tlv.encode(2, int.encode(sig.r)) + tlv.encode(2, int.encode(sig.s));
1569
+ return tlv.encode(48, seq);
1570
+ }
1571
+ };
1572
+ var _0n$1 = BigInt(0), _1n$1 = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
1573
+ function _normFnElement(Fn, key) {
1574
+ const { BYTES: expected } = Fn;
1575
+ let num;
1576
+ if (typeof key === "bigint") num = key;
1577
+ else {
1578
+ let bytes = ensureBytes("private key", key);
1579
+ try {
1580
+ num = Fn.fromBytes(bytes);
1581
+ } catch (error) {
1582
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
1583
+ }
1584
+ }
1585
+ if (!Fn.isValidNot0(num)) throw new Error("invalid private key: out of range [1..N-1]");
1586
+ return num;
1587
+ }
1588
+ /**
1589
+ * Creates weierstrass Point constructor, based on specified curve options.
1590
+ *
1591
+ * @example
1592
+ ```js
1593
+ const opts = {
1594
+ p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
1595
+ n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
1596
+ h: BigInt(1),
1597
+ a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
1598
+ b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
1599
+ Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
1600
+ Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
1601
+ };
1602
+ const p256_Point = weierstrass(opts);
1603
+ ```
1604
+ */
1605
+ function weierstrassN(params, extraOpts = {}) {
1606
+ const validated = _createCurveFields("weierstrass", params, extraOpts);
1607
+ const { Fp, Fn } = validated;
1608
+ let CURVE = validated.CURVE;
1609
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
1610
+ _validateObject(extraOpts, {}, {
1611
+ allowInfinityPoint: "boolean",
1612
+ clearCofactor: "function",
1613
+ isTorsionFree: "function",
1614
+ fromBytes: "function",
1615
+ toBytes: "function",
1616
+ endo: "object",
1617
+ wrapPrivateKey: "boolean"
1618
+ });
1619
+ const { endo } = extraOpts;
1620
+ if (endo) {
1621
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) throw new Error("invalid endo: expected \"beta\": bigint and \"basises\": array");
1622
+ }
1623
+ const lengths = getWLengths(Fp, Fn);
1624
+ function assertCompressionIsSupported() {
1625
+ if (!Fp.isOdd) throw new Error("compression is not supported: Field does not have .isOdd()");
1626
+ }
1627
+ function pointToBytes(_c, point, isCompressed) {
1628
+ const { x, y } = point.toAffine();
1629
+ const bx = Fp.toBytes(x);
1630
+ _abool2(isCompressed, "isCompressed");
1631
+ if (isCompressed) {
1632
+ assertCompressionIsSupported();
1633
+ return concatBytes(pprefix(!Fp.isOdd(y)), bx);
1634
+ } else return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
1635
+ }
1636
+ function pointFromBytes(bytes) {
1637
+ _abytes2(bytes, void 0, "Point");
1638
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
1639
+ const length = bytes.length;
1640
+ const head = bytes[0];
1641
+ const tail = bytes.subarray(1);
1642
+ if (length === comp && (head === 2 || head === 3)) {
1643
+ const x = Fp.fromBytes(tail);
1644
+ if (!Fp.isValid(x)) throw new Error("bad point: is not on curve, wrong x");
1645
+ const y2 = weierstrassEquation(x);
1646
+ let y;
1647
+ try {
1648
+ y = Fp.sqrt(y2);
1649
+ } catch (sqrtError) {
1650
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1651
+ throw new Error("bad point: is not on curve, sqrt error" + err);
1652
+ }
1653
+ assertCompressionIsSupported();
1654
+ const isYOdd = Fp.isOdd(y);
1655
+ if ((head & 1) === 1 !== isYOdd) y = Fp.neg(y);
1656
+ return {
1657
+ x,
1658
+ y
1659
+ };
1660
+ } else if (length === uncomp && head === 4) {
1661
+ const L = Fp.BYTES;
1662
+ const x = Fp.fromBytes(tail.subarray(0, L));
1663
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
1664
+ if (!isValidXY(x, y)) throw new Error("bad point: is not on curve");
1665
+ return {
1666
+ x,
1667
+ y
1668
+ };
1669
+ } else throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
1670
+ }
1671
+ const encodePoint = extraOpts.toBytes || pointToBytes;
1672
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
1673
+ function weierstrassEquation(x) {
1674
+ const x2 = Fp.sqr(x);
1675
+ const x3 = Fp.mul(x2, x);
1676
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
1677
+ }
1678
+ /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
1679
+ function isValidXY(x, y) {
1680
+ const left = Fp.sqr(y);
1681
+ const right = weierstrassEquation(x);
1682
+ return Fp.eql(left, right);
1683
+ }
1684
+ if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
1685
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
1686
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
1687
+ if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error("bad curve params: a or b");
1688
+ /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
1689
+ function acoord(title, n, banZero = false) {
1690
+ if (!Fp.isValid(n) || banZero && Fp.is0(n)) throw new Error(`bad point coordinate ${title}`);
1691
+ return n;
1692
+ }
1693
+ function aprjpoint(other) {
1694
+ if (!(other instanceof Point)) throw new Error("ProjectivePoint expected");
1695
+ }
1696
+ function splitEndoScalarN(k) {
1697
+ if (!endo || !endo.basises) throw new Error("no endo");
1698
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
1699
+ }
1700
+ const toAffineMemo = memoized((p, iz) => {
1701
+ const { X, Y, Z } = p;
1702
+ if (Fp.eql(Z, Fp.ONE)) return {
1703
+ x: X,
1704
+ y: Y
1705
+ };
1706
+ const is0 = p.is0();
1707
+ if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);
1708
+ const x = Fp.mul(X, iz);
1709
+ const y = Fp.mul(Y, iz);
1710
+ const zz = Fp.mul(Z, iz);
1711
+ if (is0) return {
1712
+ x: Fp.ZERO,
1713
+ y: Fp.ZERO
1714
+ };
1715
+ if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
1716
+ return {
1717
+ x,
1718
+ y
1719
+ };
1720
+ });
1721
+ const assertValidMemo = memoized((p) => {
1722
+ if (p.is0()) {
1723
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) return;
1724
+ throw new Error("bad point: ZERO");
1725
+ }
1726
+ const { x, y } = p.toAffine();
1727
+ if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not field elements");
1728
+ if (!isValidXY(x, y)) throw new Error("bad point: equation left != right");
1729
+ if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup");
1730
+ return true;
1731
+ });
1732
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
1733
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
1734
+ k1p = negateCt(k1neg, k1p);
1735
+ k2p = negateCt(k2neg, k2p);
1736
+ return k1p.add(k2p);
1737
+ }
1738
+ /**
1739
+ * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
1740
+ * Default Point works in 2d / affine coordinates: (x, y).
1741
+ * We're doing calculations in projective, because its operations don't require costly inversion.
1742
+ */
1743
+ class Point {
1744
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1745
+ constructor(X, Y, Z) {
1746
+ this.X = acoord("x", X);
1747
+ this.Y = acoord("y", Y, true);
1748
+ this.Z = acoord("z", Z);
1749
+ Object.freeze(this);
1750
+ }
1751
+ static CURVE() {
1752
+ return CURVE;
1753
+ }
1754
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1755
+ static fromAffine(p) {
1756
+ const { x, y } = p || {};
1757
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point");
1758
+ if (p instanceof Point) throw new Error("projective point not allowed");
1759
+ if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;
1760
+ return new Point(x, y, Fp.ONE);
1761
+ }
1762
+ static fromBytes(bytes) {
1763
+ const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
1764
+ P.assertValidity();
1765
+ return P;
1766
+ }
1767
+ static fromHex(hex) {
1768
+ return Point.fromBytes(ensureBytes("pointHex", hex));
1769
+ }
1770
+ get x() {
1771
+ return this.toAffine().x;
1772
+ }
1773
+ get y() {
1774
+ return this.toAffine().y;
1775
+ }
1776
+ /**
1777
+ *
1778
+ * @param windowSize
1779
+ * @param isLazy true will defer table computation until the first multiplication
1780
+ * @returns
1781
+ */
1782
+ precompute(windowSize = 8, isLazy = true) {
1783
+ wnaf.createCache(this, windowSize);
1784
+ if (!isLazy) this.multiply(_3n);
1785
+ return this;
1786
+ }
1787
+ /** A point on curve is valid if it conforms to equation. */
1788
+ assertValidity() {
1789
+ assertValidMemo(this);
1790
+ }
1791
+ hasEvenY() {
1792
+ const { y } = this.toAffine();
1793
+ if (!Fp.isOdd) throw new Error("Field doesn't support isOdd");
1794
+ return !Fp.isOdd(y);
1795
+ }
1796
+ /** Compare one point to another. */
1797
+ equals(other) {
1798
+ aprjpoint(other);
1799
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1800
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1801
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1802
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1803
+ return U1 && U2;
1804
+ }
1805
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
1806
+ negate() {
1807
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
1808
+ }
1809
+ double() {
1810
+ const { a, b } = CURVE;
1811
+ const b3 = Fp.mul(b, _3n);
1812
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1813
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1814
+ let t0 = Fp.mul(X1, X1);
1815
+ let t1 = Fp.mul(Y1, Y1);
1816
+ let t2 = Fp.mul(Z1, Z1);
1817
+ let t3 = Fp.mul(X1, Y1);
1818
+ t3 = Fp.add(t3, t3);
1819
+ Z3 = Fp.mul(X1, Z1);
1820
+ Z3 = Fp.add(Z3, Z3);
1821
+ X3 = Fp.mul(a, Z3);
1822
+ Y3 = Fp.mul(b3, t2);
1823
+ Y3 = Fp.add(X3, Y3);
1824
+ X3 = Fp.sub(t1, Y3);
1825
+ Y3 = Fp.add(t1, Y3);
1826
+ Y3 = Fp.mul(X3, Y3);
1827
+ X3 = Fp.mul(t3, X3);
1828
+ Z3 = Fp.mul(b3, Z3);
1829
+ t2 = Fp.mul(a, t2);
1830
+ t3 = Fp.sub(t0, t2);
1831
+ t3 = Fp.mul(a, t3);
1832
+ t3 = Fp.add(t3, Z3);
1833
+ Z3 = Fp.add(t0, t0);
1834
+ t0 = Fp.add(Z3, t0);
1835
+ t0 = Fp.add(t0, t2);
1836
+ t0 = Fp.mul(t0, t3);
1837
+ Y3 = Fp.add(Y3, t0);
1838
+ t2 = Fp.mul(Y1, Z1);
1839
+ t2 = Fp.add(t2, t2);
1840
+ t0 = Fp.mul(t2, t3);
1841
+ X3 = Fp.sub(X3, t0);
1842
+ Z3 = Fp.mul(t2, t1);
1843
+ Z3 = Fp.add(Z3, Z3);
1844
+ Z3 = Fp.add(Z3, Z3);
1845
+ return new Point(X3, Y3, Z3);
1846
+ }
1847
+ add(other) {
1848
+ aprjpoint(other);
1849
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1850
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1851
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1852
+ const a = CURVE.a;
1853
+ const b3 = Fp.mul(CURVE.b, _3n);
1854
+ let t0 = Fp.mul(X1, X2);
1855
+ let t1 = Fp.mul(Y1, Y2);
1856
+ let t2 = Fp.mul(Z1, Z2);
1857
+ let t3 = Fp.add(X1, Y1);
1858
+ let t4 = Fp.add(X2, Y2);
1859
+ t3 = Fp.mul(t3, t4);
1860
+ t4 = Fp.add(t0, t1);
1861
+ t3 = Fp.sub(t3, t4);
1862
+ t4 = Fp.add(X1, Z1);
1863
+ let t5 = Fp.add(X2, Z2);
1864
+ t4 = Fp.mul(t4, t5);
1865
+ t5 = Fp.add(t0, t2);
1866
+ t4 = Fp.sub(t4, t5);
1867
+ t5 = Fp.add(Y1, Z1);
1868
+ X3 = Fp.add(Y2, Z2);
1869
+ t5 = Fp.mul(t5, X3);
1870
+ X3 = Fp.add(t1, t2);
1871
+ t5 = Fp.sub(t5, X3);
1872
+ Z3 = Fp.mul(a, t4);
1873
+ X3 = Fp.mul(b3, t2);
1874
+ Z3 = Fp.add(X3, Z3);
1875
+ X3 = Fp.sub(t1, Z3);
1876
+ Z3 = Fp.add(t1, Z3);
1877
+ Y3 = Fp.mul(X3, Z3);
1878
+ t1 = Fp.add(t0, t0);
1879
+ t1 = Fp.add(t1, t0);
1880
+ t2 = Fp.mul(a, t2);
1881
+ t4 = Fp.mul(b3, t4);
1882
+ t1 = Fp.add(t1, t2);
1883
+ t2 = Fp.sub(t0, t2);
1884
+ t2 = Fp.mul(a, t2);
1885
+ t4 = Fp.add(t4, t2);
1886
+ t0 = Fp.mul(t1, t4);
1887
+ Y3 = Fp.add(Y3, t0);
1888
+ t0 = Fp.mul(t5, t4);
1889
+ X3 = Fp.mul(t3, X3);
1890
+ X3 = Fp.sub(X3, t0);
1891
+ t0 = Fp.mul(t3, t1);
1892
+ Z3 = Fp.mul(t5, Z3);
1893
+ Z3 = Fp.add(Z3, t0);
1894
+ return new Point(X3, Y3, Z3);
1895
+ }
1896
+ subtract(other) {
1897
+ return this.add(other.negate());
1898
+ }
1899
+ is0() {
1900
+ return this.equals(Point.ZERO);
1901
+ }
1902
+ /**
1903
+ * Constant time multiplication.
1904
+ * Uses wNAF method. Windowed method may be 10% faster,
1905
+ * but takes 2x longer to generate and consumes 2x memory.
1906
+ * Uses precomputes when available.
1907
+ * Uses endomorphism for Koblitz curves.
1908
+ * @param scalar by which the point would be multiplied
1909
+ * @returns New point
1910
+ */
1911
+ multiply(scalar) {
1912
+ const { endo } = extraOpts;
1913
+ if (!Fn.isValidNot0(scalar)) throw new Error("invalid scalar: out of range");
1914
+ let point, fake;
1915
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
1916
+ /** See docs for {@link EndomorphismOpts} */
1917
+ if (endo) {
1918
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
1919
+ const { p: k1p, f: k1f } = mul(k1);
1920
+ const { p: k2p, f: k2f } = mul(k2);
1921
+ fake = k1f.add(k2f);
1922
+ point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
1923
+ } else {
1924
+ const { p, f } = mul(scalar);
1925
+ point = p;
1926
+ fake = f;
1927
+ }
1928
+ return normalizeZ(Point, [point, fake])[0];
1929
+ }
1930
+ /**
1931
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
1932
+ * It's faster, but should only be used when you don't care about
1933
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
1934
+ */
1935
+ multiplyUnsafe(sc) {
1936
+ const { endo } = extraOpts;
1937
+ const p = this;
1938
+ if (!Fn.isValid(sc)) throw new Error("invalid scalar: out of range");
1939
+ if (sc === _0n$1 || p.is0()) return Point.ZERO;
1940
+ if (sc === _1n$1) return p;
1941
+ if (wnaf.hasCache(this)) return this.multiply(sc);
1942
+ if (endo) {
1943
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
1944
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
1945
+ return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
1946
+ } else return wnaf.unsafe(p, sc);
1947
+ }
1948
+ multiplyAndAddUnsafe(Q, a, b) {
1949
+ const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
1950
+ return sum.is0() ? void 0 : sum;
1951
+ }
1952
+ /**
1953
+ * Converts Projective point to affine (x, y) coordinates.
1954
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
1955
+ */
1956
+ toAffine(invertedZ) {
1957
+ return toAffineMemo(this, invertedZ);
1958
+ }
1959
+ /**
1960
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
1961
+ * Always torsion-free for cofactor=1 curves.
1962
+ */
1963
+ isTorsionFree() {
1964
+ const { isTorsionFree } = extraOpts;
1965
+ if (cofactor === _1n$1) return true;
1966
+ if (isTorsionFree) return isTorsionFree(Point, this);
1967
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
1968
+ }
1969
+ clearCofactor() {
1970
+ const { clearCofactor } = extraOpts;
1971
+ if (cofactor === _1n$1) return this;
1972
+ if (clearCofactor) return clearCofactor(Point, this);
1973
+ return this.multiplyUnsafe(cofactor);
1974
+ }
1975
+ isSmallOrder() {
1976
+ return this.multiplyUnsafe(cofactor).is0();
1977
+ }
1978
+ toBytes(isCompressed = true) {
1979
+ _abool2(isCompressed, "isCompressed");
1980
+ this.assertValidity();
1981
+ return encodePoint(Point, this, isCompressed);
1982
+ }
1983
+ toHex(isCompressed = true) {
1984
+ return bytesToHex(this.toBytes(isCompressed));
1985
+ }
1986
+ toString() {
1987
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1988
+ }
1989
+ get px() {
1990
+ return this.X;
1991
+ }
1992
+ get py() {
1993
+ return this.X;
1994
+ }
1995
+ get pz() {
1996
+ return this.Z;
1997
+ }
1998
+ toRawBytes(isCompressed = true) {
1999
+ return this.toBytes(isCompressed);
2000
+ }
2001
+ _setWindowSize(windowSize) {
2002
+ this.precompute(windowSize);
2003
+ }
2004
+ static normalizeZ(points) {
2005
+ return normalizeZ(Point, points);
2006
+ }
2007
+ static msm(points, scalars) {
2008
+ return pippenger(Point, Fn, points, scalars);
2009
+ }
2010
+ static fromPrivateKey(privateKey) {
2011
+ return Point.BASE.multiply(_normFnElement(Fn, privateKey));
2012
+ }
2013
+ }
2014
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2015
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
2016
+ Point.Fp = Fp;
2017
+ Point.Fn = Fn;
2018
+ const bits = Fn.BITS;
2019
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
2020
+ Point.BASE.precompute(8);
2021
+ return Point;
2022
+ }
2023
+ function pprefix(hasEvenY) {
2024
+ return Uint8Array.of(hasEvenY ? 2 : 3);
2025
+ }
2026
+ function getWLengths(Fp, Fn) {
2027
+ return {
2028
+ secretKey: Fn.BYTES,
2029
+ publicKey: 1 + Fp.BYTES,
2030
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
2031
+ publicKeyHasPrefix: true,
2032
+ signature: 2 * Fn.BYTES
2033
+ };
2034
+ }
2035
+ /**
2036
+ * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
2037
+ * This helper ensures no signature functionality is present. Less code, smaller bundle size.
2038
+ */
2039
+ function ecdh(Point, ecdhOpts = {}) {
2040
+ const { Fn } = Point;
2041
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes$1;
2042
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
2043
+ function isValidSecretKey(secretKey) {
2044
+ try {
2045
+ return !!_normFnElement(Fn, secretKey);
2046
+ } catch (error) {
2047
+ return false;
2048
+ }
2049
+ }
2050
+ function isValidPublicKey(publicKey, isCompressed) {
2051
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
2052
+ try {
2053
+ const l = publicKey.length;
2054
+ if (isCompressed === true && l !== comp) return false;
2055
+ if (isCompressed === false && l !== publicKeyUncompressed) return false;
2056
+ return !!Point.fromBytes(publicKey);
2057
+ } catch (error) {
2058
+ return false;
2059
+ }
2060
+ }
2061
+ /**
2062
+ * Produces cryptographically secure secret key from random of size
2063
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
2064
+ */
2065
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
2066
+ return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
2067
+ }
2068
+ /**
2069
+ * Computes public key for a secret key. Checks for validity of the secret key.
2070
+ * @param isCompressed whether to return compact (default), or full key
2071
+ * @returns Public key, full when isCompressed=false; short when isCompressed=true
2072
+ */
2073
+ function getPublicKey(secretKey, isCompressed = true) {
2074
+ return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
2075
+ }
2076
+ function keygen(seed) {
2077
+ const secretKey = randomSecretKey(seed);
2078
+ return {
2079
+ secretKey,
2080
+ publicKey: getPublicKey(secretKey)
2081
+ };
2082
+ }
2083
+ /**
2084
+ * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
2085
+ */
2086
+ function isProbPub(item) {
2087
+ if (typeof item === "bigint") return false;
2088
+ if (item instanceof Point) return true;
2089
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
2090
+ if (Fn.allowedLengths || secretKey === publicKey) return void 0;
2091
+ const l = ensureBytes("key", item).length;
2092
+ return l === publicKey || l === publicKeyUncompressed;
2093
+ }
2094
+ /**
2095
+ * ECDH (Elliptic Curve Diffie Hellman).
2096
+ * Computes shared public key from secret key A and public key B.
2097
+ * Checks: 1) secret key validity 2) shared key is on-curve.
2098
+ * Does NOT hash the result.
2099
+ * @param isCompressed whether to return compact (default), or full key
2100
+ * @returns shared public key
2101
+ */
2102
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
2103
+ if (isProbPub(secretKeyA) === true) throw new Error("first arg must be private key");
2104
+ if (isProbPub(publicKeyB) === false) throw new Error("second arg must be public key");
2105
+ const s = _normFnElement(Fn, secretKeyA);
2106
+ return Point.fromHex(publicKeyB).multiply(s).toBytes(isCompressed);
2107
+ }
2108
+ return Object.freeze({
2109
+ getPublicKey,
2110
+ getSharedSecret,
2111
+ keygen,
2112
+ Point,
2113
+ utils: {
2114
+ isValidSecretKey,
2115
+ isValidPublicKey,
2116
+ randomSecretKey,
2117
+ isValidPrivateKey: isValidSecretKey,
2118
+ randomPrivateKey: randomSecretKey,
2119
+ normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
2120
+ precompute(windowSize = 8, point = Point.BASE) {
2121
+ return point.precompute(windowSize, false);
2122
+ }
2123
+ },
2124
+ lengths
2125
+ });
2126
+ }
2127
+ /**
2128
+ * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
2129
+ * We need `hash` for 2 features:
2130
+ * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
2131
+ * 2. k generation in `sign`, using HMAC-drbg(hash)
2132
+ *
2133
+ * ECDSAOpts are only rarely needed.
2134
+ *
2135
+ * @example
2136
+ * ```js
2137
+ * const p256_Point = weierstrass(...);
2138
+ * const p256_sha256 = ecdsa(p256_Point, sha256);
2139
+ * const p256_sha224 = ecdsa(p256_Point, sha224);
2140
+ * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
2141
+ * ```
2142
+ */
2143
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
2144
+ ahash(hash);
2145
+ _validateObject(ecdsaOpts, {}, {
2146
+ hmac: "function",
2147
+ lowS: "boolean",
2148
+ randomBytes: "function",
2149
+ bits2int: "function",
2150
+ bits2int_modN: "function"
2151
+ });
2152
+ const randomBytes = ecdsaOpts.randomBytes || randomBytes$1;
2153
+ const hmac$1 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
2154
+ const { Fp, Fn } = Point;
2155
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
2156
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
2157
+ const defaultSigOpts = {
2158
+ prehash: false,
2159
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
2160
+ format: void 0,
2161
+ extraEntropy: false
2162
+ };
2163
+ const defaultSigOpts_format = "compact";
2164
+ function isBiggerThanHalfOrder(number) {
2165
+ return number > CURVE_ORDER >> _1n$1;
2166
+ }
2167
+ function validateRS(title, num) {
2168
+ if (!Fn.isValidNot0(num)) throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
2169
+ return num;
2170
+ }
2171
+ function validateSigLength(bytes, format) {
2172
+ validateSigFormat(format);
2173
+ const size = lengths.signature;
2174
+ return _abytes2(bytes, format === "compact" ? size : format === "recovered" ? size + 1 : void 0, `${format} signature`);
2175
+ }
2176
+ /**
2177
+ * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
2178
+ */
2179
+ class Signature {
2180
+ constructor(r, s, recovery) {
2181
+ this.r = validateRS("r", r);
2182
+ this.s = validateRS("s", s);
2183
+ if (recovery != null) this.recovery = recovery;
2184
+ Object.freeze(this);
2185
+ }
2186
+ static fromBytes(bytes, format = defaultSigOpts_format) {
2187
+ validateSigLength(bytes, format);
2188
+ let recid;
2189
+ if (format === "der") {
2190
+ const { r, s } = DER.toSig(_abytes2(bytes));
2191
+ return new Signature(r, s);
2192
+ }
2193
+ if (format === "recovered") {
2194
+ recid = bytes[0];
2195
+ format = "compact";
2196
+ bytes = bytes.subarray(1);
2197
+ }
2198
+ const L = Fn.BYTES;
2199
+ const r = bytes.subarray(0, L);
2200
+ const s = bytes.subarray(L, L * 2);
2201
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
2202
+ }
2203
+ static fromHex(hex, format) {
2204
+ return this.fromBytes(hexToBytes(hex), format);
2205
+ }
2206
+ addRecoveryBit(recovery) {
2207
+ return new Signature(this.r, this.s, recovery);
2208
+ }
2209
+ recoverPublicKey(messageHash) {
2210
+ const FIELD_ORDER = Fp.ORDER;
2211
+ const { r, s, recovery: rec } = this;
2212
+ if (rec == null || ![
2213
+ 0,
2214
+ 1,
2215
+ 2,
2216
+ 3
2217
+ ].includes(rec)) throw new Error("recovery id invalid");
2218
+ if (CURVE_ORDER * _2n$1 < FIELD_ORDER && rec > 1) throw new Error("recovery id is ambiguous for h>1 curve");
2219
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
2220
+ if (!Fp.isValid(radj)) throw new Error("recovery id 2 or 3 invalid");
2221
+ const x = Fp.toBytes(radj);
2222
+ const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
2223
+ const ir = Fn.inv(radj);
2224
+ const h = bits2int_modN(ensureBytes("msgHash", messageHash));
2225
+ const u1 = Fn.create(-h * ir);
2226
+ const u2 = Fn.create(s * ir);
2227
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
2228
+ if (Q.is0()) throw new Error("point at infinify");
2229
+ Q.assertValidity();
2230
+ return Q;
2231
+ }
2232
+ hasHighS() {
2233
+ return isBiggerThanHalfOrder(this.s);
2234
+ }
2235
+ toBytes(format = defaultSigOpts_format) {
2236
+ validateSigFormat(format);
2237
+ if (format === "der") return hexToBytes(DER.hexFromSig(this));
2238
+ const r = Fn.toBytes(this.r);
2239
+ const s = Fn.toBytes(this.s);
2240
+ if (format === "recovered") {
2241
+ if (this.recovery == null) throw new Error("recovery bit must be present");
2242
+ return concatBytes(Uint8Array.of(this.recovery), r, s);
2243
+ }
2244
+ return concatBytes(r, s);
2245
+ }
2246
+ toHex(format) {
2247
+ return bytesToHex(this.toBytes(format));
2248
+ }
2249
+ assertValidity() {}
2250
+ static fromCompact(hex) {
2251
+ return Signature.fromBytes(ensureBytes("sig", hex), "compact");
2252
+ }
2253
+ static fromDER(hex) {
2254
+ return Signature.fromBytes(ensureBytes("sig", hex), "der");
2255
+ }
2256
+ normalizeS() {
2257
+ return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
2258
+ }
2259
+ toDERRawBytes() {
2260
+ return this.toBytes("der");
2261
+ }
2262
+ toDERHex() {
2263
+ return bytesToHex(this.toBytes("der"));
2264
+ }
2265
+ toCompactRawBytes() {
2266
+ return this.toBytes("compact");
2267
+ }
2268
+ toCompactHex() {
2269
+ return bytesToHex(this.toBytes("compact"));
2270
+ }
2271
+ }
2272
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
2273
+ if (bytes.length > 8192) throw new Error("input is too large");
2274
+ const num = bytesToNumberBE(bytes);
2275
+ const delta = bytes.length * 8 - fnBits;
2276
+ return delta > 0 ? num >> BigInt(delta) : num;
2277
+ };
2278
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
2279
+ return Fn.create(bits2int(bytes));
2280
+ };
2281
+ const ORDER_MASK = bitMask(fnBits);
2282
+ /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
2283
+ function int2octets(num) {
2284
+ aInRange("num < 2^" + fnBits, num, _0n$1, ORDER_MASK);
2285
+ return Fn.toBytes(num);
2286
+ }
2287
+ function validateMsgAndHash(message, prehash) {
2288
+ _abytes2(message, void 0, "message");
2289
+ return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
2290
+ }
2291
+ /**
2292
+ * Steps A, D of RFC6979 3.2.
2293
+ * Creates RFC6979 seed; converts msg/privKey to numbers.
2294
+ * Used only in sign, not in verify.
2295
+ *
2296
+ * Warning: we cannot assume here that message has same amount of bytes as curve order,
2297
+ * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
2298
+ */
2299
+ function prepSig(message, privateKey, opts) {
2300
+ if (["recovered", "canonical"].some((k) => k in opts)) throw new Error("sign() legacy options not supported");
2301
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
2302
+ message = validateMsgAndHash(message, prehash);
2303
+ const h1int = bits2int_modN(message);
2304
+ const d = _normFnElement(Fn, privateKey);
2305
+ const seedArgs = [int2octets(d), int2octets(h1int)];
2306
+ if (extraEntropy != null && extraEntropy !== false) {
2307
+ const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
2308
+ seedArgs.push(ensureBytes("extraEntropy", e));
2309
+ }
2310
+ const seed = concatBytes(...seedArgs);
2311
+ const m = h1int;
2312
+ function k2sig(kBytes) {
2313
+ const k = bits2int(kBytes);
2314
+ if (!Fn.isValidNot0(k)) return;
2315
+ const ik = Fn.inv(k);
2316
+ const q = Point.BASE.multiply(k).toAffine();
2317
+ const r = Fn.create(q.x);
2318
+ if (r === _0n$1) return;
2319
+ const s = Fn.create(ik * Fn.create(m + r * d));
2320
+ if (s === _0n$1) return;
2321
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$1);
2322
+ let normS = s;
2323
+ if (lowS && isBiggerThanHalfOrder(s)) {
2324
+ normS = Fn.neg(s);
2325
+ recovery ^= 1;
2326
+ }
2327
+ return new Signature(r, normS, recovery);
2328
+ }
2329
+ return {
2330
+ seed,
2331
+ k2sig
2332
+ };
2333
+ }
2334
+ /**
2335
+ * Signs message hash with a secret key.
2336
+ *
2337
+ * ```
2338
+ * sign(m, d) where
2339
+ * k = rfc6979_hmac_drbg(m, d)
2340
+ * (x, y) = G × k
2341
+ * r = x mod n
2342
+ * s = (m + dr) / k mod n
2343
+ * ```
2344
+ */
2345
+ function sign(message, secretKey, opts = {}) {
2346
+ message = ensureBytes("message", message);
2347
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
2348
+ return createHmacDrbg(hash.outputLen, Fn.BYTES, hmac$1)(seed, k2sig);
2349
+ }
2350
+ function tryParsingSig(sg) {
2351
+ let sig = void 0;
2352
+ const isHex = typeof sg === "string" || isBytes(sg);
2353
+ const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
2354
+ if (!isHex && !isObj) throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
2355
+ if (isObj) sig = new Signature(sg.r, sg.s);
2356
+ else if (isHex) {
2357
+ try {
2358
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
2359
+ } catch (derError) {
2360
+ if (!(derError instanceof DER.Err)) throw derError;
2361
+ }
2362
+ if (!sig) try {
2363
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
2364
+ } catch (error) {
2365
+ return false;
2366
+ }
2367
+ }
2368
+ if (!sig) return false;
2369
+ return sig;
2370
+ }
2371
+ /**
2372
+ * Verifies a signature against message and public key.
2373
+ * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
2374
+ * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
2375
+ *
2376
+ * ```
2377
+ * verify(r, s, h, P) where
2378
+ * u1 = hs^-1 mod n
2379
+ * u2 = rs^-1 mod n
2380
+ * R = u1⋅G + u2⋅P
2381
+ * mod(R.x, n) == r
2382
+ * ```
2383
+ */
2384
+ function verify(signature, message, publicKey, opts = {}) {
2385
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
2386
+ publicKey = ensureBytes("publicKey", publicKey);
2387
+ message = validateMsgAndHash(ensureBytes("message", message), prehash);
2388
+ if ("strict" in opts) throw new Error("options.strict was renamed to lowS");
2389
+ const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
2390
+ if (sig === false) return false;
2391
+ try {
2392
+ const P = Point.fromBytes(publicKey);
2393
+ if (lowS && sig.hasHighS()) return false;
2394
+ const { r, s } = sig;
2395
+ const h = bits2int_modN(message);
2396
+ const is = Fn.inv(s);
2397
+ const u1 = Fn.create(h * is);
2398
+ const u2 = Fn.create(r * is);
2399
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
2400
+ if (R.is0()) return false;
2401
+ return Fn.create(R.x) === r;
2402
+ } catch (e) {
2403
+ return false;
2404
+ }
2405
+ }
2406
+ function recoverPublicKey(signature, message, opts = {}) {
2407
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
2408
+ message = validateMsgAndHash(message, prehash);
2409
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
2410
+ }
2411
+ return Object.freeze({
2412
+ keygen,
2413
+ getPublicKey,
2414
+ getSharedSecret,
2415
+ utils,
2416
+ lengths,
2417
+ Point,
2418
+ sign,
2419
+ verify,
2420
+ recoverPublicKey,
2421
+ Signature,
2422
+ hash
2423
+ });
2424
+ }
2425
+ function _weierstrass_legacy_opts_to_new(c) {
2426
+ const CURVE = {
2427
+ a: c.a,
2428
+ b: c.b,
2429
+ p: c.Fp.ORDER,
2430
+ n: c.n,
2431
+ h: c.h,
2432
+ Gx: c.Gx,
2433
+ Gy: c.Gy
2434
+ };
2435
+ const Fp = c.Fp;
2436
+ let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
2437
+ return {
2438
+ CURVE,
2439
+ curveOpts: {
2440
+ Fp,
2441
+ Fn: Field(CURVE.n, {
2442
+ BITS: c.nBitLength,
2443
+ allowedLengths,
2444
+ modFromBytes: c.wrapPrivateKey
2445
+ }),
2446
+ allowInfinityPoint: c.allowInfinityPoint,
2447
+ endo: c.endo,
2448
+ isTorsionFree: c.isTorsionFree,
2449
+ clearCofactor: c.clearCofactor,
2450
+ fromBytes: c.fromBytes,
2451
+ toBytes: c.toBytes
2452
+ }
2453
+ };
2454
+ }
2455
+ function _ecdsa_legacy_opts_to_new(c) {
2456
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
2457
+ const ecdsaOpts = {
2458
+ hmac: c.hmac,
2459
+ randomBytes: c.randomBytes,
2460
+ lowS: c.lowS,
2461
+ bits2int: c.bits2int,
2462
+ bits2int_modN: c.bits2int_modN
2463
+ };
2464
+ return {
2465
+ CURVE,
2466
+ curveOpts,
2467
+ hash: c.hash,
2468
+ ecdsaOpts
2469
+ };
2470
+ }
2471
+ function _ecdsa_new_output_to_legacy(c, _ecdsa) {
2472
+ const Point = _ecdsa.Point;
2473
+ return Object.assign({}, _ecdsa, {
2474
+ ProjectivePoint: Point,
2475
+ CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
2476
+ });
2477
+ }
2478
+ function weierstrass(c) {
2479
+ const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
2480
+ return _ecdsa_new_output_to_legacy(c, ecdsa(weierstrassN(CURVE, curveOpts), hash, ecdsaOpts));
2481
+ }
2482
+ //#endregion
2483
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/_shortw_utils.js
2484
+ /**
2485
+ * Utilities for short weierstrass curves, combined with noble-hashes.
2486
+ * @module
2487
+ */
2488
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2489
+ /** @deprecated use new `weierstrass()` and `ecdsa()` methods */
2490
+ function createCurve(curveDef, defHash) {
2491
+ const create = (hash) => weierstrass({
2492
+ ...curveDef,
2493
+ hash
2494
+ });
2495
+ return {
2496
+ ...create(defHash),
2497
+ create
2498
+ };
2499
+ }
2500
+ //#endregion
2501
+ //#region ../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/secp256k1.js
2502
+ /**
2503
+ * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
2504
+ *
2505
+ * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
2506
+ * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
2507
+ * @module
2508
+ */
2509
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2510
+ var secp256k1_CURVE = {
2511
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
2512
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
2513
+ h: BigInt(1),
2514
+ a: BigInt(0),
2515
+ b: BigInt(7),
2516
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
2517
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
2518
+ };
2519
+ var secp256k1_ENDO = {
2520
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
2521
+ basises: [[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")], [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]
2522
+ };
2523
+ var _0n = /* @__PURE__ */ BigInt(0);
2524
+ var _1n = /* @__PURE__ */ BigInt(1);
2525
+ var _2n = /* @__PURE__ */ BigInt(2);
2526
+ /**
2527
+ * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
2528
+ * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
2529
+ */
2530
+ function sqrtMod(y) {
2531
+ const P = secp256k1_CURVE.p;
2532
+ const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
2533
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
2534
+ const b2 = y * y * y % P;
2535
+ const b3 = b2 * b2 * y % P;
2536
+ const b11 = pow2(pow2(pow2(b3, _3n, P) * b3 % P, _3n, P) * b3 % P, _2n, P) * b2 % P;
2537
+ const b22 = pow2(b11, _11n, P) * b11 % P;
2538
+ const b44 = pow2(b22, _22n, P) * b22 % P;
2539
+ const b88 = pow2(b44, _44n, P) * b44 % P;
2540
+ 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);
2541
+ if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error("Cannot find square root");
2542
+ return root;
2543
+ }
2544
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
2545
+ /**
2546
+ * secp256k1 curve, ECDSA and ECDH methods.
2547
+ *
2548
+ * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
2549
+ *
2550
+ * @example
2551
+ * ```js
2552
+ * import { secp256k1 } from '@noble/curves/secp256k1';
2553
+ * const { secretKey, publicKey } = secp256k1.keygen();
2554
+ * const msg = new TextEncoder().encode('hello');
2555
+ * const sig = secp256k1.sign(msg, secretKey);
2556
+ * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
2557
+ * ```
2558
+ */
2559
+ var secp256k1 = createCurve({
2560
+ ...secp256k1_CURVE,
2561
+ Fp: Fpk1,
2562
+ lowS: true,
2563
+ endo: secp256k1_ENDO
2564
+ }, sha256);
2565
+ /** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
2566
+ var TAGGED_HASH_PREFIXES = {};
2567
+ function taggedHash(tag, ...messages) {
2568
+ let tagP = TAGGED_HASH_PREFIXES[tag];
2569
+ if (tagP === void 0) {
2570
+ const tagH = sha256(utf8ToBytes(tag));
2571
+ tagP = concatBytes(tagH, tagH);
2572
+ TAGGED_HASH_PREFIXES[tag] = tagP;
2573
+ }
2574
+ return sha256(concatBytes(tagP, ...messages));
2575
+ }
2576
+ var pointToBytes = (point) => point.toBytes(true).slice(1);
2577
+ var Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
2578
+ var hasEven = (y) => y % _2n === _0n;
2579
+ function schnorrGetExtPubKey(priv) {
2580
+ const { Fn, BASE } = Pointk1;
2581
+ const d_ = _normFnElement(Fn, priv);
2582
+ const p = BASE.multiply(d_);
2583
+ return {
2584
+ scalar: hasEven(p.y) ? d_ : Fn.neg(d_),
2585
+ bytes: pointToBytes(p)
2586
+ };
2587
+ }
2588
+ /**
2589
+ * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
2590
+ * @returns valid point checked for being on-curve
2591
+ */
2592
+ function lift_x(x) {
2593
+ const Fp = Fpk1;
2594
+ if (!Fp.isValidNot0(x)) throw new Error("invalid x: Fail if x ≥ p");
2595
+ const xx = Fp.create(x * x);
2596
+ const c = Fp.create(xx * x + BigInt(7));
2597
+ let y = Fp.sqrt(c);
2598
+ if (!hasEven(y)) y = Fp.neg(y);
2599
+ const p = Pointk1.fromAffine({
2600
+ x,
2601
+ y
2602
+ });
2603
+ p.assertValidity();
2604
+ return p;
2605
+ }
2606
+ var num = bytesToNumberBE;
2607
+ /**
2608
+ * Create tagged hash, convert it to bigint, reduce modulo-n.
2609
+ */
2610
+ function challenge(...args) {
2611
+ return Pointk1.Fn.create(num(taggedHash("BIP0340/challenge", ...args)));
2612
+ }
2613
+ /**
2614
+ * Schnorr public key is just `x` coordinate of Point as per BIP340.
2615
+ */
2616
+ function schnorrGetPublicKey(secretKey) {
2617
+ return schnorrGetExtPubKey(secretKey).bytes;
2618
+ }
2619
+ /**
2620
+ * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
2621
+ * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
2622
+ */
2623
+ function schnorrSign(message, secretKey, auxRand = randomBytes$1(32)) {
2624
+ const { Fn } = Pointk1;
2625
+ const m = ensureBytes("message", message);
2626
+ const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey);
2627
+ const a = ensureBytes("auxRand", auxRand, 32);
2628
+ const { bytes: rx, scalar: k } = schnorrGetExtPubKey(taggedHash("BIP0340/nonce", Fn.toBytes(d ^ num(taggedHash("BIP0340/aux", a))), px, m));
2629
+ const e = challenge(rx, px, m);
2630
+ const sig = /* @__PURE__ */ new Uint8Array(64);
2631
+ sig.set(rx, 0);
2632
+ sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
2633
+ if (!schnorrVerify(sig, m, px)) throw new Error("sign: Invalid signature produced");
2634
+ return sig;
2635
+ }
2636
+ /**
2637
+ * Verifies Schnorr signature.
2638
+ * Will swallow errors & return false except for initial type validation of arguments.
2639
+ */
2640
+ function schnorrVerify(signature, message, publicKey) {
2641
+ const { Fn, BASE } = Pointk1;
2642
+ const sig = ensureBytes("signature", signature, 64);
2643
+ const m = ensureBytes("message", message);
2644
+ const pub = ensureBytes("publicKey", publicKey, 32);
2645
+ try {
2646
+ const P = lift_x(num(pub));
2647
+ const r = num(sig.subarray(0, 32));
2648
+ if (!inRange(r, _1n, secp256k1_CURVE.p)) return false;
2649
+ const s = num(sig.subarray(32, 64));
2650
+ if (!inRange(s, _1n, secp256k1_CURVE.n)) return false;
2651
+ const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
2652
+ const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
2653
+ const { x, y } = R.toAffine();
2654
+ if (R.is0() || !hasEven(y) || x !== r) return false;
2655
+ return true;
2656
+ } catch (error) {
2657
+ return false;
2658
+ }
2659
+ }
2660
+ /**
2661
+ * Schnorr signatures over secp256k1.
2662
+ * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
2663
+ * @example
2664
+ * ```js
2665
+ * import { schnorr } from '@noble/curves/secp256k1';
2666
+ * const { secretKey, publicKey } = schnorr.keygen();
2667
+ * // const publicKey = schnorr.getPublicKey(secretKey);
2668
+ * const msg = new TextEncoder().encode('hello');
2669
+ * const sig = schnorr.sign(msg, secretKey);
2670
+ * const isValid = schnorr.verify(sig, msg, publicKey);
2671
+ * ```
2672
+ */
2673
+ var schnorr = /* @__PURE__ */ (() => {
2674
+ const size = 32;
2675
+ const seedLength = 48;
2676
+ const randomSecretKey = (seed = randomBytes$1(seedLength)) => {
2677
+ return mapHashToField(seed, secp256k1_CURVE.n);
2678
+ };
2679
+ secp256k1.utils.randomSecretKey;
2680
+ function keygen(seed) {
2681
+ const secretKey = randomSecretKey(seed);
2682
+ return {
2683
+ secretKey,
2684
+ publicKey: schnorrGetPublicKey(secretKey)
2685
+ };
2686
+ }
2687
+ return {
2688
+ keygen,
2689
+ getPublicKey: schnorrGetPublicKey,
2690
+ sign: schnorrSign,
2691
+ verify: schnorrVerify,
2692
+ Point: Pointk1,
2693
+ utils: {
2694
+ randomSecretKey,
2695
+ randomPrivateKey: randomSecretKey,
2696
+ taggedHash,
2697
+ lift_x,
2698
+ pointToBytes,
2699
+ numberToBytesBE,
2700
+ bytesToNumberBE,
2701
+ mod
2702
+ },
2703
+ lengths: {
2704
+ secretKey: size,
2705
+ publicKey: size,
2706
+ publicKeyHasPrefix: false,
2707
+ signature: size * 2,
2708
+ seed: seedLength
2709
+ }
2710
+ };
2711
+ })();
2712
+ //#endregion
2713
+ //#region src/auth/nostrCrypto.ts
2714
+ var import_dist = (/* @__PURE__ */ __commonJSMin(((exports) => {
2715
+ Object.defineProperty(exports, "__esModule", { value: true });
2716
+ exports.bech32m = exports.bech32 = void 0;
2717
+ var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
2718
+ var ALPHABET_MAP = {};
2719
+ for (let z = 0; z < 32; z++) {
2720
+ const x = ALPHABET.charAt(z);
2721
+ ALPHABET_MAP[x] = z;
2722
+ }
2723
+ function polymodStep(pre) {
2724
+ const b = pre >> 25;
2725
+ return (pre & 33554431) << 5 ^ -(b >> 0 & 1) & 996825010 ^ -(b >> 1 & 1) & 642813549 ^ -(b >> 2 & 1) & 513874426 ^ -(b >> 3 & 1) & 1027748829 ^ -(b >> 4 & 1) & 705979059;
2726
+ }
2727
+ function prefixChk(prefix) {
2728
+ let chk = 1;
2729
+ for (let i = 0; i < prefix.length; ++i) {
2730
+ const c = prefix.charCodeAt(i);
2731
+ if (c < 33 || c > 126) return "Invalid prefix (" + prefix + ")";
2732
+ chk = polymodStep(chk) ^ c >> 5;
2733
+ }
2734
+ chk = polymodStep(chk);
2735
+ for (let i = 0; i < prefix.length; ++i) {
2736
+ const v = prefix.charCodeAt(i);
2737
+ chk = polymodStep(chk) ^ v & 31;
2738
+ }
2739
+ return chk;
2740
+ }
2741
+ function convert(data, inBits, outBits, pad) {
2742
+ let value = 0;
2743
+ let bits = 0;
2744
+ const maxV = (1 << outBits) - 1;
2745
+ const result = [];
2746
+ for (let i = 0; i < data.length; ++i) {
2747
+ value = value << inBits | data[i];
2748
+ bits += inBits;
2749
+ while (bits >= outBits) {
2750
+ bits -= outBits;
2751
+ result.push(value >> bits & maxV);
2752
+ }
2753
+ }
2754
+ if (pad) {
2755
+ if (bits > 0) result.push(value << outBits - bits & maxV);
2756
+ } else {
2757
+ if (bits >= inBits) return "Excess padding";
2758
+ if (value << outBits - bits & maxV) return "Non-zero padding";
2759
+ }
2760
+ return result;
2761
+ }
2762
+ function toWords(bytes) {
2763
+ return convert(bytes, 8, 5, true);
2764
+ }
2765
+ function fromWordsUnsafe(words) {
2766
+ const res = convert(words, 5, 8, false);
2767
+ if (Array.isArray(res)) return res;
2768
+ }
2769
+ function fromWords(words) {
2770
+ const res = convert(words, 5, 8, false);
2771
+ if (Array.isArray(res)) return res;
2772
+ throw new Error(res);
2773
+ }
2774
+ function getLibraryFromEncoding(encoding) {
2775
+ let ENCODING_CONST;
2776
+ if (encoding === "bech32") ENCODING_CONST = 1;
2777
+ else ENCODING_CONST = 734539939;
2778
+ function encode(prefix, words, LIMIT) {
2779
+ LIMIT = LIMIT || 90;
2780
+ if (prefix.length + 7 + words.length > LIMIT) throw new TypeError("Exceeds length limit");
2781
+ prefix = prefix.toLowerCase();
2782
+ let chk = prefixChk(prefix);
2783
+ if (typeof chk === "string") throw new Error(chk);
2784
+ let result = prefix + "1";
2785
+ for (let i = 0; i < words.length; ++i) {
2786
+ const x = words[i];
2787
+ if (x >> 5 !== 0) throw new Error("Non 5-bit word");
2788
+ chk = polymodStep(chk) ^ x;
2789
+ result += ALPHABET.charAt(x);
2790
+ }
2791
+ for (let i = 0; i < 6; ++i) chk = polymodStep(chk);
2792
+ chk ^= ENCODING_CONST;
2793
+ for (let i = 0; i < 6; ++i) {
2794
+ const v = chk >> (5 - i) * 5 & 31;
2795
+ result += ALPHABET.charAt(v);
2796
+ }
2797
+ return result;
2798
+ }
2799
+ function __decode(str, LIMIT) {
2800
+ LIMIT = LIMIT || 90;
2801
+ if (str.length < 8) return str + " too short";
2802
+ if (str.length > LIMIT) return "Exceeds length limit";
2803
+ const lowered = str.toLowerCase();
2804
+ const uppered = str.toUpperCase();
2805
+ if (str !== lowered && str !== uppered) return "Mixed-case string " + str;
2806
+ str = lowered;
2807
+ const split = str.lastIndexOf("1");
2808
+ if (split === -1) return "No separator character for " + str;
2809
+ if (split === 0) return "Missing prefix for " + str;
2810
+ const prefix = str.slice(0, split);
2811
+ const wordChars = str.slice(split + 1);
2812
+ if (wordChars.length < 6) return "Data too short";
2813
+ let chk = prefixChk(prefix);
2814
+ if (typeof chk === "string") return chk;
2815
+ const words = [];
2816
+ for (let i = 0; i < wordChars.length; ++i) {
2817
+ const c = wordChars.charAt(i);
2818
+ const v = ALPHABET_MAP[c];
2819
+ if (v === void 0) return "Unknown character " + c;
2820
+ chk = polymodStep(chk) ^ v;
2821
+ if (i + 6 >= wordChars.length) continue;
2822
+ words.push(v);
2823
+ }
2824
+ if (chk !== ENCODING_CONST) return "Invalid checksum for " + str;
2825
+ return {
2826
+ prefix,
2827
+ words
2828
+ };
2829
+ }
2830
+ function decodeUnsafe(str, LIMIT) {
2831
+ const res = __decode(str, LIMIT);
2832
+ if (typeof res === "object") return res;
2833
+ }
2834
+ function decode(str, LIMIT) {
2835
+ const res = __decode(str, LIMIT);
2836
+ if (typeof res === "object") return res;
2837
+ throw new Error(res);
2838
+ }
2839
+ return {
2840
+ decodeUnsafe,
2841
+ decode,
2842
+ encode,
2843
+ toWords,
2844
+ fromWordsUnsafe,
2845
+ fromWords
2846
+ };
2847
+ }
2848
+ exports.bech32 = getLibraryFromEncoding("bech32");
2849
+ exports.bech32m = getLibraryFromEncoding("bech32m");
2850
+ })))();
2851
+ function generateNostrKeypair() {
2852
+ const privkeyBytes = randomBytes(32);
2853
+ const privkey = Buffer.from(privkeyBytes).toString("hex");
2854
+ const pubkeyBytes = secp256k1.getPublicKey(privkeyBytes, true);
2855
+ return {
2856
+ pubkey: Buffer.from(pubkeyBytes.slice(1)).toString("hex"),
2857
+ privkey
2858
+ };
2859
+ }
2860
+ function deriveEncryptionKey(masterSecret) {
2861
+ const salt = Buffer.from("nostr-privkey-encryption", "utf8");
2862
+ const info = Buffer.from("aes-256-gcm", "utf8");
2863
+ const keyMaterial = Buffer.from(masterSecret, "utf8");
2864
+ return Buffer.from(hkdfSync("sha256", keyMaterial, salt, info, 32));
2865
+ }
2866
+ function encryptPrivkey(privkey, masterSecret) {
2867
+ const key = deriveEncryptionKey(masterSecret);
2868
+ const iv = randomBytes(12);
2869
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
2870
+ const encrypted = Buffer.concat([cipher.update(privkey, "utf8"), cipher.final()]);
2871
+ const tag = cipher.getAuthTag();
2872
+ return {
2873
+ ciphertext: encrypted.toString("base64"),
2874
+ iv: iv.toString("base64"),
2875
+ tag: tag.toString("base64")
2876
+ };
2877
+ }
2878
+ function decryptPrivkey(encrypted, masterSecret) {
2879
+ const key = deriveEncryptionKey(masterSecret);
2880
+ const iv = Buffer.from(encrypted.iv, "base64");
2881
+ const tag = Buffer.from(encrypted.tag, "base64");
2882
+ const ciphertext = Buffer.from(encrypted.ciphertext, "base64");
2883
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
2884
+ decipher.setAuthTag(tag);
2885
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
2886
+ }
2887
+ function computeEventId(event) {
2888
+ const serialized = JSON.stringify([
2889
+ 0,
2890
+ event.pubkey,
2891
+ event.created_at,
2892
+ event.kind,
2893
+ event.tags,
2894
+ event.content
2895
+ ]);
2896
+ return createHash("sha256").update(serialized).digest("hex");
2897
+ }
2898
+ function signEvent(event, privkey) {
2899
+ const id = computeEventId(event);
2900
+ const privkeyBytes = Buffer.from(privkey, "hex");
2901
+ const idBytes = Buffer.from(id, "hex");
2902
+ const sig = schnorr.sign(idBytes, privkeyBytes);
2903
+ const sigHex = Buffer.from(sig).toString("hex");
2904
+ return {
2905
+ ...event,
2906
+ id,
2907
+ sig: sigHex
2908
+ };
2909
+ }
2910
+ function verifyNostrSignature(event) {
2911
+ if (!event.id || !event.sig) return false;
2912
+ if (computeEventId(event) !== event.id) return false;
2913
+ try {
2914
+ const sigBytes = Buffer.from(event.sig, "hex");
2915
+ const idBytes = Buffer.from(event.id, "hex");
2916
+ const pubkeyBytes = Buffer.from(event.pubkey, "hex");
2917
+ return schnorr.verify(sigBytes, idBytes, pubkeyBytes);
2918
+ } catch {
2919
+ return false;
2920
+ }
2921
+ }
2922
+ function createAuthEvent(privkey, challenge, relay) {
2923
+ const privkeyBytes = Buffer.from(privkey, "hex");
2924
+ const pubkeyBytes = secp256k1.getPublicKey(privkeyBytes, true);
2925
+ const pubkey = Buffer.from(pubkeyBytes.slice(1)).toString("hex");
2926
+ const tags = [["challenge", challenge]];
2927
+ if (relay) tags.push(["relay", relay]);
2928
+ return signEvent({
2929
+ pubkey,
2930
+ created_at: Math.floor(Date.now() / 1e3),
2931
+ kind: 22242,
2932
+ tags,
2933
+ content: ""
2934
+ }, privkey);
2935
+ }
2936
+ function verifyAuthEvent(event, expectedChallenge, maxAgeSeconds = 300) {
2937
+ if (event.kind !== 22242) return {
2938
+ valid: false,
2939
+ error: "Invalid event kind"
2940
+ };
2941
+ const age = Math.floor(Date.now() / 1e3) - event.created_at;
2942
+ if (age > maxAgeSeconds || age < -60) return {
2943
+ valid: false,
2944
+ error: "Event expired or too far in future"
2945
+ };
2946
+ const challengeTag = event.tags.find((t) => t[0] === "challenge");
2947
+ if (!challengeTag || challengeTag[1] !== expectedChallenge) return {
2948
+ valid: false,
2949
+ error: "Challenge mismatch"
2950
+ };
2951
+ if (!verifyNostrSignature(event)) return {
2952
+ valid: false,
2953
+ error: "Invalid signature"
2954
+ };
2955
+ return { valid: true };
2956
+ }
2957
+ function pubkeyToNpub(pubkey) {
2958
+ const words = import_dist.bech32.toWords(Buffer.from(pubkey, "hex"));
2959
+ return import_dist.bech32.encode("npub", words, 1e3);
2960
+ }
2961
+ function npubToPubkey(npub) {
2962
+ const { prefix, words } = import_dist.bech32.decode(npub, 1e3);
2963
+ if (prefix !== "npub") throw new Error("Invalid npub prefix");
2964
+ return Buffer.from(import_dist.bech32.fromWords(words)).toString("hex");
2965
+ }
2966
+ function privkeyToNsec(privkey) {
2967
+ const words = import_dist.bech32.toWords(Buffer.from(privkey, "hex"));
2968
+ return import_dist.bech32.encode("nsec", words, 1e3);
2969
+ }
2970
+ function nsecToPrivkey(nsec) {
2971
+ const { prefix, words } = import_dist.bech32.decode(nsec, 1e3);
2972
+ if (prefix !== "nsec") throw new Error("Invalid nsec prefix");
2973
+ return Buffer.from(import_dist.bech32.fromWords(words)).toString("hex");
2974
+ }
2975
+ function getPublicKey(privkey) {
2976
+ const privkeyBytes = Buffer.from(privkey, "hex");
2977
+ const pubkeyBytes = secp256k1.getPublicKey(privkeyBytes, true);
2978
+ return Buffer.from(pubkeyBytes.slice(1)).toString("hex");
2979
+ }
2980
+ function isValidPubkey(pubkey) {
2981
+ if (!/^[0-9a-f]{64}$/i.test(pubkey)) return false;
2982
+ try {
2983
+ const fullPubkey = Buffer.from(`02${pubkey}`, "hex");
2984
+ secp256k1.ProjectivePoint.fromHex(fullPubkey);
2985
+ return true;
2986
+ } catch {
2987
+ return false;
2988
+ }
2989
+ }
2990
+ function isValidPrivkey(privkey) {
2991
+ if (!/^[0-9a-f]{64}$/i.test(privkey)) return false;
2992
+ try {
2993
+ const privkeyBytes = Buffer.from(privkey, "hex");
2994
+ secp256k1.getPublicKey(privkeyBytes);
2995
+ return true;
2996
+ } catch {
2997
+ return false;
2998
+ }
2999
+ }
3000
+ //#endregion
3001
+ //#region src/models/NostrIdentity.ts
3002
+ var NostrIdentity_exports = /* @__PURE__ */ __exportAll({ NostrIdentity: () => NostrIdentity });
3003
+ var __defProp = Object.defineProperty;
3004
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3005
+ var __decorateClass = (decorators, target, key, kind) => {
3006
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
3007
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
3008
+ if (kind && result) __defProp(target, key, result);
3009
+ return result;
3010
+ };
3011
+ var NostrIdentity = class extends SmrtObject {
3012
+ profileId;
3013
+ /**
3014
+ * Hex-encoded secp256k1 public key (64 characters)
3015
+ */
3016
+ pubkey = "";
3017
+ /**
3018
+ * AES-256-GCM encrypted private key (base64-encoded ciphertext)
3019
+ */
3020
+ encryptedPrivkey = "";
3021
+ /**
3022
+ * Initialization vector for AES-GCM decryption (base64)
3023
+ */
3024
+ encryptionIv = "";
3025
+ /**
3026
+ * Authentication tag from AES-GCM (base64)
3027
+ */
3028
+ encryptionTag = "";
3029
+ /**
3030
+ * Email address associated with this identity
3031
+ */
3032
+ email = "";
3033
+ /**
3034
+ * Username for NIP-05 verification (e.g., "alice" for alice@domain.com)
3035
+ */
3036
+ nip05Username = "";
3037
+ /**
3038
+ * Last time this identity was used for authentication
3039
+ */
3040
+ lastUsedAt = null;
3041
+ /**
3042
+ * When this identity was verified via magic link
3043
+ */
3044
+ verifiedAt = null;
3045
+ constructor(options = {}) {
3046
+ super(options);
3047
+ if (options.profileId) this.profileId = options.profileId;
3048
+ if (options.pubkey) this.pubkey = options.pubkey;
3049
+ if (options.encryptedPrivkey) this.encryptedPrivkey = options.encryptedPrivkey;
3050
+ if (options.encryptionIv) this.encryptionIv = options.encryptionIv;
3051
+ if (options.encryptionTag) this.encryptionTag = options.encryptionTag;
3052
+ if (options.email) this.email = options.email;
3053
+ if (options.nip05Username) this.nip05Username = options.nip05Username;
3054
+ if (options.lastUsedAt !== void 0) this.lastUsedAt = options.lastUsedAt;
3055
+ if (options.verifiedAt !== void 0) this.verifiedAt = options.verifiedAt;
3056
+ }
3057
+ /**
3058
+ * Get the linked Profile
3059
+ */
3060
+ async getProfile() {
3061
+ return await this.getRelated("profileId");
3062
+ }
3063
+ /**
3064
+ * Find identity by public key
3065
+ */
3066
+ static async findByPubkey(pubkey, options = {}) {
3067
+ const { NostrIdentityCollection } = await Promise.resolve().then(() => NostrIdentityCollection_exports);
3068
+ return await (await NostrIdentityCollection.create(options)).findOne({ where: { pubkey } });
3069
+ }
3070
+ /**
3071
+ * Find identity by email
3072
+ */
3073
+ static async findByEmail(email, options = {}) {
3074
+ const { NostrIdentityCollection } = await Promise.resolve().then(() => NostrIdentityCollection_exports);
3075
+ return await (await NostrIdentityCollection.create(options)).findOne({ where: { email: email.toLowerCase() } });
3076
+ }
3077
+ /**
3078
+ * Find identity by NIP-05 username
3079
+ */
3080
+ static async findByNip05(username, options = {}) {
3081
+ const { NostrIdentityCollection } = await Promise.resolve().then(() => NostrIdentityCollection_exports);
3082
+ return await (await NostrIdentityCollection.create(options)).findOne({ where: { nip05Username: username.toLowerCase() } });
3083
+ }
3084
+ /**
3085
+ * Decrypt the private key using the server master secret
3086
+ * @param masterSecret - SERVER_MASTER_SECRET from environment
3087
+ * @returns Hex-encoded private key
3088
+ */
3089
+ decryptPrivkey(masterSecret) {
3090
+ return decryptPrivkey({
3091
+ ciphertext: this.encryptedPrivkey,
3092
+ iv: this.encryptionIv,
3093
+ tag: this.encryptionTag
3094
+ }, masterSecret);
3095
+ }
3096
+ /**
3097
+ * Get the full keypair (requires master secret)
3098
+ * @param masterSecret - SERVER_MASTER_SECRET from environment
3099
+ */
3100
+ getKeypair(masterSecret) {
3101
+ const privkey = this.decryptPrivkey(masterSecret);
3102
+ return {
3103
+ pubkey: this.pubkey,
3104
+ privkey,
3105
+ npub: pubkeyToNpub(this.pubkey),
3106
+ nsec: privkeyToNsec(privkey)
3107
+ };
3108
+ }
3109
+ /**
3110
+ * Record usage of this identity
3111
+ */
3112
+ async recordUsage() {
3113
+ this.lastUsedAt = /* @__PURE__ */ new Date();
3114
+ await this.save();
3115
+ }
3116
+ /**
3117
+ * Mark this identity as verified
3118
+ */
3119
+ async markVerified() {
3120
+ this.verifiedAt = /* @__PURE__ */ new Date();
3121
+ this.lastUsedAt = /* @__PURE__ */ new Date();
3122
+ await this.save();
3123
+ }
3124
+ /**
3125
+ * Check if this identity is verified
3126
+ */
3127
+ isVerified() {
3128
+ return this.verifiedAt !== null;
3129
+ }
3130
+ /**
3131
+ * Get the NIP-05 identifier (username@domain)
3132
+ * Note: Domain must be provided by the application
3133
+ */
3134
+ getNip05Identifier(domain) {
3135
+ return `${this.nip05Username || this.email.split("@")[0]}@${domain}`;
3136
+ }
3137
+ };
3138
+ __decorateClass([foreignKey("Profile", { required: true })], NostrIdentity.prototype, "profileId", 2);
3139
+ NostrIdentity = __decorateClass([smrt({
3140
+ tableName: "nostr_identities",
3141
+ api: { include: ["list", "get"] },
3142
+ mcp: { include: ["list", "get"] },
3143
+ cli: { include: ["list", "get"] }
3144
+ })], NostrIdentity);
3145
+ //#endregion
3146
+ //#region src/collections/NostrIdentityCollection.ts
3147
+ var NostrIdentityCollection_exports = /* @__PURE__ */ __exportAll({ NostrIdentityCollection: () => NostrIdentityCollection });
3148
+ var NostrIdentityCollection = class extends SmrtCollection {
3149
+ static _itemClass = NostrIdentity;
3150
+ /**
3151
+ * Find identities for a profile
3152
+ */
3153
+ async findByProfile(profileId) {
3154
+ return await this.list({ where: { profileId } });
3155
+ }
3156
+ /**
3157
+ * Find identity by public key
3158
+ */
3159
+ async findByPubkey(pubkey) {
3160
+ return await this.findOne({ where: { pubkey } });
3161
+ }
3162
+ /**
3163
+ * Find identity by email
3164
+ */
3165
+ async findByEmail(email) {
3166
+ return await this.findOne({ where: { email: email.toLowerCase() } });
3167
+ }
3168
+ /**
3169
+ * Find identity by NIP-05 username
3170
+ */
3171
+ async findByNip05(username) {
3172
+ return await this.findOne({ where: { nip05Username: username.toLowerCase() } });
3173
+ }
3174
+ /**
3175
+ * Link a new Nostr identity to a profile with a new keypair
3176
+ * @param profile - The profile to link to
3177
+ * @param email - Email address for this identity
3178
+ * @param masterSecret - Server master secret for encryption
3179
+ * @param nip05Username - Optional NIP-05 username (defaults to email local part)
3180
+ */
3181
+ async createForProfile(profile, email, masterSecret, nip05Username) {
3182
+ const normalizedEmail = email.toLowerCase();
3183
+ if (await this.findByEmail(normalizedEmail)) throw new Error(`Nostr identity already exists for email: ${email}`);
3184
+ const keypair = generateNostrKeypair();
3185
+ const encrypted = encryptPrivkey(keypair.privkey, masterSecret);
3186
+ const username = nip05Username?.toLowerCase() || normalizedEmail.split("@")[0];
3187
+ const identity = new NostrIdentity({
3188
+ ...this.options,
3189
+ profileId: profile.id,
3190
+ pubkey: keypair.pubkey,
3191
+ encryptedPrivkey: encrypted.ciphertext,
3192
+ encryptionIv: encrypted.iv,
3193
+ encryptionTag: encrypted.tag,
3194
+ email: normalizedEmail,
3195
+ nip05Username: username
3196
+ });
3197
+ await identity.initialize();
3198
+ await identity.save();
3199
+ return identity;
3200
+ }
3201
+ /**
3202
+ * Link an existing Nostr identity (with encrypted keypair) to a profile
3203
+ */
3204
+ async linkToProfile(profile, nostrData) {
3205
+ if (await this.findByPubkey(nostrData.pubkey)) throw new Error("Nostr identity with this public key already exists");
3206
+ if (await this.findByEmail(nostrData.email)) throw new Error("Nostr identity with this email already exists");
3207
+ const identity = new NostrIdentity({
3208
+ ...this.options,
3209
+ profileId: profile.id,
3210
+ pubkey: nostrData.pubkey,
3211
+ encryptedPrivkey: nostrData.encryptedPrivkey,
3212
+ encryptionIv: nostrData.encryptionIv,
3213
+ encryptionTag: nostrData.encryptionTag,
3214
+ email: nostrData.email.toLowerCase(),
3215
+ nip05Username: nostrData.nip05Username?.toLowerCase() || nostrData.email.toLowerCase().split("@")[0]
3216
+ });
3217
+ await identity.initialize();
3218
+ await identity.save();
3219
+ return identity;
3220
+ }
3221
+ /**
3222
+ * Unlink a Nostr identity from a profile
3223
+ */
3224
+ async unlinkFromProfile(profileId, pubkey) {
3225
+ const identity = await this.findOne({ where: {
3226
+ profileId,
3227
+ pubkey
3228
+ } });
3229
+ if (identity) {
3230
+ await identity.delete();
3231
+ return true;
3232
+ }
3233
+ return false;
3234
+ }
3235
+ /**
3236
+ * Get NIP-05 response data for the /.well-known/nostr.json endpoint
3237
+ * @param username - Optional username filter, returns all if not provided
3238
+ */
3239
+ async getNip05Response(username) {
3240
+ const where = username ? { nip05Username: username.toLowerCase() } : {};
3241
+ const identities = await this.list({ where });
3242
+ const names = {};
3243
+ for (const identity of identities) if (identity.nip05Username && identity.pubkey) names[identity.nip05Username] = identity.pubkey;
3244
+ return { names };
3245
+ }
3246
+ /**
3247
+ * Check if a NIP-05 username is available
3248
+ */
3249
+ async isNip05Available(username) {
3250
+ return await this.findByNip05(username) === null;
3251
+ }
3252
+ /**
3253
+ * Update NIP-05 username for an identity
3254
+ */
3255
+ async updateNip05Username(identity, newUsername) {
3256
+ const normalizedUsername = newUsername.toLowerCase();
3257
+ const existing = await this.findByNip05(normalizedUsername);
3258
+ if (existing && existing.id !== identity.id) throw new Error(`NIP-05 username "${newUsername}" is already taken`);
3259
+ identity.nip05Username = normalizedUsername;
3260
+ await identity.save();
3261
+ return identity;
3262
+ }
3263
+ };
3264
+ //#endregion
3265
+ export { pubkeyToNpub as _, computeEventId as a, verifyNostrSignature as b, deriveEncryptionKey as c, getPublicKey as d, isValidPrivkey as f, privkeyToNsec as g, nsecToPrivkey as h, NostrIdentity_exports as i, encryptPrivkey as l, npubToPubkey as m, NostrIdentityCollection_exports as n, createAuthEvent as o, isValidPubkey as p, NostrIdentity as r, decryptPrivkey as s, NostrIdentityCollection as t, generateNostrKeypair as u, signEvent as v, __exportAll as x, verifyAuthEvent as y };
3266
+
3267
+ //# sourceMappingURL=NostrIdentityCollection-CG6HGf6c.js.map