@happyvertical/smrt-profiles 0.30.0

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