routstrd 0.1.4 → 0.1.5

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.
package/dist/index.js CHANGED
@@ -22480,16 +22480,33 @@ var require_webSocket2 = __commonJS((exports) => {
22480
22480
  } });
22481
22481
  });
22482
22482
 
22483
+ // ../routstr-chat/node_modules/@noble/hashes/esm/cryptoNode.js
22484
+ import * as nc3 from "crypto";
22485
+ var crypto4;
22486
+ var init_cryptoNode3 = __esm(() => {
22487
+ crypto4 = nc3 && typeof nc3 === "object" && "webcrypto" in nc3 ? nc3.webcrypto : nc3 && typeof nc3 === "object" && ("randomBytes" in nc3) ? nc3 : undefined;
22488
+ });
22489
+
22483
22490
  // ../routstr-chat/node_modules/@noble/hashes/esm/utils.js
22484
22491
  function isBytes2(a) {
22485
22492
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
22486
22493
  }
22494
+ function anumber(n) {
22495
+ if (!Number.isSafeInteger(n) || n < 0)
22496
+ throw new Error("positive integer expected, got " + n);
22497
+ }
22487
22498
  function abytes(b, ...lengths) {
22488
22499
  if (!isBytes2(b))
22489
22500
  throw new Error("Uint8Array expected");
22490
22501
  if (lengths.length > 0 && !lengths.includes(b.length))
22491
22502
  throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
22492
22503
  }
22504
+ function ahash(h) {
22505
+ if (typeof h !== "function" || typeof h.create !== "function")
22506
+ throw new Error("Hash should be wrapped by utils.createHasher");
22507
+ anumber(h.outputLen);
22508
+ anumber(h.blockLen);
22509
+ }
22493
22510
  function aexists(instance, checkFinished = true) {
22494
22511
  if (instance.destroyed)
22495
22512
  throw new Error("Hash instance has been destroyed");
@@ -22514,6 +22531,49 @@ function createView4(arr) {
22514
22531
  function rotr3(word, shift) {
22515
22532
  return word << 32 - shift | word >>> shift;
22516
22533
  }
22534
+ function rotl2(word, shift) {
22535
+ return word << shift | word >>> 32 - shift >>> 0;
22536
+ }
22537
+ function bytesToHex4(bytes4) {
22538
+ abytes(bytes4);
22539
+ if (hasHexBuiltin)
22540
+ return bytes4.toHex();
22541
+ let hex2 = "";
22542
+ for (let i4 = 0;i4 < bytes4.length; i4++) {
22543
+ hex2 += hexes4[bytes4[i4]];
22544
+ }
22545
+ return hex2;
22546
+ }
22547
+ function asciiToBase162(ch) {
22548
+ if (ch >= asciis2._0 && ch <= asciis2._9)
22549
+ return ch - asciis2._0;
22550
+ if (ch >= asciis2.A && ch <= asciis2.F)
22551
+ return ch - (asciis2.A - 10);
22552
+ if (ch >= asciis2.a && ch <= asciis2.f)
22553
+ return ch - (asciis2.a - 10);
22554
+ return;
22555
+ }
22556
+ function hexToBytes4(hex2) {
22557
+ if (typeof hex2 !== "string")
22558
+ throw new Error("hex string expected, got " + typeof hex2);
22559
+ if (hasHexBuiltin)
22560
+ return Uint8Array.fromHex(hex2);
22561
+ const hl = hex2.length;
22562
+ const al = hl / 2;
22563
+ if (hl % 2)
22564
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
22565
+ const array = new Uint8Array(al);
22566
+ for (let ai = 0, hi = 0;ai < al; ai++, hi += 2) {
22567
+ const n1 = asciiToBase162(hex2.charCodeAt(hi));
22568
+ const n2 = asciiToBase162(hex2.charCodeAt(hi + 1));
22569
+ if (n1 === undefined || n2 === undefined) {
22570
+ const char = hex2[hi] + hex2[hi + 1];
22571
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
22572
+ }
22573
+ array[ai] = n1 * 16 + n2;
22574
+ }
22575
+ return array;
22576
+ }
22517
22577
  function utf8ToBytes5(str) {
22518
22578
  if (typeof str !== "string")
22519
22579
  throw new Error("string expected");
@@ -22525,6 +22585,21 @@ function toBytes4(data) {
22525
22585
  abytes(data);
22526
22586
  return data;
22527
22587
  }
22588
+ function concatBytes4(...arrays) {
22589
+ let sum = 0;
22590
+ for (let i4 = 0;i4 < arrays.length; i4++) {
22591
+ const a = arrays[i4];
22592
+ abytes(a);
22593
+ sum += a.length;
22594
+ }
22595
+ const res = new Uint8Array(sum);
22596
+ for (let i4 = 0, pad2 = 0;i4 < arrays.length; i4++) {
22597
+ const a = arrays[i4];
22598
+ res.set(a, pad2);
22599
+ pad2 += a.length;
22600
+ }
22601
+ return res;
22602
+ }
22528
22603
 
22529
22604
  class Hash3 {
22530
22605
  }
@@ -22536,8 +22611,22 @@ function createHasher(hashCons) {
22536
22611
  hashC.create = () => hashCons();
22537
22612
  return hashC;
22538
22613
  }
22614
+ function randomBytes4(bytesLength = 32) {
22615
+ if (crypto4 && typeof crypto4.getRandomValues === "function") {
22616
+ return crypto4.getRandomValues(new Uint8Array(bytesLength));
22617
+ }
22618
+ if (crypto4 && typeof crypto4.randomBytes === "function") {
22619
+ return Uint8Array.from(crypto4.randomBytes(bytesLength));
22620
+ }
22621
+ throw new Error("crypto.getRandomValues must be defined");
22622
+ }
22623
+ var hasHexBuiltin, hexes4, asciis2;
22539
22624
  var init_utils6 = __esm(() => {
22625
+ init_cryptoNode3();
22540
22626
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
22627
+ hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
22628
+ hexes4 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i4) => i4.toString(16).padStart(2, "0"));
22629
+ asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
22541
22630
  });
22542
22631
 
22543
22632
  // ../routstr-chat/node_modules/@noble/hashes/esm/_md.js
@@ -22559,7 +22648,7 @@ function Chi3(a, b, c) {
22559
22648
  function Maj3(a, b, c) {
22560
22649
  return a & b ^ a & c ^ b & c;
22561
22650
  }
22562
- var HashMD, SHA256_IV;
22651
+ var HashMD, SHA256_IV, SHA512_IV;
22563
22652
  var init__md = __esm(() => {
22564
22653
  init_utils6();
22565
22654
  HashMD = class HashMD extends Hash3 {
@@ -22662,12 +22751,57 @@ var init__md = __esm(() => {
22662
22751
  528734635,
22663
22752
  1541459225
22664
22753
  ]);
22754
+ SHA512_IV = /* @__PURE__ */ Uint32Array.from([
22755
+ 1779033703,
22756
+ 4089235720,
22757
+ 3144134277,
22758
+ 2227873595,
22759
+ 1013904242,
22760
+ 4271175723,
22761
+ 2773480762,
22762
+ 1595750129,
22763
+ 1359893119,
22764
+ 2917565137,
22765
+ 2600822924,
22766
+ 725511199,
22767
+ 528734635,
22768
+ 4215389547,
22769
+ 1541459225,
22770
+ 327033209
22771
+ ]);
22772
+ });
22773
+
22774
+ // ../routstr-chat/node_modules/@noble/hashes/esm/_u64.js
22775
+ function fromBig(n, le = false) {
22776
+ if (le)
22777
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
22778
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
22779
+ }
22780
+ function split(lst, le = false) {
22781
+ const len = lst.length;
22782
+ let Ah = new Uint32Array(len);
22783
+ let Al = new Uint32Array(len);
22784
+ for (let i4 = 0;i4 < len; i4++) {
22785
+ const { h, l } = fromBig(lst[i4], le);
22786
+ [Ah[i4], Al[i4]] = [h, l];
22787
+ }
22788
+ return [Ah, Al];
22789
+ }
22790
+ function add(Ah, Al, Bh, Bl) {
22791
+ const l = (Al >>> 0) + (Bl >>> 0);
22792
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
22793
+ }
22794
+ var U32_MASK64, _32n, shrSH = (h, _l, s) => h >>> s, shrSL = (h, l, s) => h << 32 - s | l >>> s, rotrSH = (h, l, s) => h >>> s | l << 32 - s, rotrSL = (h, l, s) => h << 32 - s | l >>> s, rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32, rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s, add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0), add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0, add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0), add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0, add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0), add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
22795
+ var init__u64 = __esm(() => {
22796
+ U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
22797
+ _32n = /* @__PURE__ */ BigInt(32);
22665
22798
  });
22666
22799
 
22667
22800
  // ../routstr-chat/node_modules/@noble/hashes/esm/sha2.js
22668
- var SHA256_K3, SHA256_W3, SHA2563, sha2563;
22801
+ var SHA256_K3, SHA256_W3, SHA2563, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, sha2563, sha512;
22669
22802
  var init_sha2 = __esm(() => {
22670
22803
  init__md();
22804
+ init__u64();
22671
22805
  init_utils6();
22672
22806
  SHA256_K3 = /* @__PURE__ */ Uint32Array.from([
22673
22807
  1116352408,
@@ -22805,7 +22939,203 @@ var init_sha2 = __esm(() => {
22805
22939
  clean(this.buffer);
22806
22940
  }
22807
22941
  };
22942
+ K512 = /* @__PURE__ */ (() => split([
22943
+ "0x428a2f98d728ae22",
22944
+ "0x7137449123ef65cd",
22945
+ "0xb5c0fbcfec4d3b2f",
22946
+ "0xe9b5dba58189dbbc",
22947
+ "0x3956c25bf348b538",
22948
+ "0x59f111f1b605d019",
22949
+ "0x923f82a4af194f9b",
22950
+ "0xab1c5ed5da6d8118",
22951
+ "0xd807aa98a3030242",
22952
+ "0x12835b0145706fbe",
22953
+ "0x243185be4ee4b28c",
22954
+ "0x550c7dc3d5ffb4e2",
22955
+ "0x72be5d74f27b896f",
22956
+ "0x80deb1fe3b1696b1",
22957
+ "0x9bdc06a725c71235",
22958
+ "0xc19bf174cf692694",
22959
+ "0xe49b69c19ef14ad2",
22960
+ "0xefbe4786384f25e3",
22961
+ "0x0fc19dc68b8cd5b5",
22962
+ "0x240ca1cc77ac9c65",
22963
+ "0x2de92c6f592b0275",
22964
+ "0x4a7484aa6ea6e483",
22965
+ "0x5cb0a9dcbd41fbd4",
22966
+ "0x76f988da831153b5",
22967
+ "0x983e5152ee66dfab",
22968
+ "0xa831c66d2db43210",
22969
+ "0xb00327c898fb213f",
22970
+ "0xbf597fc7beef0ee4",
22971
+ "0xc6e00bf33da88fc2",
22972
+ "0xd5a79147930aa725",
22973
+ "0x06ca6351e003826f",
22974
+ "0x142929670a0e6e70",
22975
+ "0x27b70a8546d22ffc",
22976
+ "0x2e1b21385c26c926",
22977
+ "0x4d2c6dfc5ac42aed",
22978
+ "0x53380d139d95b3df",
22979
+ "0x650a73548baf63de",
22980
+ "0x766a0abb3c77b2a8",
22981
+ "0x81c2c92e47edaee6",
22982
+ "0x92722c851482353b",
22983
+ "0xa2bfe8a14cf10364",
22984
+ "0xa81a664bbc423001",
22985
+ "0xc24b8b70d0f89791",
22986
+ "0xc76c51a30654be30",
22987
+ "0xd192e819d6ef5218",
22988
+ "0xd69906245565a910",
22989
+ "0xf40e35855771202a",
22990
+ "0x106aa07032bbd1b8",
22991
+ "0x19a4c116b8d2d0c8",
22992
+ "0x1e376c085141ab53",
22993
+ "0x2748774cdf8eeb99",
22994
+ "0x34b0bcb5e19b48a8",
22995
+ "0x391c0cb3c5c95a63",
22996
+ "0x4ed8aa4ae3418acb",
22997
+ "0x5b9cca4f7763e373",
22998
+ "0x682e6ff3d6b2b8a3",
22999
+ "0x748f82ee5defb2fc",
23000
+ "0x78a5636f43172f60",
23001
+ "0x84c87814a1f0ab72",
23002
+ "0x8cc702081a6439ec",
23003
+ "0x90befffa23631e28",
23004
+ "0xa4506cebde82bde9",
23005
+ "0xbef9a3f7b2c67915",
23006
+ "0xc67178f2e372532b",
23007
+ "0xca273eceea26619c",
23008
+ "0xd186b8c721c0c207",
23009
+ "0xeada7dd6cde0eb1e",
23010
+ "0xf57d4f7fee6ed178",
23011
+ "0x06f067aa72176fba",
23012
+ "0x0a637dc5a2c898a6",
23013
+ "0x113f9804bef90dae",
23014
+ "0x1b710b35131c471b",
23015
+ "0x28db77f523047d84",
23016
+ "0x32caab7b40c72493",
23017
+ "0x3c9ebe0a15c9bebc",
23018
+ "0x431d67c49c100d4c",
23019
+ "0x4cc5d4becb3e42b6",
23020
+ "0x597f299cfc657e2a",
23021
+ "0x5fcb6fab3ad6faec",
23022
+ "0x6c44198c4a475817"
23023
+ ].map((n) => BigInt(n))))();
23024
+ SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
23025
+ SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
23026
+ SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
23027
+ SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
23028
+ SHA512 = class SHA512 extends HashMD {
23029
+ constructor(outputLen = 64) {
23030
+ super(128, outputLen, 16, false);
23031
+ this.Ah = SHA512_IV[0] | 0;
23032
+ this.Al = SHA512_IV[1] | 0;
23033
+ this.Bh = SHA512_IV[2] | 0;
23034
+ this.Bl = SHA512_IV[3] | 0;
23035
+ this.Ch = SHA512_IV[4] | 0;
23036
+ this.Cl = SHA512_IV[5] | 0;
23037
+ this.Dh = SHA512_IV[6] | 0;
23038
+ this.Dl = SHA512_IV[7] | 0;
23039
+ this.Eh = SHA512_IV[8] | 0;
23040
+ this.El = SHA512_IV[9] | 0;
23041
+ this.Fh = SHA512_IV[10] | 0;
23042
+ this.Fl = SHA512_IV[11] | 0;
23043
+ this.Gh = SHA512_IV[12] | 0;
23044
+ this.Gl = SHA512_IV[13] | 0;
23045
+ this.Hh = SHA512_IV[14] | 0;
23046
+ this.Hl = SHA512_IV[15] | 0;
23047
+ }
23048
+ get() {
23049
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
23050
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
23051
+ }
23052
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
23053
+ this.Ah = Ah | 0;
23054
+ this.Al = Al | 0;
23055
+ this.Bh = Bh | 0;
23056
+ this.Bl = Bl | 0;
23057
+ this.Ch = Ch | 0;
23058
+ this.Cl = Cl | 0;
23059
+ this.Dh = Dh | 0;
23060
+ this.Dl = Dl | 0;
23061
+ this.Eh = Eh | 0;
23062
+ this.El = El | 0;
23063
+ this.Fh = Fh | 0;
23064
+ this.Fl = Fl | 0;
23065
+ this.Gh = Gh | 0;
23066
+ this.Gl = Gl | 0;
23067
+ this.Hh = Hh | 0;
23068
+ this.Hl = Hl | 0;
23069
+ }
23070
+ process(view, offset) {
23071
+ for (let i4 = 0;i4 < 16; i4++, offset += 4) {
23072
+ SHA512_W_H[i4] = view.getUint32(offset);
23073
+ SHA512_W_L[i4] = view.getUint32(offset += 4);
23074
+ }
23075
+ for (let i4 = 16;i4 < 80; i4++) {
23076
+ const W15h = SHA512_W_H[i4 - 15] | 0;
23077
+ const W15l = SHA512_W_L[i4 - 15] | 0;
23078
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
23079
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
23080
+ const W2h = SHA512_W_H[i4 - 2] | 0;
23081
+ const W2l = SHA512_W_L[i4 - 2] | 0;
23082
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
23083
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
23084
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i4 - 7], SHA512_W_L[i4 - 16]);
23085
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i4 - 7], SHA512_W_H[i4 - 16]);
23086
+ SHA512_W_H[i4] = SUMh | 0;
23087
+ SHA512_W_L[i4] = SUMl | 0;
23088
+ }
23089
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
23090
+ for (let i4 = 0;i4 < 80; i4++) {
23091
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
23092
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
23093
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
23094
+ const CHIl = El & Fl ^ ~El & Gl;
23095
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i4], SHA512_W_L[i4]);
23096
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i4], SHA512_W_H[i4]);
23097
+ const T1l = T1ll | 0;
23098
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
23099
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
23100
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
23101
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
23102
+ Hh = Gh | 0;
23103
+ Hl = Gl | 0;
23104
+ Gh = Fh | 0;
23105
+ Gl = Fl | 0;
23106
+ Fh = Eh | 0;
23107
+ Fl = El | 0;
23108
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
23109
+ Dh = Ch | 0;
23110
+ Dl = Cl | 0;
23111
+ Ch = Bh | 0;
23112
+ Cl = Bl | 0;
23113
+ Bh = Ah | 0;
23114
+ Bl = Al | 0;
23115
+ const All = add3L(T1l, sigma0l, MAJl);
23116
+ Ah = add3H(All, T1h, sigma0h, MAJh);
23117
+ Al = All | 0;
23118
+ }
23119
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
23120
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
23121
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
23122
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
23123
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
23124
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
23125
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
23126
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
23127
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
23128
+ }
23129
+ roundClean() {
23130
+ clean(SHA512_W_H, SHA512_W_L);
23131
+ }
23132
+ destroy() {
23133
+ clean(this.buffer);
23134
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
23135
+ }
23136
+ };
22808
23137
  sha2563 = /* @__PURE__ */ createHasher(() => new SHA2563);
23138
+ sha512 = /* @__PURE__ */ createHasher(() => new SHA512);
22809
23139
  });
22810
23140
 
22811
23141
  // ../routstr-chat/node_modules/applesauce-relay/dist/lib/negentropy.js
@@ -23542,9 +23872,9 @@ var require_bit_buffer = __commonJS((exports, module) => {
23542
23872
  const bufIndex = Math.floor(index / 8);
23543
23873
  return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1;
23544
23874
  },
23545
- put: function(num, length) {
23875
+ put: function(num2, length) {
23546
23876
  for (let i4 = 0;i4 < length; i4++) {
23547
- this.putBit((num >>> length - i4 - 1 & 1) === 1);
23877
+ this.putBit((num2 >>> length - i4 - 1 & 1) === 1);
23548
23878
  }
23549
23879
  },
23550
23880
  getLengthInBits: function() {
@@ -24702,15 +25032,15 @@ var require_dijkstra = __commonJS((exports, module) => {
24702
25032
  },
24703
25033
  PriorityQueue: {
24704
25034
  make: function(opts) {
24705
- var T = dijkstra.PriorityQueue, t = {}, key;
25035
+ var T2 = dijkstra.PriorityQueue, t = {}, key;
24706
25036
  opts = opts || {};
24707
- for (key in T) {
24708
- if (T.hasOwnProperty(key)) {
24709
- t[key] = T[key];
25037
+ for (key in T2) {
25038
+ if (T2.hasOwnProperty(key)) {
25039
+ t[key] = T2[key];
24710
25040
  }
24711
25041
  }
24712
25042
  t.queue = [];
24713
- t.sorter = opts.sorter || T.default_sorter;
25043
+ t.sorter = opts.sorter || T2.default_sorter;
24714
25044
  return t;
24715
25045
  },
24716
25046
  default_sorter: function(a, b) {
@@ -24981,34 +25311,34 @@ var require_qrcode = __commonJS((exports) => {
24981
25311
  function setupVersionInfo(matrix, version) {
24982
25312
  const size = matrix.size;
24983
25313
  const bits = Version.getEncodedBits(version);
24984
- let row, col, mod2;
25314
+ let row, col, mod3;
24985
25315
  for (let i4 = 0;i4 < 18; i4++) {
24986
25316
  row = Math.floor(i4 / 3);
24987
25317
  col = i4 % 3 + size - 8 - 3;
24988
- mod2 = (bits >> i4 & 1) === 1;
24989
- matrix.set(row, col, mod2, true);
24990
- matrix.set(col, row, mod2, true);
25318
+ mod3 = (bits >> i4 & 1) === 1;
25319
+ matrix.set(row, col, mod3, true);
25320
+ matrix.set(col, row, mod3, true);
24991
25321
  }
24992
25322
  }
24993
25323
  function setupFormatInfo(matrix, errorCorrectionLevel, maskPattern) {
24994
25324
  const size = matrix.size;
24995
25325
  const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
24996
- let i4, mod2;
25326
+ let i4, mod3;
24997
25327
  for (i4 = 0;i4 < 15; i4++) {
24998
- mod2 = (bits >> i4 & 1) === 1;
25328
+ mod3 = (bits >> i4 & 1) === 1;
24999
25329
  if (i4 < 6) {
25000
- matrix.set(i4, 8, mod2, true);
25330
+ matrix.set(i4, 8, mod3, true);
25001
25331
  } else if (i4 < 8) {
25002
- matrix.set(i4 + 1, 8, mod2, true);
25332
+ matrix.set(i4 + 1, 8, mod3, true);
25003
25333
  } else {
25004
- matrix.set(size - 15 + i4, 8, mod2, true);
25334
+ matrix.set(size - 15 + i4, 8, mod3, true);
25005
25335
  }
25006
25336
  if (i4 < 8) {
25007
- matrix.set(8, size - i4 - 1, mod2, true);
25337
+ matrix.set(8, size - i4 - 1, mod3, true);
25008
25338
  } else if (i4 < 9) {
25009
- matrix.set(8, 15 - i4 - 1 + 1, mod2, true);
25339
+ matrix.set(8, 15 - i4 - 1 + 1, mod3, true);
25010
25340
  } else {
25011
- matrix.set(8, 15 - i4 - 1, mod2, true);
25341
+ matrix.set(8, 15 - i4 - 1, mod3, true);
25012
25342
  }
25013
25343
  }
25014
25344
  matrix.set(size - 8, 8, 1, true);
@@ -25915,7 +26245,7 @@ var require_bitmapper = __commonJS((exports) => {
25915
26245
  function bitRetriever(data, depth) {
25916
26246
  let leftOver = [];
25917
26247
  let i4 = 0;
25918
- function split() {
26248
+ function split2() {
25919
26249
  if (i4 === data.length) {
25920
26250
  throw new Error("Ran out of data");
25921
26251
  }
@@ -25958,7 +26288,7 @@ var require_bitmapper = __commonJS((exports) => {
25958
26288
  return {
25959
26289
  get: function(count) {
25960
26290
  while (leftOver.length < count) {
25961
- split();
26291
+ split2();
25962
26292
  }
25963
26293
  let returner = leftOver.slice(0, count);
25964
26294
  leftOver = leftOver.slice(count);
@@ -27067,16 +27397,16 @@ var require_png = __commonJS((exports) => {
27067
27397
 
27068
27398
  // node_modules/qrcode/lib/renderer/utils.js
27069
27399
  var require_utils2 = __commonJS((exports) => {
27070
- function hex2rgba(hex2) {
27071
- if (typeof hex2 === "number") {
27072
- hex2 = hex2.toString();
27400
+ function hex2rgba(hex3) {
27401
+ if (typeof hex3 === "number") {
27402
+ hex3 = hex3.toString();
27073
27403
  }
27074
- if (typeof hex2 !== "string") {
27404
+ if (typeof hex3 !== "string") {
27075
27405
  throw new Error("Color should be defined as hex string");
27076
27406
  }
27077
- let hexCode = hex2.slice().replace("#", "").split("");
27407
+ let hexCode = hex3.slice().replace("#", "").split("");
27078
27408
  if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
27079
- throw new Error("Invalid hex color: " + hex2);
27409
+ throw new Error("Invalid hex color: " + hex3);
27080
27410
  }
27081
27411
  if (hexCode.length === 3 || hexCode.length === 4) {
27082
27412
  hexCode = Array.prototype.concat.apply([], hexCode.map(function(c) {
@@ -27569,7 +27899,7 @@ var require_browser2 = __commonJS((exports) => {
27569
27899
  exports.create = QRCode.create;
27570
27900
  exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render);
27571
27901
  exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL);
27572
- exports.toString = renderCanvas.bind(null, function(data, _, opts) {
27902
+ exports.toString = renderCanvas.bind(null, function(data, _2, opts) {
27573
27903
  return SvgRenderer.render(data, opts);
27574
27904
  });
27575
27905
  });
@@ -27994,8 +28324,8 @@ function renderBox(lines, width, title) {
27994
28324
  result.push(`\u250C${"\u2500".repeat(Math.max(0, width - 2))}\u2510`);
27995
28325
  }
27996
28326
  for (const line of lines) {
27997
- const padding2 = Math.max(0, innerWidth - stripAnsi(line).length);
27998
- result.push(`\u2502 ${line}${" ".repeat(padding2)} \u2502`);
28327
+ const padding3 = Math.max(0, innerWidth - stripAnsi(line).length);
28328
+ result.push(`\u2502 ${line}${" ".repeat(padding3)} \u2502`);
27999
28329
  }
28000
28330
  result.push(`\u2514${"\u2500".repeat(Math.max(0, width - 2))}\u2518`);
28001
28331
  return result.join(`
@@ -30392,6 +30722,4324 @@ init_observable();
30392
30722
  // ../routstr-chat/sdk/dist/index.mjs
30393
30723
  init_dist();
30394
30724
 
30725
+ // ../routstr-chat/node_modules/@noble/curves/esm/secp256k1.js
30726
+ init_sha2();
30727
+ init_utils6();
30728
+
30729
+ // ../routstr-chat/node_modules/@noble/hashes/esm/hmac.js
30730
+ init_utils6();
30731
+
30732
+ class HMAC3 extends Hash3 {
30733
+ constructor(hash3, _key) {
30734
+ super();
30735
+ this.finished = false;
30736
+ this.destroyed = false;
30737
+ ahash(hash3);
30738
+ const key = toBytes4(_key);
30739
+ this.iHash = hash3.create();
30740
+ if (typeof this.iHash.update !== "function")
30741
+ throw new Error("Expected instance of class which extends utils.Hash");
30742
+ this.blockLen = this.iHash.blockLen;
30743
+ this.outputLen = this.iHash.outputLen;
30744
+ const blockLen = this.blockLen;
30745
+ const pad2 = new Uint8Array(blockLen);
30746
+ pad2.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
30747
+ for (let i4 = 0;i4 < pad2.length; i4++)
30748
+ pad2[i4] ^= 54;
30749
+ this.iHash.update(pad2);
30750
+ this.oHash = hash3.create();
30751
+ for (let i4 = 0;i4 < pad2.length; i4++)
30752
+ pad2[i4] ^= 54 ^ 92;
30753
+ this.oHash.update(pad2);
30754
+ clean(pad2);
30755
+ }
30756
+ update(buf) {
30757
+ aexists(this);
30758
+ this.iHash.update(buf);
30759
+ return this;
30760
+ }
30761
+ digestInto(out) {
30762
+ aexists(this);
30763
+ abytes(out, this.outputLen);
30764
+ this.finished = true;
30765
+ this.iHash.digestInto(out);
30766
+ this.oHash.update(out);
30767
+ this.oHash.digestInto(out);
30768
+ this.destroy();
30769
+ }
30770
+ digest() {
30771
+ const out = new Uint8Array(this.oHash.outputLen);
30772
+ this.digestInto(out);
30773
+ return out;
30774
+ }
30775
+ _cloneInto(to) {
30776
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
30777
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
30778
+ to = to;
30779
+ to.finished = finished;
30780
+ to.destroyed = destroyed;
30781
+ to.blockLen = blockLen;
30782
+ to.outputLen = outputLen;
30783
+ to.oHash = oHash._cloneInto(to.oHash);
30784
+ to.iHash = iHash._cloneInto(to.iHash);
30785
+ return to;
30786
+ }
30787
+ clone() {
30788
+ return this._cloneInto();
30789
+ }
30790
+ destroy() {
30791
+ this.destroyed = true;
30792
+ this.oHash.destroy();
30793
+ this.iHash.destroy();
30794
+ }
30795
+ }
30796
+ var hmac3 = (hash3, key, message) => new HMAC3(hash3, key).update(message).digest();
30797
+ hmac3.create = (hash3, key) => new HMAC3(hash3, key);
30798
+
30799
+ // ../routstr-chat/node_modules/@noble/curves/esm/abstract/weierstrass.js
30800
+ init_utils6();
30801
+
30802
+ // ../routstr-chat/node_modules/@noble/curves/esm/utils.js
30803
+ init_utils6();
30804
+ init_utils6();
30805
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
30806
+ var _0n6 = /* @__PURE__ */ BigInt(0);
30807
+ var _1n6 = /* @__PURE__ */ BigInt(1);
30808
+ function _abool2(value, title = "") {
30809
+ if (typeof value !== "boolean") {
30810
+ const prefix = title && `"${title}"`;
30811
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
30812
+ }
30813
+ return value;
30814
+ }
30815
+ function _abytes2(value, length, title = "") {
30816
+ const bytes4 = isBytes2(value);
30817
+ const len = value?.length;
30818
+ const needsLen = length !== undefined;
30819
+ if (!bytes4 || needsLen && len !== length) {
30820
+ const prefix = title && `"${title}" `;
30821
+ const ofLen = needsLen ? ` of length ${length}` : "";
30822
+ const got = bytes4 ? `length=${len}` : `type=${typeof value}`;
30823
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
30824
+ }
30825
+ return value;
30826
+ }
30827
+ function numberToHexUnpadded2(num) {
30828
+ const hex2 = num.toString(16);
30829
+ return hex2.length & 1 ? "0" + hex2 : hex2;
30830
+ }
30831
+ function hexToNumber2(hex2) {
30832
+ if (typeof hex2 !== "string")
30833
+ throw new Error("hex string expected, got " + typeof hex2);
30834
+ return hex2 === "" ? _0n6 : BigInt("0x" + hex2);
30835
+ }
30836
+ function bytesToNumberBE2(bytes4) {
30837
+ return hexToNumber2(bytesToHex4(bytes4));
30838
+ }
30839
+ function bytesToNumberLE2(bytes4) {
30840
+ abytes(bytes4);
30841
+ return hexToNumber2(bytesToHex4(Uint8Array.from(bytes4).reverse()));
30842
+ }
30843
+ function numberToBytesBE2(n, len) {
30844
+ return hexToBytes4(n.toString(16).padStart(len * 2, "0"));
30845
+ }
30846
+ function numberToBytesLE2(n, len) {
30847
+ return numberToBytesBE2(n, len).reverse();
30848
+ }
30849
+ function ensureBytes2(title, hex2, expectedLength) {
30850
+ let res;
30851
+ if (typeof hex2 === "string") {
30852
+ try {
30853
+ res = hexToBytes4(hex2);
30854
+ } catch (e) {
30855
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
30856
+ }
30857
+ } else if (isBytes2(hex2)) {
30858
+ res = Uint8Array.from(hex2);
30859
+ } else {
30860
+ throw new Error(title + " must be hex string or Uint8Array");
30861
+ }
30862
+ const len = res.length;
30863
+ if (typeof expectedLength === "number" && len !== expectedLength)
30864
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
30865
+ return res;
30866
+ }
30867
+ var isPosBig = (n) => typeof n === "bigint" && _0n6 <= n;
30868
+ function inRange(n, min, max) {
30869
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
30870
+ }
30871
+ function aInRange(title, n, min, max) {
30872
+ if (!inRange(n, min, max))
30873
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
30874
+ }
30875
+ function bitLen2(n) {
30876
+ let len;
30877
+ for (len = 0;n > _0n6; n >>= _1n6, len += 1)
30878
+ ;
30879
+ return len;
30880
+ }
30881
+ var bitMask2 = (n) => (_1n6 << BigInt(n)) - _1n6;
30882
+ function createHmacDrbg2(hashLen, qByteLen, hmacFn) {
30883
+ if (typeof hashLen !== "number" || hashLen < 2)
30884
+ throw new Error("hashLen must be a number");
30885
+ if (typeof qByteLen !== "number" || qByteLen < 2)
30886
+ throw new Error("qByteLen must be a number");
30887
+ if (typeof hmacFn !== "function")
30888
+ throw new Error("hmacFn must be a function");
30889
+ const u8n2 = (len) => new Uint8Array(len);
30890
+ const u8of = (byte) => Uint8Array.of(byte);
30891
+ let v = u8n2(hashLen);
30892
+ let k = u8n2(hashLen);
30893
+ let i4 = 0;
30894
+ const reset = () => {
30895
+ v.fill(1);
30896
+ k.fill(0);
30897
+ i4 = 0;
30898
+ };
30899
+ const h = (...b) => hmacFn(k, v, ...b);
30900
+ const reseed = (seed = u8n2(0)) => {
30901
+ k = h(u8of(0), seed);
30902
+ v = h();
30903
+ if (seed.length === 0)
30904
+ return;
30905
+ k = h(u8of(1), seed);
30906
+ v = h();
30907
+ };
30908
+ const gen = () => {
30909
+ if (i4++ >= 1000)
30910
+ throw new Error("drbg: tried 1000 values");
30911
+ let len = 0;
30912
+ const out = [];
30913
+ while (len < qByteLen) {
30914
+ v = h();
30915
+ const sl = v.slice();
30916
+ out.push(sl);
30917
+ len += v.length;
30918
+ }
30919
+ return concatBytes4(...out);
30920
+ };
30921
+ const genUntil = (seed, pred) => {
30922
+ reset();
30923
+ reseed(seed);
30924
+ let res = undefined;
30925
+ while (!(res = pred(gen())))
30926
+ reseed();
30927
+ reset();
30928
+ return res;
30929
+ };
30930
+ return genUntil;
30931
+ }
30932
+ function _validateObject(object, fields, optFields = {}) {
30933
+ if (!object || typeof object !== "object")
30934
+ throw new Error("expected valid options object");
30935
+ function checkField(fieldName, expectedType, isOpt) {
30936
+ const val = object[fieldName];
30937
+ if (isOpt && val === undefined)
30938
+ return;
30939
+ const current = typeof val;
30940
+ if (current !== expectedType || val === null)
30941
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
30942
+ }
30943
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
30944
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
30945
+ }
30946
+ function memoized(fn) {
30947
+ const map13 = new WeakMap;
30948
+ return (arg, ...args) => {
30949
+ const val = map13.get(arg);
30950
+ if (val !== undefined)
30951
+ return val;
30952
+ const computed = fn(arg, ...args);
30953
+ map13.set(arg, computed);
30954
+ return computed;
30955
+ };
30956
+ }
30957
+
30958
+ // ../routstr-chat/node_modules/@noble/curves/esm/abstract/modular.js
30959
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
30960
+ var _0n7 = BigInt(0);
30961
+ var _1n7 = BigInt(1);
30962
+ var _2n5 = /* @__PURE__ */ BigInt(2);
30963
+ var _3n3 = /* @__PURE__ */ BigInt(3);
30964
+ var _4n3 = /* @__PURE__ */ BigInt(4);
30965
+ var _5n2 = /* @__PURE__ */ BigInt(5);
30966
+ var _7n = /* @__PURE__ */ BigInt(7);
30967
+ var _8n2 = /* @__PURE__ */ BigInt(8);
30968
+ var _9n2 = /* @__PURE__ */ BigInt(9);
30969
+ var _16n2 = /* @__PURE__ */ BigInt(16);
30970
+ function mod2(a, b) {
30971
+ const result = a % b;
30972
+ return result >= _0n7 ? result : b + result;
30973
+ }
30974
+ function pow22(x, power, modulo) {
30975
+ let res = x;
30976
+ while (power-- > _0n7) {
30977
+ res *= res;
30978
+ res %= modulo;
30979
+ }
30980
+ return res;
30981
+ }
30982
+ function invert2(number4, modulo) {
30983
+ if (number4 === _0n7)
30984
+ throw new Error("invert: expected non-zero number");
30985
+ if (modulo <= _0n7)
30986
+ throw new Error("invert: expected positive modulus, got " + modulo);
30987
+ let a = mod2(number4, modulo);
30988
+ let b = modulo;
30989
+ let x = _0n7, y = _1n7, u = _1n7, v = _0n7;
30990
+ while (a !== _0n7) {
30991
+ const q = b / a;
30992
+ const r = b % a;
30993
+ const m = x - u * q;
30994
+ const n = y - v * q;
30995
+ b = a, a = r, x = u, y = v, u = m, v = n;
30996
+ }
30997
+ const gcd2 = b;
30998
+ if (gcd2 !== _1n7)
30999
+ throw new Error("invert: does not exist");
31000
+ return mod2(x, modulo);
31001
+ }
31002
+ function assertIsSquare(Fp2, root, n) {
31003
+ if (!Fp2.eql(Fp2.sqr(root), n))
31004
+ throw new Error("Cannot find square root");
31005
+ }
31006
+ function sqrt3mod4(Fp2, n) {
31007
+ const p1div4 = (Fp2.ORDER + _1n7) / _4n3;
31008
+ const root = Fp2.pow(n, p1div4);
31009
+ assertIsSquare(Fp2, root, n);
31010
+ return root;
31011
+ }
31012
+ function sqrt5mod8(Fp2, n) {
31013
+ const p5div8 = (Fp2.ORDER - _5n2) / _8n2;
31014
+ const n2 = Fp2.mul(n, _2n5);
31015
+ const v = Fp2.pow(n2, p5div8);
31016
+ const nv = Fp2.mul(n, v);
31017
+ const i4 = Fp2.mul(Fp2.mul(nv, _2n5), v);
31018
+ const root = Fp2.mul(nv, Fp2.sub(i4, Fp2.ONE));
31019
+ assertIsSquare(Fp2, root, n);
31020
+ return root;
31021
+ }
31022
+ function sqrt9mod16(P) {
31023
+ const Fp_ = Field2(P);
31024
+ const tn = tonelliShanks2(P);
31025
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
31026
+ const c2 = tn(Fp_, c1);
31027
+ const c3 = tn(Fp_, Fp_.neg(c1));
31028
+ const c4 = (P + _7n) / _16n2;
31029
+ return (Fp2, n) => {
31030
+ let tv1 = Fp2.pow(n, c4);
31031
+ let tv2 = Fp2.mul(tv1, c1);
31032
+ const tv3 = Fp2.mul(tv1, c2);
31033
+ const tv4 = Fp2.mul(tv1, c3);
31034
+ const e1 = Fp2.eql(Fp2.sqr(tv2), n);
31035
+ const e2 = Fp2.eql(Fp2.sqr(tv3), n);
31036
+ tv1 = Fp2.cmov(tv1, tv2, e1);
31037
+ tv2 = Fp2.cmov(tv4, tv3, e2);
31038
+ const e3 = Fp2.eql(Fp2.sqr(tv2), n);
31039
+ const root = Fp2.cmov(tv1, tv2, e3);
31040
+ assertIsSquare(Fp2, root, n);
31041
+ return root;
31042
+ };
31043
+ }
31044
+ function tonelliShanks2(P) {
31045
+ if (P < _3n3)
31046
+ throw new Error("sqrt is not defined for small field");
31047
+ let Q = P - _1n7;
31048
+ let S = 0;
31049
+ while (Q % _2n5 === _0n7) {
31050
+ Q /= _2n5;
31051
+ S++;
31052
+ }
31053
+ let Z = _2n5;
31054
+ const _Fp = Field2(P);
31055
+ while (FpLegendre(_Fp, Z) === 1) {
31056
+ if (Z++ > 1000)
31057
+ throw new Error("Cannot find square root: probably non-prime P");
31058
+ }
31059
+ if (S === 1)
31060
+ return sqrt3mod4;
31061
+ let cc = _Fp.pow(Z, Q);
31062
+ const Q1div2 = (Q + _1n7) / _2n5;
31063
+ return function tonelliSlow(Fp2, n) {
31064
+ if (Fp2.is0(n))
31065
+ return n;
31066
+ if (FpLegendre(Fp2, n) !== 1)
31067
+ throw new Error("Cannot find square root");
31068
+ let M = S;
31069
+ let c = Fp2.mul(Fp2.ONE, cc);
31070
+ let t = Fp2.pow(n, Q);
31071
+ let R = Fp2.pow(n, Q1div2);
31072
+ while (!Fp2.eql(t, Fp2.ONE)) {
31073
+ if (Fp2.is0(t))
31074
+ return Fp2.ZERO;
31075
+ let i4 = 1;
31076
+ let t_tmp = Fp2.sqr(t);
31077
+ while (!Fp2.eql(t_tmp, Fp2.ONE)) {
31078
+ i4++;
31079
+ t_tmp = Fp2.sqr(t_tmp);
31080
+ if (i4 === M)
31081
+ throw new Error("Cannot find square root");
31082
+ }
31083
+ const exponent = _1n7 << BigInt(M - i4 - 1);
31084
+ const b = Fp2.pow(c, exponent);
31085
+ M = i4;
31086
+ c = Fp2.sqr(b);
31087
+ t = Fp2.mul(t, c);
31088
+ R = Fp2.mul(R, b);
31089
+ }
31090
+ return R;
31091
+ };
31092
+ }
31093
+ function FpSqrt2(P) {
31094
+ if (P % _4n3 === _3n3)
31095
+ return sqrt3mod4;
31096
+ if (P % _8n2 === _5n2)
31097
+ return sqrt5mod8;
31098
+ if (P % _16n2 === _9n2)
31099
+ return sqrt9mod16(P);
31100
+ return tonelliShanks2(P);
31101
+ }
31102
+ var FIELD_FIELDS2 = [
31103
+ "create",
31104
+ "isValid",
31105
+ "is0",
31106
+ "neg",
31107
+ "inv",
31108
+ "sqrt",
31109
+ "sqr",
31110
+ "eql",
31111
+ "add",
31112
+ "sub",
31113
+ "mul",
31114
+ "pow",
31115
+ "div",
31116
+ "addN",
31117
+ "subN",
31118
+ "mulN",
31119
+ "sqrN"
31120
+ ];
31121
+ function validateField2(field) {
31122
+ const initial = {
31123
+ ORDER: "bigint",
31124
+ MASK: "bigint",
31125
+ BYTES: "number",
31126
+ BITS: "number"
31127
+ };
31128
+ const opts = FIELD_FIELDS2.reduce((map13, val) => {
31129
+ map13[val] = "function";
31130
+ return map13;
31131
+ }, initial);
31132
+ _validateObject(field, opts);
31133
+ return field;
31134
+ }
31135
+ function FpPow2(Fp2, num, power) {
31136
+ if (power < _0n7)
31137
+ throw new Error("invalid exponent, negatives unsupported");
31138
+ if (power === _0n7)
31139
+ return Fp2.ONE;
31140
+ if (power === _1n7)
31141
+ return num;
31142
+ let p = Fp2.ONE;
31143
+ let d = num;
31144
+ while (power > _0n7) {
31145
+ if (power & _1n7)
31146
+ p = Fp2.mul(p, d);
31147
+ d = Fp2.sqr(d);
31148
+ power >>= _1n7;
31149
+ }
31150
+ return p;
31151
+ }
31152
+ function FpInvertBatch2(Fp2, nums, passZero = false) {
31153
+ const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : undefined);
31154
+ const multipliedAcc = nums.reduce((acc, num, i4) => {
31155
+ if (Fp2.is0(num))
31156
+ return acc;
31157
+ inverted[i4] = acc;
31158
+ return Fp2.mul(acc, num);
31159
+ }, Fp2.ONE);
31160
+ const invertedAcc = Fp2.inv(multipliedAcc);
31161
+ nums.reduceRight((acc, num, i4) => {
31162
+ if (Fp2.is0(num))
31163
+ return acc;
31164
+ inverted[i4] = Fp2.mul(acc, inverted[i4]);
31165
+ return Fp2.mul(acc, num);
31166
+ }, invertedAcc);
31167
+ return inverted;
31168
+ }
31169
+ function FpLegendre(Fp2, n) {
31170
+ const p1mod2 = (Fp2.ORDER - _1n7) / _2n5;
31171
+ const powered = Fp2.pow(n, p1mod2);
31172
+ const yes = Fp2.eql(powered, Fp2.ONE);
31173
+ const zero = Fp2.eql(powered, Fp2.ZERO);
31174
+ const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
31175
+ if (!yes && !zero && !no)
31176
+ throw new Error("invalid Legendre symbol result");
31177
+ return yes ? 1 : zero ? 0 : -1;
31178
+ }
31179
+ function nLength2(n, nBitLength) {
31180
+ if (nBitLength !== undefined)
31181
+ anumber(nBitLength);
31182
+ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
31183
+ const nByteLength = Math.ceil(_nBitLength / 8);
31184
+ return { nBitLength: _nBitLength, nByteLength };
31185
+ }
31186
+ function Field2(ORDER, bitLenOrOpts, isLE4 = false, opts = {}) {
31187
+ if (ORDER <= _0n7)
31188
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
31189
+ let _nbitLength = undefined;
31190
+ let _sqrt = undefined;
31191
+ let modFromBytes = false;
31192
+ let allowedLengths = undefined;
31193
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
31194
+ if (opts.sqrt || isLE4)
31195
+ throw new Error("cannot specify opts in two arguments");
31196
+ const _opts = bitLenOrOpts;
31197
+ if (_opts.BITS)
31198
+ _nbitLength = _opts.BITS;
31199
+ if (_opts.sqrt)
31200
+ _sqrt = _opts.sqrt;
31201
+ if (typeof _opts.isLE === "boolean")
31202
+ isLE4 = _opts.isLE;
31203
+ if (typeof _opts.modFromBytes === "boolean")
31204
+ modFromBytes = _opts.modFromBytes;
31205
+ allowedLengths = _opts.allowedLengths;
31206
+ } else {
31207
+ if (typeof bitLenOrOpts === "number")
31208
+ _nbitLength = bitLenOrOpts;
31209
+ if (opts.sqrt)
31210
+ _sqrt = opts.sqrt;
31211
+ }
31212
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength2(ORDER, _nbitLength);
31213
+ if (BYTES > 2048)
31214
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
31215
+ let sqrtP;
31216
+ const f = Object.freeze({
31217
+ ORDER,
31218
+ isLE: isLE4,
31219
+ BITS,
31220
+ BYTES,
31221
+ MASK: bitMask2(BITS),
31222
+ ZERO: _0n7,
31223
+ ONE: _1n7,
31224
+ allowedLengths,
31225
+ create: (num) => mod2(num, ORDER),
31226
+ isValid: (num) => {
31227
+ if (typeof num !== "bigint")
31228
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
31229
+ return _0n7 <= num && num < ORDER;
31230
+ },
31231
+ is0: (num) => num === _0n7,
31232
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
31233
+ isOdd: (num) => (num & _1n7) === _1n7,
31234
+ neg: (num) => mod2(-num, ORDER),
31235
+ eql: (lhs, rhs) => lhs === rhs,
31236
+ sqr: (num) => mod2(num * num, ORDER),
31237
+ add: (lhs, rhs) => mod2(lhs + rhs, ORDER),
31238
+ sub: (lhs, rhs) => mod2(lhs - rhs, ORDER),
31239
+ mul: (lhs, rhs) => mod2(lhs * rhs, ORDER),
31240
+ pow: (num, power) => FpPow2(f, num, power),
31241
+ div: (lhs, rhs) => mod2(lhs * invert2(rhs, ORDER), ORDER),
31242
+ sqrN: (num) => num * num,
31243
+ addN: (lhs, rhs) => lhs + rhs,
31244
+ subN: (lhs, rhs) => lhs - rhs,
31245
+ mulN: (lhs, rhs) => lhs * rhs,
31246
+ inv: (num) => invert2(num, ORDER),
31247
+ sqrt: _sqrt || ((n) => {
31248
+ if (!sqrtP)
31249
+ sqrtP = FpSqrt2(ORDER);
31250
+ return sqrtP(f, n);
31251
+ }),
31252
+ toBytes: (num) => isLE4 ? numberToBytesLE2(num, BYTES) : numberToBytesBE2(num, BYTES),
31253
+ fromBytes: (bytes4, skipValidation = true) => {
31254
+ if (allowedLengths) {
31255
+ if (!allowedLengths.includes(bytes4.length) || bytes4.length > BYTES) {
31256
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes4.length);
31257
+ }
31258
+ const padded = new Uint8Array(BYTES);
31259
+ padded.set(bytes4, isLE4 ? 0 : padded.length - bytes4.length);
31260
+ bytes4 = padded;
31261
+ }
31262
+ if (bytes4.length !== BYTES)
31263
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes4.length);
31264
+ let scalar = isLE4 ? bytesToNumberLE2(bytes4) : bytesToNumberBE2(bytes4);
31265
+ if (modFromBytes)
31266
+ scalar = mod2(scalar, ORDER);
31267
+ if (!skipValidation) {
31268
+ if (!f.isValid(scalar))
31269
+ throw new Error("invalid field element: outside of range 0..ORDER");
31270
+ }
31271
+ return scalar;
31272
+ },
31273
+ invertBatch: (lst) => FpInvertBatch2(f, lst),
31274
+ cmov: (a, b, c) => c ? b : a
31275
+ });
31276
+ return Object.freeze(f);
31277
+ }
31278
+ function getFieldBytesLength2(fieldOrder) {
31279
+ if (typeof fieldOrder !== "bigint")
31280
+ throw new Error("field order must be bigint");
31281
+ const bitLength = fieldOrder.toString(2).length;
31282
+ return Math.ceil(bitLength / 8);
31283
+ }
31284
+ function getMinHashLength2(fieldOrder) {
31285
+ const length = getFieldBytesLength2(fieldOrder);
31286
+ return length + Math.ceil(length / 2);
31287
+ }
31288
+ function mapHashToField2(key, fieldOrder, isLE4 = false) {
31289
+ const len = key.length;
31290
+ const fieldLen = getFieldBytesLength2(fieldOrder);
31291
+ const minLen = getMinHashLength2(fieldOrder);
31292
+ if (len < 16 || len < minLen || len > 1024)
31293
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
31294
+ const num = isLE4 ? bytesToNumberLE2(key) : bytesToNumberBE2(key);
31295
+ const reduced = mod2(num, fieldOrder - _1n7) + _1n7;
31296
+ return isLE4 ? numberToBytesLE2(reduced, fieldLen) : numberToBytesBE2(reduced, fieldLen);
31297
+ }
31298
+
31299
+ // ../routstr-chat/node_modules/@noble/curves/esm/abstract/curve.js
31300
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
31301
+ var _0n8 = BigInt(0);
31302
+ var _1n8 = BigInt(1);
31303
+ function negateCt(condition, item) {
31304
+ const neg = item.negate();
31305
+ return condition ? neg : item;
31306
+ }
31307
+ function normalizeZ(c, points) {
31308
+ const invertedZs = FpInvertBatch2(c.Fp, points.map((p) => p.Z));
31309
+ return points.map((p, i4) => c.fromAffine(p.toAffine(invertedZs[i4])));
31310
+ }
31311
+ function validateW(W, bits) {
31312
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
31313
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
31314
+ }
31315
+ function calcWOpts(W, scalarBits) {
31316
+ validateW(W, scalarBits);
31317
+ const windows = Math.ceil(scalarBits / W) + 1;
31318
+ const windowSize = 2 ** (W - 1);
31319
+ const maxNumber = 2 ** W;
31320
+ const mask = bitMask2(W);
31321
+ const shiftBy = BigInt(W);
31322
+ return { windows, windowSize, mask, maxNumber, shiftBy };
31323
+ }
31324
+ function calcOffsets(n, window2, wOpts) {
31325
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
31326
+ let wbits = Number(n & mask);
31327
+ let nextN = n >> shiftBy;
31328
+ if (wbits > windowSize) {
31329
+ wbits -= maxNumber;
31330
+ nextN += _1n8;
31331
+ }
31332
+ const offsetStart = window2 * windowSize;
31333
+ const offset = offsetStart + Math.abs(wbits) - 1;
31334
+ const isZero = wbits === 0;
31335
+ const isNeg = wbits < 0;
31336
+ const isNegF = window2 % 2 !== 0;
31337
+ const offsetF = offsetStart;
31338
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
31339
+ }
31340
+ function validateMSMPoints(points, c) {
31341
+ if (!Array.isArray(points))
31342
+ throw new Error("array expected");
31343
+ points.forEach((p, i4) => {
31344
+ if (!(p instanceof c))
31345
+ throw new Error("invalid point at index " + i4);
31346
+ });
31347
+ }
31348
+ function validateMSMScalars(scalars, field) {
31349
+ if (!Array.isArray(scalars))
31350
+ throw new Error("array of scalars expected");
31351
+ scalars.forEach((s, i4) => {
31352
+ if (!field.isValid(s))
31353
+ throw new Error("invalid scalar at index " + i4);
31354
+ });
31355
+ }
31356
+ var pointPrecomputes = new WeakMap;
31357
+ var pointWindowSizes = new WeakMap;
31358
+ function getW(P) {
31359
+ return pointWindowSizes.get(P) || 1;
31360
+ }
31361
+ function assert0(n) {
31362
+ if (n !== _0n8)
31363
+ throw new Error("invalid wNAF");
31364
+ }
31365
+
31366
+ class wNAF2 {
31367
+ constructor(Point2, bits) {
31368
+ this.BASE = Point2.BASE;
31369
+ this.ZERO = Point2.ZERO;
31370
+ this.Fn = Point2.Fn;
31371
+ this.bits = bits;
31372
+ }
31373
+ _unsafeLadder(elm, n, p = this.ZERO) {
31374
+ let d = elm;
31375
+ while (n > _0n8) {
31376
+ if (n & _1n8)
31377
+ p = p.add(d);
31378
+ d = d.double();
31379
+ n >>= _1n8;
31380
+ }
31381
+ return p;
31382
+ }
31383
+ precomputeWindow(point, W) {
31384
+ const { windows, windowSize } = calcWOpts(W, this.bits);
31385
+ const points = [];
31386
+ let p = point;
31387
+ let base2 = p;
31388
+ for (let window2 = 0;window2 < windows; window2++) {
31389
+ base2 = p;
31390
+ points.push(base2);
31391
+ for (let i4 = 1;i4 < windowSize; i4++) {
31392
+ base2 = base2.add(p);
31393
+ points.push(base2);
31394
+ }
31395
+ p = base2.double();
31396
+ }
31397
+ return points;
31398
+ }
31399
+ wNAF(W, precomputes, n) {
31400
+ if (!this.Fn.isValid(n))
31401
+ throw new Error("invalid scalar");
31402
+ let p = this.ZERO;
31403
+ let f = this.BASE;
31404
+ const wo = calcWOpts(W, this.bits);
31405
+ for (let window2 = 0;window2 < wo.windows; window2++) {
31406
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo);
31407
+ n = nextN;
31408
+ if (isZero) {
31409
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
31410
+ } else {
31411
+ p = p.add(negateCt(isNeg, precomputes[offset]));
31412
+ }
31413
+ }
31414
+ assert0(n);
31415
+ return { p, f };
31416
+ }
31417
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
31418
+ const wo = calcWOpts(W, this.bits);
31419
+ for (let window2 = 0;window2 < wo.windows; window2++) {
31420
+ if (n === _0n8)
31421
+ break;
31422
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, wo);
31423
+ n = nextN;
31424
+ if (isZero) {
31425
+ continue;
31426
+ } else {
31427
+ const item = precomputes[offset];
31428
+ acc = acc.add(isNeg ? item.negate() : item);
31429
+ }
31430
+ }
31431
+ assert0(n);
31432
+ return acc;
31433
+ }
31434
+ getPrecomputes(W, point, transform) {
31435
+ let comp = pointPrecomputes.get(point);
31436
+ if (!comp) {
31437
+ comp = this.precomputeWindow(point, W);
31438
+ if (W !== 1) {
31439
+ if (typeof transform === "function")
31440
+ comp = transform(comp);
31441
+ pointPrecomputes.set(point, comp);
31442
+ }
31443
+ }
31444
+ return comp;
31445
+ }
31446
+ cached(point, scalar, transform) {
31447
+ const W = getW(point);
31448
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
31449
+ }
31450
+ unsafe(point, scalar, transform, prev) {
31451
+ const W = getW(point);
31452
+ if (W === 1)
31453
+ return this._unsafeLadder(point, scalar, prev);
31454
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
31455
+ }
31456
+ createCache(P, W) {
31457
+ validateW(W, this.bits);
31458
+ pointWindowSizes.set(P, W);
31459
+ pointPrecomputes.delete(P);
31460
+ }
31461
+ hasCache(elm) {
31462
+ return getW(elm) !== 1;
31463
+ }
31464
+ }
31465
+ function mulEndoUnsafe(Point2, point, k1, k2) {
31466
+ let acc = point;
31467
+ let p1 = Point2.ZERO;
31468
+ let p2 = Point2.ZERO;
31469
+ while (k1 > _0n8 || k2 > _0n8) {
31470
+ if (k1 & _1n8)
31471
+ p1 = p1.add(acc);
31472
+ if (k2 & _1n8)
31473
+ p2 = p2.add(acc);
31474
+ acc = acc.double();
31475
+ k1 >>= _1n8;
31476
+ k2 >>= _1n8;
31477
+ }
31478
+ return { p1, p2 };
31479
+ }
31480
+ function pippenger(c, fieldN, points, scalars) {
31481
+ validateMSMPoints(points, c);
31482
+ validateMSMScalars(scalars, fieldN);
31483
+ const plength = points.length;
31484
+ const slength = scalars.length;
31485
+ if (plength !== slength)
31486
+ throw new Error("arrays of points and scalars must have equal length");
31487
+ const zero = c.ZERO;
31488
+ const wbits = bitLen2(BigInt(plength));
31489
+ let windowSize = 1;
31490
+ if (wbits > 12)
31491
+ windowSize = wbits - 3;
31492
+ else if (wbits > 4)
31493
+ windowSize = wbits - 2;
31494
+ else if (wbits > 0)
31495
+ windowSize = 2;
31496
+ const MASK = bitMask2(windowSize);
31497
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
31498
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
31499
+ let sum = zero;
31500
+ for (let i4 = lastBits;i4 >= 0; i4 -= windowSize) {
31501
+ buckets.fill(zero);
31502
+ for (let j = 0;j < slength; j++) {
31503
+ const scalar = scalars[j];
31504
+ const wbits2 = Number(scalar >> BigInt(i4) & MASK);
31505
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
31506
+ }
31507
+ let resI = zero;
31508
+ for (let j = buckets.length - 1, sumI = zero;j > 0; j--) {
31509
+ sumI = sumI.add(buckets[j]);
31510
+ resI = resI.add(sumI);
31511
+ }
31512
+ sum = sum.add(resI);
31513
+ if (i4 !== 0)
31514
+ for (let j = 0;j < windowSize; j++)
31515
+ sum = sum.double();
31516
+ }
31517
+ return sum;
31518
+ }
31519
+ function createField(order, field, isLE4) {
31520
+ if (field) {
31521
+ if (field.ORDER !== order)
31522
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
31523
+ validateField2(field);
31524
+ return field;
31525
+ } else {
31526
+ return Field2(order, { isLE: isLE4 });
31527
+ }
31528
+ }
31529
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
31530
+ if (FpFnLE === undefined)
31531
+ FpFnLE = type === "edwards";
31532
+ if (!CURVE || typeof CURVE !== "object")
31533
+ throw new Error(`expected valid ${type} CURVE object`);
31534
+ for (const p of ["p", "n", "h"]) {
31535
+ const val = CURVE[p];
31536
+ if (!(typeof val === "bigint" && val > _0n8))
31537
+ throw new Error(`CURVE.${p} must be positive bigint`);
31538
+ }
31539
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
31540
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
31541
+ const _b = type === "weierstrass" ? "b" : "d";
31542
+ const params = ["Gx", "Gy", "a", _b];
31543
+ for (const p of params) {
31544
+ if (!Fp2.isValid(CURVE[p]))
31545
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
31546
+ }
31547
+ CURVE = Object.freeze(Object.assign({}, CURVE));
31548
+ return { CURVE, Fp: Fp2, Fn };
31549
+ }
31550
+
31551
+ // ../routstr-chat/node_modules/@noble/curves/esm/abstract/weierstrass.js
31552
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
31553
+ var divNearest2 = (num, den) => (num + (num >= 0 ? den : -den) / _2n6) / den;
31554
+ function _splitEndoScalar(k, basis, n) {
31555
+ const [[a1, b1], [a2, b2]] = basis;
31556
+ const c1 = divNearest2(b2 * k, n);
31557
+ const c2 = divNearest2(-b1 * k, n);
31558
+ let k1 = k - c1 * a1 - c2 * a2;
31559
+ let k2 = -c1 * b1 - c2 * b2;
31560
+ const k1neg = k1 < _0n9;
31561
+ const k2neg = k2 < _0n9;
31562
+ if (k1neg)
31563
+ k1 = -k1;
31564
+ if (k2neg)
31565
+ k2 = -k2;
31566
+ const MAX_NUM = bitMask2(Math.ceil(bitLen2(n) / 2)) + _1n9;
31567
+ if (k1 < _0n9 || k1 >= MAX_NUM || k2 < _0n9 || k2 >= MAX_NUM) {
31568
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
31569
+ }
31570
+ return { k1neg, k1, k2neg, k2 };
31571
+ }
31572
+ function validateSigFormat(format) {
31573
+ if (!["compact", "recovered", "der"].includes(format))
31574
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
31575
+ return format;
31576
+ }
31577
+ function validateSigOpts(opts, def) {
31578
+ const optsn = {};
31579
+ for (let optName of Object.keys(def)) {
31580
+ optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
31581
+ }
31582
+ _abool2(optsn.lowS, "lowS");
31583
+ _abool2(optsn.prehash, "prehash");
31584
+ if (optsn.format !== undefined)
31585
+ validateSigFormat(optsn.format);
31586
+ return optsn;
31587
+ }
31588
+
31589
+ class DERErr2 extends Error {
31590
+ constructor(m = "") {
31591
+ super(m);
31592
+ }
31593
+ }
31594
+ var DER2 = {
31595
+ Err: DERErr2,
31596
+ _tlv: {
31597
+ encode: (tag, data) => {
31598
+ const { Err: E } = DER2;
31599
+ if (tag < 0 || tag > 256)
31600
+ throw new E("tlv.encode: wrong tag");
31601
+ if (data.length & 1)
31602
+ throw new E("tlv.encode: unpadded data");
31603
+ const dataLen = data.length / 2;
31604
+ const len = numberToHexUnpadded2(dataLen);
31605
+ if (len.length / 2 & 128)
31606
+ throw new E("tlv.encode: long form length too big");
31607
+ const lenLen = dataLen > 127 ? numberToHexUnpadded2(len.length / 2 | 128) : "";
31608
+ const t = numberToHexUnpadded2(tag);
31609
+ return t + lenLen + len + data;
31610
+ },
31611
+ decode(tag, data) {
31612
+ const { Err: E } = DER2;
31613
+ let pos = 0;
31614
+ if (tag < 0 || tag > 256)
31615
+ throw new E("tlv.encode: wrong tag");
31616
+ if (data.length < 2 || data[pos++] !== tag)
31617
+ throw new E("tlv.decode: wrong tlv");
31618
+ const first = data[pos++];
31619
+ const isLong = !!(first & 128);
31620
+ let length = 0;
31621
+ if (!isLong)
31622
+ length = first;
31623
+ else {
31624
+ const lenLen = first & 127;
31625
+ if (!lenLen)
31626
+ throw new E("tlv.decode(long): indefinite length not supported");
31627
+ if (lenLen > 4)
31628
+ throw new E("tlv.decode(long): byte length is too big");
31629
+ const lengthBytes = data.subarray(pos, pos + lenLen);
31630
+ if (lengthBytes.length !== lenLen)
31631
+ throw new E("tlv.decode: length bytes not complete");
31632
+ if (lengthBytes[0] === 0)
31633
+ throw new E("tlv.decode(long): zero leftmost byte");
31634
+ for (const b of lengthBytes)
31635
+ length = length << 8 | b;
31636
+ pos += lenLen;
31637
+ if (length < 128)
31638
+ throw new E("tlv.decode(long): not minimal encoding");
31639
+ }
31640
+ const v = data.subarray(pos, pos + length);
31641
+ if (v.length !== length)
31642
+ throw new E("tlv.decode: wrong value length");
31643
+ return { v, l: data.subarray(pos + length) };
31644
+ }
31645
+ },
31646
+ _int: {
31647
+ encode(num) {
31648
+ const { Err: E } = DER2;
31649
+ if (num < _0n9)
31650
+ throw new E("integer: negative integers are not allowed");
31651
+ let hex2 = numberToHexUnpadded2(num);
31652
+ if (Number.parseInt(hex2[0], 16) & 8)
31653
+ hex2 = "00" + hex2;
31654
+ if (hex2.length & 1)
31655
+ throw new E("unexpected DER parsing assertion: unpadded hex");
31656
+ return hex2;
31657
+ },
31658
+ decode(data) {
31659
+ const { Err: E } = DER2;
31660
+ if (data[0] & 128)
31661
+ throw new E("invalid signature integer: negative");
31662
+ if (data[0] === 0 && !(data[1] & 128))
31663
+ throw new E("invalid signature integer: unnecessary leading zero");
31664
+ return bytesToNumberBE2(data);
31665
+ }
31666
+ },
31667
+ toSig(hex2) {
31668
+ const { Err: E, _int: int, _tlv: tlv } = DER2;
31669
+ const data = ensureBytes2("signature", hex2);
31670
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
31671
+ if (seqLeftBytes.length)
31672
+ throw new E("invalid signature: left bytes after parsing");
31673
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
31674
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
31675
+ if (sLeftBytes.length)
31676
+ throw new E("invalid signature: left bytes after parsing");
31677
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
31678
+ },
31679
+ hexFromSig(sig) {
31680
+ const { _tlv: tlv, _int: int } = DER2;
31681
+ const rs = tlv.encode(2, int.encode(sig.r));
31682
+ const ss = tlv.encode(2, int.encode(sig.s));
31683
+ const seq = rs + ss;
31684
+ return tlv.encode(48, seq);
31685
+ }
31686
+ };
31687
+ var _0n9 = BigInt(0);
31688
+ var _1n9 = BigInt(1);
31689
+ var _2n6 = BigInt(2);
31690
+ var _3n4 = BigInt(3);
31691
+ var _4n4 = BigInt(4);
31692
+ function _normFnElement(Fn, key) {
31693
+ const { BYTES: expected } = Fn;
31694
+ let num;
31695
+ if (typeof key === "bigint") {
31696
+ num = key;
31697
+ } else {
31698
+ let bytes4 = ensureBytes2("private key", key);
31699
+ try {
31700
+ num = Fn.fromBytes(bytes4);
31701
+ } catch (error) {
31702
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
31703
+ }
31704
+ }
31705
+ if (!Fn.isValidNot0(num))
31706
+ throw new Error("invalid private key: out of range [1..N-1]");
31707
+ return num;
31708
+ }
31709
+ function weierstrassN(params, extraOpts = {}) {
31710
+ const validated = _createCurveFields("weierstrass", params, extraOpts);
31711
+ const { Fp: Fp2, Fn } = validated;
31712
+ let CURVE = validated.CURVE;
31713
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
31714
+ _validateObject(extraOpts, {}, {
31715
+ allowInfinityPoint: "boolean",
31716
+ clearCofactor: "function",
31717
+ isTorsionFree: "function",
31718
+ fromBytes: "function",
31719
+ toBytes: "function",
31720
+ endo: "object",
31721
+ wrapPrivateKey: "boolean"
31722
+ });
31723
+ const { endo } = extraOpts;
31724
+ if (endo) {
31725
+ if (!Fp2.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
31726
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
31727
+ }
31728
+ }
31729
+ const lengths = getWLengths(Fp2, Fn);
31730
+ function assertCompressionIsSupported() {
31731
+ if (!Fp2.isOdd)
31732
+ throw new Error("compression is not supported: Field does not have .isOdd()");
31733
+ }
31734
+ function pointToBytes2(_c, point, isCompressed) {
31735
+ const { x, y } = point.toAffine();
31736
+ const bx = Fp2.toBytes(x);
31737
+ _abool2(isCompressed, "isCompressed");
31738
+ if (isCompressed) {
31739
+ assertCompressionIsSupported();
31740
+ const hasEvenY = !Fp2.isOdd(y);
31741
+ return concatBytes4(pprefix(hasEvenY), bx);
31742
+ } else {
31743
+ return concatBytes4(Uint8Array.of(4), bx, Fp2.toBytes(y));
31744
+ }
31745
+ }
31746
+ function pointFromBytes(bytes4) {
31747
+ _abytes2(bytes4, undefined, "Point");
31748
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
31749
+ const length = bytes4.length;
31750
+ const head = bytes4[0];
31751
+ const tail = bytes4.subarray(1);
31752
+ if (length === comp && (head === 2 || head === 3)) {
31753
+ const x = Fp2.fromBytes(tail);
31754
+ if (!Fp2.isValid(x))
31755
+ throw new Error("bad point: is not on curve, wrong x");
31756
+ const y2 = weierstrassEquation(x);
31757
+ let y;
31758
+ try {
31759
+ y = Fp2.sqrt(y2);
31760
+ } catch (sqrtError) {
31761
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
31762
+ throw new Error("bad point: is not on curve, sqrt error" + err);
31763
+ }
31764
+ assertCompressionIsSupported();
31765
+ const isYOdd = Fp2.isOdd(y);
31766
+ const isHeadOdd = (head & 1) === 1;
31767
+ if (isHeadOdd !== isYOdd)
31768
+ y = Fp2.neg(y);
31769
+ return { x, y };
31770
+ } else if (length === uncomp && head === 4) {
31771
+ const L = Fp2.BYTES;
31772
+ const x = Fp2.fromBytes(tail.subarray(0, L));
31773
+ const y = Fp2.fromBytes(tail.subarray(L, L * 2));
31774
+ if (!isValidXY(x, y))
31775
+ throw new Error("bad point: is not on curve");
31776
+ return { x, y };
31777
+ } else {
31778
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
31779
+ }
31780
+ }
31781
+ const encodePoint = extraOpts.toBytes || pointToBytes2;
31782
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
31783
+ function weierstrassEquation(x) {
31784
+ const x2 = Fp2.sqr(x);
31785
+ const x3 = Fp2.mul(x2, x);
31786
+ return Fp2.add(Fp2.add(x3, Fp2.mul(x, CURVE.a)), CURVE.b);
31787
+ }
31788
+ function isValidXY(x, y) {
31789
+ const left = Fp2.sqr(y);
31790
+ const right = weierstrassEquation(x);
31791
+ return Fp2.eql(left, right);
31792
+ }
31793
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
31794
+ throw new Error("bad curve params: generator point");
31795
+ const _4a3 = Fp2.mul(Fp2.pow(CURVE.a, _3n4), _4n4);
31796
+ const _27b2 = Fp2.mul(Fp2.sqr(CURVE.b), BigInt(27));
31797
+ if (Fp2.is0(Fp2.add(_4a3, _27b2)))
31798
+ throw new Error("bad curve params: a or b");
31799
+ function acoord(title, n, banZero = false) {
31800
+ if (!Fp2.isValid(n) || banZero && Fp2.is0(n))
31801
+ throw new Error(`bad point coordinate ${title}`);
31802
+ return n;
31803
+ }
31804
+ function aprjpoint(other) {
31805
+ if (!(other instanceof Point2))
31806
+ throw new Error("ProjectivePoint expected");
31807
+ }
31808
+ function splitEndoScalarN(k) {
31809
+ if (!endo || !endo.basises)
31810
+ throw new Error("no endo");
31811
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
31812
+ }
31813
+ const toAffineMemo = memoized((p, iz) => {
31814
+ const { X, Y, Z } = p;
31815
+ if (Fp2.eql(Z, Fp2.ONE))
31816
+ return { x: X, y: Y };
31817
+ const is0 = p.is0();
31818
+ if (iz == null)
31819
+ iz = is0 ? Fp2.ONE : Fp2.inv(Z);
31820
+ const x = Fp2.mul(X, iz);
31821
+ const y = Fp2.mul(Y, iz);
31822
+ const zz = Fp2.mul(Z, iz);
31823
+ if (is0)
31824
+ return { x: Fp2.ZERO, y: Fp2.ZERO };
31825
+ if (!Fp2.eql(zz, Fp2.ONE))
31826
+ throw new Error("invZ was invalid");
31827
+ return { x, y };
31828
+ });
31829
+ const assertValidMemo = memoized((p) => {
31830
+ if (p.is0()) {
31831
+ if (extraOpts.allowInfinityPoint && !Fp2.is0(p.Y))
31832
+ return;
31833
+ throw new Error("bad point: ZERO");
31834
+ }
31835
+ const { x, y } = p.toAffine();
31836
+ if (!Fp2.isValid(x) || !Fp2.isValid(y))
31837
+ throw new Error("bad point: x or y not field elements");
31838
+ if (!isValidXY(x, y))
31839
+ throw new Error("bad point: equation left != right");
31840
+ if (!p.isTorsionFree())
31841
+ throw new Error("bad point: not in prime-order subgroup");
31842
+ return true;
31843
+ });
31844
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
31845
+ k2p = new Point2(Fp2.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
31846
+ k1p = negateCt(k1neg, k1p);
31847
+ k2p = negateCt(k2neg, k2p);
31848
+ return k1p.add(k2p);
31849
+ }
31850
+
31851
+ class Point2 {
31852
+ constructor(X, Y, Z) {
31853
+ this.X = acoord("x", X);
31854
+ this.Y = acoord("y", Y, true);
31855
+ this.Z = acoord("z", Z);
31856
+ Object.freeze(this);
31857
+ }
31858
+ static CURVE() {
31859
+ return CURVE;
31860
+ }
31861
+ static fromAffine(p) {
31862
+ const { x, y } = p || {};
31863
+ if (!p || !Fp2.isValid(x) || !Fp2.isValid(y))
31864
+ throw new Error("invalid affine point");
31865
+ if (p instanceof Point2)
31866
+ throw new Error("projective point not allowed");
31867
+ if (Fp2.is0(x) && Fp2.is0(y))
31868
+ return Point2.ZERO;
31869
+ return new Point2(x, y, Fp2.ONE);
31870
+ }
31871
+ static fromBytes(bytes4) {
31872
+ const P = Point2.fromAffine(decodePoint(_abytes2(bytes4, undefined, "point")));
31873
+ P.assertValidity();
31874
+ return P;
31875
+ }
31876
+ static fromHex(hex2) {
31877
+ return Point2.fromBytes(ensureBytes2("pointHex", hex2));
31878
+ }
31879
+ get x() {
31880
+ return this.toAffine().x;
31881
+ }
31882
+ get y() {
31883
+ return this.toAffine().y;
31884
+ }
31885
+ precompute(windowSize = 8, isLazy = true) {
31886
+ wnaf.createCache(this, windowSize);
31887
+ if (!isLazy)
31888
+ this.multiply(_3n4);
31889
+ return this;
31890
+ }
31891
+ assertValidity() {
31892
+ assertValidMemo(this);
31893
+ }
31894
+ hasEvenY() {
31895
+ const { y } = this.toAffine();
31896
+ if (!Fp2.isOdd)
31897
+ throw new Error("Field doesn't support isOdd");
31898
+ return !Fp2.isOdd(y);
31899
+ }
31900
+ equals(other) {
31901
+ aprjpoint(other);
31902
+ const { X: X1, Y: Y1, Z: Z1 } = this;
31903
+ const { X: X2, Y: Y2, Z: Z2 } = other;
31904
+ const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
31905
+ const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
31906
+ return U1 && U2;
31907
+ }
31908
+ negate() {
31909
+ return new Point2(this.X, Fp2.neg(this.Y), this.Z);
31910
+ }
31911
+ double() {
31912
+ const { a, b } = CURVE;
31913
+ const b3 = Fp2.mul(b, _3n4);
31914
+ const { X: X1, Y: Y1, Z: Z1 } = this;
31915
+ let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp2;
31916
+ let t0 = Fp2.mul(X1, X1);
31917
+ let t1 = Fp2.mul(Y1, Y1);
31918
+ let t2 = Fp2.mul(Z1, Z1);
31919
+ let t3 = Fp2.mul(X1, Y1);
31920
+ t3 = Fp2.add(t3, t3);
31921
+ Z3 = Fp2.mul(X1, Z1);
31922
+ Z3 = Fp2.add(Z3, Z3);
31923
+ X3 = Fp2.mul(a, Z3);
31924
+ Y3 = Fp2.mul(b3, t2);
31925
+ Y3 = Fp2.add(X3, Y3);
31926
+ X3 = Fp2.sub(t1, Y3);
31927
+ Y3 = Fp2.add(t1, Y3);
31928
+ Y3 = Fp2.mul(X3, Y3);
31929
+ X3 = Fp2.mul(t3, X3);
31930
+ Z3 = Fp2.mul(b3, Z3);
31931
+ t2 = Fp2.mul(a, t2);
31932
+ t3 = Fp2.sub(t0, t2);
31933
+ t3 = Fp2.mul(a, t3);
31934
+ t3 = Fp2.add(t3, Z3);
31935
+ Z3 = Fp2.add(t0, t0);
31936
+ t0 = Fp2.add(Z3, t0);
31937
+ t0 = Fp2.add(t0, t2);
31938
+ t0 = Fp2.mul(t0, t3);
31939
+ Y3 = Fp2.add(Y3, t0);
31940
+ t2 = Fp2.mul(Y1, Z1);
31941
+ t2 = Fp2.add(t2, t2);
31942
+ t0 = Fp2.mul(t2, t3);
31943
+ X3 = Fp2.sub(X3, t0);
31944
+ Z3 = Fp2.mul(t2, t1);
31945
+ Z3 = Fp2.add(Z3, Z3);
31946
+ Z3 = Fp2.add(Z3, Z3);
31947
+ return new Point2(X3, Y3, Z3);
31948
+ }
31949
+ add(other) {
31950
+ aprjpoint(other);
31951
+ const { X: X1, Y: Y1, Z: Z1 } = this;
31952
+ const { X: X2, Y: Y2, Z: Z2 } = other;
31953
+ let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp2;
31954
+ const a = CURVE.a;
31955
+ const b3 = Fp2.mul(CURVE.b, _3n4);
31956
+ let t0 = Fp2.mul(X1, X2);
31957
+ let t1 = Fp2.mul(Y1, Y2);
31958
+ let t2 = Fp2.mul(Z1, Z2);
31959
+ let t3 = Fp2.add(X1, Y1);
31960
+ let t4 = Fp2.add(X2, Y2);
31961
+ t3 = Fp2.mul(t3, t4);
31962
+ t4 = Fp2.add(t0, t1);
31963
+ t3 = Fp2.sub(t3, t4);
31964
+ t4 = Fp2.add(X1, Z1);
31965
+ let t5 = Fp2.add(X2, Z2);
31966
+ t4 = Fp2.mul(t4, t5);
31967
+ t5 = Fp2.add(t0, t2);
31968
+ t4 = Fp2.sub(t4, t5);
31969
+ t5 = Fp2.add(Y1, Z1);
31970
+ X3 = Fp2.add(Y2, Z2);
31971
+ t5 = Fp2.mul(t5, X3);
31972
+ X3 = Fp2.add(t1, t2);
31973
+ t5 = Fp2.sub(t5, X3);
31974
+ Z3 = Fp2.mul(a, t4);
31975
+ X3 = Fp2.mul(b3, t2);
31976
+ Z3 = Fp2.add(X3, Z3);
31977
+ X3 = Fp2.sub(t1, Z3);
31978
+ Z3 = Fp2.add(t1, Z3);
31979
+ Y3 = Fp2.mul(X3, Z3);
31980
+ t1 = Fp2.add(t0, t0);
31981
+ t1 = Fp2.add(t1, t0);
31982
+ t2 = Fp2.mul(a, t2);
31983
+ t4 = Fp2.mul(b3, t4);
31984
+ t1 = Fp2.add(t1, t2);
31985
+ t2 = Fp2.sub(t0, t2);
31986
+ t2 = Fp2.mul(a, t2);
31987
+ t4 = Fp2.add(t4, t2);
31988
+ t0 = Fp2.mul(t1, t4);
31989
+ Y3 = Fp2.add(Y3, t0);
31990
+ t0 = Fp2.mul(t5, t4);
31991
+ X3 = Fp2.mul(t3, X3);
31992
+ X3 = Fp2.sub(X3, t0);
31993
+ t0 = Fp2.mul(t3, t1);
31994
+ Z3 = Fp2.mul(t5, Z3);
31995
+ Z3 = Fp2.add(Z3, t0);
31996
+ return new Point2(X3, Y3, Z3);
31997
+ }
31998
+ subtract(other) {
31999
+ return this.add(other.negate());
32000
+ }
32001
+ is0() {
32002
+ return this.equals(Point2.ZERO);
32003
+ }
32004
+ multiply(scalar) {
32005
+ const { endo: endo2 } = extraOpts;
32006
+ if (!Fn.isValidNot0(scalar))
32007
+ throw new Error("invalid scalar: out of range");
32008
+ let point, fake;
32009
+ const mul3 = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point2, p));
32010
+ if (endo2) {
32011
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
32012
+ const { p: k1p, f: k1f } = mul3(k1);
32013
+ const { p: k2p, f: k2f } = mul3(k2);
32014
+ fake = k1f.add(k2f);
32015
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
32016
+ } else {
32017
+ const { p, f } = mul3(scalar);
32018
+ point = p;
32019
+ fake = f;
32020
+ }
32021
+ return normalizeZ(Point2, [point, fake])[0];
32022
+ }
32023
+ multiplyUnsafe(sc) {
32024
+ const { endo: endo2 } = extraOpts;
32025
+ const p = this;
32026
+ if (!Fn.isValid(sc))
32027
+ throw new Error("invalid scalar: out of range");
32028
+ if (sc === _0n9 || p.is0())
32029
+ return Point2.ZERO;
32030
+ if (sc === _1n9)
32031
+ return p;
32032
+ if (wnaf.hasCache(this))
32033
+ return this.multiply(sc);
32034
+ if (endo2) {
32035
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
32036
+ const { p1, p2 } = mulEndoUnsafe(Point2, p, k1, k2);
32037
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
32038
+ } else {
32039
+ return wnaf.unsafe(p, sc);
32040
+ }
32041
+ }
32042
+ multiplyAndAddUnsafe(Q, a, b) {
32043
+ const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
32044
+ return sum.is0() ? undefined : sum;
32045
+ }
32046
+ toAffine(invertedZ) {
32047
+ return toAffineMemo(this, invertedZ);
32048
+ }
32049
+ isTorsionFree() {
32050
+ const { isTorsionFree } = extraOpts;
32051
+ if (cofactor === _1n9)
32052
+ return true;
32053
+ if (isTorsionFree)
32054
+ return isTorsionFree(Point2, this);
32055
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
32056
+ }
32057
+ clearCofactor() {
32058
+ const { clearCofactor } = extraOpts;
32059
+ if (cofactor === _1n9)
32060
+ return this;
32061
+ if (clearCofactor)
32062
+ return clearCofactor(Point2, this);
32063
+ return this.multiplyUnsafe(cofactor);
32064
+ }
32065
+ isSmallOrder() {
32066
+ return this.multiplyUnsafe(cofactor).is0();
32067
+ }
32068
+ toBytes(isCompressed = true) {
32069
+ _abool2(isCompressed, "isCompressed");
32070
+ this.assertValidity();
32071
+ return encodePoint(Point2, this, isCompressed);
32072
+ }
32073
+ toHex(isCompressed = true) {
32074
+ return bytesToHex4(this.toBytes(isCompressed));
32075
+ }
32076
+ toString() {
32077
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
32078
+ }
32079
+ get px() {
32080
+ return this.X;
32081
+ }
32082
+ get py() {
32083
+ return this.X;
32084
+ }
32085
+ get pz() {
32086
+ return this.Z;
32087
+ }
32088
+ toRawBytes(isCompressed = true) {
32089
+ return this.toBytes(isCompressed);
32090
+ }
32091
+ _setWindowSize(windowSize) {
32092
+ this.precompute(windowSize);
32093
+ }
32094
+ static normalizeZ(points) {
32095
+ return normalizeZ(Point2, points);
32096
+ }
32097
+ static msm(points, scalars) {
32098
+ return pippenger(Point2, Fn, points, scalars);
32099
+ }
32100
+ static fromPrivateKey(privateKey) {
32101
+ return Point2.BASE.multiply(_normFnElement(Fn, privateKey));
32102
+ }
32103
+ }
32104
+ Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE);
32105
+ Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO);
32106
+ Point2.Fp = Fp2;
32107
+ Point2.Fn = Fn;
32108
+ const bits = Fn.BITS;
32109
+ const wnaf = new wNAF2(Point2, extraOpts.endo ? Math.ceil(bits / 2) : bits);
32110
+ Point2.BASE.precompute(8);
32111
+ return Point2;
32112
+ }
32113
+ function pprefix(hasEvenY) {
32114
+ return Uint8Array.of(hasEvenY ? 2 : 3);
32115
+ }
32116
+ function getWLengths(Fp2, Fn) {
32117
+ return {
32118
+ secretKey: Fn.BYTES,
32119
+ publicKey: 1 + Fp2.BYTES,
32120
+ publicKeyUncompressed: 1 + 2 * Fp2.BYTES,
32121
+ publicKeyHasPrefix: true,
32122
+ signature: 2 * Fn.BYTES
32123
+ };
32124
+ }
32125
+ function ecdh(Point2, ecdhOpts = {}) {
32126
+ const { Fn } = Point2;
32127
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes4;
32128
+ const lengths = Object.assign(getWLengths(Point2.Fp, Fn), { seed: getMinHashLength2(Fn.ORDER) });
32129
+ function isValidSecretKey(secretKey) {
32130
+ try {
32131
+ return !!_normFnElement(Fn, secretKey);
32132
+ } catch (error) {
32133
+ return false;
32134
+ }
32135
+ }
32136
+ function isValidPublicKey(publicKey, isCompressed) {
32137
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
32138
+ try {
32139
+ const l = publicKey.length;
32140
+ if (isCompressed === true && l !== comp)
32141
+ return false;
32142
+ if (isCompressed === false && l !== publicKeyUncompressed)
32143
+ return false;
32144
+ return !!Point2.fromBytes(publicKey);
32145
+ } catch (error) {
32146
+ return false;
32147
+ }
32148
+ }
32149
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
32150
+ return mapHashToField2(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
32151
+ }
32152
+ function getPublicKey4(secretKey, isCompressed = true) {
32153
+ return Point2.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
32154
+ }
32155
+ function keygen(seed) {
32156
+ const secretKey = randomSecretKey(seed);
32157
+ return { secretKey, publicKey: getPublicKey4(secretKey) };
32158
+ }
32159
+ function isProbPub(item) {
32160
+ if (typeof item === "bigint")
32161
+ return false;
32162
+ if (item instanceof Point2)
32163
+ return true;
32164
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
32165
+ if (Fn.allowedLengths || secretKey === publicKey)
32166
+ return;
32167
+ const l = ensureBytes2("key", item).length;
32168
+ return l === publicKey || l === publicKeyUncompressed;
32169
+ }
32170
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
32171
+ if (isProbPub(secretKeyA) === true)
32172
+ throw new Error("first arg must be private key");
32173
+ if (isProbPub(publicKeyB) === false)
32174
+ throw new Error("second arg must be public key");
32175
+ const s = _normFnElement(Fn, secretKeyA);
32176
+ const b = Point2.fromHex(publicKeyB);
32177
+ return b.multiply(s).toBytes(isCompressed);
32178
+ }
32179
+ const utils = {
32180
+ isValidSecretKey,
32181
+ isValidPublicKey,
32182
+ randomSecretKey,
32183
+ isValidPrivateKey: isValidSecretKey,
32184
+ randomPrivateKey: randomSecretKey,
32185
+ normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
32186
+ precompute(windowSize = 8, point = Point2.BASE) {
32187
+ return point.precompute(windowSize, false);
32188
+ }
32189
+ };
32190
+ return Object.freeze({ getPublicKey: getPublicKey4, getSharedSecret, keygen, Point: Point2, utils, lengths });
32191
+ }
32192
+ function ecdsa(Point2, hash3, ecdsaOpts = {}) {
32193
+ ahash(hash3);
32194
+ _validateObject(ecdsaOpts, {}, {
32195
+ hmac: "function",
32196
+ lowS: "boolean",
32197
+ randomBytes: "function",
32198
+ bits2int: "function",
32199
+ bits2int_modN: "function"
32200
+ });
32201
+ const randomBytes5 = ecdsaOpts.randomBytes || randomBytes4;
32202
+ const hmac4 = ecdsaOpts.hmac || ((key, ...msgs) => hmac3(hash3, key, concatBytes4(...msgs)));
32203
+ const { Fp: Fp2, Fn } = Point2;
32204
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
32205
+ const { keygen, getPublicKey: getPublicKey4, getSharedSecret, utils, lengths } = ecdh(Point2, ecdsaOpts);
32206
+ const defaultSigOpts = {
32207
+ prehash: false,
32208
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
32209
+ format: undefined,
32210
+ extraEntropy: false
32211
+ };
32212
+ const defaultSigOpts_format = "compact";
32213
+ function isBiggerThanHalfOrder(number4) {
32214
+ const HALF = CURVE_ORDER >> _1n9;
32215
+ return number4 > HALF;
32216
+ }
32217
+ function validateRS(title, num) {
32218
+ if (!Fn.isValidNot0(num))
32219
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
32220
+ return num;
32221
+ }
32222
+ function validateSigLength(bytes4, format) {
32223
+ validateSigFormat(format);
32224
+ const size = lengths.signature;
32225
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : undefined;
32226
+ return _abytes2(bytes4, sizer, `${format} signature`);
32227
+ }
32228
+
32229
+ class Signature {
32230
+ constructor(r, s, recovery) {
32231
+ this.r = validateRS("r", r);
32232
+ this.s = validateRS("s", s);
32233
+ if (recovery != null)
32234
+ this.recovery = recovery;
32235
+ Object.freeze(this);
32236
+ }
32237
+ static fromBytes(bytes4, format = defaultSigOpts_format) {
32238
+ validateSigLength(bytes4, format);
32239
+ let recid;
32240
+ if (format === "der") {
32241
+ const { r: r2, s: s2 } = DER2.toSig(_abytes2(bytes4));
32242
+ return new Signature(r2, s2);
32243
+ }
32244
+ if (format === "recovered") {
32245
+ recid = bytes4[0];
32246
+ format = "compact";
32247
+ bytes4 = bytes4.subarray(1);
32248
+ }
32249
+ const L = Fn.BYTES;
32250
+ const r = bytes4.subarray(0, L);
32251
+ const s = bytes4.subarray(L, L * 2);
32252
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
32253
+ }
32254
+ static fromHex(hex2, format) {
32255
+ return this.fromBytes(hexToBytes4(hex2), format);
32256
+ }
32257
+ addRecoveryBit(recovery) {
32258
+ return new Signature(this.r, this.s, recovery);
32259
+ }
32260
+ recoverPublicKey(messageHash) {
32261
+ const FIELD_ORDER = Fp2.ORDER;
32262
+ const { r, s, recovery: rec } = this;
32263
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
32264
+ throw new Error("recovery id invalid");
32265
+ const hasCofactor = CURVE_ORDER * _2n6 < FIELD_ORDER;
32266
+ if (hasCofactor && rec > 1)
32267
+ throw new Error("recovery id is ambiguous for h>1 curve");
32268
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
32269
+ if (!Fp2.isValid(radj))
32270
+ throw new Error("recovery id 2 or 3 invalid");
32271
+ const x = Fp2.toBytes(radj);
32272
+ const R = Point2.fromBytes(concatBytes4(pprefix((rec & 1) === 0), x));
32273
+ const ir = Fn.inv(radj);
32274
+ const h = bits2int_modN(ensureBytes2("msgHash", messageHash));
32275
+ const u1 = Fn.create(-h * ir);
32276
+ const u2 = Fn.create(s * ir);
32277
+ const Q = Point2.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
32278
+ if (Q.is0())
32279
+ throw new Error("point at infinify");
32280
+ Q.assertValidity();
32281
+ return Q;
32282
+ }
32283
+ hasHighS() {
32284
+ return isBiggerThanHalfOrder(this.s);
32285
+ }
32286
+ toBytes(format = defaultSigOpts_format) {
32287
+ validateSigFormat(format);
32288
+ if (format === "der")
32289
+ return hexToBytes4(DER2.hexFromSig(this));
32290
+ const r = Fn.toBytes(this.r);
32291
+ const s = Fn.toBytes(this.s);
32292
+ if (format === "recovered") {
32293
+ if (this.recovery == null)
32294
+ throw new Error("recovery bit must be present");
32295
+ return concatBytes4(Uint8Array.of(this.recovery), r, s);
32296
+ }
32297
+ return concatBytes4(r, s);
32298
+ }
32299
+ toHex(format) {
32300
+ return bytesToHex4(this.toBytes(format));
32301
+ }
32302
+ assertValidity() {}
32303
+ static fromCompact(hex2) {
32304
+ return Signature.fromBytes(ensureBytes2("sig", hex2), "compact");
32305
+ }
32306
+ static fromDER(hex2) {
32307
+ return Signature.fromBytes(ensureBytes2("sig", hex2), "der");
32308
+ }
32309
+ normalizeS() {
32310
+ return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
32311
+ }
32312
+ toDERRawBytes() {
32313
+ return this.toBytes("der");
32314
+ }
32315
+ toDERHex() {
32316
+ return bytesToHex4(this.toBytes("der"));
32317
+ }
32318
+ toCompactRawBytes() {
32319
+ return this.toBytes("compact");
32320
+ }
32321
+ toCompactHex() {
32322
+ return bytesToHex4(this.toBytes("compact"));
32323
+ }
32324
+ }
32325
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes4) {
32326
+ if (bytes4.length > 8192)
32327
+ throw new Error("input is too large");
32328
+ const num = bytesToNumberBE2(bytes4);
32329
+ const delta = bytes4.length * 8 - fnBits;
32330
+ return delta > 0 ? num >> BigInt(delta) : num;
32331
+ };
32332
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes4) {
32333
+ return Fn.create(bits2int(bytes4));
32334
+ };
32335
+ const ORDER_MASK = bitMask2(fnBits);
32336
+ function int2octets(num) {
32337
+ aInRange("num < 2^" + fnBits, num, _0n9, ORDER_MASK);
32338
+ return Fn.toBytes(num);
32339
+ }
32340
+ function validateMsgAndHash(message, prehash) {
32341
+ _abytes2(message, undefined, "message");
32342
+ return prehash ? _abytes2(hash3(message), undefined, "prehashed message") : message;
32343
+ }
32344
+ function prepSig(message, privateKey, opts) {
32345
+ if (["recovered", "canonical"].some((k) => (k in opts)))
32346
+ throw new Error("sign() legacy options not supported");
32347
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
32348
+ message = validateMsgAndHash(message, prehash);
32349
+ const h1int = bits2int_modN(message);
32350
+ const d = _normFnElement(Fn, privateKey);
32351
+ const seedArgs = [int2octets(d), int2octets(h1int)];
32352
+ if (extraEntropy != null && extraEntropy !== false) {
32353
+ const e = extraEntropy === true ? randomBytes5(lengths.secretKey) : extraEntropy;
32354
+ seedArgs.push(ensureBytes2("extraEntropy", e));
32355
+ }
32356
+ const seed = concatBytes4(...seedArgs);
32357
+ const m = h1int;
32358
+ function k2sig(kBytes) {
32359
+ const k = bits2int(kBytes);
32360
+ if (!Fn.isValidNot0(k))
32361
+ return;
32362
+ const ik = Fn.inv(k);
32363
+ const q = Point2.BASE.multiply(k).toAffine();
32364
+ const r = Fn.create(q.x);
32365
+ if (r === _0n9)
32366
+ return;
32367
+ const s = Fn.create(ik * Fn.create(m + r * d));
32368
+ if (s === _0n9)
32369
+ return;
32370
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n9);
32371
+ let normS = s;
32372
+ if (lowS && isBiggerThanHalfOrder(s)) {
32373
+ normS = Fn.neg(s);
32374
+ recovery ^= 1;
32375
+ }
32376
+ return new Signature(r, normS, recovery);
32377
+ }
32378
+ return { seed, k2sig };
32379
+ }
32380
+ function sign2(message, secretKey, opts = {}) {
32381
+ message = ensureBytes2("message", message);
32382
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
32383
+ const drbg = createHmacDrbg2(hash3.outputLen, Fn.BYTES, hmac4);
32384
+ const sig = drbg(seed, k2sig);
32385
+ return sig;
32386
+ }
32387
+ function tryParsingSig(sg) {
32388
+ let sig = undefined;
32389
+ const isHex = typeof sg === "string" || isBytes2(sg);
32390
+ const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
32391
+ if (!isHex && !isObj)
32392
+ throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
32393
+ if (isObj) {
32394
+ sig = new Signature(sg.r, sg.s);
32395
+ } else if (isHex) {
32396
+ try {
32397
+ sig = Signature.fromBytes(ensureBytes2("sig", sg), "der");
32398
+ } catch (derError) {
32399
+ if (!(derError instanceof DER2.Err))
32400
+ throw derError;
32401
+ }
32402
+ if (!sig) {
32403
+ try {
32404
+ sig = Signature.fromBytes(ensureBytes2("sig", sg), "compact");
32405
+ } catch (error) {
32406
+ return false;
32407
+ }
32408
+ }
32409
+ }
32410
+ if (!sig)
32411
+ return false;
32412
+ return sig;
32413
+ }
32414
+ function verify(signature, message, publicKey, opts = {}) {
32415
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
32416
+ publicKey = ensureBytes2("publicKey", publicKey);
32417
+ message = validateMsgAndHash(ensureBytes2("message", message), prehash);
32418
+ if ("strict" in opts)
32419
+ throw new Error("options.strict was renamed to lowS");
32420
+ const sig = format === undefined ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes2("sig", signature), format);
32421
+ if (sig === false)
32422
+ return false;
32423
+ try {
32424
+ const P = Point2.fromBytes(publicKey);
32425
+ if (lowS && sig.hasHighS())
32426
+ return false;
32427
+ const { r, s } = sig;
32428
+ const h = bits2int_modN(message);
32429
+ const is = Fn.inv(s);
32430
+ const u1 = Fn.create(h * is);
32431
+ const u2 = Fn.create(r * is);
32432
+ const R = Point2.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
32433
+ if (R.is0())
32434
+ return false;
32435
+ const v = Fn.create(R.x);
32436
+ return v === r;
32437
+ } catch (e) {
32438
+ return false;
32439
+ }
32440
+ }
32441
+ function recoverPublicKey(signature, message, opts = {}) {
32442
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
32443
+ message = validateMsgAndHash(message, prehash);
32444
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
32445
+ }
32446
+ return Object.freeze({
32447
+ keygen,
32448
+ getPublicKey: getPublicKey4,
32449
+ getSharedSecret,
32450
+ utils,
32451
+ lengths,
32452
+ Point: Point2,
32453
+ sign: sign2,
32454
+ verify,
32455
+ recoverPublicKey,
32456
+ Signature,
32457
+ hash: hash3
32458
+ });
32459
+ }
32460
+ function _weierstrass_legacy_opts_to_new(c) {
32461
+ const CURVE = {
32462
+ a: c.a,
32463
+ b: c.b,
32464
+ p: c.Fp.ORDER,
32465
+ n: c.n,
32466
+ h: c.h,
32467
+ Gx: c.Gx,
32468
+ Gy: c.Gy
32469
+ };
32470
+ const Fp2 = c.Fp;
32471
+ let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : undefined;
32472
+ const Fn = Field2(CURVE.n, {
32473
+ BITS: c.nBitLength,
32474
+ allowedLengths,
32475
+ modFromBytes: c.wrapPrivateKey
32476
+ });
32477
+ const curveOpts = {
32478
+ Fp: Fp2,
32479
+ Fn,
32480
+ allowInfinityPoint: c.allowInfinityPoint,
32481
+ endo: c.endo,
32482
+ isTorsionFree: c.isTorsionFree,
32483
+ clearCofactor: c.clearCofactor,
32484
+ fromBytes: c.fromBytes,
32485
+ toBytes: c.toBytes
32486
+ };
32487
+ return { CURVE, curveOpts };
32488
+ }
32489
+ function _ecdsa_legacy_opts_to_new(c) {
32490
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
32491
+ const ecdsaOpts = {
32492
+ hmac: c.hmac,
32493
+ randomBytes: c.randomBytes,
32494
+ lowS: c.lowS,
32495
+ bits2int: c.bits2int,
32496
+ bits2int_modN: c.bits2int_modN
32497
+ };
32498
+ return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
32499
+ }
32500
+ function _ecdsa_new_output_to_legacy(c, _ecdsa) {
32501
+ const Point2 = _ecdsa.Point;
32502
+ return Object.assign({}, _ecdsa, {
32503
+ ProjectivePoint: Point2,
32504
+ CURVE: Object.assign({}, c, nLength2(Point2.Fn.ORDER, Point2.Fn.BITS))
32505
+ });
32506
+ }
32507
+ function weierstrass2(c) {
32508
+ const { CURVE, curveOpts, hash: hash3, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
32509
+ const Point2 = weierstrassN(CURVE, curveOpts);
32510
+ const signs = ecdsa(Point2, hash3, ecdsaOpts);
32511
+ return _ecdsa_new_output_to_legacy(c, signs);
32512
+ }
32513
+
32514
+ // ../routstr-chat/node_modules/@noble/curves/esm/_shortw_utils.js
32515
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
32516
+ function createCurve2(curveDef, defHash) {
32517
+ const create = (hash3) => weierstrass2({ ...curveDef, hash: hash3 });
32518
+ return { ...create(defHash), create };
32519
+ }
32520
+
32521
+ // ../routstr-chat/node_modules/@noble/curves/esm/secp256k1.js
32522
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
32523
+ var secp256k1_CURVE = {
32524
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
32525
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
32526
+ h: BigInt(1),
32527
+ a: BigInt(0),
32528
+ b: BigInt(7),
32529
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
32530
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
32531
+ };
32532
+ var secp256k1_ENDO = {
32533
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
32534
+ basises: [
32535
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
32536
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
32537
+ ]
32538
+ };
32539
+ var _0n10 = /* @__PURE__ */ BigInt(0);
32540
+ var _1n10 = /* @__PURE__ */ BigInt(1);
32541
+ var _2n7 = /* @__PURE__ */ BigInt(2);
32542
+ function sqrtMod2(y) {
32543
+ const P = secp256k1_CURVE.p;
32544
+ const _3n5 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
32545
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
32546
+ const b2 = y * y * y % P;
32547
+ const b3 = b2 * b2 * y % P;
32548
+ const b6 = pow22(b3, _3n5, P) * b3 % P;
32549
+ const b9 = pow22(b6, _3n5, P) * b3 % P;
32550
+ const b11 = pow22(b9, _2n7, P) * b2 % P;
32551
+ const b22 = pow22(b11, _11n, P) * b11 % P;
32552
+ const b44 = pow22(b22, _22n, P) * b22 % P;
32553
+ const b88 = pow22(b44, _44n, P) * b44 % P;
32554
+ const b176 = pow22(b88, _88n, P) * b88 % P;
32555
+ const b220 = pow22(b176, _44n, P) * b44 % P;
32556
+ const b223 = pow22(b220, _3n5, P) * b3 % P;
32557
+ const t1 = pow22(b223, _23n, P) * b22 % P;
32558
+ const t2 = pow22(t1, _6n, P) * b2 % P;
32559
+ const root = pow22(t2, _2n7, P);
32560
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
32561
+ throw new Error("Cannot find square root");
32562
+ return root;
32563
+ }
32564
+ var Fpk1 = Field2(secp256k1_CURVE.p, { sqrt: sqrtMod2 });
32565
+ var secp256k12 = createCurve2({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha2563);
32566
+ var TAGGED_HASH_PREFIXES2 = {};
32567
+ function taggedHash2(tag, ...messages) {
32568
+ let tagP = TAGGED_HASH_PREFIXES2[tag];
32569
+ if (tagP === undefined) {
32570
+ const tagH = sha2563(utf8ToBytes5(tag));
32571
+ tagP = concatBytes4(tagH, tagH);
32572
+ TAGGED_HASH_PREFIXES2[tag] = tagP;
32573
+ }
32574
+ return sha2563(concatBytes4(tagP, ...messages));
32575
+ }
32576
+ var pointToBytes2 = (point) => point.toBytes(true).slice(1);
32577
+ var Pointk1 = /* @__PURE__ */ (() => secp256k12.Point)();
32578
+ var hasEven = (y) => y % _2n7 === _0n10;
32579
+ function schnorrGetExtPubKey2(priv) {
32580
+ const { Fn, BASE } = Pointk1;
32581
+ const d_ = _normFnElement(Fn, priv);
32582
+ const p = BASE.multiply(d_);
32583
+ const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
32584
+ return { scalar, bytes: pointToBytes2(p) };
32585
+ }
32586
+ function lift_x2(x) {
32587
+ const Fp2 = Fpk1;
32588
+ if (!Fp2.isValidNot0(x))
32589
+ throw new Error("invalid x: Fail if x \u2265 p");
32590
+ const xx = Fp2.create(x * x);
32591
+ const c = Fp2.create(xx * x + BigInt(7));
32592
+ let y = Fp2.sqrt(c);
32593
+ if (!hasEven(y))
32594
+ y = Fp2.neg(y);
32595
+ const p = Pointk1.fromAffine({ x, y });
32596
+ p.assertValidity();
32597
+ return p;
32598
+ }
32599
+ var num = bytesToNumberBE2;
32600
+ function challenge2(...args) {
32601
+ return Pointk1.Fn.create(num(taggedHash2("BIP0340/challenge", ...args)));
32602
+ }
32603
+ function schnorrGetPublicKey2(secretKey) {
32604
+ return schnorrGetExtPubKey2(secretKey).bytes;
32605
+ }
32606
+ function schnorrSign2(message, secretKey, auxRand = randomBytes4(32)) {
32607
+ const { Fn } = Pointk1;
32608
+ const m = ensureBytes2("message", message);
32609
+ const { bytes: px, scalar: d } = schnorrGetExtPubKey2(secretKey);
32610
+ const a = ensureBytes2("auxRand", auxRand, 32);
32611
+ const t = Fn.toBytes(d ^ num(taggedHash2("BIP0340/aux", a)));
32612
+ const rand = taggedHash2("BIP0340/nonce", t, px, m);
32613
+ const { bytes: rx, scalar: k } = schnorrGetExtPubKey2(rand);
32614
+ const e = challenge2(rx, px, m);
32615
+ const sig = new Uint8Array(64);
32616
+ sig.set(rx, 0);
32617
+ sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
32618
+ if (!schnorrVerify2(sig, m, px))
32619
+ throw new Error("sign: Invalid signature produced");
32620
+ return sig;
32621
+ }
32622
+ function schnorrVerify2(signature, message, publicKey) {
32623
+ const { Fn, BASE } = Pointk1;
32624
+ const sig = ensureBytes2("signature", signature, 64);
32625
+ const m = ensureBytes2("message", message);
32626
+ const pub = ensureBytes2("publicKey", publicKey, 32);
32627
+ try {
32628
+ const P = lift_x2(num(pub));
32629
+ const r = num(sig.subarray(0, 32));
32630
+ if (!inRange(r, _1n10, secp256k1_CURVE.p))
32631
+ return false;
32632
+ const s = num(sig.subarray(32, 64));
32633
+ if (!inRange(s, _1n10, secp256k1_CURVE.n))
32634
+ return false;
32635
+ const e = challenge2(Fn.toBytes(r), pointToBytes2(P), m);
32636
+ const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
32637
+ const { x, y } = R.toAffine();
32638
+ if (R.is0() || !hasEven(y) || x !== r)
32639
+ return false;
32640
+ return true;
32641
+ } catch (error) {
32642
+ return false;
32643
+ }
32644
+ }
32645
+ var schnorr2 = /* @__PURE__ */ (() => {
32646
+ const size = 32;
32647
+ const seedLength = 48;
32648
+ const randomSecretKey = (seed = randomBytes4(seedLength)) => {
32649
+ return mapHashToField2(seed, secp256k1_CURVE.n);
32650
+ };
32651
+ secp256k12.utils.randomSecretKey;
32652
+ function keygen(seed) {
32653
+ const secretKey = randomSecretKey(seed);
32654
+ return { secretKey, publicKey: schnorrGetPublicKey2(secretKey) };
32655
+ }
32656
+ return {
32657
+ keygen,
32658
+ getPublicKey: schnorrGetPublicKey2,
32659
+ sign: schnorrSign2,
32660
+ verify: schnorrVerify2,
32661
+ Point: Pointk1,
32662
+ utils: {
32663
+ randomSecretKey,
32664
+ randomPrivateKey: randomSecretKey,
32665
+ taggedHash: taggedHash2,
32666
+ lift_x: lift_x2,
32667
+ pointToBytes: pointToBytes2,
32668
+ numberToBytesBE: numberToBytesBE2,
32669
+ bytesToNumberBE: bytesToNumberBE2,
32670
+ mod: mod2
32671
+ },
32672
+ lengths: {
32673
+ secretKey: size,
32674
+ publicKey: size,
32675
+ publicKeyHasPrefix: false,
32676
+ signature: size * 2,
32677
+ seed: seedLength
32678
+ }
32679
+ };
32680
+ })();
32681
+
32682
+ // ../routstr-chat/node_modules/@cashu/cashu-ts/lib/cashu-ts.es.js
32683
+ init_sha2();
32684
+ init_utils6();
32685
+
32686
+ // ../routstr-chat/node_modules/@noble/hashes/esm/legacy.js
32687
+ init__md();
32688
+ init_utils6();
32689
+ var Rho160 = /* @__PURE__ */ Uint8Array.from([
32690
+ 7,
32691
+ 4,
32692
+ 13,
32693
+ 1,
32694
+ 10,
32695
+ 6,
32696
+ 15,
32697
+ 3,
32698
+ 12,
32699
+ 0,
32700
+ 9,
32701
+ 5,
32702
+ 2,
32703
+ 14,
32704
+ 11,
32705
+ 8
32706
+ ]);
32707
+ var Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i4) => i4)))();
32708
+ var Pi160 = /* @__PURE__ */ (() => Id160.map((i4) => (9 * i4 + 5) % 16))();
32709
+ var idxLR = /* @__PURE__ */ (() => {
32710
+ const L = [Id160];
32711
+ const R = [Pi160];
32712
+ const res = [L, R];
32713
+ for (let i4 = 0;i4 < 4; i4++)
32714
+ for (let j of res)
32715
+ j.push(j[i4].map((k) => Rho160[k]));
32716
+ return res;
32717
+ })();
32718
+ var idxL = /* @__PURE__ */ (() => idxLR[0])();
32719
+ var idxR = /* @__PURE__ */ (() => idxLR[1])();
32720
+ var shifts160 = /* @__PURE__ */ [
32721
+ [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
32722
+ [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
32723
+ [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
32724
+ [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
32725
+ [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]
32726
+ ].map((i4) => Uint8Array.from(i4));
32727
+ var shiftsL160 = /* @__PURE__ */ idxL.map((idx, i4) => idx.map((j) => shifts160[i4][j]));
32728
+ var shiftsR160 = /* @__PURE__ */ idxR.map((idx, i4) => idx.map((j) => shifts160[i4][j]));
32729
+ var Kl160 = /* @__PURE__ */ Uint32Array.from([
32730
+ 0,
32731
+ 1518500249,
32732
+ 1859775393,
32733
+ 2400959708,
32734
+ 2840853838
32735
+ ]);
32736
+ var Kr160 = /* @__PURE__ */ Uint32Array.from([
32737
+ 1352829926,
32738
+ 1548603684,
32739
+ 1836072691,
32740
+ 2053994217,
32741
+ 0
32742
+ ]);
32743
+ function ripemd_f(group2, x, y, z) {
32744
+ if (group2 === 0)
32745
+ return x ^ y ^ z;
32746
+ if (group2 === 1)
32747
+ return x & y | ~x & z;
32748
+ if (group2 === 2)
32749
+ return (x | ~y) ^ z;
32750
+ if (group2 === 3)
32751
+ return x & z | y & ~z;
32752
+ return x ^ (y | ~z);
32753
+ }
32754
+ var BUF_160 = /* @__PURE__ */ new Uint32Array(16);
32755
+
32756
+ class RIPEMD160 extends HashMD {
32757
+ constructor() {
32758
+ super(64, 20, 8, true);
32759
+ this.h0 = 1732584193 | 0;
32760
+ this.h1 = 4023233417 | 0;
32761
+ this.h2 = 2562383102 | 0;
32762
+ this.h3 = 271733878 | 0;
32763
+ this.h4 = 3285377520 | 0;
32764
+ }
32765
+ get() {
32766
+ const { h0, h1, h2, h3, h4 } = this;
32767
+ return [h0, h1, h2, h3, h4];
32768
+ }
32769
+ set(h0, h1, h2, h3, h4) {
32770
+ this.h0 = h0 | 0;
32771
+ this.h1 = h1 | 0;
32772
+ this.h2 = h2 | 0;
32773
+ this.h3 = h3 | 0;
32774
+ this.h4 = h4 | 0;
32775
+ }
32776
+ process(view, offset) {
32777
+ for (let i4 = 0;i4 < 16; i4++, offset += 4)
32778
+ BUF_160[i4] = view.getUint32(offset, true);
32779
+ let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
32780
+ for (let group2 = 0;group2 < 5; group2++) {
32781
+ const rGroup = 4 - group2;
32782
+ const hbl = Kl160[group2], hbr = Kr160[group2];
32783
+ const rl = idxL[group2], rr = idxR[group2];
32784
+ const sl = shiftsL160[group2], sr = shiftsR160[group2];
32785
+ for (let i4 = 0;i4 < 16; i4++) {
32786
+ const tl = rotl2(al + ripemd_f(group2, bl, cl, dl) + BUF_160[rl[i4]] + hbl, sl[i4]) + el | 0;
32787
+ al = el, el = dl, dl = rotl2(cl, 10) | 0, cl = bl, bl = tl;
32788
+ }
32789
+ for (let i4 = 0;i4 < 16; i4++) {
32790
+ const tr = rotl2(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i4]] + hbr, sr[i4]) + er | 0;
32791
+ ar = er, er = dr, dr = rotl2(cr, 10) | 0, cr = br, br = tr;
32792
+ }
32793
+ }
32794
+ this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0);
32795
+ }
32796
+ roundClean() {
32797
+ clean(BUF_160);
32798
+ }
32799
+ destroy() {
32800
+ this.destroyed = true;
32801
+ clean(this.buffer);
32802
+ this.set(0, 0, 0, 0, 0);
32803
+ }
32804
+ }
32805
+ var ripemd160 = /* @__PURE__ */ createHasher(() => new RIPEMD160);
32806
+
32807
+ // ../routstr-chat/node_modules/@scure/bip32/lib/esm/index.js
32808
+ init_sha2();
32809
+ init_utils6();
32810
+
32811
+ // ../routstr-chat/node_modules/@scure/base/lib/esm/index.js
32812
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
32813
+ function isBytes3(a) {
32814
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
32815
+ }
32816
+ function abytes2(b, ...lengths) {
32817
+ if (!isBytes3(b))
32818
+ throw new Error("Uint8Array expected");
32819
+ if (lengths.length > 0 && !lengths.includes(b.length))
32820
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
32821
+ }
32822
+ function isArrayOf(isString, arr) {
32823
+ if (!Array.isArray(arr))
32824
+ return false;
32825
+ if (arr.length === 0)
32826
+ return true;
32827
+ if (isString) {
32828
+ return arr.every((item) => typeof item === "string");
32829
+ } else {
32830
+ return arr.every((item) => Number.isSafeInteger(item));
32831
+ }
32832
+ }
32833
+ function afn(input) {
32834
+ if (typeof input !== "function")
32835
+ throw new Error("function expected");
32836
+ return true;
32837
+ }
32838
+ function astr(label, input) {
32839
+ if (typeof input !== "string")
32840
+ throw new Error(`${label}: string expected`);
32841
+ return true;
32842
+ }
32843
+ function anumber2(n) {
32844
+ if (!Number.isSafeInteger(n))
32845
+ throw new Error(`invalid integer: ${n}`);
32846
+ }
32847
+ function aArr(input) {
32848
+ if (!Array.isArray(input))
32849
+ throw new Error("array expected");
32850
+ }
32851
+ function astrArr(label, input) {
32852
+ if (!isArrayOf(true, input))
32853
+ throw new Error(`${label}: array of strings expected`);
32854
+ }
32855
+ function anumArr(label, input) {
32856
+ if (!isArrayOf(false, input))
32857
+ throw new Error(`${label}: array of numbers expected`);
32858
+ }
32859
+ function chain2(...args) {
32860
+ const id = (a) => a;
32861
+ const wrap = (a, b) => (c) => a(b(c));
32862
+ const encode = args.map((x) => x.encode).reduceRight(wrap, id);
32863
+ const decode2 = args.map((x) => x.decode).reduce(wrap, id);
32864
+ return { encode, decode: decode2 };
32865
+ }
32866
+ function alphabet2(letters) {
32867
+ const lettersA = typeof letters === "string" ? letters.split("") : letters;
32868
+ const len = lettersA.length;
32869
+ astrArr("alphabet", lettersA);
32870
+ const indexes = new Map(lettersA.map((l, i4) => [l, i4]));
32871
+ return {
32872
+ encode: (digits) => {
32873
+ aArr(digits);
32874
+ return digits.map((i4) => {
32875
+ if (!Number.isSafeInteger(i4) || i4 < 0 || i4 >= len)
32876
+ throw new Error(`alphabet.encode: digit index outside alphabet "${i4}". Allowed: ${letters}`);
32877
+ return lettersA[i4];
32878
+ });
32879
+ },
32880
+ decode: (input) => {
32881
+ aArr(input);
32882
+ return input.map((letter) => {
32883
+ astr("alphabet.decode", letter);
32884
+ const i4 = indexes.get(letter);
32885
+ if (i4 === undefined)
32886
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
32887
+ return i4;
32888
+ });
32889
+ }
32890
+ };
32891
+ }
32892
+ function join4(separator = "") {
32893
+ astr("join", separator);
32894
+ return {
32895
+ encode: (from7) => {
32896
+ astrArr("join.decode", from7);
32897
+ return from7.join(separator);
32898
+ },
32899
+ decode: (to) => {
32900
+ astr("join.decode", to);
32901
+ return to.split(separator);
32902
+ }
32903
+ };
32904
+ }
32905
+ function padding2(bits, chr = "=") {
32906
+ anumber2(bits);
32907
+ astr("padding", chr);
32908
+ return {
32909
+ encode(data) {
32910
+ astrArr("padding.encode", data);
32911
+ while (data.length * bits % 8)
32912
+ data.push(chr);
32913
+ return data;
32914
+ },
32915
+ decode(input) {
32916
+ astrArr("padding.decode", input);
32917
+ let end = input.length;
32918
+ if (end * bits % 8)
32919
+ throw new Error("padding: invalid, string should have whole number of bytes");
32920
+ for (;end > 0 && input[end - 1] === chr; end--) {
32921
+ const last = end - 1;
32922
+ const byte = last * bits;
32923
+ if (byte % 8 === 0)
32924
+ throw new Error("padding: invalid, string has too much padding");
32925
+ }
32926
+ return input.slice(0, end);
32927
+ }
32928
+ };
32929
+ }
32930
+ function normalize2(fn) {
32931
+ afn(fn);
32932
+ return { encode: (from7) => from7, decode: (to) => fn(to) };
32933
+ }
32934
+ function convertRadix3(data, from7, to) {
32935
+ if (from7 < 2)
32936
+ throw new Error(`convertRadix: invalid from=${from7}, base cannot be less than 2`);
32937
+ if (to < 2)
32938
+ throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
32939
+ aArr(data);
32940
+ if (!data.length)
32941
+ return [];
32942
+ let pos = 0;
32943
+ const res = [];
32944
+ const digits = Array.from(data, (d) => {
32945
+ anumber2(d);
32946
+ if (d < 0 || d >= from7)
32947
+ throw new Error(`invalid integer: ${d}`);
32948
+ return d;
32949
+ });
32950
+ const dlen = digits.length;
32951
+ while (true) {
32952
+ let carry = 0;
32953
+ let done = true;
32954
+ for (let i4 = pos;i4 < dlen; i4++) {
32955
+ const digit = digits[i4];
32956
+ const fromCarry = from7 * carry;
32957
+ const digitBase = fromCarry + digit;
32958
+ if (!Number.isSafeInteger(digitBase) || fromCarry / from7 !== carry || digitBase - digit !== fromCarry) {
32959
+ throw new Error("convertRadix: carry overflow");
32960
+ }
32961
+ const div = digitBase / to;
32962
+ carry = digitBase % to;
32963
+ const rounded = Math.floor(div);
32964
+ digits[i4] = rounded;
32965
+ if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
32966
+ throw new Error("convertRadix: carry overflow");
32967
+ if (!done)
32968
+ continue;
32969
+ else if (!rounded)
32970
+ pos = i4;
32971
+ else
32972
+ done = false;
32973
+ }
32974
+ res.push(carry);
32975
+ if (done)
32976
+ break;
32977
+ }
32978
+ for (let i4 = 0;i4 < data.length - 1 && data[i4] === 0; i4++)
32979
+ res.push(0);
32980
+ return res.reverse();
32981
+ }
32982
+ var gcd2 = (a, b) => b === 0 ? a : gcd2(b, a % b);
32983
+ var radix2carry2 = (from7, to) => from7 + (to - gcd2(from7, to));
32984
+ var powers = /* @__PURE__ */ (() => {
32985
+ let res = [];
32986
+ for (let i4 = 0;i4 < 40; i4++)
32987
+ res.push(2 ** i4);
32988
+ return res;
32989
+ })();
32990
+ function convertRadix22(data, from7, to, padding3) {
32991
+ aArr(data);
32992
+ if (from7 <= 0 || from7 > 32)
32993
+ throw new Error(`convertRadix2: wrong from=${from7}`);
32994
+ if (to <= 0 || to > 32)
32995
+ throw new Error(`convertRadix2: wrong to=${to}`);
32996
+ if (radix2carry2(from7, to) > 32) {
32997
+ throw new Error(`convertRadix2: carry overflow from=${from7} to=${to} carryBits=${radix2carry2(from7, to)}`);
32998
+ }
32999
+ let carry = 0;
33000
+ let pos = 0;
33001
+ const max = powers[from7];
33002
+ const mask = powers[to] - 1;
33003
+ const res = [];
33004
+ for (const n of data) {
33005
+ anumber2(n);
33006
+ if (n >= max)
33007
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from7}`);
33008
+ carry = carry << from7 | n;
33009
+ if (pos + from7 > 32)
33010
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from7}`);
33011
+ pos += from7;
33012
+ for (;pos >= to; pos -= to)
33013
+ res.push((carry >> pos - to & mask) >>> 0);
33014
+ const pow3 = powers[pos];
33015
+ if (pow3 === undefined)
33016
+ throw new Error("invalid carry");
33017
+ carry &= pow3 - 1;
33018
+ }
33019
+ carry = carry << to - pos & mask;
33020
+ if (!padding3 && pos >= from7)
33021
+ throw new Error("Excess padding");
33022
+ if (!padding3 && carry > 0)
33023
+ throw new Error(`Non-zero padding: ${carry}`);
33024
+ if (padding3 && pos > 0)
33025
+ res.push(carry >>> 0);
33026
+ return res;
33027
+ }
33028
+ function radix3(num2) {
33029
+ anumber2(num2);
33030
+ const _256 = 2 ** 8;
33031
+ return {
33032
+ encode: (bytes4) => {
33033
+ if (!isBytes3(bytes4))
33034
+ throw new Error("radix.encode input should be Uint8Array");
33035
+ return convertRadix3(Array.from(bytes4), _256, num2);
33036
+ },
33037
+ decode: (digits) => {
33038
+ anumArr("radix.decode", digits);
33039
+ return Uint8Array.from(convertRadix3(digits, num2, _256));
33040
+ }
33041
+ };
33042
+ }
33043
+ function radix22(bits, revPadding = false) {
33044
+ anumber2(bits);
33045
+ if (bits <= 0 || bits > 32)
33046
+ throw new Error("radix2: bits should be in (0..32]");
33047
+ if (radix2carry2(8, bits) > 32 || radix2carry2(bits, 8) > 32)
33048
+ throw new Error("radix2: carry overflow");
33049
+ return {
33050
+ encode: (bytes4) => {
33051
+ if (!isBytes3(bytes4))
33052
+ throw new Error("radix2.encode input should be Uint8Array");
33053
+ return convertRadix22(Array.from(bytes4), 8, bits, !revPadding);
33054
+ },
33055
+ decode: (digits) => {
33056
+ anumArr("radix2.decode", digits);
33057
+ return Uint8Array.from(convertRadix22(digits, bits, 8, revPadding));
33058
+ }
33059
+ };
33060
+ }
33061
+ function unsafeWrapper2(fn) {
33062
+ afn(fn);
33063
+ return function(...args) {
33064
+ try {
33065
+ return fn.apply(null, args);
33066
+ } catch (e) {}
33067
+ };
33068
+ }
33069
+ function checksum(len, fn) {
33070
+ anumber2(len);
33071
+ afn(fn);
33072
+ return {
33073
+ encode(data) {
33074
+ if (!isBytes3(data))
33075
+ throw new Error("checksum.encode: input should be Uint8Array");
33076
+ const sum = fn(data).slice(0, len);
33077
+ const res = new Uint8Array(data.length + len);
33078
+ res.set(data);
33079
+ res.set(sum, data.length);
33080
+ return res;
33081
+ },
33082
+ decode(data) {
33083
+ if (!isBytes3(data))
33084
+ throw new Error("checksum.decode: input should be Uint8Array");
33085
+ const payload = data.slice(0, -len);
33086
+ const oldChecksum = data.slice(-len);
33087
+ const newChecksum = fn(payload).slice(0, len);
33088
+ for (let i4 = 0;i4 < len; i4++)
33089
+ if (newChecksum[i4] !== oldChecksum[i4])
33090
+ throw new Error("Invalid checksum");
33091
+ return payload;
33092
+ }
33093
+ };
33094
+ }
33095
+ var base162 = chain2(radix22(4), alphabet2("0123456789ABCDEF"), join4(""));
33096
+ var base322 = chain2(radix22(5), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding2(5), join4(""));
33097
+ var base32nopad = chain2(radix22(5), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), join4(""));
33098
+ var base32hex2 = chain2(radix22(5), alphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding2(5), join4(""));
33099
+ var base32hexnopad = chain2(radix22(5), alphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUV"), join4(""));
33100
+ var base32crockford2 = chain2(radix22(5), alphabet2("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join4(""), normalize2((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
33101
+ var hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")();
33102
+ var decodeBase64Builtin = (s, isUrl) => {
33103
+ astr("base64", s);
33104
+ const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;
33105
+ const alphabet3 = isUrl ? "base64url" : "base64";
33106
+ if (s.length > 0 && !re.test(s))
33107
+ throw new Error("invalid base64");
33108
+ return Uint8Array.fromBase64(s, { alphabet: alphabet3, lastChunkHandling: "strict" });
33109
+ };
33110
+ var base642 = hasBase64Builtin ? {
33111
+ encode(b) {
33112
+ abytes2(b);
33113
+ return b.toBase64();
33114
+ },
33115
+ decode(s) {
33116
+ return decodeBase64Builtin(s, false);
33117
+ }
33118
+ } : chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding2(6), join4(""));
33119
+ var base64nopad = chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), join4(""));
33120
+ var base64url2 = hasBase64Builtin ? {
33121
+ encode(b) {
33122
+ abytes2(b);
33123
+ return b.toBase64({ alphabet: "base64url" });
33124
+ },
33125
+ decode(s) {
33126
+ return decodeBase64Builtin(s, true);
33127
+ }
33128
+ } : chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding2(6), join4(""));
33129
+ var base64urlnopad = chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), join4(""));
33130
+ var genBase582 = (abc) => chain2(radix3(58), alphabet2(abc), join4(""));
33131
+ var base582 = genBase582("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
33132
+ var base58flickr2 = genBase582("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
33133
+ var base58xrp2 = genBase582("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
33134
+ var createBase58check = (sha2564) => chain2(checksum(4, (data) => sha2564(sha2564(data))), base582);
33135
+ var BECH_ALPHABET2 = chain2(alphabet2("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join4(""));
33136
+ var POLYMOD_GENERATORS2 = [996825010, 642813549, 513874426, 1027748829, 705979059];
33137
+ function bech32Polymod2(pre) {
33138
+ const b = pre >> 25;
33139
+ let chk = (pre & 33554431) << 5;
33140
+ for (let i4 = 0;i4 < POLYMOD_GENERATORS2.length; i4++) {
33141
+ if ((b >> i4 & 1) === 1)
33142
+ chk ^= POLYMOD_GENERATORS2[i4];
33143
+ }
33144
+ return chk;
33145
+ }
33146
+ function bechChecksum2(prefix, words, encodingConst = 1) {
33147
+ const len = prefix.length;
33148
+ let chk = 1;
33149
+ for (let i4 = 0;i4 < len; i4++) {
33150
+ const c = prefix.charCodeAt(i4);
33151
+ if (c < 33 || c > 126)
33152
+ throw new Error(`Invalid prefix (${prefix})`);
33153
+ chk = bech32Polymod2(chk) ^ c >> 5;
33154
+ }
33155
+ chk = bech32Polymod2(chk);
33156
+ for (let i4 = 0;i4 < len; i4++)
33157
+ chk = bech32Polymod2(chk) ^ prefix.charCodeAt(i4) & 31;
33158
+ for (let v of words)
33159
+ chk = bech32Polymod2(chk) ^ v;
33160
+ for (let i4 = 0;i4 < 6; i4++)
33161
+ chk = bech32Polymod2(chk);
33162
+ chk ^= encodingConst;
33163
+ return BECH_ALPHABET2.encode(convertRadix22([chk % powers[30]], 30, 5, false));
33164
+ }
33165
+ function genBech322(encoding) {
33166
+ const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
33167
+ const _words = radix22(5);
33168
+ const fromWords = _words.decode;
33169
+ const toWords = _words.encode;
33170
+ const fromWordsUnsafe = unsafeWrapper2(fromWords);
33171
+ function encode(prefix, words, limit2 = 90) {
33172
+ astr("bech32.encode prefix", prefix);
33173
+ if (isBytes3(words))
33174
+ words = Array.from(words);
33175
+ anumArr("bech32.encode", words);
33176
+ const plen = prefix.length;
33177
+ if (plen === 0)
33178
+ throw new TypeError(`Invalid prefix length ${plen}`);
33179
+ const actualLength = plen + 7 + words.length;
33180
+ if (limit2 !== false && actualLength > limit2)
33181
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit2}`);
33182
+ const lowered = prefix.toLowerCase();
33183
+ const sum = bechChecksum2(lowered, words, ENCODING_CONST);
33184
+ return `${lowered}1${BECH_ALPHABET2.encode(words)}${sum}`;
33185
+ }
33186
+ function decode2(str, limit2 = 90) {
33187
+ astr("bech32.decode input", str);
33188
+ const slen = str.length;
33189
+ if (slen < 8 || limit2 !== false && slen > limit2)
33190
+ throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit2})`);
33191
+ const lowered = str.toLowerCase();
33192
+ if (str !== lowered && str !== str.toUpperCase())
33193
+ throw new Error(`String must be lowercase or uppercase`);
33194
+ const sepIndex = lowered.lastIndexOf("1");
33195
+ if (sepIndex === 0 || sepIndex === -1)
33196
+ throw new Error(`Letter "1" must be present between prefix and data only`);
33197
+ const prefix = lowered.slice(0, sepIndex);
33198
+ const data = lowered.slice(sepIndex + 1);
33199
+ if (data.length < 6)
33200
+ throw new Error("Data must be at least 6 characters long");
33201
+ const words = BECH_ALPHABET2.decode(data).slice(0, -6);
33202
+ const sum = bechChecksum2(prefix, words, ENCODING_CONST);
33203
+ if (!data.endsWith(sum))
33204
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
33205
+ return { prefix, words };
33206
+ }
33207
+ const decodeUnsafe = unsafeWrapper2(decode2);
33208
+ function decodeToBytes(str) {
33209
+ const { prefix, words } = decode2(str, false);
33210
+ return { prefix, words, bytes: fromWords(words) };
33211
+ }
33212
+ function encodeFromBytes(prefix, bytes4) {
33213
+ return encode(prefix, toWords(bytes4));
33214
+ }
33215
+ return {
33216
+ encode,
33217
+ decode: decode2,
33218
+ encodeFromBytes,
33219
+ decodeToBytes,
33220
+ decodeUnsafe,
33221
+ fromWords,
33222
+ fromWordsUnsafe,
33223
+ toWords
33224
+ };
33225
+ }
33226
+ var bech322 = genBech322("bech32");
33227
+ var bech32m2 = genBech322("bech32m");
33228
+ var hasHexBuiltin2 = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
33229
+ var hexBuiltin = {
33230
+ encode(data) {
33231
+ abytes2(data);
33232
+ return data.toHex();
33233
+ },
33234
+ decode(s) {
33235
+ astr("hex", s);
33236
+ return Uint8Array.fromHex(s);
33237
+ }
33238
+ };
33239
+ var hex2 = hasHexBuiltin2 ? hexBuiltin : chain2(radix22(4), alphabet2("0123456789abcdef"), join4(""), normalize2((s) => {
33240
+ if (typeof s !== "string" || s.length % 2 !== 0)
33241
+ throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
33242
+ return s.toLowerCase();
33243
+ }));
33244
+
33245
+ // ../routstr-chat/node_modules/@scure/bip32/lib/esm/index.js
33246
+ /*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
33247
+ var Point2 = secp256k12.ProjectivePoint;
33248
+ var base58check = createBase58check(sha2563);
33249
+ function bytesToNumber(bytes4) {
33250
+ abytes(bytes4);
33251
+ const h = bytes4.length === 0 ? "0" : bytesToHex4(bytes4);
33252
+ return BigInt("0x" + h);
33253
+ }
33254
+ function numberToBytes(num2) {
33255
+ if (typeof num2 !== "bigint")
33256
+ throw new Error("bigint expected");
33257
+ return hexToBytes4(num2.toString(16).padStart(64, "0"));
33258
+ }
33259
+ var MASTER_SECRET = utf8ToBytes5("Bitcoin seed");
33260
+ var BITCOIN_VERSIONS = { private: 76066276, public: 76067358 };
33261
+ var HARDENED_OFFSET = 2147483648;
33262
+ var hash160 = (data) => ripemd160(sha2563(data));
33263
+ var fromU32 = (data) => createView4(data).getUint32(0, false);
33264
+ var toU32 = (n) => {
33265
+ if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {
33266
+ throw new Error("invalid number, should be from 0 to 2**32-1, got " + n);
33267
+ }
33268
+ const buf = new Uint8Array(4);
33269
+ createView4(buf).setUint32(0, n, false);
33270
+ return buf;
33271
+ };
33272
+
33273
+ class HDKey {
33274
+ get fingerprint() {
33275
+ if (!this.pubHash) {
33276
+ throw new Error("No publicKey set!");
33277
+ }
33278
+ return fromU32(this.pubHash);
33279
+ }
33280
+ get identifier() {
33281
+ return this.pubHash;
33282
+ }
33283
+ get pubKeyHash() {
33284
+ return this.pubHash;
33285
+ }
33286
+ get privateKey() {
33287
+ return this.privKeyBytes || null;
33288
+ }
33289
+ get publicKey() {
33290
+ return this.pubKey || null;
33291
+ }
33292
+ get privateExtendedKey() {
33293
+ const priv = this.privateKey;
33294
+ if (!priv) {
33295
+ throw new Error("No private key");
33296
+ }
33297
+ return base58check.encode(this.serialize(this.versions.private, concatBytes4(new Uint8Array([0]), priv)));
33298
+ }
33299
+ get publicExtendedKey() {
33300
+ if (!this.pubKey) {
33301
+ throw new Error("No public key");
33302
+ }
33303
+ return base58check.encode(this.serialize(this.versions.public, this.pubKey));
33304
+ }
33305
+ static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
33306
+ abytes(seed);
33307
+ if (8 * seed.length < 128 || 8 * seed.length > 512) {
33308
+ throw new Error("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got " + seed.length);
33309
+ }
33310
+ const I = hmac3(sha512, MASTER_SECRET, seed);
33311
+ return new HDKey({
33312
+ versions,
33313
+ chainCode: I.slice(32),
33314
+ privateKey: I.slice(0, 32)
33315
+ });
33316
+ }
33317
+ static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
33318
+ const keyBuffer = base58check.decode(base58key);
33319
+ const keyView = createView4(keyBuffer);
33320
+ const version = keyView.getUint32(0, false);
33321
+ const opt = {
33322
+ versions,
33323
+ depth: keyBuffer[4],
33324
+ parentFingerprint: keyView.getUint32(5, false),
33325
+ index: keyView.getUint32(9, false),
33326
+ chainCode: keyBuffer.slice(13, 45)
33327
+ };
33328
+ const key = keyBuffer.slice(45);
33329
+ const isPriv = key[0] === 0;
33330
+ if (version !== versions[isPriv ? "private" : "public"]) {
33331
+ throw new Error("Version mismatch");
33332
+ }
33333
+ if (isPriv) {
33334
+ return new HDKey({ ...opt, privateKey: key.slice(1) });
33335
+ } else {
33336
+ return new HDKey({ ...opt, publicKey: key });
33337
+ }
33338
+ }
33339
+ static fromJSON(json2) {
33340
+ return HDKey.fromExtendedKey(json2.xpriv);
33341
+ }
33342
+ constructor(opt) {
33343
+ this.depth = 0;
33344
+ this.index = 0;
33345
+ this.chainCode = null;
33346
+ this.parentFingerprint = 0;
33347
+ if (!opt || typeof opt !== "object") {
33348
+ throw new Error("HDKey.constructor must not be called directly");
33349
+ }
33350
+ this.versions = opt.versions || BITCOIN_VERSIONS;
33351
+ this.depth = opt.depth || 0;
33352
+ this.chainCode = opt.chainCode || null;
33353
+ this.index = opt.index || 0;
33354
+ this.parentFingerprint = opt.parentFingerprint || 0;
33355
+ if (!this.depth) {
33356
+ if (this.parentFingerprint || this.index) {
33357
+ throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");
33358
+ }
33359
+ }
33360
+ if (opt.publicKey && opt.privateKey) {
33361
+ throw new Error("HDKey: publicKey and privateKey at same time.");
33362
+ }
33363
+ if (opt.privateKey) {
33364
+ if (!secp256k12.utils.isValidPrivateKey(opt.privateKey)) {
33365
+ throw new Error("Invalid private key");
33366
+ }
33367
+ this.privKey = typeof opt.privateKey === "bigint" ? opt.privateKey : bytesToNumber(opt.privateKey);
33368
+ this.privKeyBytes = numberToBytes(this.privKey);
33369
+ this.pubKey = secp256k12.getPublicKey(opt.privateKey, true);
33370
+ } else if (opt.publicKey) {
33371
+ this.pubKey = Point2.fromHex(opt.publicKey).toRawBytes(true);
33372
+ } else {
33373
+ throw new Error("HDKey: no public or private key provided");
33374
+ }
33375
+ this.pubHash = hash160(this.pubKey);
33376
+ }
33377
+ derive(path) {
33378
+ if (!/^[mM]'?/.test(path)) {
33379
+ throw new Error('Path must start with "m" or "M"');
33380
+ }
33381
+ if (/^[mM]'?$/.test(path)) {
33382
+ return this;
33383
+ }
33384
+ const parts = path.replace(/^[mM]'?\//, "").split("/");
33385
+ let child = this;
33386
+ for (const c of parts) {
33387
+ const m = /^(\d+)('?)$/.exec(c);
33388
+ const m1 = m && m[1];
33389
+ if (!m || m.length !== 3 || typeof m1 !== "string")
33390
+ throw new Error("invalid child index: " + c);
33391
+ let idx = +m1;
33392
+ if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
33393
+ throw new Error("Invalid index");
33394
+ }
33395
+ if (m[2] === "'") {
33396
+ idx += HARDENED_OFFSET;
33397
+ }
33398
+ child = child.deriveChild(idx);
33399
+ }
33400
+ return child;
33401
+ }
33402
+ deriveChild(index) {
33403
+ if (!this.pubKey || !this.chainCode) {
33404
+ throw new Error("No publicKey or chainCode set");
33405
+ }
33406
+ let data = toU32(index);
33407
+ if (index >= HARDENED_OFFSET) {
33408
+ const priv = this.privateKey;
33409
+ if (!priv) {
33410
+ throw new Error("Could not derive hardened child key");
33411
+ }
33412
+ data = concatBytes4(new Uint8Array([0]), priv, data);
33413
+ } else {
33414
+ data = concatBytes4(this.pubKey, data);
33415
+ }
33416
+ const I = hmac3(sha512, this.chainCode, data);
33417
+ const childTweak = bytesToNumber(I.slice(0, 32));
33418
+ const chainCode = I.slice(32);
33419
+ if (!secp256k12.utils.isValidPrivateKey(childTweak)) {
33420
+ throw new Error("Tweak bigger than curve order");
33421
+ }
33422
+ const opt = {
33423
+ versions: this.versions,
33424
+ chainCode,
33425
+ depth: this.depth + 1,
33426
+ parentFingerprint: this.fingerprint,
33427
+ index
33428
+ };
33429
+ try {
33430
+ if (this.privateKey) {
33431
+ const added = mod2(this.privKey + childTweak, secp256k12.CURVE.n);
33432
+ if (!secp256k12.utils.isValidPrivateKey(added)) {
33433
+ throw new Error("The tweak was out of range or the resulted private key is invalid");
33434
+ }
33435
+ opt.privateKey = added;
33436
+ } else {
33437
+ const added = Point2.fromHex(this.pubKey).add(Point2.fromPrivateKey(childTweak));
33438
+ if (added.equals(Point2.ZERO)) {
33439
+ throw new Error("The tweak was equal to negative P, which made the result key invalid");
33440
+ }
33441
+ opt.publicKey = added.toRawBytes(true);
33442
+ }
33443
+ return new HDKey(opt);
33444
+ } catch (err) {
33445
+ return this.deriveChild(index + 1);
33446
+ }
33447
+ }
33448
+ sign(hash3) {
33449
+ if (!this.privateKey) {
33450
+ throw new Error("No privateKey set!");
33451
+ }
33452
+ abytes(hash3, 32);
33453
+ return secp256k12.sign(hash3, this.privKey).toCompactRawBytes();
33454
+ }
33455
+ verify(hash3, signature) {
33456
+ abytes(hash3, 32);
33457
+ abytes(signature, 64);
33458
+ if (!this.publicKey) {
33459
+ throw new Error("No publicKey set!");
33460
+ }
33461
+ let sig;
33462
+ try {
33463
+ sig = secp256k12.Signature.fromCompact(signature);
33464
+ } catch (error) {
33465
+ return false;
33466
+ }
33467
+ return secp256k12.verify(sig, hash3, this.publicKey);
33468
+ }
33469
+ wipePrivateData() {
33470
+ this.privKey = undefined;
33471
+ if (this.privKeyBytes) {
33472
+ this.privKeyBytes.fill(0);
33473
+ this.privKeyBytes = undefined;
33474
+ }
33475
+ return this;
33476
+ }
33477
+ toJSON() {
33478
+ return {
33479
+ xpriv: this.privateExtendedKey,
33480
+ xpub: this.publicExtendedKey
33481
+ };
33482
+ }
33483
+ serialize(version, key) {
33484
+ if (!this.chainCode) {
33485
+ throw new Error("No chainCode set");
33486
+ }
33487
+ abytes(key, 33);
33488
+ return concatBytes4(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
33489
+ }
33490
+ }
33491
+
33492
+ // ../routstr-chat/node_modules/@cashu/cashu-ts/lib/cashu-ts.es.js
33493
+ var ut = {
33494
+ UNPAID: "UNPAID",
33495
+ PENDING: "PENDING",
33496
+ PAID: "PAID"
33497
+ };
33498
+ var Tt = {
33499
+ UNPAID: "UNPAID",
33500
+ PAID: "PAID",
33501
+ ISSUED: "ISSUED"
33502
+ };
33503
+
33504
+ class ht extends Error {
33505
+ constructor(t, e) {
33506
+ super(t), this.status = e, this.name = "HttpResponseError", Object.setPrototypeOf(this, ht.prototype);
33507
+ }
33508
+ }
33509
+
33510
+ class Kt extends Error {
33511
+ constructor(t) {
33512
+ super(t), this.name = "NetworkError", Object.setPrototypeOf(this, Kt.prototype);
33513
+ }
33514
+ }
33515
+
33516
+ class Dt extends ht {
33517
+ constructor(t, e) {
33518
+ super(e || "Unknown mint operation error", 400), this.code = t, this.name = "MintOperationError", Object.setPrototypeOf(this, Dt.prototype);
33519
+ }
33520
+ }
33521
+ var L = {
33522
+ error() {},
33523
+ warn() {},
33524
+ info() {},
33525
+ debug() {},
33526
+ trace() {},
33527
+ log() {}
33528
+ };
33529
+ function lt(s, t, e = L, n) {
33530
+ if (s)
33531
+ try {
33532
+ const r = s(t);
33533
+ r && typeof r.then == "function" && r.catch((i4) => {
33534
+ try {
33535
+ e.warn("callback failed", {
33536
+ ...n ?? {},
33537
+ error: i4,
33538
+ cb: s.name ?? ""
33539
+ });
33540
+ } catch {}
33541
+ });
33542
+ } catch (r) {
33543
+ try {
33544
+ e.warn("callback failed", {
33545
+ ...n ?? {},
33546
+ error: r,
33547
+ cb: s.name ?? ""
33548
+ });
33549
+ } catch {}
33550
+ }
33551
+ }
33552
+ var fe2 = {};
33553
+ var ge2 = L;
33554
+ function je(s) {
33555
+ ge2 = s;
33556
+ }
33557
+ async function Qe({
33558
+ endpoint: s,
33559
+ requestBody: t,
33560
+ headers: e,
33561
+ ...n
33562
+ }) {
33563
+ const r = t ? JSON.stringify(t) : undefined, i4 = {
33564
+ Accept: "application/json, text/plain, */*",
33565
+ ...r ? { "Content-Type": "application/json" } : undefined,
33566
+ ...e
33567
+ };
33568
+ let o;
33569
+ try {
33570
+ o = await fetch(s, { body: r, headers: i4, ...n });
33571
+ } catch (a) {
33572
+ throw new Kt(a instanceof Error ? a.message : "Network request failed");
33573
+ }
33574
+ if (!o.ok) {
33575
+ let a;
33576
+ try {
33577
+ a = await o.json();
33578
+ } catch {
33579
+ a = { error: "bad response" };
33580
+ }
33581
+ if (o.status === 400 && "code" in a && typeof a.code == "number" && "detail" in a && typeof a.detail == "string")
33582
+ throw new Dt(a.code, a.detail);
33583
+ let c = "HTTP request failed";
33584
+ throw "error" in a && typeof a.error == "string" ? c = a.error : ("detail" in a) && typeof a.detail == "string" && (c = a.detail), new ht(c, o.status);
33585
+ }
33586
+ try {
33587
+ return await o.json();
33588
+ } catch (a) {
33589
+ throw ge2.error("Failed to parse HTTP response", { err: a }), new ht("bad response", o.status);
33590
+ }
33591
+ }
33592
+ async function pe(s) {
33593
+ return await Qe({ ...s, ...fe2 });
33594
+ }
33595
+ var pt;
33596
+ typeof WebSocket < "u" && (pt = WebSocket);
33597
+ function ze() {
33598
+ if (pt === undefined)
33599
+ throw new Error("WebSocket implementation not initialized");
33600
+ return pt;
33601
+ }
33602
+
33603
+ class _ {
33604
+ static fromHex(t) {
33605
+ if (t = t.trim(), t.length === 0)
33606
+ return new Uint8Array(0);
33607
+ if (t.length < 2 || t.length & 1)
33608
+ throw new Error("Invalid hex string: odd length.");
33609
+ if ((t.startsWith("0x") || t.startsWith("0X")) && (t = t.slice(2)), !t.match(/^[0-9a-fA-F]*$/))
33610
+ throw new Error("Invalid hex string: contains non-hex characters");
33611
+ const n = t.match(/.{1,2}/g);
33612
+ if (!n)
33613
+ throw new Error("Invalid hex string");
33614
+ return new Uint8Array(n.map((r) => parseInt(r, 16)));
33615
+ }
33616
+ static toHex(t) {
33617
+ return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
33618
+ }
33619
+ static fromString(t) {
33620
+ return t = t.trim(), new TextEncoder().encode(t);
33621
+ }
33622
+ static toString(t) {
33623
+ return new TextDecoder("utf-8").decode(t);
33624
+ }
33625
+ static concat(...t) {
33626
+ const e = t.reduce((i4, o) => i4 + o.length, 0), n = new Uint8Array(e);
33627
+ let r = 0;
33628
+ for (const i4 of t)
33629
+ n.set(i4, r), r += i4.length;
33630
+ return n;
33631
+ }
33632
+ static alloc(t) {
33633
+ return new Uint8Array(t);
33634
+ }
33635
+ static writeBigUint64BE(t) {
33636
+ const e = new ArrayBuffer(8);
33637
+ return new DataView(e).setBigUint64(0, t, false), new Uint8Array(e);
33638
+ }
33639
+ static toBase64(t) {
33640
+ if (typeof Buffer < "u")
33641
+ return Buffer.from(t).toString("base64");
33642
+ if (t.length > 32768) {
33643
+ let e = "";
33644
+ for (let n = 0;n < t.length; n += 32768) {
33645
+ const r = t.slice(n, n + 32768);
33646
+ e += btoa(String.fromCharCode(...r));
33647
+ }
33648
+ return e;
33649
+ }
33650
+ return btoa(String.fromCharCode(...t));
33651
+ }
33652
+ static fromBase64(t) {
33653
+ t = t.trim();
33654
+ let e = t.replace(/-/g, "+").replace(/_/g, "/");
33655
+ for (;e.length % 4; )
33656
+ e += "=";
33657
+ return typeof Buffer < "u" ? new Uint8Array(Buffer.from(e, "base64")) : new Uint8Array([...atob(e)].map((n) => n.charCodeAt(0)));
33658
+ }
33659
+ static equals(t, e) {
33660
+ if (t.length !== e.length)
33661
+ return false;
33662
+ let n = 0;
33663
+ for (let r = 0;r < t.length; r++)
33664
+ n |= t[r] ^ e[r];
33665
+ return n === 0;
33666
+ }
33667
+ static compare(t, e) {
33668
+ const n = Math.min(t.length, e.length);
33669
+ for (let r = 0;r < n; r++) {
33670
+ if (t[r] < e[r])
33671
+ return -1;
33672
+ if (t[r] > e[r])
33673
+ return 1;
33674
+ }
33675
+ return t.length - e.length;
33676
+ }
33677
+ }
33678
+ function It(s) {
33679
+ return _.toBase64(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
33680
+ }
33681
+ function qt(s) {
33682
+ return _.fromBase64(s);
33683
+ }
33684
+ function me(s) {
33685
+ const t = JSON.stringify(s);
33686
+ return Je(_.toBase64(_.fromString(t)));
33687
+ }
33688
+ function Je(s) {
33689
+ return s.replace(/\+/g, "-").replace(/\//g, "_").split("=")[0];
33690
+ }
33691
+ function Ut(s) {
33692
+ if (typeof s != "string" || s.length === 0)
33693
+ return false;
33694
+ const t = /^[A-Za-z0-9\-_]+={0,2}$/, e = /^[A-Za-z0-9+/]+={0,2}$/;
33695
+ if (!t.test(s) && !e.test(s))
33696
+ return false;
33697
+ const n = s.replace(/-/g, "+").replace(/_/g, "/"), r = (4 - n.length % 4) % 4;
33698
+ if (r > 2)
33699
+ return false;
33700
+ const i4 = n + "=".repeat(r);
33701
+ try {
33702
+ const o = _.fromBase64(i4), a = _.toBase64(o), c = a.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""), u = n.replace(/=+$/, "");
33703
+ return a.replace(/=+$/, "") === u || c === u;
33704
+ } catch {
33705
+ return false;
33706
+ }
33707
+ }
33708
+ var Zt = utf8ToBytes5("Cashu_P2BK_v1");
33709
+ function gn(s, t, e) {
33710
+ if (!s.length)
33711
+ return { blinded: [], Ehex: "" };
33712
+ e = e ?? secp256k12.utils.randomSecretKey();
33713
+ const n = secp256k12.Point.Fn.fromBytes(e), r = secp256k12.getPublicKey(e, true), i4 = hexToBytes4(t);
33714
+ return { blinded: s.map((a, c) => {
33715
+ const u = X(a), l = we(u, n, i4, c), h = u.add(secp256k12.Point.BASE.multiply(l));
33716
+ if (h.equals(secp256k12.Point.ZERO))
33717
+ throw new Error("Blinded key at infinity");
33718
+ return h.toHex(true);
33719
+ }), Ehex: bytesToHex4(r) };
33720
+ }
33721
+ function we(s, t, e, n) {
33722
+ const r = s.multiply(t).toBytes(true).slice(1), i4 = new Uint8Array([n & 255]);
33723
+ let o = $(sha2563(_.concat(Zt, r, e, i4)));
33724
+ if ((o === 0n || o >= secp256k12.Point.CURVE().n) && (o = $(sha2563(_.concat(Zt, r, e, i4, new Uint8Array([255])))), o === 0n || o >= secp256k12.Point.CURVE().n))
33725
+ throw new Error("P2BK: tweak derivation failed");
33726
+ return o;
33727
+ }
33728
+ var wn = (s, t) => {
33729
+ const e = sha2563(s), n = schnorr2.sign(e, t);
33730
+ return bytesToHex4(n);
33731
+ };
33732
+ var Pe = (s, t) => {
33733
+ const e = s.B_.toHex(true), n = wn(e, t);
33734
+ return s.witness = { signatures: [n] }, s;
33735
+ };
33736
+ var An = hexToBytes4("536563703235366b315f48617368546f43757276655f43617368755f");
33737
+ function ft(s) {
33738
+ const t = sha2563(_.concat(An, s)), e = new Uint32Array(1), n = 2 ** 16;
33739
+ for (let r = 0;r < n; r++) {
33740
+ const i4 = new Uint8Array(e.buffer), o = sha2563(_.concat(t, i4));
33741
+ try {
33742
+ return X(bytesToHex4(_.concat(new Uint8Array([2]), o)));
33743
+ } catch {
33744
+ e[0]++;
33745
+ }
33746
+ }
33747
+ throw new Error("No valid point found");
33748
+ }
33749
+ function Ae(s) {
33750
+ const e = s.map((n) => n.toHex(false)).join("");
33751
+ return sha2563(new TextEncoder().encode(e));
33752
+ }
33753
+ function X(s) {
33754
+ return secp256k12.Point.fromHex(s);
33755
+ }
33756
+ var vn = (s) => {
33757
+ let t;
33758
+ return /^[a-fA-F0-9]+$/.test(s) ? t = dt(s) % BigInt(2 ** 31 - 1) : t = $(qt(s)) % BigInt(2 ** 31 - 1), t;
33759
+ };
33760
+ function gt(s, t, e) {
33761
+ const n = ft(s);
33762
+ t || (t = $(secp256k12.utils.randomSecretKey()));
33763
+ const r = secp256k12.Point.BASE.multiply(t), i4 = n.add(r);
33764
+ return e !== undefined ? Pe({ B_: i4, r: t, secret: s }, e) : { B_: i4, r: t, secret: s };
33765
+ }
33766
+ function En(s, t, e) {
33767
+ return s.subtract(e.multiply(t));
33768
+ }
33769
+ function Sn(s, t, e, n) {
33770
+ const r = n, i4 = En(s.C_, t, r);
33771
+ return {
33772
+ id: s.id,
33773
+ amount: s.amount,
33774
+ secret: e,
33775
+ C: i4
33776
+ };
33777
+ }
33778
+ var Tn = (s) => ({
33779
+ amount: s.amount,
33780
+ C: s.C.toHex(true),
33781
+ id: s.id,
33782
+ secret: new TextDecoder().decode(s.secret),
33783
+ witness: JSON.stringify(s.witness)
33784
+ });
33785
+ var Cn = "m/129372'/0'";
33786
+ var xn = (s, t, e) => {
33787
+ const n = /^[a-fA-F0-9]+$/.test(t);
33788
+ if (!n && Ut(t) || n && t.startsWith("00"))
33789
+ return yt(s, t, e, 0);
33790
+ if (n && t.startsWith("01"))
33791
+ return Ee(s, t, e, 0);
33792
+ throw new Error(`Unrecognized keyset ID version ${t.slice(0, 2)}`);
33793
+ };
33794
+ var Bn = (s, t, e) => {
33795
+ const n = /^[a-fA-F0-9]+$/.test(t);
33796
+ if (!n && Ut(t) || n && t.startsWith("00"))
33797
+ return yt(s, t, e, 1);
33798
+ if (n && t.startsWith("01"))
33799
+ return Ee(s, t, e, 1);
33800
+ throw new Error(`Unrecognized keyset ID version ${t.slice(0, 2)}`);
33801
+ };
33802
+ var Ee = (s, t, e, n) => {
33803
+ let r = _.concat(_.fromString("Cashu_KDF_HMAC_SHA256"), _.fromHex(t), _.writeBigUint64BE(BigInt(e)));
33804
+ switch (n) {
33805
+ case 0:
33806
+ r = _.concat(r, _.fromHex("00"));
33807
+ break;
33808
+ case 1:
33809
+ r = _.concat(r, _.fromHex("01"));
33810
+ }
33811
+ return hmac3(sha2563, s, r);
33812
+ };
33813
+ var yt = (s, t, e, n) => {
33814
+ const r = HDKey.fromMasterSeed(s), i4 = vn(t), o = `${Cn}/${i4}'/${e}'/${n}`, a = r.derive(o);
33815
+ if (a.privateKey === null)
33816
+ throw new Error("Could not derive private key");
33817
+ return a.privateKey;
33818
+ };
33819
+ function On(s, t) {
33820
+ if (s.length !== t.length)
33821
+ return false;
33822
+ for (let e = 0;e < s.length; e++)
33823
+ if (s[e] !== t[e])
33824
+ return false;
33825
+ return true;
33826
+ }
33827
+ var Kn = (s, t, e, n) => {
33828
+ const r = secp256k12.Point.BASE.multiply(secp256k12.Point.Fn.fromBytes(s.s)), i4 = n.multiply($(s.e)), o = t.multiply($(s.s)), a = e.multiply($(s.e)), c = r.subtract(i4), u = o.subtract(a), l = Ae([c, u, n, e]);
33829
+ return On(l, s.e);
33830
+ };
33831
+ var Dn = (s, t, e, n) => {
33832
+ if (t.r === undefined)
33833
+ throw new Error("verifyDLEQProof_reblind: Undefined blinding factor");
33834
+ const r = ft(s), i4 = e.add(n.multiply(t.r)), o = secp256k12.Point.BASE.multiply(t.r), a = r.add(o);
33835
+ return Kn(t, a, i4, n);
33836
+ };
33837
+ function G(s, t, e, n) {
33838
+ if (e) {
33839
+ const i4 = ee(e);
33840
+ if (s === 0 && i4 === 0)
33841
+ return e;
33842
+ const o = e.filter((c) => c > 0), a = ee(o);
33843
+ if (a > s)
33844
+ throw new Error(`Split is greater than total amount: ${a} > ${s}`);
33845
+ if (o.some((c) => !Ie(c, t)))
33846
+ throw new Error("Provided amount preferences do not match the amounts of the mint keyset.");
33847
+ if (a === s)
33848
+ return o;
33849
+ e = o, s -= a;
33850
+ } else
33851
+ e = [];
33852
+ const r = Te(t, "desc");
33853
+ if (!r || r.length === 0)
33854
+ throw new Error("Cannot split amount, keyset is inactive or contains no keys");
33855
+ for (const i4 of r) {
33856
+ if (i4 <= 0)
33857
+ continue;
33858
+ const o = Math.floor(s / i4);
33859
+ if (e.push(...Array(o).fill(i4)), s -= i4 * o, s === 0)
33860
+ break;
33861
+ }
33862
+ if (s !== 0)
33863
+ throw new Error(`Unable to split remaining amount: ${s}`);
33864
+ return n ? e.sort((i4, o) => n === "desc" ? o - i4 : i4 - o) : e;
33865
+ }
33866
+ function Te(s, t = "desc") {
33867
+ return t == "desc" ? Object.keys(s).map((e) => parseInt(e)).sort((e, n) => n - e) : Object.keys(s).map((e) => parseInt(e)).sort((e, n) => e - n);
33868
+ }
33869
+ function Ie(s, t) {
33870
+ return s in t;
33871
+ }
33872
+ function $(s) {
33873
+ return dt(bytesToHex4(s));
33874
+ }
33875
+ function dt(s) {
33876
+ return BigInt(`0x${s}`);
33877
+ }
33878
+ function Mt(s) {
33879
+ return s.toString(16).padStart(64, "0");
33880
+ }
33881
+ function Ct(s) {
33882
+ return /^[a-f0-9]*$/i.test(s);
33883
+ }
33884
+ function Qt(s, t, e, n = 0, r = false) {
33885
+ if (r) {
33886
+ const c = Object.entries(s).sort((h, d) => +h[0] - +d[0]).map(([, h]) => h).reduce((h, d) => h + d, ""), u = sha2563(c);
33887
+ return _.toBase64(u).slice(0, 12);
33888
+ }
33889
+ let i4 = Object.entries(s).sort((c, u) => +c[0] - +u[0]).map(([, c]) => hexToBytes4(c)).reduce((c, u) => Pt(c, u), new Uint8Array), o, a;
33890
+ switch (n) {
33891
+ case 0:
33892
+ return o = sha2563(i4), a = _.toHex(o).slice(0, 14), "00" + a;
33893
+ case 1:
33894
+ if (!t)
33895
+ throw new Error("Cannot compute keyset ID version 01: unit is required.");
33896
+ return i4 = Pt(i4, _.fromString("unit:" + t)), e && (i4 = Pt(i4, _.fromString("final_expiry:" + e.toString()))), o = sha2563(i4), a = _.toHex(o), "01" + a;
33897
+ default:
33898
+ throw new Error(`Unrecognized keyset ID version: ${n}`);
33899
+ }
33900
+ }
33901
+ function Pt(s, t) {
33902
+ const e = new Uint8Array(s.length + t.length);
33903
+ return e.set(s), e.set(t, s.length), e;
33904
+ }
33905
+ function T(s) {
33906
+ return typeof s == "object";
33907
+ }
33908
+ function W(...s) {
33909
+ return s.map((t) => t.replace(/(^\/+|\/+$)/g, "")).join("/");
33910
+ }
33911
+ function Oe(s) {
33912
+ return s.replace(/\/$/, "");
33913
+ }
33914
+ class Ln {
33915
+ get value() {
33916
+ return this._value;
33917
+ }
33918
+ set value(t) {
33919
+ this._value = t;
33920
+ }
33921
+ get next() {
33922
+ return this._next;
33923
+ }
33924
+ set next(t) {
33925
+ this._next = t;
33926
+ }
33927
+ constructor(t) {
33928
+ this._value = t, this._next = null;
33929
+ }
33930
+ }
33931
+
33932
+ class $n {
33933
+ get first() {
33934
+ return this._first;
33935
+ }
33936
+ set first(t) {
33937
+ this._first = t;
33938
+ }
33939
+ get last() {
33940
+ return this._last;
33941
+ }
33942
+ set last(t) {
33943
+ this._last = t;
33944
+ }
33945
+ get size() {
33946
+ return this._size;
33947
+ }
33948
+ set size(t) {
33949
+ this._size = t;
33950
+ }
33951
+ constructor() {
33952
+ this._first = null, this._last = null, this._size = 0;
33953
+ }
33954
+ enqueue(t) {
33955
+ const e = new Ln(t);
33956
+ return this._size === 0 || !this._last ? (this._first = e, this._last = e) : (this._last.next = e, this._last = e), this._size++, true;
33957
+ }
33958
+ dequeue() {
33959
+ if (this._size === 0 || !this._first)
33960
+ return null;
33961
+ const t = this._first;
33962
+ return this._first = t.next, t.next = null, this._size--, t.value;
33963
+ }
33964
+ }
33965
+ function De(s, t) {
33966
+ if (s.dleq == null)
33967
+ return false;
33968
+ const e = {
33969
+ e: hexToBytes4(s.dleq.e),
33970
+ s: hexToBytes4(s.dleq.s),
33971
+ r: dt(s.dleq.r ?? "00")
33972
+ };
33973
+ if (!Ie(s.amount, t.keys))
33974
+ throw new Error(`undefined key for amount ${s.amount}`);
33975
+ const n = t.keys[s.amount];
33976
+ return Dn(new TextEncoder().encode(s.secret), e, X(s.C), X(n));
33977
+ }
33978
+ function ee(s) {
33979
+ return s.reduce((t, e) => t + e, 0);
33980
+ }
33981
+ class it {
33982
+ constructor() {
33983
+ this.connectionMap = /* @__PURE__ */ new Map;
33984
+ }
33985
+ static getInstance() {
33986
+ return it.instance || (it.instance = new it), it.instance;
33987
+ }
33988
+ getConnection(t, e) {
33989
+ if (this.connectionMap.has(t))
33990
+ return this.connectionMap.get(t);
33991
+ const n = new jn(t, e);
33992
+ return this.connectionMap.set(t, n), n;
33993
+ }
33994
+ }
33995
+
33996
+ class jn {
33997
+ constructor(t, e) {
33998
+ this.subListeners = {}, this.rpcListeners = {}, this.rpcId = 0, this.onCloseCallbacks = [], this._WS = ze(), this.url = new URL(t), this.messageQueue = new $n, this._logger = e ?? L;
33999
+ }
34000
+ connect() {
34001
+ return this.connectionPromise || (this.connectionPromise = new Promise((t, e) => {
34002
+ try {
34003
+ this.ws = new this._WS(this.url.toString()), this.onCloseCallbacks = [];
34004
+ } catch (n) {
34005
+ e(n instanceof Error ? n : new Error(String(n)));
34006
+ return;
34007
+ }
34008
+ this.ws.onopen = () => {
34009
+ t();
34010
+ }, this.ws.onerror = () => {
34011
+ e(new Error("Failed to open WebSocket"));
34012
+ }, this.ws.onmessage = (n) => {
34013
+ this.messageQueue.enqueue(n.data), this.handlingInterval || (this.handlingInterval = setInterval(this.handleNextMessage.bind(this), 0));
34014
+ }, this.ws.onclose = (n) => {
34015
+ this.connectionPromise = undefined, this.onCloseCallbacks.forEach((r) => r(n));
34016
+ };
34017
+ })), this.connectionPromise;
34018
+ }
34019
+ sendRequest(t, e) {
34020
+ if (this.ws?.readyState !== 1) {
34021
+ if (t === "unsubscribe")
34022
+ return;
34023
+ throw this._logger.error("Attempted sendRequest, but socket was not open"), new Error("Socket not open");
34024
+ }
34025
+ const n = this.rpcId;
34026
+ this.rpcId++;
34027
+ const r = JSON.stringify({ jsonrpc: "2.0", method: t, params: e, id: n });
34028
+ this.ws?.send(r);
34029
+ }
34030
+ closeSubscription(t) {
34031
+ this.ws?.send(JSON.stringify(["CLOSE", t]));
34032
+ }
34033
+ addSubListener(t, e) {
34034
+ (this.subListeners[t] = this.subListeners[t] || []).push(e);
34035
+ }
34036
+ addRpcListener(t, e, n) {
34037
+ this.rpcListeners[n] = { callback: t, errorCallback: e };
34038
+ }
34039
+ removeRpcListener(t) {
34040
+ delete this.rpcListeners[t];
34041
+ }
34042
+ removeListener(t, e) {
34043
+ if (this.subListeners[t]) {
34044
+ if (this.subListeners[t].length === 1) {
34045
+ delete this.subListeners[t];
34046
+ return;
34047
+ }
34048
+ this.subListeners[t] = this.subListeners[t].filter((n) => n !== e);
34049
+ }
34050
+ }
34051
+ async ensureConnection() {
34052
+ this.ws?.readyState !== 1 && await this.connect();
34053
+ }
34054
+ handleNextMessage() {
34055
+ if (this.messageQueue.size === 0) {
34056
+ clearInterval(this.handlingInterval), this.handlingInterval = undefined;
34057
+ return;
34058
+ }
34059
+ const t = this.messageQueue.dequeue();
34060
+ let e;
34061
+ try {
34062
+ if (e = JSON.parse(t), "result" in e && e.id != null)
34063
+ this.rpcListeners[e.id] && (this.rpcListeners[e.id].callback(), this.removeRpcListener(e.id));
34064
+ else if ("error" in e && e.id != null)
34065
+ this.rpcListeners[e.id] && (this.rpcListeners[e.id].errorCallback(new Error(e.error.message)), this.removeRpcListener(e.id));
34066
+ else if ("method" in e && !("id" in e)) {
34067
+ const n = e.params?.subId;
34068
+ if (!n)
34069
+ return;
34070
+ if (this.subListeners[n]?.length > 0) {
34071
+ const r = e;
34072
+ this.subListeners[n].forEach((i4) => i4(r.params?.payload));
34073
+ }
34074
+ }
34075
+ } catch (n) {
34076
+ this._logger.error("Error doing handleNextMessage", { e: n });
34077
+ return;
34078
+ }
34079
+ }
34080
+ createSubscription(t, e, n) {
34081
+ if (this.ws?.readyState !== 1)
34082
+ throw this._logger.error("Attempted createSubscription, but socket was not open"), new Error("Socket is not open");
34083
+ const r = (Math.random() + 1).toString(36).substring(7);
34084
+ return this.addRpcListener(() => {
34085
+ this.addSubListener(r, e);
34086
+ }, n, this.rpcId), this.sendRequest("subscribe", { ...t, subId: r }), this.rpcId++, r;
34087
+ }
34088
+ cancelSubscription(t, e, n) {
34089
+ this.removeListener(t, e), this.addRpcListener(() => {
34090
+ this._logger.info("Unsubscribed {subId}", { subId: t });
34091
+ }, n || ((r) => this._logger.error("Unsubscribe failed", { e: r })), this.rpcId), this.sendRequest("unsubscribe", { subId: t });
34092
+ }
34093
+ get activeSubscriptions() {
34094
+ return Object.keys(this.subListeners);
34095
+ }
34096
+ close() {
34097
+ this.ws && this.ws?.close();
34098
+ }
34099
+ onClose(t) {
34100
+ this.onCloseCallbacks.push(t);
34101
+ }
34102
+ }
34103
+ function At(s, t) {
34104
+ return s.state || (t.warn("Field 'state' not found in MeltQuoteResponse. Update NUT-05 of mint: https://github.com/cashubtc/nuts/pull/136)"), typeof s.paid == "boolean" && (s.state = s.paid ? ut.PAID : ut.UNPAID)), s;
34105
+ }
34106
+ function se(s, t) {
34107
+ return s.state || (t.warn("Field 'state' not found in MintQuoteResponse. Update NUT-04 of mint: https://github.com/cashubtc/nuts/pull/141)"), typeof s.paid == "boolean" && (s.state = s.paid ? Tt.PAID : Tt.UNPAID)), s;
34108
+ }
34109
+ function Qn(s, t) {
34110
+ return Array.isArray(s?.contact) && s?.contact.length > 0 && (s.contact = s.contact.map((e) => Array.isArray(e) && e.length === 2 && typeof e[0] == "string" && typeof e[1] == "string" ? (t.warn("Mint returned deprecated 'contact' field: Update NUT-06: https://github.com/cashubtc/nuts/pull/117"), { method: e[0], info: e[1] }) : e)), s;
34111
+ }
34112
+
34113
+ class wt {
34114
+ constructor(t) {
34115
+ this.REGEX_METACHAR = /[\\^$.*+?()[\]{}|]/, this._mintInfo = t;
34116
+ const e = this.toEndpoints(t?.nuts?.[22]?.protected_endpoints);
34117
+ this._protected22 = this.buildIndex(e);
34118
+ const n = this.toEndpoints(t?.nuts?.[21]?.protected_endpoints);
34119
+ this._protected21 = this.buildIndex(n);
34120
+ }
34121
+ isSupported(t) {
34122
+ switch (t) {
34123
+ case 4:
34124
+ case 5:
34125
+ return this.checkMintMelt(t);
34126
+ case 7:
34127
+ case 8:
34128
+ case 9:
34129
+ case 10:
34130
+ case 11:
34131
+ case 12:
34132
+ case 14:
34133
+ case 20:
34134
+ return this.checkGenericNut(t);
34135
+ case 17:
34136
+ return this.checkNut17();
34137
+ case 15:
34138
+ return this.checkNut15();
34139
+ default:
34140
+ throw new Error("nut is not supported by cashu-ts");
34141
+ }
34142
+ }
34143
+ requiresBlindAuthToken(t, e) {
34144
+ return this.matchesProtected(this._protected22, t, e);
34145
+ }
34146
+ requiresClearAuthToken(t, e) {
34147
+ return this.matchesProtected(this._protected21, t, e);
34148
+ }
34149
+ matchesProtected(t, e, n) {
34150
+ if (!t)
34151
+ return false;
34152
+ const r = `${e} ${n}`, i4 = t.cache[r];
34153
+ if (typeof i4 == "boolean")
34154
+ return i4;
34155
+ const o = t.exact.some((u) => u.method === e && u.path === n), a = o ? false : t.regex.some((u) => u.method === e && u.regex.test(n)), c = o || a;
34156
+ return t.cache[r] = c, c;
34157
+ }
34158
+ checkGenericNut(t) {
34159
+ return this._mintInfo.nuts[t]?.supported ? { supported: true } : { supported: false };
34160
+ }
34161
+ checkMintMelt(t) {
34162
+ const e = this._mintInfo.nuts[t];
34163
+ return e && e.methods.length > 0 && !e.disabled ? { disabled: false, params: e.methods } : { disabled: true, params: e?.methods ?? [] };
34164
+ }
34165
+ checkNut17() {
34166
+ return this._mintInfo.nuts[17] && this._mintInfo.nuts[17].supported.length > 0 ? { supported: true, params: this._mintInfo.nuts[17].supported } : { supported: false };
34167
+ }
34168
+ checkNut15() {
34169
+ return this._mintInfo.nuts[15] && this._mintInfo.nuts[15].methods.length > 0 ? { supported: true, params: this._mintInfo.nuts[15].methods } : { supported: false };
34170
+ }
34171
+ toEndpoints(t) {
34172
+ if (!Array.isArray(t))
34173
+ return [];
34174
+ const e = [];
34175
+ for (const n of t)
34176
+ if (n && typeof n == "object") {
34177
+ const r = n, i4 = r.method, o = r.path;
34178
+ if (typeof i4 == "string" && typeof o == "string") {
34179
+ const a = i4.toUpperCase();
34180
+ (a === "GET" || a === "POST") && e.push({ method: a, path: o });
34181
+ }
34182
+ }
34183
+ return e;
34184
+ }
34185
+ buildIndex(t) {
34186
+ if (!t || t.length === 0)
34187
+ return;
34188
+ const e = [], n = [], r = this.REGEX_METACHAR;
34189
+ for (const o of t) {
34190
+ if (o.path.startsWith("^") || o.path.endsWith("$") || r.test(o.path))
34191
+ try {
34192
+ n.push({ method: o.method, regex: new RegExp(o.path) });
34193
+ continue;
34194
+ } catch {}
34195
+ e.push({ method: o.method, path: o.path });
34196
+ }
34197
+ return { cache: {}, exact: e, regex: n };
34198
+ }
34199
+ get contact() {
34200
+ return this._mintInfo.contact;
34201
+ }
34202
+ get description() {
34203
+ return this._mintInfo.description;
34204
+ }
34205
+ get description_long() {
34206
+ return this._mintInfo.description_long;
34207
+ }
34208
+ get name() {
34209
+ return this._mintInfo.name;
34210
+ }
34211
+ get pubkey() {
34212
+ return this._mintInfo.pubkey;
34213
+ }
34214
+ get nuts() {
34215
+ return this._mintInfo.nuts;
34216
+ }
34217
+ get version() {
34218
+ return this._mintInfo.version;
34219
+ }
34220
+ get motd() {
34221
+ return this._mintInfo.motd;
34222
+ }
34223
+ get supportsBolt12Description() {
34224
+ return this.supportsNut04Description("bolt12");
34225
+ }
34226
+ supportsNut04Description(t, e) {
34227
+ return this._mintInfo.nuts[4]?.methods.some((n) => n.method === t && (e ? n.unit === e : true) && (n.options?.description === true || n.description === true));
34228
+ }
34229
+ }
34230
+
34231
+ class zt {
34232
+ constructor(t, e) {
34233
+ this.tokenListeners = [], this.discoveryUrl = t, this.logger = e?.logger ?? L, this.clientId = e?.clientId ?? "cashu-client", this.scope = e?.scope ?? "openid", this.onTokens = e?.onTokens;
34234
+ }
34235
+ static fromMintInfo(t, e) {
34236
+ const n = t?.nuts?.["21"];
34237
+ if (!n?.openid_discovery)
34238
+ throw new Error("OIDCAuth: mint does not advertise NUT-21 openid_discovery");
34239
+ const r = e?.clientId ?? n.client_id ?? "cashu-client";
34240
+ return new zt(n.openid_discovery, { ...e, clientId: r });
34241
+ }
34242
+ setClient(t) {
34243
+ this.clientId = t;
34244
+ }
34245
+ setScope(t) {
34246
+ this.scope = t ?? "openid";
34247
+ }
34248
+ addTokenListener(t) {
34249
+ this.tokenListeners.push(t);
34250
+ }
34251
+ async loadConfig() {
34252
+ if (this.config)
34253
+ return this.config;
34254
+ const t = await fetch(this.discoveryUrl, {
34255
+ method: "GET",
34256
+ headers: { Accept: "application/json" }
34257
+ }), e = await t.text();
34258
+ let n;
34259
+ try {
34260
+ n = e ? JSON.parse(e) : undefined;
34261
+ } catch (i4) {
34262
+ this.logger.warn("OIDCAuth: bad discovery JSON", { err: i4 });
34263
+ }
34264
+ if (!t.ok || !n)
34265
+ throw new Error("OIDCAuth: invalid discovery document");
34266
+ const r = n;
34267
+ if (typeof r.token_endpoint != "string" || r.token_endpoint.length === 0)
34268
+ throw new Error("OIDCAuth: invalid discovery document, missing token_endpoint");
34269
+ return this.config = r, r;
34270
+ }
34271
+ generatePKCE() {
34272
+ const t = randomBytes4(48), e = It(t), n = _.fromString(e), r = sha2563(n), i4 = It(r);
34273
+ return { verifier: e, challenge: i4 };
34274
+ }
34275
+ async buildAuthCodeUrl(t) {
34276
+ const e = await this.loadConfig(), n = t.scope ?? this.scope, r = new URLSearchParams({
34277
+ response_type: "code",
34278
+ client_id: this.clientId,
34279
+ redirect_uri: t.redirectUri,
34280
+ scope: n,
34281
+ code_challenge_method: t.codeChallengeMethod ?? "S256",
34282
+ code_challenge: t.codeChallenge
34283
+ });
34284
+ if (t.state && r.set("state", t.state), !e.authorization_endpoint)
34285
+ throw new Error("OIDCAuth: discovery lacks authorization_endpoint");
34286
+ return `${e.authorization_endpoint}?${r.toString()}`;
34287
+ }
34288
+ async exchangeAuthCode(t) {
34289
+ const e = await this.loadConfig(), n = this.toForm({
34290
+ grant_type: "authorization_code",
34291
+ code: t.code,
34292
+ redirect_uri: t.redirectUri,
34293
+ client_id: this.clientId,
34294
+ code_verifier: t.codeVerifier
34295
+ }), r = await this.postFormStrict(e.token_endpoint, n);
34296
+ return this.handleTokens(r), r;
34297
+ }
34298
+ async deviceStart() {
34299
+ const e = (await this.loadConfig()).device_authorization_endpoint;
34300
+ if (!e)
34301
+ throw new Error("OIDCAuth: provider lacks device_authorization_endpoint");
34302
+ const n = this.toForm({ client_id: this.clientId, scope: this.scope });
34303
+ return this.postFormStrict(e, n);
34304
+ }
34305
+ async devicePoll(t, e = 5) {
34306
+ const n = await this.loadConfig();
34307
+ let r = Math.max(1, e);
34308
+ for (;; ) {
34309
+ await this.sleep(r * 1000);
34310
+ const i4 = this.toForm({
34311
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
34312
+ device_code: t,
34313
+ client_id: this.clientId
34314
+ }), o = await this.postFormLoose(n.token_endpoint, i4);
34315
+ if (o.access_token)
34316
+ return this.handleTokens(o), o;
34317
+ const a = (o.error ?? "").toString();
34318
+ if (a === "authorization_pending")
34319
+ continue;
34320
+ if (a === "slow_down") {
34321
+ r = Math.max(r + 5, r * 2);
34322
+ continue;
34323
+ }
34324
+ const c = o.error_description || a || "device authorization failed";
34325
+ throw new Error(`OIDCAuth: ${c}`);
34326
+ }
34327
+ }
34328
+ async startDeviceAuth(t = 5) {
34329
+ const e = await this.deviceStart(), n = Math.max(e.interval ?? 1, t);
34330
+ let r = false;
34331
+ return { ...e, poll: async () => {
34332
+ const a = await this.loadConfig();
34333
+ let c = Math.max(1, n);
34334
+ for (;; ) {
34335
+ if (r)
34336
+ throw new Error("OIDCAuth: device polling cancelled");
34337
+ await this.sleep(c * 1000);
34338
+ const u = this.toForm({
34339
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
34340
+ device_code: e.device_code,
34341
+ client_id: this.clientId
34342
+ }), l = await this.postFormLoose(a.token_endpoint, u);
34343
+ if (l.access_token)
34344
+ return this.handleTokens(l), l;
34345
+ const h = (l.error ?? "").toString();
34346
+ if (h === "authorization_pending")
34347
+ continue;
34348
+ if (h === "slow_down") {
34349
+ c = Math.max(c + 5, c * 2);
34350
+ continue;
34351
+ }
34352
+ const d = l.error_description || h || "device authorization failed";
34353
+ throw new Error(`OIDCAuth: ${d}`);
34354
+ }
34355
+ }, cancel: () => {
34356
+ r = true;
34357
+ } };
34358
+ }
34359
+ async refresh(t) {
34360
+ const e = await this.loadConfig(), n = this.toForm({
34361
+ grant_type: "refresh_token",
34362
+ refresh_token: t,
34363
+ client_id: this.clientId
34364
+ }), r = await this.postFormStrict(e.token_endpoint, n);
34365
+ return this.handleTokens(r), r;
34366
+ }
34367
+ async passwordGrant(t, e) {
34368
+ const n = await this.loadConfig(), r = this.toForm({
34369
+ grant_type: "password",
34370
+ client_id: this.clientId,
34371
+ username: t,
34372
+ password: e,
34373
+ scope: this.scope
34374
+ }), i4 = await this.postFormStrict(n.token_endpoint, r);
34375
+ return this.handleTokens(i4), i4;
34376
+ }
34377
+ handleTokens(t) {
34378
+ if (!t.access_token) {
34379
+ const e = t.error_description || t.error || "token response missing access_token";
34380
+ throw new Error(`OIDCAuth: ${e}`);
34381
+ }
34382
+ queueMicrotask(() => lt(this.onTokens, t, this.logger, { where: "OIDCAuth.handleTokens" }));
34383
+ for (const e of this.tokenListeners)
34384
+ queueMicrotask(() => lt(e, t, this.logger, {
34385
+ where: "OIDCAuth.handleTokens.listener"
34386
+ }));
34387
+ }
34388
+ toForm(t) {
34389
+ const e = (n) => encodeURIComponent(n).replace(/%20/g, "+");
34390
+ return Object.entries(t).map(([n, r]) => `${e(n)}=${e(r)}`).join("&");
34391
+ }
34392
+ async postFormStrict(t, e) {
34393
+ try {
34394
+ this.logger.debug("OIDCAuth Request", { formBody: e });
34395
+ const n = await fetch(t, {
34396
+ method: "POST",
34397
+ headers: {
34398
+ "Content-Type": "application/x-www-form-urlencoded",
34399
+ Accept: "application/json"
34400
+ },
34401
+ body: e
34402
+ }), r = await n.text();
34403
+ let i4;
34404
+ try {
34405
+ i4 = r ? JSON.parse(r) : undefined;
34406
+ } catch (o) {
34407
+ this.logger.warn("OIDCAuth: bad JSON (strict)", { err: o });
34408
+ }
34409
+ if (!n.ok) {
34410
+ const o = i4 ?? {}, a = o.error_description || o.error || `HTTP ${n.status}`;
34411
+ throw new Error(`OIDCAuth: ${a}`);
34412
+ }
34413
+ return this.logger.debug("OIDCAuth Response", { json: i4 }), i4 ?? {};
34414
+ } catch (n) {
34415
+ throw this.logger.error("OIDCAuth: postFormStrict failed", { err: n }), n;
34416
+ }
34417
+ }
34418
+ async postFormLoose(t, e) {
34419
+ try {
34420
+ this.logger.debug("OIDCAuth Request", { formBody: e });
34421
+ const r = await (await fetch(t, {
34422
+ method: "POST",
34423
+ headers: {
34424
+ "Content-Type": "application/x-www-form-urlencoded",
34425
+ Accept: "application/json"
34426
+ },
34427
+ body: e
34428
+ })).text();
34429
+ let i4;
34430
+ try {
34431
+ i4 = r ? JSON.parse(r) : undefined;
34432
+ } catch (o) {
34433
+ this.logger.warn("OIDCAuth: bad JSON (loose)", { err: o });
34434
+ }
34435
+ return this.logger.debug("OIDCAuth Response", { json: i4 }), i4 ?? {};
34436
+ } catch (n) {
34437
+ return this.logger.error("OIDCAuth: postFormLoose network error", { err: n }), { error: "network_error", error_description: String(n) };
34438
+ }
34439
+ }
34440
+ sleep(t) {
34441
+ return new Promise((e) => setTimeout(e, t));
34442
+ }
34443
+ }
34444
+
34445
+ class Vt {
34446
+ constructor(t, e) {
34447
+ this._mintUrl = Oe(t), this._request = e?.customRequest ?? pe, this._authProvider = e?.authProvider, this._logger = e?.logger ?? L, je(this._logger);
34448
+ }
34449
+ get mintUrl() {
34450
+ return this._mintUrl;
34451
+ }
34452
+ async oidcAuth(t) {
34453
+ const e = (await this.getLazyMintInfo()).nuts[21];
34454
+ if (!e?.openid_discovery)
34455
+ throw new Error("Mint: no NUT-21 openid_discovery");
34456
+ return new zt(e.openid_discovery, {
34457
+ ...t,
34458
+ clientId: t?.clientId ?? e.client_id ?? "cashu-client"
34459
+ });
34460
+ }
34461
+ async getInfo(t) {
34462
+ const n = await (t ?? this._request)({
34463
+ endpoint: W(this._mintUrl, "/v1/info")
34464
+ });
34465
+ return Qn(n, this._logger);
34466
+ }
34467
+ async getLazyMintInfo() {
34468
+ if (this._mintInfo)
34469
+ return this._mintInfo;
34470
+ const t = await this.getInfo();
34471
+ return this._mintInfo = new wt(t), this._mintInfo;
34472
+ }
34473
+ async swap(t, e) {
34474
+ const n = await this.requestWithAuth("POST", "/v1/swap", { requestBody: t }, e);
34475
+ if (!T(n) || !Array.isArray(n?.signatures)) {
34476
+ const r = T(n) && "detail" in n ? n.detail : undefined;
34477
+ throw new Error(r ?? "bad response");
34478
+ }
34479
+ return n;
34480
+ }
34481
+ async createMintQuoteBolt11(t, e) {
34482
+ const n = await this.requestWithAuth("POST", "/v1/mint/quote/bolt11", { requestBody: t }, e);
34483
+ return se(n, this._logger);
34484
+ }
34485
+ async createMintQuoteBolt12(t, e) {
34486
+ return await this.requestWithAuth("POST", "/v1/mint/quote/bolt12", { requestBody: t }, e);
34487
+ }
34488
+ async checkMintQuoteBolt11(t, e) {
34489
+ const n = await this.requestWithAuth("GET", `/v1/mint/quote/bolt11/${t}`, {}, e);
34490
+ return se(n, this._logger);
34491
+ }
34492
+ async checkMintQuoteBolt12(t, e) {
34493
+ return await this.requestWithAuth("GET", `/v1/mint/quote/bolt12/${t}`, {}, e);
34494
+ }
34495
+ async mintBolt11(t, e) {
34496
+ const n = await this.requestWithAuth("POST", "/v1/mint/bolt11", { requestBody: t }, e);
34497
+ if (!T(n) || !Array.isArray(n?.signatures)) {
34498
+ const r = T(n) && "detail" in n ? n.detail : undefined;
34499
+ throw new Error(r ?? "bad response");
34500
+ }
34501
+ return n;
34502
+ }
34503
+ async mintBolt12(t, e) {
34504
+ const n = await this.requestWithAuth("POST", "/v1/mint/bolt12", { requestBody: t }, e);
34505
+ if (!T(n) || !Array.isArray(n?.signatures)) {
34506
+ const r = T(n) && "detail" in n ? n.detail : undefined;
34507
+ throw new Error(r ?? "bad response");
34508
+ }
34509
+ return n;
34510
+ }
34511
+ async createMeltQuoteBolt11(t, e) {
34512
+ const n = await this.requestWithAuth("POST", "/v1/melt/quote/bolt11", { requestBody: t }, e), r = At(n, this._logger);
34513
+ if (!T(r) || typeof r?.amount != "number" || typeof r?.fee_reserve != "number" || typeof r?.quote != "string") {
34514
+ const i4 = T(r) && "detail" in r ? r.detail : undefined;
34515
+ throw new Error(i4 ?? "bad response");
34516
+ }
34517
+ return r;
34518
+ }
34519
+ async createMeltQuoteBolt12(t, e) {
34520
+ return await this.requestWithAuth("POST", "/v1/melt/quote/bolt12", { requestBody: t }, e);
34521
+ }
34522
+ async checkMeltQuoteBolt11(t, e) {
34523
+ const n = await this.requestWithAuth("GET", `/v1/melt/quote/bolt11/${t}`, {}, e), r = At(n, this._logger);
34524
+ if (!T(r) || typeof r?.amount != "number" || typeof r?.fee_reserve != "number" || typeof r?.quote != "string" || typeof r?.state != "string" || !Object.values(ut).includes(r.state)) {
34525
+ const i4 = T(r) && "detail" in r ? r.detail : undefined;
34526
+ throw new Error(i4 ?? "bad response");
34527
+ }
34528
+ return r;
34529
+ }
34530
+ async checkMeltQuoteBolt12(t, e) {
34531
+ return await this.requestWithAuth("GET", `/v1/melt/quote/bolt12/${t}`, {}, e);
34532
+ }
34533
+ async meltBolt11(t, e) {
34534
+ const n = {
34535
+ ...e?.preferAsync ? { Prefer: "respond-async" } : {}
34536
+ }, r = await this.requestWithAuth("POST", "/v1/melt/bolt11", {
34537
+ requestBody: t,
34538
+ headers: n
34539
+ }, e?.customRequest), i4 = At(r, this._logger);
34540
+ if (!T(i4) || typeof i4?.state != "string" || !Object.values(ut).includes(i4.state)) {
34541
+ const o = T(i4) && "detail" in i4 ? i4.detail : undefined;
34542
+ throw new Error(o ?? "bad response");
34543
+ }
34544
+ return i4;
34545
+ }
34546
+ async meltBolt12(t, e) {
34547
+ const n = {
34548
+ ...e?.preferAsync ? { Prefer: "respond-async" } : {}
34549
+ };
34550
+ return await this.requestWithAuth("POST", "/v1/melt/bolt12", {
34551
+ requestBody: t,
34552
+ headers: n
34553
+ }, e?.customRequest);
34554
+ }
34555
+ async check(t, e) {
34556
+ const n = await this.requestWithAuth("POST", "/v1/checkstate", { requestBody: t }, e);
34557
+ if (!T(n) || !Array.isArray(n?.states)) {
34558
+ const r = T(n) && "detail" in n ? n.detail : undefined;
34559
+ throw new Error(r ?? "bad response");
34560
+ }
34561
+ return n;
34562
+ }
34563
+ async getKeys(t, e, n) {
34564
+ const r = e || this._mintUrl;
34565
+ t && (t = t.replace(/\//g, "_").replace(/\+/g, "-"));
34566
+ const o = await (n ?? this._request)({
34567
+ endpoint: t ? W(r, "/v1/keys", t) : W(r, "/v1/keys")
34568
+ });
34569
+ if (!T(o) || !Array.isArray(o.keysets)) {
34570
+ const a = T(o) && "detail" in o ? o.detail : undefined;
34571
+ throw new Error(a ?? "bad response");
34572
+ }
34573
+ return o;
34574
+ }
34575
+ async getKeySets(t) {
34576
+ return (t ?? this._request)({ endpoint: W(this._mintUrl, "/v1/keysets") });
34577
+ }
34578
+ async restore(t, e) {
34579
+ const r = await (e ?? this._request)({
34580
+ endpoint: W(this._mintUrl, "/v1/restore"),
34581
+ method: "POST",
34582
+ requestBody: t
34583
+ });
34584
+ if (!T(r) || !Array.isArray(r?.outputs) || !Array.isArray(r?.signatures)) {
34585
+ const i4 = T(r) && "detail" in r ? r.detail : undefined;
34586
+ throw new Error(i4 ?? "bad response");
34587
+ }
34588
+ return r;
34589
+ }
34590
+ async connectWebSocket() {
34591
+ if (this.ws)
34592
+ await this.ws.ensureConnection();
34593
+ else {
34594
+ const t = new URL(this._mintUrl), e = "v1/ws";
34595
+ t.pathname && (t.pathname.endsWith("/") ? t.pathname += e : t.pathname += "/" + e), this.ws = it.getInstance().getConnection(`${t.protocol === "https:" ? "wss" : "ws"}://${t.host}${t.pathname}`);
34596
+ try {
34597
+ await this.ws.connect();
34598
+ } catch (n) {
34599
+ throw this._logger.error("Failed to connect to WebSocket...", { e: n }), new Error("Failed to connect to WebSocket...");
34600
+ }
34601
+ }
34602
+ }
34603
+ disconnectWebSocket() {
34604
+ this.ws && this.ws.close();
34605
+ }
34606
+ get webSocketConnection() {
34607
+ return this.ws;
34608
+ }
34609
+ async handleClearAuth(t, e) {
34610
+ if (!(!this._authProvider || !(await this.getLazyMintInfo()).requiresClearAuthToken(t, e)))
34611
+ return this._logger.error("Clear Authentication Token...", { cat: this._authProvider.getCAT() }), this._authProvider.getCAT();
34612
+ }
34613
+ async handleBlindAuth(t, e) {
34614
+ if (!this._authProvider || !(await this.getLazyMintInfo()).requiresBlindAuthToken(t, e))
34615
+ return;
34616
+ const r = await this._authProvider.getBlindAuthToken({ method: t, path: e });
34617
+ return this._logger.error("Blind Authentication Token...", { bat: r }), r;
34618
+ }
34619
+ async requestWithAuth(t, e, n = {}, r) {
34620
+ const i4 = r ?? this._request, o = await this.handleBlindAuth(t, e), a = await this.handleClearAuth(t, e), c = {
34621
+ ...n.headers ?? {},
34622
+ ...o ? { "Blind-auth": o } : {},
34623
+ ...a ? { "Clear-auth": a } : {}
34624
+ };
34625
+ return i4({
34626
+ ...n,
34627
+ endpoint: W(this._mintUrl, e),
34628
+ method: t,
34629
+ headers: c
34630
+ });
34631
+ }
34632
+ }
34633
+
34634
+ class zn {
34635
+ constructor(t, e, n, r, i4) {
34636
+ this._keys = {}, this._id = t, this._unit = e, this._active = n, this._input_fee_ppk = r, this._final_expiry = i4;
34637
+ }
34638
+ get id() {
34639
+ return this._id;
34640
+ }
34641
+ get unit() {
34642
+ return this._unit;
34643
+ }
34644
+ get isActive() {
34645
+ return this._active;
34646
+ }
34647
+ get fee() {
34648
+ return this._input_fee_ppk ?? 0;
34649
+ }
34650
+ get expiry() {
34651
+ return this._final_expiry;
34652
+ }
34653
+ get hasKeys() {
34654
+ return Object.keys(this._keys).length > 0;
34655
+ }
34656
+ get hasHexId() {
34657
+ return Ct(this._id);
34658
+ }
34659
+ get keys() {
34660
+ return this._keys;
34661
+ }
34662
+ set keys(t) {
34663
+ this._keys = t;
34664
+ }
34665
+ get active() {
34666
+ return this._active;
34667
+ }
34668
+ get input_fee_ppk() {
34669
+ return this._input_fee_ppk ?? 0;
34670
+ }
34671
+ get final_expiry() {
34672
+ return this._final_expiry;
34673
+ }
34674
+ toMintKeyset() {
34675
+ return {
34676
+ id: this._id,
34677
+ unit: this._unit,
34678
+ active: this._active,
34679
+ input_fee_ppk: this._input_fee_ppk,
34680
+ final_expiry: this._final_expiry
34681
+ };
34682
+ }
34683
+ toMintKeys() {
34684
+ return this.hasKeys ? {
34685
+ id: this._id,
34686
+ unit: this._unit,
34687
+ keys: this._keys
34688
+ } : null;
34689
+ }
34690
+ verify() {
34691
+ if (!this.hasKeys)
34692
+ return false;
34693
+ const t = hexToBytes4(this._id)[0];
34694
+ return Qt(this._keys, this._unit, this._final_expiry, t) === this._id;
34695
+ }
34696
+ }
34697
+
34698
+ class Ue {
34699
+ constructor(t, e, n, r) {
34700
+ if (this.keysets = {}, this.mint = typeof t == "string" ? new Vt(t) : t, this.unit = e, n && r) {
34701
+ const i4 = Array.isArray(r) ? r : [r];
34702
+ this.buildKeychain(n, i4);
34703
+ }
34704
+ }
34705
+ async init(t) {
34706
+ if (Object.keys(this.keysets).length > 0 && !t)
34707
+ return;
34708
+ const [e, n] = await Promise.all([this.mint.getKeySets(), this.mint.getKeys()]);
34709
+ this.buildKeychain(e.keysets, n.keysets), this.getCheapestKeyset();
34710
+ }
34711
+ buildKeychain(t, e) {
34712
+ this.keysets = {}, t.filter((i4) => i4.unit === this.unit).forEach((i4) => {
34713
+ this.keysets[i4.id] = new zn(i4.id, i4.unit, i4.active, i4.input_fee_ppk, i4.final_expiry);
34714
+ });
34715
+ const r = new Map(e.filter((i4) => i4.unit === this.unit).map((i4) => [i4.id, i4]));
34716
+ Object.values(this.keysets).forEach((i4) => {
34717
+ if (!i4.hasHexId || !i4.isActive)
34718
+ return;
34719
+ const o = r.get(i4.id);
34720
+ if (o && (i4.keys = o.keys, !i4.verify()))
34721
+ throw new Error(`Keyset verification failed for ID ${i4.id}`);
34722
+ });
34723
+ }
34724
+ getKeyset(t) {
34725
+ const e = t ? this.keysets[t] : this.getCheapestKeyset();
34726
+ if (!e)
34727
+ throw new Error(`Keyset '${t}' not found`);
34728
+ return e;
34729
+ }
34730
+ getCheapestKeyset() {
34731
+ if (Object.keys(this.keysets).length === 0)
34732
+ throw new Error("KeyChain not initialized");
34733
+ const t = Object.values(this.keysets).filter((e) => e.isActive && e.hasHexId && e.hasKeys);
34734
+ if (t.length === 0)
34735
+ throw new Error("No active keyset found");
34736
+ return t.sort((e, n) => e.fee - n.fee)[0];
34737
+ }
34738
+ getKeysets() {
34739
+ if (Object.keys(this.keysets).length === 0)
34740
+ throw new Error("KeyChain not initialized");
34741
+ return Object.values(this.keysets);
34742
+ }
34743
+ getCache() {
34744
+ const t = this.getKeysets(), e = t.filter((n) => n.hasKeys).map((n) => n.toMintKeys()).filter((n) => n !== null);
34745
+ return {
34746
+ keysets: t.map((n) => n.toMintKeyset()),
34747
+ keys: e,
34748
+ unit: this.unit,
34749
+ mintUrl: this.mint.mintUrl
34750
+ };
34751
+ }
34752
+ }
34753
+
34754
+ class vt {
34755
+ constructor(t, e, n) {
34756
+ this.amount = t, this.B_ = e, this.id = n;
34757
+ }
34758
+ getSerializedBlindedMessage() {
34759
+ return { amount: this.amount, B_: this.B_.toHex(true), id: this.id };
34760
+ }
34761
+ }
34762
+ var Vn = /* @__PURE__ */ new Set([
34763
+ "locktime",
34764
+ "pubkeys",
34765
+ "n_sigs",
34766
+ "refund",
34767
+ "n_sigs_refund"
34768
+ ]);
34769
+ function Re(s) {
34770
+ if (!s || typeof s != "string")
34771
+ throw new Error("tag key must be a non empty string");
34772
+ if (Vn.has(s))
34773
+ throw new Error(`additionalTags must not use reserved key "${s}"`);
34774
+ }
34775
+ var re = 1024;
34776
+ var xt = /* @__PURE__ */ new WeakMap;
34777
+ function Gn(s, t) {
34778
+ t && xt.set(s, t);
34779
+ }
34780
+ function Jn(s) {
34781
+ const t = xt.get(s);
34782
+ if (t)
34783
+ return xt.delete(s), t;
34784
+ }
34785
+
34786
+ class N {
34787
+ constructor(t, e, n) {
34788
+ this.secret = n, this.blindingFactor = e, this.blindedMessage = t;
34789
+ }
34790
+ toProof(t, e) {
34791
+ let n;
34792
+ t.dleq && (n = {
34793
+ s: hexToBytes4(t.dleq.s),
34794
+ e: hexToBytes4(t.dleq.e),
34795
+ r: this.blindingFactor
34796
+ });
34797
+ const r = {
34798
+ id: t.id,
34799
+ amount: t.amount,
34800
+ C_: X(t.C_)
34801
+ }, i4 = X(e.keys[t.amount]), o = Sn(r, this.blindingFactor, this.secret, i4), a = {
34802
+ ...Tn(o),
34803
+ ...n && {
34804
+ dleq: {
34805
+ s: bytesToHex4(n.s),
34806
+ e: bytesToHex4(n.e),
34807
+ r: Mt(n.r ?? BigInt(0))
34808
+ }
34809
+ }
34810
+ }, c = Jn(this);
34811
+ return c && (a.p2pk_e = c), a;
34812
+ }
34813
+ static createP2PKData(t, e, n, r) {
34814
+ return G(e, n.keys, r).map((o) => this.createSingleP2PKData(t, o, n.id));
34815
+ }
34816
+ static createSingleP2PKData(t, e, n) {
34817
+ const r = Array.isArray(t.pubkey) ? t.pubkey : [t.pubkey], i4 = t.refundKeys ?? [], o = Math.max(1, Math.min(t.requiredSignatures ?? 1, r.length)), a = Math.max(1, Math.min(t.requiredRefundSignatures ?? 1, i4.length || 1));
34818
+ let c = r[0], u = r.slice(1), l = i4, h;
34819
+ if (t.blindKeys) {
34820
+ const x = [c, ...u, ...i4], { blinded: S, Ehex: B } = gn(x, n);
34821
+ c = S[0], u = S.slice(1, r.length), l = S.slice(r.length), h = B;
34822
+ }
34823
+ const d = [], p = t.locktime ?? NaN;
34824
+ if (Number.isSafeInteger(p) && p >= 0 && d.push(["locktime", String(p)]), u.length > 0 && (d.push(["pubkeys", ...u]), o > 1 && d.push(["n_sigs", String(o)])), l.length > 0 && (d.push(["refund", ...l]), a > 1 && d.push(["n_sigs_refund", String(a)])), t.additionalTags?.length) {
34825
+ const x = t.additionalTags.map(([S, ...B]) => (Re(S), [S, ...B.map(String)]));
34826
+ d.push(...x);
34827
+ }
34828
+ const m = [
34829
+ "P2PK",
34830
+ {
34831
+ nonce: bytesToHex4(randomBytes4(32)),
34832
+ data: c,
34833
+ tags: d
34834
+ }
34835
+ ], P = JSON.stringify(m), A = [...P].length;
34836
+ if (A > re)
34837
+ throw new Error(`Secret too long (${A} characters), maximum is ${re}`);
34838
+ const w = new TextEncoder().encode(P), { r: v, B_: I } = gt(w), U = new N(new vt(e, I, n).getSerializedBlindedMessage(), v, w);
34839
+ return t.blindKeys && h && Gn(U, h), U;
34840
+ }
34841
+ static createRandomData(t, e, n) {
34842
+ return G(t, e.keys, n).map((i4) => this.createSingleRandomData(i4, e.id));
34843
+ }
34844
+ static createSingleRandomData(t, e) {
34845
+ const n = bytesToHex4(randomBytes4(32)), r = new TextEncoder().encode(n), { r: i4, B_: o } = gt(r);
34846
+ return new N(new vt(t, o, e).getSerializedBlindedMessage(), i4, r);
34847
+ }
34848
+ static createDeterministicData(t, e, n, r, i4) {
34849
+ return G(t, r.keys, i4).map((a, c) => this.createSingleDeterministicData(a, e, n + c, r.id));
34850
+ }
34851
+ static createSingleDeterministicData(t, e, n, r) {
34852
+ const i4 = xn(e, r, n), o = bytesToHex4(i4), a = new TextEncoder().encode(o), c = $(Bn(e, r, n)), { r: u, B_: l } = gt(a, c);
34853
+ return new N(new vt(t, l, r).getSerializedBlindedMessage(), u, a);
34854
+ }
34855
+ static sumOutputAmounts(t) {
34856
+ return t.reduce((e, n) => e + n.blindedMessage.amount, 0);
34857
+ }
34858
+ }
34859
+ var kt = class kt2 {
34860
+ constructor(t, e) {
34861
+ this.tokens = {}, this.pool = [], this.desiredPoolSize = 10, this.maxPerMint = 10, this.mintUrl = t, this.req = e?.request ?? pe, this.logger = e?.logger ?? L, this.desiredPoolSize = Math.max(1, e?.desiredPoolSize ?? this.desiredPoolSize), this.maxPerMint = Math.max(1, e?.maxPerMint ?? this.maxPerMint);
34862
+ }
34863
+ attachOIDC(t) {
34864
+ return this.oidc = t, this.oidc.addTokenListener((e) => this.updateFromOIDC(e)), this;
34865
+ }
34866
+ get poolSize() {
34867
+ return this.pool.length;
34868
+ }
34869
+ get poolTarget() {
34870
+ return this.desiredPoolSize;
34871
+ }
34872
+ get activeAuthKeysetId() {
34873
+ try {
34874
+ return this.keychain?.getCheapestKeyset().id;
34875
+ } catch {
34876
+ return;
34877
+ }
34878
+ }
34879
+ get hasCAT() {
34880
+ return !!this.tokens.accessToken;
34881
+ }
34882
+ getCAT() {
34883
+ return this.tokens.accessToken;
34884
+ }
34885
+ setCAT(t) {
34886
+ this.tokens.accessToken = t, t || (this.tokens.refreshToken = undefined, this.tokens.expiresAt = undefined);
34887
+ }
34888
+ async ensureCAT(t) {
34889
+ return this.validForAtLeast(t) ? this.tokens.accessToken : !this.oidc || !this.tokens.refreshToken ? this.tokens.accessToken : (this.inflightRefresh || (this.inflightRefresh = (async () => {
34890
+ try {
34891
+ const e = await this.oidc.refresh(this.tokens.refreshToken);
34892
+ this.updateFromOIDC(e);
34893
+ } catch (e) {
34894
+ this.logger.warn("AuthManager: CAT refresh failed", { err: e });
34895
+ } finally {
34896
+ this.inflightRefresh = undefined;
34897
+ }
34898
+ })()), await this.inflightRefresh, this.validForAtLeast(0) ? this.tokens.accessToken : undefined);
34899
+ }
34900
+ validForAtLeast(t = kt2.MIN_VALID_SECS) {
34901
+ const { accessToken: e, expiresAt: n } = this.tokens;
34902
+ return e ? n ? Date.now() + t * 1000 < n : true : false;
34903
+ }
34904
+ updateFromOIDC(t) {
34905
+ if (!t.access_token)
34906
+ return;
34907
+ const e = Date.now();
34908
+ if (this.tokens.accessToken = t.access_token, t.refresh_token && (this.tokens.refreshToken = t.refresh_token), typeof t.expires_in == "number" && t.expires_in > 0)
34909
+ this.tokens.expiresAt = e + t.expires_in * 1000;
34910
+ else {
34911
+ const n = this.parseJwtExpSec(t.access_token);
34912
+ this.tokens.expiresAt = n ? n * 1000 : undefined;
34913
+ }
34914
+ this.logger.debug("AuthManager: OIDC tokens updated", { expiresAt: this.tokens.expiresAt });
34915
+ }
34916
+ async ensure(t) {
34917
+ if (await this.init(), this.pool.length >= t)
34918
+ return;
34919
+ const e = Math.max(this.desiredPoolSize, t), n = this.getBatMaxMint(), r = Math.min(e - this.pool.length, n);
34920
+ r <= 0 || await this.topUp(r);
34921
+ }
34922
+ async getBlindAuthToken({
34923
+ method: t,
34924
+ path: e
34925
+ }) {
34926
+ return this.info && !this.info.requiresBlindAuthToken(t, e) && this.logger.warn("Endpoint is not marked as protected by NUT-22; still issuing BAT", {
34927
+ method: t,
34928
+ path: e
34929
+ }), this.withLock(async () => {
34930
+ if (await this.ensure(1), this.pool.length === 0)
34931
+ throw new Error("AuthManager: no BATs available and minting failed");
34932
+ const n = this.pool.pop();
34933
+ return this.logger.debug("AuthManager: BAT requested", {
34934
+ method: t,
34935
+ path: e,
34936
+ remaining: this.pool.length
34937
+ }), as(n);
34938
+ });
34939
+ }
34940
+ importPool(t, e = "replace") {
34941
+ e === "replace" && (this.pool = []);
34942
+ const n = new Map(this.pool.map((r) => [r.secret, r]));
34943
+ for (const r of t)
34944
+ !r || !r.secret || !r.C || !r.id || n.has(r.secret) || (this.pool.push(r), n.set(r.secret, r));
34945
+ }
34946
+ exportPool() {
34947
+ return this.pool.map((t) => ({ ...t, dleq: t.dleq ? { ...t.dleq } : undefined }));
34948
+ }
34949
+ parseJwtExpSec(t) {
34950
+ if (!t)
34951
+ return;
34952
+ const e = t.split(".");
34953
+ if (e.length === 3)
34954
+ try {
34955
+ const n = _.toString(_.fromBase64(e[1])), r = JSON.parse(n), i4 = typeof r.exp == "number" ? r.exp : Number(r.exp);
34956
+ if (Number.isFinite(i4) && i4 > 0)
34957
+ return i4;
34958
+ } catch {
34959
+ this.logger.warn("JWT access token was malformed.", {
34960
+ token: t
34961
+ });
34962
+ }
34963
+ }
34964
+ async withLock(t) {
34965
+ const e = this.lockChain ?? Promise.resolve();
34966
+ let n;
34967
+ const r = new Promise((o) => {
34968
+ n = o;
34969
+ }), i4 = e.then(() => r);
34970
+ this.lockChain = i4;
34971
+ try {
34972
+ return await e, await t();
34973
+ } finally {
34974
+ n(), this.lockChain === i4 && (this.lockChain = undefined);
34975
+ }
34976
+ }
34977
+ async init() {
34978
+ if (!this.info) {
34979
+ const t = await this.req({
34980
+ endpoint: W(this.mintUrl, "/v1/info"),
34981
+ method: "GET"
34982
+ });
34983
+ this.info = new wt(t);
34984
+ }
34985
+ if (!this.keychain) {
34986
+ const [t, e] = await Promise.all([
34987
+ this.req({
34988
+ endpoint: W(this.mintUrl, "/v1/auth/blind/keysets"),
34989
+ method: "GET"
34990
+ }),
34991
+ this.req({
34992
+ endpoint: W(this.mintUrl, "/v1/auth/blind/keys"),
34993
+ method: "GET"
34994
+ })
34995
+ ]);
34996
+ this.keychain = new Ue(this.mintUrl, "auth", t.keysets, e.keysets), this.keychain.getCheapestKeyset();
34997
+ }
34998
+ }
34999
+ getBatMaxMint() {
35000
+ if (!this.info)
35001
+ throw new Error("AuthManager: mint info not loaded");
35002
+ const e = this.info.nuts[22]?.bat_max_mint ?? this.maxPerMint;
35003
+ return Math.max(1, Math.min(this.maxPerMint, e));
35004
+ }
35005
+ getActiveKeys() {
35006
+ if (!this.keychain)
35007
+ throw new Error("AuthManager: keyset not loaded for active keyset");
35008
+ return this.keychain.getCheapestKeyset();
35009
+ }
35010
+ async topUp(t) {
35011
+ if (!this.info)
35012
+ throw new Error("AuthManager: mint info not loaded");
35013
+ const e = this.info.requiresClearAuthToken("POST", "/v1/auth/blind/mint");
35014
+ let n;
35015
+ if (e && (n = await this.ensureCAT(), !n))
35016
+ throw new Error("AuthManager: Clear-auth token required for /v1/auth/blind/mint but not available. Authenticate with the mint to obtain a CAT first.");
35017
+ const r = this.getActiveKeys(), i4 = N.createRandomData(t, r), o = { outputs: i4.map((l) => l.blindedMessage) }, a = {};
35018
+ n && (a["Clear-auth"] = n);
35019
+ const c = await this.req({
35020
+ endpoint: W(this.mintUrl, "/v1/auth/blind/mint"),
35021
+ method: "POST",
35022
+ headers: a,
35023
+ requestBody: o
35024
+ });
35025
+ if (!Array.isArray(c?.signatures) || c.signatures.length !== i4.length)
35026
+ throw new Error("AuthManager: bad BAT mint response");
35027
+ const u = i4.map((l, h) => l.toProof(c.signatures[h], r));
35028
+ for (const l of u)
35029
+ if (!De(l, r))
35030
+ throw new Error("AuthManager: mint returned BAT with invalid DLEQ");
35031
+ this.pool.push(...u), this.logger.debug("AuthManager: performed topUp", {
35032
+ minted: u.length,
35033
+ pool: this.pool.length
35034
+ });
35035
+ }
35036
+ };
35037
+ kt.MIN_VALID_SECS = 30;
35038
+ function as(s) {
35039
+ const t = { id: s.id, secret: s.secret, C: s.C };
35040
+ return `authA${me(t)}`;
35041
+ }
35042
+
30395
35043
  // ../routstr-chat/node_modules/zustand/esm/vanilla.mjs
30396
35044
  var createStoreImpl = (createState) => {
30397
35045
  let state;
@@ -31479,8 +36127,8 @@ Current mode: ${currentMode}`);
31479
36127
  rl.question(`
31480
36128
  Enter choice (1-2): `, (answer) => {
31481
36129
  rl.close();
31482
- const num = parseInt(answer, 10);
31483
- resolve(Number.isFinite(num) && num >= 1 && num <= 2 ? num - 1 : 0);
36130
+ const num2 = parseInt(answer, 10);
36131
+ resolve(Number.isFinite(num2) && num2 >= 1 && num2 <= 2 ? num2 - 1 : 0);
31484
36132
  });
31485
36133
  });
31486
36134
  const selectedMode = modes[selectedIndex];