@kehto/paja 0.3.5 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1697,13 +1697,13 @@ function legacyScopedKey(pubkey, dTag, aggregateHash, userKey) {
1697
1697
  }
1698
1698
  function byteLength(str) {
1699
1699
  let bytes = 0;
1700
- for (let i = 0; i < str.length; i++) {
1701
- const c = str.charCodeAt(i);
1700
+ for (let i2 = 0; i2 < str.length; i2++) {
1701
+ const c = str.charCodeAt(i2);
1702
1702
  if (c < 128) bytes += 1;
1703
1703
  else if (c < 2048) bytes += 2;
1704
1704
  else if (c < 55296 || c >= 57344) bytes += 3;
1705
1705
  else {
1706
- i++;
1706
+ i2++;
1707
1707
  bytes += 4;
1708
1708
  }
1709
1709
  }
@@ -2003,13 +2003,13 @@ function createNapEnvelopeDispatcher(handlers) {
2003
2003
  }
2004
2004
  function utf8ByteLength(str) {
2005
2005
  let bytes = 0;
2006
- for (let i = 0; i < str.length; i++) {
2007
- const c = str.charCodeAt(i);
2006
+ for (let i2 = 0; i2 < str.length; i2++) {
2007
+ const c = str.charCodeAt(i2);
2008
2008
  if (c < 128) bytes += 1;
2009
2009
  else if (c < 2048) bytes += 2;
2010
2010
  else if (c < 55296 || c >= 57344) bytes += 3;
2011
2011
  else {
2012
- i++;
2012
+ i2++;
2013
2013
  bytes += 4;
2014
2014
  }
2015
2015
  }
@@ -2252,8 +2252,8 @@ function bytesToHex(bytes) {
2252
2252
  }
2253
2253
  function hexToBytes(hex) {
2254
2254
  const bytes = new Uint8Array(hex.length / 2);
2255
- for (let i = 0; i < hex.length; i += 2) {
2256
- bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
2255
+ for (let i2 = 0; i2 < hex.length; i2 += 2) {
2256
+ bytes[i2 / 2] = parseInt(hex.substring(i2, i2 + 2), 16);
2257
2257
  }
2258
2258
  return bytes;
2259
2259
  }
@@ -2427,8 +2427,8 @@ function createStatePersistence() {
2427
2427
  clear(prefix) {
2428
2428
  try {
2429
2429
  const keysToRemove = [];
2430
- for (let i = 0; i < localStorage.length; i++) {
2431
- const key = localStorage.key(i);
2430
+ for (let i2 = 0; i2 < localStorage.length; i2++) {
2431
+ const key = localStorage.key(i2);
2432
2432
  if (key?.startsWith(prefix)) keysToRemove.push(key);
2433
2433
  }
2434
2434
  for (const key of keysToRemove) localStorage.removeItem(key);
@@ -2438,8 +2438,8 @@ function createStatePersistence() {
2438
2438
  keys(prefix) {
2439
2439
  try {
2440
2440
  const result = [];
2441
- for (let i = 0; i < localStorage.length; i++) {
2442
- const key = localStorage.key(i);
2441
+ for (let i2 = 0; i2 < localStorage.length; i2++) {
2442
+ const key = localStorage.key(i2);
2443
2443
  if (key?.startsWith(prefix)) result.push(key);
2444
2444
  }
2445
2445
  return result;
@@ -2450,8 +2450,8 @@ function createStatePersistence() {
2450
2450
  calculateBytes(prefix, excludeKey) {
2451
2451
  try {
2452
2452
  let total = 0;
2453
- for (let i = 0; i < localStorage.length; i++) {
2454
- const key = localStorage.key(i);
2453
+ for (let i2 = 0; i2 < localStorage.length; i2++) {
2454
+ const key = localStorage.key(i2);
2455
2455
  if (!key?.startsWith(prefix)) continue;
2456
2456
  if (excludeKey && key === excludeKey) continue;
2457
2457
  const value = localStorage.getItem(key) ?? "";
@@ -3465,6 +3465,12 @@ function createShellBridge(hooks) {
3465
3465
  function isBytes(a) {
3466
3466
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
3467
3467
  }
3468
+ function anumber(n, title = "") {
3469
+ if (!Number.isSafeInteger(n) || n < 0) {
3470
+ const prefix = title && `"${title}" `;
3471
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
3472
+ }
3473
+ }
3468
3474
  function abytes(value, length, title = "") {
3469
3475
  const bytes = isBytes(value);
3470
3476
  const len = value?.length;
@@ -3477,18 +3483,42 @@ function abytes(value, length, title = "") {
3477
3483
  }
3478
3484
  return value;
3479
3485
  }
3486
+ function aexists(instance, checkFinished = true) {
3487
+ if (instance.destroyed)
3488
+ throw new Error("Hash instance has been destroyed");
3489
+ if (checkFinished && instance.finished)
3490
+ throw new Error("Hash#digest() has already been called");
3491
+ }
3492
+ function aoutput(out, instance) {
3493
+ abytes(out, void 0, "digestInto() output");
3494
+ const min = instance.outputLen;
3495
+ if (out.length < min) {
3496
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
3497
+ }
3498
+ }
3499
+ function clean(...arrays) {
3500
+ for (let i2 = 0; i2 < arrays.length; i2++) {
3501
+ arrays[i2].fill(0);
3502
+ }
3503
+ }
3504
+ function createView(arr) {
3505
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3506
+ }
3507
+ function rotr(word, shift) {
3508
+ return word << 32 - shift | word >>> shift;
3509
+ }
3480
3510
  var hasHexBuiltin = /* @__PURE__ */ (() => (
3481
3511
  // @ts-ignore
3482
3512
  typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
3483
3513
  ))();
3484
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
3514
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0"));
3485
3515
  function bytesToHex2(bytes) {
3486
3516
  abytes(bytes);
3487
3517
  if (hasHexBuiltin)
3488
3518
  return bytes.toHex();
3489
3519
  let hex = "";
3490
- for (let i = 0; i < bytes.length; i++) {
3491
- hex += hexes[bytes[i]];
3520
+ for (let i2 = 0; i2 < bytes.length; i2++) {
3521
+ hex += hexes[bytes[i2]];
3492
3522
  }
3493
3523
  return hex;
3494
3524
  }
@@ -3525,19 +3555,37 @@ function hexToBytes2(hex) {
3525
3555
  }
3526
3556
  function concatBytes(...arrays) {
3527
3557
  let sum = 0;
3528
- for (let i = 0; i < arrays.length; i++) {
3529
- const a = arrays[i];
3558
+ for (let i2 = 0; i2 < arrays.length; i2++) {
3559
+ const a = arrays[i2];
3530
3560
  abytes(a);
3531
3561
  sum += a.length;
3532
3562
  }
3533
3563
  const res = new Uint8Array(sum);
3534
- for (let i = 0, pad = 0; i < arrays.length; i++) {
3535
- const a = arrays[i];
3564
+ for (let i2 = 0, pad = 0; i2 < arrays.length; i2++) {
3565
+ const a = arrays[i2];
3536
3566
  res.set(a, pad);
3537
3567
  pad += a.length;
3538
3568
  }
3539
3569
  return res;
3540
3570
  }
3571
+ function createHasher(hashCons, info = {}) {
3572
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
3573
+ const tmp = hashCons(void 0);
3574
+ hashC.outputLen = tmp.outputLen;
3575
+ hashC.blockLen = tmp.blockLen;
3576
+ hashC.create = (opts) => hashCons(opts);
3577
+ Object.assign(hashC, info);
3578
+ return Object.freeze(hashC);
3579
+ }
3580
+ function randomBytes(bytesLength = 32) {
3581
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
3582
+ if (typeof cr?.getRandomValues !== "function")
3583
+ throw new Error("crypto.getRandomValues must be defined");
3584
+ return cr.getRandomValues(new Uint8Array(bytesLength));
3585
+ }
3586
+ var oidNist = (suffix) => ({
3587
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
3588
+ });
3541
3589
 
3542
3590
  // ../../node_modules/.pnpm/@scure+base@2.0.0/node_modules/@scure/base/index.js
3543
3591
  function isBytes2(a) {
@@ -3564,7 +3612,7 @@ function astr(label, input) {
3564
3612
  throw new Error(`${label}: string expected`);
3565
3613
  return true;
3566
3614
  }
3567
- function anumber(n) {
3615
+ function anumber2(n) {
3568
3616
  if (!Number.isSafeInteger(n))
3569
3617
  throw new Error(`invalid integer: ${n}`);
3570
3618
  }
@@ -3593,24 +3641,24 @@ function alphabet(letters) {
3593
3641
  const lettersA = typeof letters === "string" ? letters.split("") : letters;
3594
3642
  const len = lettersA.length;
3595
3643
  astrArr("alphabet", lettersA);
3596
- const indexes = new Map(lettersA.map((l, i) => [l, i]));
3644
+ const indexes = new Map(lettersA.map((l, i2) => [l, i2]));
3597
3645
  return {
3598
3646
  encode: (digits) => {
3599
3647
  aArr(digits);
3600
- return digits.map((i) => {
3601
- if (!Number.isSafeInteger(i) || i < 0 || i >= len)
3602
- throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
3603
- return lettersA[i];
3648
+ return digits.map((i2) => {
3649
+ if (!Number.isSafeInteger(i2) || i2 < 0 || i2 >= len)
3650
+ throw new Error(`alphabet.encode: digit index outside alphabet "${i2}". Allowed: ${letters}`);
3651
+ return lettersA[i2];
3604
3652
  });
3605
3653
  },
3606
3654
  decode: (input) => {
3607
3655
  aArr(input);
3608
3656
  return input.map((letter) => {
3609
3657
  astr("alphabet.decode", letter);
3610
- const i = indexes.get(letter);
3611
- if (i === void 0)
3658
+ const i2 = indexes.get(letter);
3659
+ if (i2 === void 0)
3612
3660
  throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
3613
- return i;
3661
+ return i2;
3614
3662
  });
3615
3663
  }
3616
3664
  };
@@ -3633,8 +3681,8 @@ var gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
3633
3681
  var radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
3634
3682
  var powers = /* @__PURE__ */ (() => {
3635
3683
  let res = [];
3636
- for (let i = 0; i < 40; i++)
3637
- res.push(2 ** i);
3684
+ for (let i2 = 0; i2 < 40; i2++)
3685
+ res.push(2 ** i2);
3638
3686
  return res;
3639
3687
  })();
3640
3688
  function convertRadix2(data, from, to, padding) {
@@ -3652,7 +3700,7 @@ function convertRadix2(data, from, to, padding) {
3652
3700
  const mask = powers[to] - 1;
3653
3701
  const res = [];
3654
3702
  for (const n of data) {
3655
- anumber(n);
3703
+ anumber2(n);
3656
3704
  if (n >= max)
3657
3705
  throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
3658
3706
  carry = carry << from | n;
@@ -3677,7 +3725,7 @@ function convertRadix2(data, from, to, padding) {
3677
3725
  }
3678
3726
  // @__NO_SIDE_EFFECTS__
3679
3727
  function radix2(bits, revPadding = false) {
3680
- anumber(bits);
3728
+ anumber2(bits);
3681
3729
  if (bits <= 0 || bits > 32)
3682
3730
  throw new Error("radix2: bits should be in (0..32]");
3683
3731
  if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32)
@@ -3708,27 +3756,27 @@ var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059
3708
3756
  function bech32Polymod(pre) {
3709
3757
  const b = pre >> 25;
3710
3758
  let chk = (pre & 33554431) << 5;
3711
- for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
3712
- if ((b >> i & 1) === 1)
3713
- chk ^= POLYMOD_GENERATORS[i];
3759
+ for (let i2 = 0; i2 < POLYMOD_GENERATORS.length; i2++) {
3760
+ if ((b >> i2 & 1) === 1)
3761
+ chk ^= POLYMOD_GENERATORS[i2];
3714
3762
  }
3715
3763
  return chk;
3716
3764
  }
3717
3765
  function bechChecksum(prefix, words, encodingConst = 1) {
3718
3766
  const len = prefix.length;
3719
3767
  let chk = 1;
3720
- for (let i = 0; i < len; i++) {
3721
- const c = prefix.charCodeAt(i);
3768
+ for (let i2 = 0; i2 < len; i2++) {
3769
+ const c = prefix.charCodeAt(i2);
3722
3770
  if (c < 33 || c > 126)
3723
3771
  throw new Error(`Invalid prefix (${prefix})`);
3724
3772
  chk = bech32Polymod(chk) ^ c >> 5;
3725
3773
  }
3726
3774
  chk = bech32Polymod(chk);
3727
- for (let i = 0; i < len; i++)
3728
- chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31;
3775
+ for (let i2 = 0; i2 < len; i2++)
3776
+ chk = bech32Polymod(chk) ^ prefix.charCodeAt(i2) & 31;
3729
3777
  for (let v of words)
3730
3778
  chk = bech32Polymod(chk) ^ v;
3731
- for (let i = 0; i < 6; i++)
3779
+ for (let i2 = 0; i2 < 6; i2++)
3732
3780
  chk = bech32Polymod(chk);
3733
3781
  chk ^= encodingConst;
3734
3782
  return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
@@ -3951,6 +3999,1668 @@ function encodeTLV(tlv) {
3951
3999
  return concatBytes(...entries);
3952
4000
  }
3953
4001
 
4002
+ // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_md.js
4003
+ function Chi(a, b, c) {
4004
+ return a & b ^ ~a & c;
4005
+ }
4006
+ function Maj(a, b, c) {
4007
+ return a & b ^ a & c ^ b & c;
4008
+ }
4009
+ var HashMD = class {
4010
+ blockLen;
4011
+ outputLen;
4012
+ padOffset;
4013
+ isLE;
4014
+ // For partial updates less than block size
4015
+ buffer;
4016
+ view;
4017
+ finished = false;
4018
+ length = 0;
4019
+ pos = 0;
4020
+ destroyed = false;
4021
+ constructor(blockLen, outputLen, padOffset, isLE) {
4022
+ this.blockLen = blockLen;
4023
+ this.outputLen = outputLen;
4024
+ this.padOffset = padOffset;
4025
+ this.isLE = isLE;
4026
+ this.buffer = new Uint8Array(blockLen);
4027
+ this.view = createView(this.buffer);
4028
+ }
4029
+ update(data) {
4030
+ aexists(this);
4031
+ abytes(data);
4032
+ const { view, buffer, blockLen } = this;
4033
+ const len = data.length;
4034
+ for (let pos = 0; pos < len; ) {
4035
+ const take = Math.min(blockLen - this.pos, len - pos);
4036
+ if (take === blockLen) {
4037
+ const dataView = createView(data);
4038
+ for (; blockLen <= len - pos; pos += blockLen)
4039
+ this.process(dataView, pos);
4040
+ continue;
4041
+ }
4042
+ buffer.set(data.subarray(pos, pos + take), this.pos);
4043
+ this.pos += take;
4044
+ pos += take;
4045
+ if (this.pos === blockLen) {
4046
+ this.process(view, 0);
4047
+ this.pos = 0;
4048
+ }
4049
+ }
4050
+ this.length += data.length;
4051
+ this.roundClean();
4052
+ return this;
4053
+ }
4054
+ digestInto(out) {
4055
+ aexists(this);
4056
+ aoutput(out, this);
4057
+ this.finished = true;
4058
+ const { buffer, view, blockLen, isLE } = this;
4059
+ let { pos } = this;
4060
+ buffer[pos++] = 128;
4061
+ clean(this.buffer.subarray(pos));
4062
+ if (this.padOffset > blockLen - pos) {
4063
+ this.process(view, 0);
4064
+ pos = 0;
4065
+ }
4066
+ for (let i2 = pos; i2 < blockLen; i2++)
4067
+ buffer[i2] = 0;
4068
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
4069
+ this.process(view, 0);
4070
+ const oview = createView(out);
4071
+ const len = this.outputLen;
4072
+ if (len % 4)
4073
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
4074
+ const outLen = len / 4;
4075
+ const state = this.get();
4076
+ if (outLen > state.length)
4077
+ throw new Error("_sha2: outputLen bigger than state");
4078
+ for (let i2 = 0; i2 < outLen; i2++)
4079
+ oview.setUint32(4 * i2, state[i2], isLE);
4080
+ }
4081
+ digest() {
4082
+ const { buffer, outputLen } = this;
4083
+ this.digestInto(buffer);
4084
+ const res = buffer.slice(0, outputLen);
4085
+ this.destroy();
4086
+ return res;
4087
+ }
4088
+ _cloneInto(to) {
4089
+ to ||= new this.constructor();
4090
+ to.set(...this.get());
4091
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
4092
+ to.destroyed = destroyed;
4093
+ to.finished = finished;
4094
+ to.length = length;
4095
+ to.pos = pos;
4096
+ if (length % blockLen)
4097
+ to.buffer.set(buffer);
4098
+ return to;
4099
+ }
4100
+ clone() {
4101
+ return this._cloneInto();
4102
+ }
4103
+ };
4104
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
4105
+ 1779033703,
4106
+ 3144134277,
4107
+ 1013904242,
4108
+ 2773480762,
4109
+ 1359893119,
4110
+ 2600822924,
4111
+ 528734635,
4112
+ 1541459225
4113
+ ]);
4114
+
4115
+ // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/sha2.js
4116
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
4117
+ 1116352408,
4118
+ 1899447441,
4119
+ 3049323471,
4120
+ 3921009573,
4121
+ 961987163,
4122
+ 1508970993,
4123
+ 2453635748,
4124
+ 2870763221,
4125
+ 3624381080,
4126
+ 310598401,
4127
+ 607225278,
4128
+ 1426881987,
4129
+ 1925078388,
4130
+ 2162078206,
4131
+ 2614888103,
4132
+ 3248222580,
4133
+ 3835390401,
4134
+ 4022224774,
4135
+ 264347078,
4136
+ 604807628,
4137
+ 770255983,
4138
+ 1249150122,
4139
+ 1555081692,
4140
+ 1996064986,
4141
+ 2554220882,
4142
+ 2821834349,
4143
+ 2952996808,
4144
+ 3210313671,
4145
+ 3336571891,
4146
+ 3584528711,
4147
+ 113926993,
4148
+ 338241895,
4149
+ 666307205,
4150
+ 773529912,
4151
+ 1294757372,
4152
+ 1396182291,
4153
+ 1695183700,
4154
+ 1986661051,
4155
+ 2177026350,
4156
+ 2456956037,
4157
+ 2730485921,
4158
+ 2820302411,
4159
+ 3259730800,
4160
+ 3345764771,
4161
+ 3516065817,
4162
+ 3600352804,
4163
+ 4094571909,
4164
+ 275423344,
4165
+ 430227734,
4166
+ 506948616,
4167
+ 659060556,
4168
+ 883997877,
4169
+ 958139571,
4170
+ 1322822218,
4171
+ 1537002063,
4172
+ 1747873779,
4173
+ 1955562222,
4174
+ 2024104815,
4175
+ 2227730452,
4176
+ 2361852424,
4177
+ 2428436474,
4178
+ 2756734187,
4179
+ 3204031479,
4180
+ 3329325298
4181
+ ]);
4182
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
4183
+ var SHA2_32B = class extends HashMD {
4184
+ constructor(outputLen) {
4185
+ super(64, outputLen, 8, false);
4186
+ }
4187
+ get() {
4188
+ const { A, B, C, D, E, F, G, H } = this;
4189
+ return [A, B, C, D, E, F, G, H];
4190
+ }
4191
+ // prettier-ignore
4192
+ set(A, B, C, D, E, F, G, H) {
4193
+ this.A = A | 0;
4194
+ this.B = B | 0;
4195
+ this.C = C | 0;
4196
+ this.D = D | 0;
4197
+ this.E = E | 0;
4198
+ this.F = F | 0;
4199
+ this.G = G | 0;
4200
+ this.H = H | 0;
4201
+ }
4202
+ process(view, offset) {
4203
+ for (let i2 = 0; i2 < 16; i2++, offset += 4)
4204
+ SHA256_W[i2] = view.getUint32(offset, false);
4205
+ for (let i2 = 16; i2 < 64; i2++) {
4206
+ const W15 = SHA256_W[i2 - 15];
4207
+ const W2 = SHA256_W[i2 - 2];
4208
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
4209
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
4210
+ SHA256_W[i2] = s1 + SHA256_W[i2 - 7] + s0 + SHA256_W[i2 - 16] | 0;
4211
+ }
4212
+ let { A, B, C, D, E, F, G, H } = this;
4213
+ for (let i2 = 0; i2 < 64; i2++) {
4214
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
4215
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i2] + SHA256_W[i2] | 0;
4216
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
4217
+ const T2 = sigma0 + Maj(A, B, C) | 0;
4218
+ H = G;
4219
+ G = F;
4220
+ F = E;
4221
+ E = D + T1 | 0;
4222
+ D = C;
4223
+ C = B;
4224
+ B = A;
4225
+ A = T1 + T2 | 0;
4226
+ }
4227
+ A = A + this.A | 0;
4228
+ B = B + this.B | 0;
4229
+ C = C + this.C | 0;
4230
+ D = D + this.D | 0;
4231
+ E = E + this.E | 0;
4232
+ F = F + this.F | 0;
4233
+ G = G + this.G | 0;
4234
+ H = H + this.H | 0;
4235
+ this.set(A, B, C, D, E, F, G, H);
4236
+ }
4237
+ roundClean() {
4238
+ clean(SHA256_W);
4239
+ }
4240
+ destroy() {
4241
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
4242
+ clean(this.buffer);
4243
+ }
4244
+ };
4245
+ var _SHA256 = class extends SHA2_32B {
4246
+ // We cannot use array here since array allows indexing by variable
4247
+ // which means optimizer/compiler cannot use registers.
4248
+ A = SHA256_IV[0] | 0;
4249
+ B = SHA256_IV[1] | 0;
4250
+ C = SHA256_IV[2] | 0;
4251
+ D = SHA256_IV[3] | 0;
4252
+ E = SHA256_IV[4] | 0;
4253
+ F = SHA256_IV[5] | 0;
4254
+ G = SHA256_IV[6] | 0;
4255
+ H = SHA256_IV[7] | 0;
4256
+ constructor() {
4257
+ super(32);
4258
+ }
4259
+ };
4260
+ var sha256 = /* @__PURE__ */ createHasher(
4261
+ () => new _SHA256(),
4262
+ /* @__PURE__ */ oidNist(1)
4263
+ );
4264
+
4265
+ // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/utils.js
4266
+ var _0n = /* @__PURE__ */ BigInt(0);
4267
+ var _1n = /* @__PURE__ */ BigInt(1);
4268
+ function abool(value, title = "") {
4269
+ if (typeof value !== "boolean") {
4270
+ const prefix = title && `"${title}" `;
4271
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
4272
+ }
4273
+ return value;
4274
+ }
4275
+ function abignumber(n) {
4276
+ if (typeof n === "bigint") {
4277
+ if (!isPosBig(n))
4278
+ throw new Error("positive bigint expected, got " + n);
4279
+ } else
4280
+ anumber(n);
4281
+ return n;
4282
+ }
4283
+ function hexToNumber(hex) {
4284
+ if (typeof hex !== "string")
4285
+ throw new Error("hex string expected, got " + typeof hex);
4286
+ return hex === "" ? _0n : BigInt("0x" + hex);
4287
+ }
4288
+ function bytesToNumberBE(bytes) {
4289
+ return hexToNumber(bytesToHex2(bytes));
4290
+ }
4291
+ function bytesToNumberLE(bytes) {
4292
+ return hexToNumber(bytesToHex2(copyBytes(abytes(bytes)).reverse()));
4293
+ }
4294
+ function numberToBytesBE(n, len) {
4295
+ anumber(len);
4296
+ n = abignumber(n);
4297
+ const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
4298
+ if (res.length !== len)
4299
+ throw new Error("number too large");
4300
+ return res;
4301
+ }
4302
+ function numberToBytesLE(n, len) {
4303
+ return numberToBytesBE(n, len).reverse();
4304
+ }
4305
+ function copyBytes(bytes) {
4306
+ return Uint8Array.from(bytes);
4307
+ }
4308
+ function asciiToBytes(ascii) {
4309
+ return Uint8Array.from(ascii, (c, i2) => {
4310
+ const charCode = c.charCodeAt(0);
4311
+ if (c.length !== 1 || charCode > 127) {
4312
+ throw new Error(`string contains non-ASCII character "${ascii[i2]}" with code ${charCode} at position ${i2}`);
4313
+ }
4314
+ return charCode;
4315
+ });
4316
+ }
4317
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
4318
+ function bitLen(n) {
4319
+ let len;
4320
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
4321
+ ;
4322
+ return len;
4323
+ }
4324
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
4325
+ function validateObject(object, fields = {}, optFields = {}) {
4326
+ if (!object || typeof object !== "object")
4327
+ throw new Error("expected valid options object");
4328
+ function checkField(fieldName, expectedType, isOpt) {
4329
+ const val = object[fieldName];
4330
+ if (isOpt && val === void 0)
4331
+ return;
4332
+ const current = typeof val;
4333
+ if (current !== expectedType || val === null)
4334
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
4335
+ }
4336
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
4337
+ iter(fields, false);
4338
+ iter(optFields, true);
4339
+ }
4340
+ function memoized(fn) {
4341
+ const map = /* @__PURE__ */ new WeakMap();
4342
+ return (arg, ...args) => {
4343
+ const val = map.get(arg);
4344
+ if (val !== void 0)
4345
+ return val;
4346
+ const computed = fn(arg, ...args);
4347
+ map.set(arg, computed);
4348
+ return computed;
4349
+ };
4350
+ }
4351
+
4352
+ // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/modular.js
4353
+ var _0n2 = /* @__PURE__ */ BigInt(0);
4354
+ var _1n2 = /* @__PURE__ */ BigInt(1);
4355
+ var _2n = /* @__PURE__ */ BigInt(2);
4356
+ var _3n = /* @__PURE__ */ BigInt(3);
4357
+ var _4n = /* @__PURE__ */ BigInt(4);
4358
+ var _5n = /* @__PURE__ */ BigInt(5);
4359
+ var _7n = /* @__PURE__ */ BigInt(7);
4360
+ var _8n = /* @__PURE__ */ BigInt(8);
4361
+ var _9n = /* @__PURE__ */ BigInt(9);
4362
+ var _16n = /* @__PURE__ */ BigInt(16);
4363
+ function mod(a, b) {
4364
+ const result = a % b;
4365
+ return result >= _0n2 ? result : b + result;
4366
+ }
4367
+ function pow2(x, power, modulo) {
4368
+ let res = x;
4369
+ while (power-- > _0n2) {
4370
+ res *= res;
4371
+ res %= modulo;
4372
+ }
4373
+ return res;
4374
+ }
4375
+ function invert(number, modulo) {
4376
+ if (number === _0n2)
4377
+ throw new Error("invert: expected non-zero number");
4378
+ if (modulo <= _0n2)
4379
+ throw new Error("invert: expected positive modulus, got " + modulo);
4380
+ let a = mod(number, modulo);
4381
+ let b = modulo;
4382
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
4383
+ while (a !== _0n2) {
4384
+ const q = b / a;
4385
+ const r = b % a;
4386
+ const m = x - u * q;
4387
+ const n = y - v * q;
4388
+ b = a, a = r, x = u, y = v, u = m, v = n;
4389
+ }
4390
+ const gcd2 = b;
4391
+ if (gcd2 !== _1n2)
4392
+ throw new Error("invert: does not exist");
4393
+ return mod(x, modulo);
4394
+ }
4395
+ function assertIsSquare(Fp, root, n) {
4396
+ if (!Fp.eql(Fp.sqr(root), n))
4397
+ throw new Error("Cannot find square root");
4398
+ }
4399
+ function sqrt3mod4(Fp, n) {
4400
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
4401
+ const root = Fp.pow(n, p1div4);
4402
+ assertIsSquare(Fp, root, n);
4403
+ return root;
4404
+ }
4405
+ function sqrt5mod8(Fp, n) {
4406
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
4407
+ const n2 = Fp.mul(n, _2n);
4408
+ const v = Fp.pow(n2, p5div8);
4409
+ const nv = Fp.mul(n, v);
4410
+ const i2 = Fp.mul(Fp.mul(nv, _2n), v);
4411
+ const root = Fp.mul(nv, Fp.sub(i2, Fp.ONE));
4412
+ assertIsSquare(Fp, root, n);
4413
+ return root;
4414
+ }
4415
+ function sqrt9mod16(P) {
4416
+ const Fp_ = Field(P);
4417
+ const tn = tonelliShanks(P);
4418
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
4419
+ const c2 = tn(Fp_, c1);
4420
+ const c3 = tn(Fp_, Fp_.neg(c1));
4421
+ const c4 = (P + _7n) / _16n;
4422
+ return (Fp, n) => {
4423
+ let tv1 = Fp.pow(n, c4);
4424
+ let tv2 = Fp.mul(tv1, c1);
4425
+ const tv3 = Fp.mul(tv1, c2);
4426
+ const tv4 = Fp.mul(tv1, c3);
4427
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
4428
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
4429
+ tv1 = Fp.cmov(tv1, tv2, e1);
4430
+ tv2 = Fp.cmov(tv4, tv3, e2);
4431
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
4432
+ const root = Fp.cmov(tv1, tv2, e3);
4433
+ assertIsSquare(Fp, root, n);
4434
+ return root;
4435
+ };
4436
+ }
4437
+ function tonelliShanks(P) {
4438
+ if (P < _3n)
4439
+ throw new Error("sqrt is not defined for small field");
4440
+ let Q = P - _1n2;
4441
+ let S = 0;
4442
+ while (Q % _2n === _0n2) {
4443
+ Q /= _2n;
4444
+ S++;
4445
+ }
4446
+ let Z = _2n;
4447
+ const _Fp = Field(P);
4448
+ while (FpLegendre(_Fp, Z) === 1) {
4449
+ if (Z++ > 1e3)
4450
+ throw new Error("Cannot find square root: probably non-prime P");
4451
+ }
4452
+ if (S === 1)
4453
+ return sqrt3mod4;
4454
+ let cc = _Fp.pow(Z, Q);
4455
+ const Q1div2 = (Q + _1n2) / _2n;
4456
+ return function tonelliSlow(Fp, n) {
4457
+ if (Fp.is0(n))
4458
+ return n;
4459
+ if (FpLegendre(Fp, n) !== 1)
4460
+ throw new Error("Cannot find square root");
4461
+ let M = S;
4462
+ let c = Fp.mul(Fp.ONE, cc);
4463
+ let t = Fp.pow(n, Q);
4464
+ let R = Fp.pow(n, Q1div2);
4465
+ while (!Fp.eql(t, Fp.ONE)) {
4466
+ if (Fp.is0(t))
4467
+ return Fp.ZERO;
4468
+ let i2 = 1;
4469
+ let t_tmp = Fp.sqr(t);
4470
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
4471
+ i2++;
4472
+ t_tmp = Fp.sqr(t_tmp);
4473
+ if (i2 === M)
4474
+ throw new Error("Cannot find square root");
4475
+ }
4476
+ const exponent = _1n2 << BigInt(M - i2 - 1);
4477
+ const b = Fp.pow(c, exponent);
4478
+ M = i2;
4479
+ c = Fp.sqr(b);
4480
+ t = Fp.mul(t, c);
4481
+ R = Fp.mul(R, b);
4482
+ }
4483
+ return R;
4484
+ };
4485
+ }
4486
+ function FpSqrt(P) {
4487
+ if (P % _4n === _3n)
4488
+ return sqrt3mod4;
4489
+ if (P % _8n === _5n)
4490
+ return sqrt5mod8;
4491
+ if (P % _16n === _9n)
4492
+ return sqrt9mod16(P);
4493
+ return tonelliShanks(P);
4494
+ }
4495
+ var FIELD_FIELDS = [
4496
+ "create",
4497
+ "isValid",
4498
+ "is0",
4499
+ "neg",
4500
+ "inv",
4501
+ "sqrt",
4502
+ "sqr",
4503
+ "eql",
4504
+ "add",
4505
+ "sub",
4506
+ "mul",
4507
+ "pow",
4508
+ "div",
4509
+ "addN",
4510
+ "subN",
4511
+ "mulN",
4512
+ "sqrN"
4513
+ ];
4514
+ function validateField(field) {
4515
+ const initial = {
4516
+ ORDER: "bigint",
4517
+ BYTES: "number",
4518
+ BITS: "number"
4519
+ };
4520
+ const opts = FIELD_FIELDS.reduce((map, val) => {
4521
+ map[val] = "function";
4522
+ return map;
4523
+ }, initial);
4524
+ validateObject(field, opts);
4525
+ return field;
4526
+ }
4527
+ function FpPow(Fp, num2, power) {
4528
+ if (power < _0n2)
4529
+ throw new Error("invalid exponent, negatives unsupported");
4530
+ if (power === _0n2)
4531
+ return Fp.ONE;
4532
+ if (power === _1n2)
4533
+ return num2;
4534
+ let p = Fp.ONE;
4535
+ let d = num2;
4536
+ while (power > _0n2) {
4537
+ if (power & _1n2)
4538
+ p = Fp.mul(p, d);
4539
+ d = Fp.sqr(d);
4540
+ power >>= _1n2;
4541
+ }
4542
+ return p;
4543
+ }
4544
+ function FpInvertBatch(Fp, nums, passZero = false) {
4545
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
4546
+ const multipliedAcc = nums.reduce((acc, num2, i2) => {
4547
+ if (Fp.is0(num2))
4548
+ return acc;
4549
+ inverted[i2] = acc;
4550
+ return Fp.mul(acc, num2);
4551
+ }, Fp.ONE);
4552
+ const invertedAcc = Fp.inv(multipliedAcc);
4553
+ nums.reduceRight((acc, num2, i2) => {
4554
+ if (Fp.is0(num2))
4555
+ return acc;
4556
+ inverted[i2] = Fp.mul(acc, inverted[i2]);
4557
+ return Fp.mul(acc, num2);
4558
+ }, invertedAcc);
4559
+ return inverted;
4560
+ }
4561
+ function FpLegendre(Fp, n) {
4562
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
4563
+ const powered = Fp.pow(n, p1mod2);
4564
+ const yes = Fp.eql(powered, Fp.ONE);
4565
+ const zero = Fp.eql(powered, Fp.ZERO);
4566
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
4567
+ if (!yes && !zero && !no)
4568
+ throw new Error("invalid Legendre symbol result");
4569
+ return yes ? 1 : zero ? 0 : -1;
4570
+ }
4571
+ function nLength(n, nBitLength) {
4572
+ if (nBitLength !== void 0)
4573
+ anumber(nBitLength);
4574
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
4575
+ const nByteLength = Math.ceil(_nBitLength / 8);
4576
+ return { nBitLength: _nBitLength, nByteLength };
4577
+ }
4578
+ var _Field = class {
4579
+ ORDER;
4580
+ BITS;
4581
+ BYTES;
4582
+ isLE;
4583
+ ZERO = _0n2;
4584
+ ONE = _1n2;
4585
+ _lengths;
4586
+ _sqrt;
4587
+ // cached sqrt
4588
+ _mod;
4589
+ constructor(ORDER, opts = {}) {
4590
+ if (ORDER <= _0n2)
4591
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
4592
+ let _nbitLength = void 0;
4593
+ this.isLE = false;
4594
+ if (opts != null && typeof opts === "object") {
4595
+ if (typeof opts.BITS === "number")
4596
+ _nbitLength = opts.BITS;
4597
+ if (typeof opts.sqrt === "function")
4598
+ this.sqrt = opts.sqrt;
4599
+ if (typeof opts.isLE === "boolean")
4600
+ this.isLE = opts.isLE;
4601
+ if (opts.allowedLengths)
4602
+ this._lengths = opts.allowedLengths?.slice();
4603
+ if (typeof opts.modFromBytes === "boolean")
4604
+ this._mod = opts.modFromBytes;
4605
+ }
4606
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
4607
+ if (nByteLength > 2048)
4608
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
4609
+ this.ORDER = ORDER;
4610
+ this.BITS = nBitLength;
4611
+ this.BYTES = nByteLength;
4612
+ this._sqrt = void 0;
4613
+ Object.preventExtensions(this);
4614
+ }
4615
+ create(num2) {
4616
+ return mod(num2, this.ORDER);
4617
+ }
4618
+ isValid(num2) {
4619
+ if (typeof num2 !== "bigint")
4620
+ throw new Error("invalid field element: expected bigint, got " + typeof num2);
4621
+ return _0n2 <= num2 && num2 < this.ORDER;
4622
+ }
4623
+ is0(num2) {
4624
+ return num2 === _0n2;
4625
+ }
4626
+ // is valid and invertible
4627
+ isValidNot0(num2) {
4628
+ return !this.is0(num2) && this.isValid(num2);
4629
+ }
4630
+ isOdd(num2) {
4631
+ return (num2 & _1n2) === _1n2;
4632
+ }
4633
+ neg(num2) {
4634
+ return mod(-num2, this.ORDER);
4635
+ }
4636
+ eql(lhs, rhs) {
4637
+ return lhs === rhs;
4638
+ }
4639
+ sqr(num2) {
4640
+ return mod(num2 * num2, this.ORDER);
4641
+ }
4642
+ add(lhs, rhs) {
4643
+ return mod(lhs + rhs, this.ORDER);
4644
+ }
4645
+ sub(lhs, rhs) {
4646
+ return mod(lhs - rhs, this.ORDER);
4647
+ }
4648
+ mul(lhs, rhs) {
4649
+ return mod(lhs * rhs, this.ORDER);
4650
+ }
4651
+ pow(num2, power) {
4652
+ return FpPow(this, num2, power);
4653
+ }
4654
+ div(lhs, rhs) {
4655
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
4656
+ }
4657
+ // Same as above, but doesn't normalize
4658
+ sqrN(num2) {
4659
+ return num2 * num2;
4660
+ }
4661
+ addN(lhs, rhs) {
4662
+ return lhs + rhs;
4663
+ }
4664
+ subN(lhs, rhs) {
4665
+ return lhs - rhs;
4666
+ }
4667
+ mulN(lhs, rhs) {
4668
+ return lhs * rhs;
4669
+ }
4670
+ inv(num2) {
4671
+ return invert(num2, this.ORDER);
4672
+ }
4673
+ sqrt(num2) {
4674
+ if (!this._sqrt)
4675
+ this._sqrt = FpSqrt(this.ORDER);
4676
+ return this._sqrt(this, num2);
4677
+ }
4678
+ toBytes(num2) {
4679
+ return this.isLE ? numberToBytesLE(num2, this.BYTES) : numberToBytesBE(num2, this.BYTES);
4680
+ }
4681
+ fromBytes(bytes, skipValidation = false) {
4682
+ abytes(bytes);
4683
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
4684
+ if (allowedLengths) {
4685
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
4686
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
4687
+ }
4688
+ const padded = new Uint8Array(BYTES);
4689
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
4690
+ bytes = padded;
4691
+ }
4692
+ if (bytes.length !== BYTES)
4693
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
4694
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
4695
+ if (modFromBytes)
4696
+ scalar = mod(scalar, ORDER);
4697
+ if (!skipValidation) {
4698
+ if (!this.isValid(scalar))
4699
+ throw new Error("invalid field element: outside of range 0..ORDER");
4700
+ }
4701
+ return scalar;
4702
+ }
4703
+ // TODO: we don't need it here, move out to separate fn
4704
+ invertBatch(lst) {
4705
+ return FpInvertBatch(this, lst);
4706
+ }
4707
+ // We can't move this out because Fp6, Fp12 implement it
4708
+ // and it's unclear what to return in there.
4709
+ cmov(a, b, condition) {
4710
+ return condition ? b : a;
4711
+ }
4712
+ };
4713
+ function Field(ORDER, opts = {}) {
4714
+ return new _Field(ORDER, opts);
4715
+ }
4716
+ function getFieldBytesLength(fieldOrder) {
4717
+ if (typeof fieldOrder !== "bigint")
4718
+ throw new Error("field order must be bigint");
4719
+ const bitLength = fieldOrder.toString(2).length;
4720
+ return Math.ceil(bitLength / 8);
4721
+ }
4722
+ function getMinHashLength(fieldOrder) {
4723
+ const length = getFieldBytesLength(fieldOrder);
4724
+ return length + Math.ceil(length / 2);
4725
+ }
4726
+ function mapHashToField(key, fieldOrder, isLE = false) {
4727
+ abytes(key);
4728
+ const len = key.length;
4729
+ const fieldLen = getFieldBytesLength(fieldOrder);
4730
+ const minLen = getMinHashLength(fieldOrder);
4731
+ if (len < 16 || len < minLen || len > 1024)
4732
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
4733
+ const num2 = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
4734
+ const reduced = mod(num2, fieldOrder - _1n2) + _1n2;
4735
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
4736
+ }
4737
+
4738
+ // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/curve.js
4739
+ var _0n3 = /* @__PURE__ */ BigInt(0);
4740
+ var _1n3 = /* @__PURE__ */ BigInt(1);
4741
+ function negateCt(condition, item) {
4742
+ const neg = item.negate();
4743
+ return condition ? neg : item;
4744
+ }
4745
+ function normalizeZ(c, points) {
4746
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
4747
+ return points.map((p, i2) => c.fromAffine(p.toAffine(invertedZs[i2])));
4748
+ }
4749
+ function validateW(W, bits) {
4750
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
4751
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
4752
+ }
4753
+ function calcWOpts(W, scalarBits) {
4754
+ validateW(W, scalarBits);
4755
+ const windows = Math.ceil(scalarBits / W) + 1;
4756
+ const windowSize = 2 ** (W - 1);
4757
+ const maxNumber = 2 ** W;
4758
+ const mask = bitMask(W);
4759
+ const shiftBy = BigInt(W);
4760
+ return { windows, windowSize, mask, maxNumber, shiftBy };
4761
+ }
4762
+ function calcOffsets(n, window2, wOpts) {
4763
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
4764
+ let wbits = Number(n & mask);
4765
+ let nextN = n >> shiftBy;
4766
+ if (wbits > windowSize) {
4767
+ wbits -= maxNumber;
4768
+ nextN += _1n3;
4769
+ }
4770
+ const offsetStart = window2 * windowSize;
4771
+ const offset = offsetStart + Math.abs(wbits) - 1;
4772
+ const isZero = wbits === 0;
4773
+ const isNeg = wbits < 0;
4774
+ const isNegF = window2 % 2 !== 0;
4775
+ const offsetF = offsetStart;
4776
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
4777
+ }
4778
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
4779
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
4780
+ function getW(P) {
4781
+ return pointWindowSizes.get(P) || 1;
4782
+ }
4783
+ function assert0(n) {
4784
+ if (n !== _0n3)
4785
+ throw new Error("invalid wNAF");
4786
+ }
4787
+ var wNAF = class {
4788
+ BASE;
4789
+ ZERO;
4790
+ Fn;
4791
+ bits;
4792
+ // Parametrized with a given Point class (not individual point)
4793
+ constructor(Point, bits) {
4794
+ this.BASE = Point.BASE;
4795
+ this.ZERO = Point.ZERO;
4796
+ this.Fn = Point.Fn;
4797
+ this.bits = bits;
4798
+ }
4799
+ // non-const time multiplication ladder
4800
+ _unsafeLadder(elm, n, p = this.ZERO) {
4801
+ let d = elm;
4802
+ while (n > _0n3) {
4803
+ if (n & _1n3)
4804
+ p = p.add(d);
4805
+ d = d.double();
4806
+ n >>= _1n3;
4807
+ }
4808
+ return p;
4809
+ }
4810
+ /**
4811
+ * Creates a wNAF precomputation window. Used for caching.
4812
+ * Default window size is set by `utils.precompute()` and is equal to 8.
4813
+ * Number of precomputed points depends on the curve size:
4814
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
4815
+ * - 𝑊 is the window size
4816
+ * - 𝑛 is the bitlength of the curve order.
4817
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
4818
+ * @param point Point instance
4819
+ * @param W window size
4820
+ * @returns precomputed point tables flattened to a single array
4821
+ */
4822
+ precomputeWindow(point, W) {
4823
+ const { windows, windowSize } = calcWOpts(W, this.bits);
4824
+ const points = [];
4825
+ let p = point;
4826
+ let base = p;
4827
+ for (let window2 = 0; window2 < windows; window2++) {
4828
+ base = p;
4829
+ points.push(base);
4830
+ for (let i2 = 1; i2 < windowSize; i2++) {
4831
+ base = base.add(p);
4832
+ points.push(base);
4833
+ }
4834
+ p = base.double();
4835
+ }
4836
+ return points;
4837
+ }
4838
+ /**
4839
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
4840
+ * More compact implementation:
4841
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
4842
+ * @returns real and fake (for const-time) points
4843
+ */
4844
+ wNAF(W, precomputes, n) {
4845
+ if (!this.Fn.isValid(n))
4846
+ throw new Error("invalid scalar");
4847
+ let p = this.ZERO;
4848
+ let f = this.BASE;
4849
+ const wo = calcWOpts(W, this.bits);
4850
+ for (let window2 = 0; window2 < wo.windows; window2++) {
4851
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo);
4852
+ n = nextN;
4853
+ if (isZero) {
4854
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
4855
+ } else {
4856
+ p = p.add(negateCt(isNeg, precomputes[offset]));
4857
+ }
4858
+ }
4859
+ assert0(n);
4860
+ return { p, f };
4861
+ }
4862
+ /**
4863
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
4864
+ * @param acc accumulator point to add result of multiplication
4865
+ * @returns point
4866
+ */
4867
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
4868
+ const wo = calcWOpts(W, this.bits);
4869
+ for (let window2 = 0; window2 < wo.windows; window2++) {
4870
+ if (n === _0n3)
4871
+ break;
4872
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, wo);
4873
+ n = nextN;
4874
+ if (isZero) {
4875
+ continue;
4876
+ } else {
4877
+ const item = precomputes[offset];
4878
+ acc = acc.add(isNeg ? item.negate() : item);
4879
+ }
4880
+ }
4881
+ assert0(n);
4882
+ return acc;
4883
+ }
4884
+ getPrecomputes(W, point, transform) {
4885
+ let comp = pointPrecomputes.get(point);
4886
+ if (!comp) {
4887
+ comp = this.precomputeWindow(point, W);
4888
+ if (W !== 1) {
4889
+ if (typeof transform === "function")
4890
+ comp = transform(comp);
4891
+ pointPrecomputes.set(point, comp);
4892
+ }
4893
+ }
4894
+ return comp;
4895
+ }
4896
+ cached(point, scalar, transform) {
4897
+ const W = getW(point);
4898
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
4899
+ }
4900
+ unsafe(point, scalar, transform, prev) {
4901
+ const W = getW(point);
4902
+ if (W === 1)
4903
+ return this._unsafeLadder(point, scalar, prev);
4904
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
4905
+ }
4906
+ // We calculate precomputes for elliptic curve point multiplication
4907
+ // using windowed method. This specifies window size and
4908
+ // stores precomputed values. Usually only base point would be precomputed.
4909
+ createCache(P, W) {
4910
+ validateW(W, this.bits);
4911
+ pointWindowSizes.set(P, W);
4912
+ pointPrecomputes.delete(P);
4913
+ }
4914
+ hasCache(elm) {
4915
+ return getW(elm) !== 1;
4916
+ }
4917
+ };
4918
+ function mulEndoUnsafe(Point, point, k1, k2) {
4919
+ let acc = point;
4920
+ let p1 = Point.ZERO;
4921
+ let p2 = Point.ZERO;
4922
+ while (k1 > _0n3 || k2 > _0n3) {
4923
+ if (k1 & _1n3)
4924
+ p1 = p1.add(acc);
4925
+ if (k2 & _1n3)
4926
+ p2 = p2.add(acc);
4927
+ acc = acc.double();
4928
+ k1 >>= _1n3;
4929
+ k2 >>= _1n3;
4930
+ }
4931
+ return { p1, p2 };
4932
+ }
4933
+ function createField(order, field, isLE) {
4934
+ if (field) {
4935
+ if (field.ORDER !== order)
4936
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
4937
+ validateField(field);
4938
+ return field;
4939
+ } else {
4940
+ return Field(order, { isLE });
4941
+ }
4942
+ }
4943
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
4944
+ if (FpFnLE === void 0)
4945
+ FpFnLE = type === "edwards";
4946
+ if (!CURVE || typeof CURVE !== "object")
4947
+ throw new Error(`expected valid ${type} CURVE object`);
4948
+ for (const p of ["p", "n", "h"]) {
4949
+ const val = CURVE[p];
4950
+ if (!(typeof val === "bigint" && val > _0n3))
4951
+ throw new Error(`CURVE.${p} must be positive bigint`);
4952
+ }
4953
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
4954
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
4955
+ const _b = type === "weierstrass" ? "b" : "d";
4956
+ const params = ["Gx", "Gy", "a", _b];
4957
+ for (const p of params) {
4958
+ if (!Fp.isValid(CURVE[p]))
4959
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
4960
+ }
4961
+ CURVE = Object.freeze(Object.assign({}, CURVE));
4962
+ return { CURVE, Fp, Fn };
4963
+ }
4964
+ function createKeygen(randomSecretKey, getPublicKey2) {
4965
+ return function keygen(seed) {
4966
+ const secretKey = randomSecretKey(seed);
4967
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
4968
+ };
4969
+ }
4970
+
4971
+ // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/weierstrass.js
4972
+ var divNearest = (num2, den) => (num2 + (num2 >= 0 ? den : -den) / _2n2) / den;
4973
+ function _splitEndoScalar(k, basis, n) {
4974
+ const [[a1, b1], [a2, b2]] = basis;
4975
+ const c1 = divNearest(b2 * k, n);
4976
+ const c2 = divNearest(-b1 * k, n);
4977
+ let k1 = k - c1 * a1 - c2 * a2;
4978
+ let k2 = -c1 * b1 - c2 * b2;
4979
+ const k1neg = k1 < _0n4;
4980
+ const k2neg = k2 < _0n4;
4981
+ if (k1neg)
4982
+ k1 = -k1;
4983
+ if (k2neg)
4984
+ k2 = -k2;
4985
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
4986
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
4987
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
4988
+ }
4989
+ return { k1neg, k1, k2neg, k2 };
4990
+ }
4991
+ var _0n4 = BigInt(0);
4992
+ var _1n4 = BigInt(1);
4993
+ var _2n2 = BigInt(2);
4994
+ var _3n2 = BigInt(3);
4995
+ var _4n2 = BigInt(4);
4996
+ function weierstrass(params, extraOpts = {}) {
4997
+ const validated = createCurveFields("weierstrass", params, extraOpts);
4998
+ const { Fp, Fn } = validated;
4999
+ let CURVE = validated.CURVE;
5000
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
5001
+ validateObject(extraOpts, {}, {
5002
+ allowInfinityPoint: "boolean",
5003
+ clearCofactor: "function",
5004
+ isTorsionFree: "function",
5005
+ fromBytes: "function",
5006
+ toBytes: "function",
5007
+ endo: "object"
5008
+ });
5009
+ const { endo } = extraOpts;
5010
+ if (endo) {
5011
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
5012
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
5013
+ }
5014
+ }
5015
+ const lengths = getWLengths(Fp, Fn);
5016
+ function assertCompressionIsSupported() {
5017
+ if (!Fp.isOdd)
5018
+ throw new Error("compression is not supported: Field does not have .isOdd()");
5019
+ }
5020
+ function pointToBytes2(_c, point, isCompressed) {
5021
+ const { x, y } = point.toAffine();
5022
+ const bx = Fp.toBytes(x);
5023
+ abool(isCompressed, "isCompressed");
5024
+ if (isCompressed) {
5025
+ assertCompressionIsSupported();
5026
+ const hasEvenY = !Fp.isOdd(y);
5027
+ return concatBytes(pprefix(hasEvenY), bx);
5028
+ } else {
5029
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
5030
+ }
5031
+ }
5032
+ function pointFromBytes(bytes) {
5033
+ abytes(bytes, void 0, "Point");
5034
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
5035
+ const length = bytes.length;
5036
+ const head = bytes[0];
5037
+ const tail = bytes.subarray(1);
5038
+ if (length === comp && (head === 2 || head === 3)) {
5039
+ const x = Fp.fromBytes(tail);
5040
+ if (!Fp.isValid(x))
5041
+ throw new Error("bad point: is not on curve, wrong x");
5042
+ const y2 = weierstrassEquation(x);
5043
+ let y;
5044
+ try {
5045
+ y = Fp.sqrt(y2);
5046
+ } catch (sqrtError) {
5047
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
5048
+ throw new Error("bad point: is not on curve, sqrt error" + err);
5049
+ }
5050
+ assertCompressionIsSupported();
5051
+ const evenY = Fp.isOdd(y);
5052
+ const evenH = (head & 1) === 1;
5053
+ if (evenH !== evenY)
5054
+ y = Fp.neg(y);
5055
+ return { x, y };
5056
+ } else if (length === uncomp && head === 4) {
5057
+ const L = Fp.BYTES;
5058
+ const x = Fp.fromBytes(tail.subarray(0, L));
5059
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
5060
+ if (!isValidXY(x, y))
5061
+ throw new Error("bad point: is not on curve");
5062
+ return { x, y };
5063
+ } else {
5064
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
5065
+ }
5066
+ }
5067
+ const encodePoint = extraOpts.toBytes || pointToBytes2;
5068
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
5069
+ function weierstrassEquation(x) {
5070
+ const x2 = Fp.sqr(x);
5071
+ const x3 = Fp.mul(x2, x);
5072
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
5073
+ }
5074
+ function isValidXY(x, y) {
5075
+ const left = Fp.sqr(y);
5076
+ const right = weierstrassEquation(x);
5077
+ return Fp.eql(left, right);
5078
+ }
5079
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
5080
+ throw new Error("bad curve params: generator point");
5081
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
5082
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
5083
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
5084
+ throw new Error("bad curve params: a or b");
5085
+ function acoord(title, n, banZero = false) {
5086
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
5087
+ throw new Error(`bad point coordinate ${title}`);
5088
+ return n;
5089
+ }
5090
+ function aprjpoint(other) {
5091
+ if (!(other instanceof Point))
5092
+ throw new Error("Weierstrass Point expected");
5093
+ }
5094
+ function splitEndoScalarN(k) {
5095
+ if (!endo || !endo.basises)
5096
+ throw new Error("no endo");
5097
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
5098
+ }
5099
+ const toAffineMemo = memoized((p, iz) => {
5100
+ const { X, Y, Z } = p;
5101
+ if (Fp.eql(Z, Fp.ONE))
5102
+ return { x: X, y: Y };
5103
+ const is0 = p.is0();
5104
+ if (iz == null)
5105
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
5106
+ const x = Fp.mul(X, iz);
5107
+ const y = Fp.mul(Y, iz);
5108
+ const zz = Fp.mul(Z, iz);
5109
+ if (is0)
5110
+ return { x: Fp.ZERO, y: Fp.ZERO };
5111
+ if (!Fp.eql(zz, Fp.ONE))
5112
+ throw new Error("invZ was invalid");
5113
+ return { x, y };
5114
+ });
5115
+ const assertValidMemo = memoized((p) => {
5116
+ if (p.is0()) {
5117
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
5118
+ return;
5119
+ throw new Error("bad point: ZERO");
5120
+ }
5121
+ const { x, y } = p.toAffine();
5122
+ if (!Fp.isValid(x) || !Fp.isValid(y))
5123
+ throw new Error("bad point: x or y not field elements");
5124
+ if (!isValidXY(x, y))
5125
+ throw new Error("bad point: equation left != right");
5126
+ if (!p.isTorsionFree())
5127
+ throw new Error("bad point: not in prime-order subgroup");
5128
+ return true;
5129
+ });
5130
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
5131
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
5132
+ k1p = negateCt(k1neg, k1p);
5133
+ k2p = negateCt(k2neg, k2p);
5134
+ return k1p.add(k2p);
5135
+ }
5136
+ class Point {
5137
+ // base / generator point
5138
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
5139
+ // zero / infinity / identity point
5140
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
5141
+ // 0, 1, 0
5142
+ // math field
5143
+ static Fp = Fp;
5144
+ // scalar field
5145
+ static Fn = Fn;
5146
+ X;
5147
+ Y;
5148
+ Z;
5149
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
5150
+ constructor(X, Y, Z) {
5151
+ this.X = acoord("x", X);
5152
+ this.Y = acoord("y", Y, true);
5153
+ this.Z = acoord("z", Z);
5154
+ Object.freeze(this);
5155
+ }
5156
+ static CURVE() {
5157
+ return CURVE;
5158
+ }
5159
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
5160
+ static fromAffine(p) {
5161
+ const { x, y } = p || {};
5162
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
5163
+ throw new Error("invalid affine point");
5164
+ if (p instanceof Point)
5165
+ throw new Error("projective point not allowed");
5166
+ if (Fp.is0(x) && Fp.is0(y))
5167
+ return Point.ZERO;
5168
+ return new Point(x, y, Fp.ONE);
5169
+ }
5170
+ static fromBytes(bytes) {
5171
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
5172
+ P.assertValidity();
5173
+ return P;
5174
+ }
5175
+ static fromHex(hex) {
5176
+ return Point.fromBytes(hexToBytes2(hex));
5177
+ }
5178
+ get x() {
5179
+ return this.toAffine().x;
5180
+ }
5181
+ get y() {
5182
+ return this.toAffine().y;
5183
+ }
5184
+ /**
5185
+ *
5186
+ * @param windowSize
5187
+ * @param isLazy true will defer table computation until the first multiplication
5188
+ * @returns
5189
+ */
5190
+ precompute(windowSize = 8, isLazy = true) {
5191
+ wnaf.createCache(this, windowSize);
5192
+ if (!isLazy)
5193
+ this.multiply(_3n2);
5194
+ return this;
5195
+ }
5196
+ // TODO: return `this`
5197
+ /** A point on curve is valid if it conforms to equation. */
5198
+ assertValidity() {
5199
+ assertValidMemo(this);
5200
+ }
5201
+ hasEvenY() {
5202
+ const { y } = this.toAffine();
5203
+ if (!Fp.isOdd)
5204
+ throw new Error("Field doesn't support isOdd");
5205
+ return !Fp.isOdd(y);
5206
+ }
5207
+ /** Compare one point to another. */
5208
+ equals(other) {
5209
+ aprjpoint(other);
5210
+ const { X: X1, Y: Y1, Z: Z1 } = this;
5211
+ const { X: X2, Y: Y2, Z: Z2 } = other;
5212
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
5213
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
5214
+ return U1 && U2;
5215
+ }
5216
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
5217
+ negate() {
5218
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
5219
+ }
5220
+ // Renes-Costello-Batina exception-free doubling formula.
5221
+ // There is 30% faster Jacobian formula, but it is not complete.
5222
+ // https://eprint.iacr.org/2015/1060, algorithm 3
5223
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
5224
+ double() {
5225
+ const { a, b } = CURVE;
5226
+ const b3 = Fp.mul(b, _3n2);
5227
+ const { X: X1, Y: Y1, Z: Z1 } = this;
5228
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
5229
+ let t0 = Fp.mul(X1, X1);
5230
+ let t1 = Fp.mul(Y1, Y1);
5231
+ let t2 = Fp.mul(Z1, Z1);
5232
+ let t3 = Fp.mul(X1, Y1);
5233
+ t3 = Fp.add(t3, t3);
5234
+ Z3 = Fp.mul(X1, Z1);
5235
+ Z3 = Fp.add(Z3, Z3);
5236
+ X3 = Fp.mul(a, Z3);
5237
+ Y3 = Fp.mul(b3, t2);
5238
+ Y3 = Fp.add(X3, Y3);
5239
+ X3 = Fp.sub(t1, Y3);
5240
+ Y3 = Fp.add(t1, Y3);
5241
+ Y3 = Fp.mul(X3, Y3);
5242
+ X3 = Fp.mul(t3, X3);
5243
+ Z3 = Fp.mul(b3, Z3);
5244
+ t2 = Fp.mul(a, t2);
5245
+ t3 = Fp.sub(t0, t2);
5246
+ t3 = Fp.mul(a, t3);
5247
+ t3 = Fp.add(t3, Z3);
5248
+ Z3 = Fp.add(t0, t0);
5249
+ t0 = Fp.add(Z3, t0);
5250
+ t0 = Fp.add(t0, t2);
5251
+ t0 = Fp.mul(t0, t3);
5252
+ Y3 = Fp.add(Y3, t0);
5253
+ t2 = Fp.mul(Y1, Z1);
5254
+ t2 = Fp.add(t2, t2);
5255
+ t0 = Fp.mul(t2, t3);
5256
+ X3 = Fp.sub(X3, t0);
5257
+ Z3 = Fp.mul(t2, t1);
5258
+ Z3 = Fp.add(Z3, Z3);
5259
+ Z3 = Fp.add(Z3, Z3);
5260
+ return new Point(X3, Y3, Z3);
5261
+ }
5262
+ // Renes-Costello-Batina exception-free addition formula.
5263
+ // There is 30% faster Jacobian formula, but it is not complete.
5264
+ // https://eprint.iacr.org/2015/1060, algorithm 1
5265
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
5266
+ add(other) {
5267
+ aprjpoint(other);
5268
+ const { X: X1, Y: Y1, Z: Z1 } = this;
5269
+ const { X: X2, Y: Y2, Z: Z2 } = other;
5270
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
5271
+ const a = CURVE.a;
5272
+ const b3 = Fp.mul(CURVE.b, _3n2);
5273
+ let t0 = Fp.mul(X1, X2);
5274
+ let t1 = Fp.mul(Y1, Y2);
5275
+ let t2 = Fp.mul(Z1, Z2);
5276
+ let t3 = Fp.add(X1, Y1);
5277
+ let t4 = Fp.add(X2, Y2);
5278
+ t3 = Fp.mul(t3, t4);
5279
+ t4 = Fp.add(t0, t1);
5280
+ t3 = Fp.sub(t3, t4);
5281
+ t4 = Fp.add(X1, Z1);
5282
+ let t5 = Fp.add(X2, Z2);
5283
+ t4 = Fp.mul(t4, t5);
5284
+ t5 = Fp.add(t0, t2);
5285
+ t4 = Fp.sub(t4, t5);
5286
+ t5 = Fp.add(Y1, Z1);
5287
+ X3 = Fp.add(Y2, Z2);
5288
+ t5 = Fp.mul(t5, X3);
5289
+ X3 = Fp.add(t1, t2);
5290
+ t5 = Fp.sub(t5, X3);
5291
+ Z3 = Fp.mul(a, t4);
5292
+ X3 = Fp.mul(b3, t2);
5293
+ Z3 = Fp.add(X3, Z3);
5294
+ X3 = Fp.sub(t1, Z3);
5295
+ Z3 = Fp.add(t1, Z3);
5296
+ Y3 = Fp.mul(X3, Z3);
5297
+ t1 = Fp.add(t0, t0);
5298
+ t1 = Fp.add(t1, t0);
5299
+ t2 = Fp.mul(a, t2);
5300
+ t4 = Fp.mul(b3, t4);
5301
+ t1 = Fp.add(t1, t2);
5302
+ t2 = Fp.sub(t0, t2);
5303
+ t2 = Fp.mul(a, t2);
5304
+ t4 = Fp.add(t4, t2);
5305
+ t0 = Fp.mul(t1, t4);
5306
+ Y3 = Fp.add(Y3, t0);
5307
+ t0 = Fp.mul(t5, t4);
5308
+ X3 = Fp.mul(t3, X3);
5309
+ X3 = Fp.sub(X3, t0);
5310
+ t0 = Fp.mul(t3, t1);
5311
+ Z3 = Fp.mul(t5, Z3);
5312
+ Z3 = Fp.add(Z3, t0);
5313
+ return new Point(X3, Y3, Z3);
5314
+ }
5315
+ subtract(other) {
5316
+ return this.add(other.negate());
5317
+ }
5318
+ is0() {
5319
+ return this.equals(Point.ZERO);
5320
+ }
5321
+ /**
5322
+ * Constant time multiplication.
5323
+ * Uses wNAF method. Windowed method may be 10% faster,
5324
+ * but takes 2x longer to generate and consumes 2x memory.
5325
+ * Uses precomputes when available.
5326
+ * Uses endomorphism for Koblitz curves.
5327
+ * @param scalar by which the point would be multiplied
5328
+ * @returns New point
5329
+ */
5330
+ multiply(scalar) {
5331
+ const { endo: endo2 } = extraOpts;
5332
+ if (!Fn.isValidNot0(scalar))
5333
+ throw new Error("invalid scalar: out of range");
5334
+ let point, fake;
5335
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
5336
+ if (endo2) {
5337
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
5338
+ const { p: k1p, f: k1f } = mul(k1);
5339
+ const { p: k2p, f: k2f } = mul(k2);
5340
+ fake = k1f.add(k2f);
5341
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
5342
+ } else {
5343
+ const { p, f } = mul(scalar);
5344
+ point = p;
5345
+ fake = f;
5346
+ }
5347
+ return normalizeZ(Point, [point, fake])[0];
5348
+ }
5349
+ /**
5350
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
5351
+ * It's faster, but should only be used when you don't care about
5352
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
5353
+ */
5354
+ multiplyUnsafe(sc) {
5355
+ const { endo: endo2 } = extraOpts;
5356
+ const p = this;
5357
+ if (!Fn.isValid(sc))
5358
+ throw new Error("invalid scalar: out of range");
5359
+ if (sc === _0n4 || p.is0())
5360
+ return Point.ZERO;
5361
+ if (sc === _1n4)
5362
+ return p;
5363
+ if (wnaf.hasCache(this))
5364
+ return this.multiply(sc);
5365
+ if (endo2) {
5366
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
5367
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
5368
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
5369
+ } else {
5370
+ return wnaf.unsafe(p, sc);
5371
+ }
5372
+ }
5373
+ /**
5374
+ * Converts Projective point to affine (x, y) coordinates.
5375
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
5376
+ */
5377
+ toAffine(invertedZ) {
5378
+ return toAffineMemo(this, invertedZ);
5379
+ }
5380
+ /**
5381
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
5382
+ * Always torsion-free for cofactor=1 curves.
5383
+ */
5384
+ isTorsionFree() {
5385
+ const { isTorsionFree } = extraOpts;
5386
+ if (cofactor === _1n4)
5387
+ return true;
5388
+ if (isTorsionFree)
5389
+ return isTorsionFree(Point, this);
5390
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
5391
+ }
5392
+ clearCofactor() {
5393
+ const { clearCofactor } = extraOpts;
5394
+ if (cofactor === _1n4)
5395
+ return this;
5396
+ if (clearCofactor)
5397
+ return clearCofactor(Point, this);
5398
+ return this.multiplyUnsafe(cofactor);
5399
+ }
5400
+ isSmallOrder() {
5401
+ return this.multiplyUnsafe(cofactor).is0();
5402
+ }
5403
+ toBytes(isCompressed = true) {
5404
+ abool(isCompressed, "isCompressed");
5405
+ this.assertValidity();
5406
+ return encodePoint(Point, this, isCompressed);
5407
+ }
5408
+ toHex(isCompressed = true) {
5409
+ return bytesToHex2(this.toBytes(isCompressed));
5410
+ }
5411
+ toString() {
5412
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
5413
+ }
5414
+ }
5415
+ const bits = Fn.BITS;
5416
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
5417
+ Point.BASE.precompute(8);
5418
+ return Point;
5419
+ }
5420
+ function pprefix(hasEvenY) {
5421
+ return Uint8Array.of(hasEvenY ? 2 : 3);
5422
+ }
5423
+ function getWLengths(Fp, Fn) {
5424
+ return {
5425
+ secretKey: Fn.BYTES,
5426
+ publicKey: 1 + Fp.BYTES,
5427
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
5428
+ publicKeyHasPrefix: true,
5429
+ signature: 2 * Fn.BYTES
5430
+ };
5431
+ }
5432
+
5433
+ // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/secp256k1.js
5434
+ var secp256k1_CURVE = {
5435
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
5436
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
5437
+ h: BigInt(1),
5438
+ a: BigInt(0),
5439
+ b: BigInt(7),
5440
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
5441
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
5442
+ };
5443
+ var secp256k1_ENDO = {
5444
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
5445
+ basises: [
5446
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
5447
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
5448
+ ]
5449
+ };
5450
+ var _0n5 = /* @__PURE__ */ BigInt(0);
5451
+ var _2n3 = /* @__PURE__ */ BigInt(2);
5452
+ function sqrtMod(y) {
5453
+ const P = secp256k1_CURVE.p;
5454
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
5455
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
5456
+ const b2 = y * y * y % P;
5457
+ const b3 = b2 * b2 * y % P;
5458
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
5459
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
5460
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
5461
+ const b22 = pow2(b11, _11n, P) * b11 % P;
5462
+ const b44 = pow2(b22, _22n, P) * b22 % P;
5463
+ const b88 = pow2(b44, _44n, P) * b44 % P;
5464
+ const b176 = pow2(b88, _88n, P) * b88 % P;
5465
+ const b220 = pow2(b176, _44n, P) * b44 % P;
5466
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
5467
+ const t1 = pow2(b223, _23n, P) * b22 % P;
5468
+ const t2 = pow2(t1, _6n, P) * b2 % P;
5469
+ const root = pow2(t2, _2n3, P);
5470
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
5471
+ throw new Error("Cannot find square root");
5472
+ return root;
5473
+ }
5474
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
5475
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
5476
+ Fp: Fpk1,
5477
+ endo: secp256k1_ENDO
5478
+ });
5479
+ var TAGGED_HASH_PREFIXES = {};
5480
+ function taggedHash(tag, ...messages) {
5481
+ let tagP = TAGGED_HASH_PREFIXES[tag];
5482
+ if (tagP === void 0) {
5483
+ const tagH = sha256(asciiToBytes(tag));
5484
+ tagP = concatBytes(tagH, tagH);
5485
+ TAGGED_HASH_PREFIXES[tag] = tagP;
5486
+ }
5487
+ return sha256(concatBytes(tagP, ...messages));
5488
+ }
5489
+ var pointToBytes = (point) => point.toBytes(true).slice(1);
5490
+ var hasEven = (y) => y % _2n3 === _0n5;
5491
+ function schnorrGetExtPubKey(priv) {
5492
+ const { Fn, BASE } = Pointk1;
5493
+ const d_ = Fn.fromBytes(priv);
5494
+ const p = BASE.multiply(d_);
5495
+ const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
5496
+ return { scalar, bytes: pointToBytes(p) };
5497
+ }
5498
+ function lift_x(x) {
5499
+ const Fp = Fpk1;
5500
+ if (!Fp.isValidNot0(x))
5501
+ throw new Error("invalid x: Fail if x \u2265 p");
5502
+ const xx = Fp.create(x * x);
5503
+ const c = Fp.create(xx * x + BigInt(7));
5504
+ let y = Fp.sqrt(c);
5505
+ if (!hasEven(y))
5506
+ y = Fp.neg(y);
5507
+ const p = Pointk1.fromAffine({ x, y });
5508
+ p.assertValidity();
5509
+ return p;
5510
+ }
5511
+ var num = bytesToNumberBE;
5512
+ function challenge(...args) {
5513
+ return Pointk1.Fn.create(num(taggedHash("BIP0340/challenge", ...args)));
5514
+ }
5515
+ function schnorrGetPublicKey(secretKey) {
5516
+ return schnorrGetExtPubKey(secretKey).bytes;
5517
+ }
5518
+ function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
5519
+ const { Fn } = Pointk1;
5520
+ const m = abytes(message, void 0, "message");
5521
+ const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey);
5522
+ const a = abytes(auxRand, 32, "auxRand");
5523
+ const t = Fn.toBytes(d ^ num(taggedHash("BIP0340/aux", a)));
5524
+ const rand = taggedHash("BIP0340/nonce", t, px, m);
5525
+ const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
5526
+ const e = challenge(rx, px, m);
5527
+ const sig = new Uint8Array(64);
5528
+ sig.set(rx, 0);
5529
+ sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
5530
+ if (!schnorrVerify(sig, m, px))
5531
+ throw new Error("sign: Invalid signature produced");
5532
+ return sig;
5533
+ }
5534
+ function schnorrVerify(signature, message, publicKey) {
5535
+ const { Fp, Fn, BASE } = Pointk1;
5536
+ const sig = abytes(signature, 64, "signature");
5537
+ const m = abytes(message, void 0, "message");
5538
+ const pub = abytes(publicKey, 32, "publicKey");
5539
+ try {
5540
+ const P = lift_x(num(pub));
5541
+ const r = num(sig.subarray(0, 32));
5542
+ if (!Fp.isValidNot0(r))
5543
+ return false;
5544
+ const s = num(sig.subarray(32, 64));
5545
+ if (!Fn.isValidNot0(s))
5546
+ return false;
5547
+ const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
5548
+ const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
5549
+ const { x, y } = R.toAffine();
5550
+ if (R.is0() || !hasEven(y) || x !== r)
5551
+ return false;
5552
+ return true;
5553
+ } catch (error) {
5554
+ return false;
5555
+ }
5556
+ }
5557
+ var schnorr = /* @__PURE__ */ (() => {
5558
+ const size = 32;
5559
+ const seedLength = 48;
5560
+ const randomSecretKey = (seed = randomBytes(seedLength)) => {
5561
+ return mapHashToField(seed, secp256k1_CURVE.n);
5562
+ };
5563
+ return {
5564
+ keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),
5565
+ getPublicKey: schnorrGetPublicKey,
5566
+ sign: schnorrSign,
5567
+ verify: schnorrVerify,
5568
+ Point: Pointk1,
5569
+ utils: {
5570
+ randomSecretKey,
5571
+ taggedHash,
5572
+ lift_x,
5573
+ pointToBytes
5574
+ },
5575
+ lengths: {
5576
+ secretKey: size,
5577
+ publicKey: size,
5578
+ publicKeyHasPrefix: false,
5579
+ signature: size * 2,
5580
+ seed: seedLength
5581
+ }
5582
+ };
5583
+ })();
5584
+
5585
+ // ../../node_modules/.pnpm/nostr-tools@2.23.3_typescript@5.9.3/node_modules/nostr-tools/lib/esm/pure.js
5586
+ var verifiedSymbol = /* @__PURE__ */ Symbol("verified");
5587
+ var isRecord = (obj) => obj instanceof Object;
5588
+ function validateEvent(event) {
5589
+ if (!isRecord(event))
5590
+ return false;
5591
+ if (typeof event.kind !== "number")
5592
+ return false;
5593
+ if (typeof event.content !== "string")
5594
+ return false;
5595
+ if (typeof event.created_at !== "number")
5596
+ return false;
5597
+ if (typeof event.pubkey !== "string")
5598
+ return false;
5599
+ if (!event.pubkey.match(/^[a-f0-9]{64}$/))
5600
+ return false;
5601
+ if (!Array.isArray(event.tags))
5602
+ return false;
5603
+ for (let i2 = 0; i2 < event.tags.length; i2++) {
5604
+ let tag = event.tags[i2];
5605
+ if (!Array.isArray(tag))
5606
+ return false;
5607
+ for (let j = 0; j < tag.length; j++) {
5608
+ if (typeof tag[j] !== "string")
5609
+ return false;
5610
+ }
5611
+ }
5612
+ return true;
5613
+ }
5614
+ var utf8Decoder2 = new TextDecoder("utf-8");
5615
+ var utf8Encoder2 = new TextEncoder();
5616
+ var JS = class {
5617
+ generateSecretKey() {
5618
+ return schnorr.utils.randomSecretKey();
5619
+ }
5620
+ getPublicKey(secretKey) {
5621
+ return bytesToHex2(schnorr.getPublicKey(secretKey));
5622
+ }
5623
+ finalizeEvent(t, secretKey) {
5624
+ const event = t;
5625
+ event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey));
5626
+ event.id = getEventHash(event);
5627
+ event.sig = bytesToHex2(schnorr.sign(hexToBytes2(getEventHash(event)), secretKey));
5628
+ event[verifiedSymbol] = true;
5629
+ return event;
5630
+ }
5631
+ verifyEvent(event) {
5632
+ if (typeof event[verifiedSymbol] === "boolean")
5633
+ return event[verifiedSymbol];
5634
+ try {
5635
+ const hash = getEventHash(event);
5636
+ if (hash !== event.id) {
5637
+ event[verifiedSymbol] = false;
5638
+ return false;
5639
+ }
5640
+ const valid = schnorr.verify(hexToBytes2(event.sig), hexToBytes2(hash), hexToBytes2(event.pubkey));
5641
+ event[verifiedSymbol] = valid;
5642
+ return valid;
5643
+ } catch (err) {
5644
+ event[verifiedSymbol] = false;
5645
+ return false;
5646
+ }
5647
+ }
5648
+ };
5649
+ function serializeEvent(evt) {
5650
+ if (!validateEvent(evt))
5651
+ throw new Error("can't serialize event with wrong or missing properties");
5652
+ return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]);
5653
+ }
5654
+ function getEventHash(event) {
5655
+ let eventHash = sha256(utf8Encoder2.encode(serializeEvent(event)));
5656
+ return bytesToHex2(eventHash);
5657
+ }
5658
+ var i = new JS();
5659
+ var generateSecretKey = i.generateSecretKey;
5660
+ var getPublicKey = i.getPublicKey;
5661
+ var finalizeEvent = i.finalizeEvent;
5662
+ var verifyEvent = i.verifyEvent;
5663
+
3954
5664
  // ../services/dist/index.js
3955
5665
  var NOTIFICATION_SERVICE_VERSION = "1.0.0";
3956
5666
  var DEFAULT_MAX_PER_WINDOW = 100;
@@ -4412,11 +6122,11 @@ function parseChord(chord) {
4412
6122
  if (chord.length === 0) throw new Error("empty chord");
4413
6123
  const parts = chord.split("+");
4414
6124
  const out = { ctrl: false, alt: false, shift: false, meta: false, key: "" };
4415
- for (let i = 0; i < parts.length - 1; i++) {
4416
- const tok = parts[i].trim().toLowerCase();
6125
+ for (let i2 = 0; i2 < parts.length - 1; i2++) {
6126
+ const tok = parts[i2].trim().toLowerCase();
4417
6127
  if (tok.length === 0) continue;
4418
6128
  const slot = MODIFIER_ALIASES[tok];
4419
- if (!slot) throw new Error(`unknown modifier: ${parts[i]}`);
6129
+ if (!slot) throw new Error(`unknown modifier: ${parts[i2]}`);
4420
6130
  out[slot] = true;
4421
6131
  }
4422
6132
  const keyTok = parts[parts.length - 1].trim();
@@ -5313,8 +7023,8 @@ function arrayBufferToBase64(buf) {
5313
7023
  const bytes = new Uint8Array(buf);
5314
7024
  const CHUNK = 32768;
5315
7025
  let binary = "";
5316
- for (let i = 0; i < bytes.length; i += CHUNK) {
5317
- binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
7026
+ for (let i2 = 0; i2 < bytes.length; i2 += CHUNK) {
7027
+ binary += String.fromCharCode(...bytes.subarray(i2, i2 + CHUNK));
5318
7028
  }
5319
7029
  return btoa(binary);
5320
7030
  }
@@ -6858,16 +8568,6 @@ function settleAction(action, pubkeys, context, send, resultType, id, unavailabl
6858
8568
  );
6859
8569
  }
6860
8570
 
6861
- // src/simulation.ts
6862
- function summarizePajaSimulation(simulation) {
6863
- const relay = simulation.relay.mode === "memory" ? `relay:${simulation.relay.urls.length}` : "relay:off";
6864
- const identity = simulation.identity.mode === "fixed" ? "identity:fixed" : "identity:anon";
6865
- const storage = `storage:${simulation.storage.mode}`;
6866
- const theme = `theme:${simulation.theme.mode}`;
6867
- const disabled = simulation.capabilities.disabledDomains.length > 0 ? `off:${simulation.capabilities.disabledDomains.join(",")}` : "off:none";
6868
- return `${identity} ${relay} ${storage} ${theme} ${disabled}`;
6869
- }
6870
-
6871
8571
  // src/development-services.ts
6872
8572
  var DEV_LISTS_EVENT_ID = "3".repeat(64);
6873
8573
  var DEV_SERIAL_LABEL = "Paja serial";
@@ -7043,10 +8743,12 @@ function createDevWebrtcController() {
7043
8743
  };
7044
8744
  }
7045
8745
 
7046
- // src/browser-host.ts
8746
+ // src/browser-adapter.ts
7047
8747
  var DEV_INTENT_ARCHETYPE = "paja-target";
7048
8748
  var DEV_COMMON_PUBKEY = "1".repeat(64);
7049
8749
  var DEV_COMMON_EVENT_ID = "2".repeat(64);
8750
+ var DEV_SIGNER_SECRET_KEY = generateSecretKey();
8751
+ var PAJA_DEV_SIGNER_PUBKEY = getPublicKey(DEV_SIGNER_SECRET_KEY);
7050
8752
  var DEV_CVM_SERVER = {
7051
8753
  pubkey: "0".repeat(64),
7052
8754
  name: "Kehto Paja ContextVM",
@@ -7054,33 +8756,6 @@ var DEV_CVM_SERVER = {
7054
8756
  relays: ["wss://relay.kehto.dev"],
7055
8757
  capabilities: ["echo"]
7056
8758
  };
7057
- function readConfig() {
7058
- const script = document.getElementById("kehto-paja-config");
7059
- if (!script?.textContent) {
7060
- throw new Error("Missing Kehto Paja config.");
7061
- }
7062
- return JSON.parse(script.textContent);
7063
- }
7064
- function setStatus(state, status) {
7065
- state.status = status;
7066
- const statusEl = document.getElementById("lifecycle-status");
7067
- if (statusEl) statusEl.textContent = status;
7068
- }
7069
- function setSimulationStatus(state) {
7070
- const statusEl = document.getElementById("simulation-status");
7071
- if (statusEl) statusEl.textContent = summarizePajaSimulation(state.simulation);
7072
- const themeSelect = document.getElementById("simulation-theme");
7073
- if (themeSelect instanceof HTMLSelectElement) themeSelect.value = state.simulation.theme.mode;
7074
- }
7075
- function getFrame() {
7076
- const frame = document.getElementById("napplet-frame");
7077
- if (!(frame instanceof HTMLIFrameElement)) {
7078
- throw new Error("Missing Kehto Paja iframe.");
7079
- }
7080
- frame.sandbox.add("allow-scripts");
7081
- frame.sandbox.remove("allow-same-origin");
7082
- return frame;
7083
- }
7084
8759
  function matchesFilter2(event, filter) {
7085
8760
  const ids = filter.ids;
7086
8761
  if (ids && !ids.includes(event.id)) return false;
@@ -7093,7 +8768,7 @@ function matchesFilter2(event, filter) {
7093
8768
  function matchesAnyFilter2(event, filters) {
7094
8769
  return filters.length === 0 || filters.some((filter) => matchesFilter2(event, filter));
7095
8770
  }
7096
- function createMemoryRelayPool(getSimulation) {
8771
+ function createMemoryRelayPool(getSimulation, confirmRequest) {
7097
8772
  const events = getSimulation().relay.fixtures.flatMap(toNostrEvent);
7098
8773
  const subscribers = /* @__PURE__ */ new Set();
7099
8774
  return {
@@ -7121,6 +8796,7 @@ function createMemoryRelayPool(getSimulation) {
7121
8796
  },
7122
8797
  publish(_relayUrls, event) {
7123
8798
  if (getSimulation().relay.mode === "disabled") return;
8799
+ if (!confirmRequest({ action: "publish", event })) return;
7124
8800
  events.push(event);
7125
8801
  for (const subscriber of subscribers) {
7126
8802
  if (matchesAnyFilter2(event, subscriber.filters)) subscriber.next(event);
@@ -7261,7 +8937,7 @@ function createDevCvmTransport(getSimulation) {
7261
8937
  }
7262
8938
  };
7263
8939
  }
7264
- function createOutboxRouter(pool, getSimulation) {
8940
+ function createOutboxRouter(pool, getSimulation, confirmRequest) {
7265
8941
  return {
7266
8942
  async query(filters) {
7267
8943
  const relayUrls = getRelayUrls(getSimulation());
@@ -7284,16 +8960,13 @@ function createOutboxRouter(pool, getSimulation) {
7284
8960
  return { close: () => sub.unsubscribe() };
7285
8961
  },
7286
8962
  async publish(template) {
7287
- const event = {
7288
- id: crypto.randomUUID().replace(/-/g, "").padEnd(64, "0").slice(0, 64),
7289
- pubkey: "0".repeat(64),
8963
+ const event = await createDevSigner(getSimulation, confirmRequest).signEvent({
7290
8964
  created_at: Math.floor(Date.now() / 1e3),
7291
8965
  kind: 1,
7292
8966
  tags: [],
7293
8967
  content: "",
7294
- sig: "0".repeat(128),
7295
8968
  ...template
7296
- };
8969
+ });
7297
8970
  const relayUrls = getRelayUrls(getSimulation());
7298
8971
  pool.publish(relayUrls, event);
7299
8972
  return { ok: true, event, eventId: event.id, relays: { [relayUrls[0] ?? "dev"]: true } };
@@ -7313,13 +8986,23 @@ function createDevTheme(mode, values) {
7313
8986
  }
7314
8987
  };
7315
8988
  }
7316
- function createDevSigner(getSimulation) {
8989
+ function createDevSigner(getSimulation, confirmRequest) {
7317
8990
  return {
7318
- getPublicKey: () => getSimulation().identity.pubkey,
7319
- getRelays: () => Object.fromEntries(getRelayUrls(getSimulation()).map((relay) => [relay, { read: true, write: true }]))
8991
+ getPublicKey: () => getSimulation().identity.pubkey || PAJA_DEV_SIGNER_PUBKEY,
8992
+ getRelays: () => Object.fromEntries(getRelayUrls(getSimulation()).map((relay) => [relay, { read: true, write: true }])),
8993
+ async signEvent(event) {
8994
+ if (!confirmRequest({ action: "sign", event })) {
8995
+ throw new Error("Paja signing request denied");
8996
+ }
8997
+ const template = { ...event };
8998
+ template.created_at ??= Math.floor(Date.now() / 1e3);
8999
+ template.tags ??= [];
9000
+ template.content ??= "";
9001
+ return finalizeEvent(template, DEV_SIGNER_SECRET_KEY);
9002
+ }
7320
9003
  };
7321
9004
  }
7322
- function createDevServices(pool, getSimulation, onThemeService) {
9005
+ function createDevServices(pool, getSimulation, onThemeService, confirmRequest) {
7323
9006
  const notification = createNotificationService({ maxPerWindow: 50 });
7324
9007
  const theme = createThemeService({
7325
9008
  initialTheme: createDevTheme(getSimulation().theme.mode, getSimulation().theme.values),
@@ -7360,12 +9043,10 @@ function createDevServices(pool, getSimulation, onThemeService) {
7360
9043
  selectRelayTier: () => getRelayUrls(getSimulation()),
7361
9044
  isAvailable: () => getSimulation().relay.mode === "memory"
7362
9045
  });
7363
- services.outbox = createOutboxService({ router: createOutboxRouter(pool, getSimulation) });
9046
+ services.outbox = createOutboxService({ router: createOutboxRouter(pool, getSimulation, confirmRequest) });
7364
9047
  }
7365
- if (getSimulation().identity.mode === "fixed") {
7366
- services.identity = createIdentityService({ getSigner: () => createDevSigner(getSimulation) });
7367
- } else if (getSimulation().capabilities.domains.identity) {
7368
- services.identity = createIdentityService({ getSigner: () => null });
9048
+ if (getSimulation().capabilities.domains.identity) {
9049
+ services.identity = createIdentityService({ getSigner: () => createDevSigner(getSimulation, confirmRequest) });
7369
9050
  }
7370
9051
  if (getSimulation().notifications.enabled) {
7371
9052
  services.notifications = notification;
@@ -7438,8 +9119,8 @@ function createDevServices(pool, getSimulation, onThemeService) {
7438
9119
  }
7439
9120
  return services;
7440
9121
  }
7441
- function createPajaAdapter(config, getSimulation, onThemeService) {
7442
- const pool = createMemoryRelayPool(getSimulation);
9122
+ function createPajaAdapter(config, getSimulation, onThemeService, confirmRequest) {
9123
+ const pool = createMemoryRelayPool(getSimulation, confirmRequest);
7443
9124
  const workerRelayEvents = [];
7444
9125
  return {
7445
9126
  relayPool: createRelayHooks(pool, getSimulation),
@@ -7456,11 +9137,13 @@ function createPajaAdapter(config, getSimulation, onThemeService) {
7456
9137
  },
7457
9138
  windowManager: { createWindow: () => null },
7458
9139
  auth: {
7459
- getUserPubkey: () => getSimulation().identity.pubkey,
7460
- getSigner: () => getSimulation().identity.mode === "fixed" ? createDevSigner(getSimulation) : null
9140
+ getUserPubkey: () => getSimulation().identity.pubkey || PAJA_DEV_SIGNER_PUBKEY,
9141
+ getSigner: () => createDevSigner(getSimulation, confirmRequest)
9142
+ },
9143
+ services: createDevServices(pool, getSimulation, onThemeService, confirmRequest),
9144
+ get capabilities() {
9145
+ return { disabledDomains: getSimulation().capabilities.disabledDomains };
7461
9146
  },
7462
- services: createDevServices(pool, getSimulation, onThemeService),
7463
- capabilities: { disabledDomains: getSimulation().capabilities.disabledDomains },
7464
9147
  config: { getNappUpdateBehavior: () => "auto-grant" },
7465
9148
  hotkeys: { executeHotkeyFromForward: () => {
7466
9149
  } },
@@ -7482,6 +9165,259 @@ function createPajaAdapter(config, getSimulation, onThemeService) {
7482
9165
  })
7483
9166
  };
7484
9167
  }
9168
+
9169
+ // src/simulation.ts
9170
+ var PAJA_SIMULATION_DOMAINS = [
9171
+ "relay",
9172
+ "outbox",
9173
+ "storage",
9174
+ "identity",
9175
+ "keys",
9176
+ "config",
9177
+ "resource",
9178
+ "theme",
9179
+ "notify",
9180
+ "media",
9181
+ "upload",
9182
+ "intent",
9183
+ "link",
9184
+ "common",
9185
+ "lists",
9186
+ "serial",
9187
+ "ble",
9188
+ "webrtc",
9189
+ "cvm",
9190
+ "inc"
9191
+ ];
9192
+ function summarizePajaSimulation(simulation) {
9193
+ const relay = simulation.relay.mode === "memory" ? `relay:${simulation.relay.urls.length}` : "relay:off";
9194
+ const identity = simulation.identity.mode === "fixed" ? "identity:fixed" : "identity:anon";
9195
+ const storage = `storage:${simulation.storage.mode}`;
9196
+ const theme = `theme:${simulation.theme.mode}`;
9197
+ const disabled = simulation.capabilities.disabledDomains.length > 0 ? `off:${simulation.capabilities.disabledDomains.join(",")}` : "off:none";
9198
+ return `${identity} ${relay} ${storage} ${theme} ${disabled}`;
9199
+ }
9200
+
9201
+ // src/browser-devtools.ts
9202
+ var PAJA_LOG_LIMIT = 500;
9203
+ var proxyToReal = /* @__PURE__ */ new WeakMap();
9204
+ function isNappletMessage(value) {
9205
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.type === "string";
9206
+ }
9207
+ function describeMessage(raw) {
9208
+ if (isNappletMessage(raw)) return raw.type;
9209
+ if (Array.isArray(raw) && typeof raw[0] === "string") return raw[0];
9210
+ return "unknown";
9211
+ }
9212
+ function previewMessage(raw) {
9213
+ try {
9214
+ return JSON.stringify(raw);
9215
+ } catch (error) {
9216
+ return `unserializable:${error instanceof Error ? error.message : String(error)}`;
9217
+ }
9218
+ }
9219
+ function domainEnabled(simulation, domain) {
9220
+ return simulation.capabilities.domains[domain] === true;
9221
+ }
9222
+ function getTargetIdentity(config) {
9223
+ return {
9224
+ pubkey: "",
9225
+ dTag: config.window.dTag,
9226
+ aggregateHash: config.window.aggregateHash
9227
+ };
9228
+ }
9229
+ function appendPajaMessageLog(state, direction, raw, windowId) {
9230
+ if (!state) return;
9231
+ state.messageLog.push({
9232
+ index: state.messageLog.length,
9233
+ timestamp: Date.now(),
9234
+ direction,
9235
+ type: describeMessage(raw),
9236
+ windowId,
9237
+ preview: previewMessage(raw)
9238
+ });
9239
+ if (state.messageLog.length > PAJA_LOG_LIMIT) {
9240
+ state.messageLog.splice(0, state.messageLog.length - PAJA_LOG_LIMIT);
9241
+ }
9242
+ renderPajaMessageLog(state);
9243
+ }
9244
+ function createPajaPostMessageProxy(realWin, state, windowId) {
9245
+ const proxy = new Proxy(realWin, {
9246
+ get(target, prop) {
9247
+ if (prop === "postMessage") {
9248
+ return (msg, targetOrigin, transfer) => {
9249
+ appendPajaMessageLog(state, "shell->napplet", msg, windowId);
9250
+ return target.postMessage(msg, targetOrigin, transfer);
9251
+ };
9252
+ }
9253
+ try {
9254
+ const val = Reflect.get(target, prop, target);
9255
+ return typeof val === "function" ? val.bind(target) : val;
9256
+ } catch {
9257
+ return void 0;
9258
+ }
9259
+ }
9260
+ });
9261
+ proxyToReal.set(proxy, realWin);
9262
+ return proxy;
9263
+ }
9264
+ function installPajaOriginRegistryProxy(originRegistry2, stateRef) {
9265
+ const originalGetIframeWindow = originRegistry2.getIframeWindow.bind(originRegistry2);
9266
+ originRegistry2.getIframeWindow = (windowId) => {
9267
+ const win = originalGetIframeWindow(windowId);
9268
+ if (!win) return null;
9269
+ return createPajaPostMessageProxy(win, stateRef(), windowId);
9270
+ };
9271
+ const originalGetWindowId = originRegistry2.getWindowId.bind(originRegistry2);
9272
+ originRegistry2.getWindowId = (win) => {
9273
+ const result = originalGetWindowId(win);
9274
+ if (result) return result;
9275
+ const real = proxyToReal.get(win);
9276
+ return real ? originalGetWindowId(real) : void 0;
9277
+ };
9278
+ }
9279
+ function renderPajaDevtools(state, options) {
9280
+ renderInterfaceControls(state);
9281
+ renderAclControls(state, options.bridge);
9282
+ renderSignerStatus(state, options.signerPubkey);
9283
+ }
9284
+ function renderPajaMessageLog(state) {
9285
+ const container = document.getElementById("message-log");
9286
+ if (!container) return;
9287
+ const filter = state.messageFilter.trim().toLowerCase();
9288
+ const rows = state.messageLog.filter((entry) => filter.length === 0 || `${entry.direction} ${entry.type} ${entry.preview}`.toLowerCase().includes(filter)).slice(-120).map((entry) => {
9289
+ const row = document.createElement("div");
9290
+ row.className = "log-row";
9291
+ row.dataset.messageType = entry.type;
9292
+ const dir = document.createElement("div");
9293
+ dir.className = "log-dir";
9294
+ dir.textContent = entry.direction;
9295
+ const type = document.createElement("div");
9296
+ type.className = "log-type";
9297
+ type.title = entry.preview;
9298
+ type.textContent = entry.type;
9299
+ row.append(dir, type);
9300
+ return row;
9301
+ });
9302
+ container.replaceChildren(...rows);
9303
+ container.scrollTop = container.scrollHeight;
9304
+ }
9305
+ function renderInterfaceControls(state) {
9306
+ const container = document.getElementById("interface-toggles");
9307
+ if (!container) return;
9308
+ container.replaceChildren(...PAJA_SIMULATION_DOMAINS.map((domain) => {
9309
+ const enabled = domainEnabled(state.simulation, domain);
9310
+ const button = document.createElement("button");
9311
+ button.type = "button";
9312
+ button.className = "toggle";
9313
+ button.dataset.interfaceDomain = domain;
9314
+ button.dataset.enabled = String(enabled);
9315
+ button.textContent = domain;
9316
+ button.title = `${domain} injection ${enabled ? "enabled" : "disabled"}`;
9317
+ button.addEventListener("click", () => {
9318
+ state.setDomainEnabled(domain, !domainEnabled(state.simulation, domain));
9319
+ });
9320
+ return button;
9321
+ }));
9322
+ }
9323
+ function renderAclControls(state, bridge) {
9324
+ const container = document.getElementById("acl-controls");
9325
+ if (!container) return;
9326
+ const identity = getTargetIdentity(state.config);
9327
+ container.replaceChildren(...ALL_CAPABILITIES.map((capability) => {
9328
+ const allowed = bridge?.runtime.aclState.check(
9329
+ identity.pubkey,
9330
+ identity.dTag,
9331
+ identity.aggregateHash,
9332
+ capability
9333
+ ) ?? true;
9334
+ const button = document.createElement("button");
9335
+ button.type = "button";
9336
+ button.className = "toggle";
9337
+ button.dataset.aclCapability = capability;
9338
+ button.dataset.enabled = String(allowed);
9339
+ button.textContent = capability;
9340
+ button.title = `${capability} ${allowed ? "allowed" : "blocked"}`;
9341
+ button.addEventListener("click", () => state.setAclCapability(capability, !allowed));
9342
+ return button;
9343
+ }));
9344
+ }
9345
+ function renderSignerStatus(state, signerPubkey) {
9346
+ const el = document.getElementById("signer-status");
9347
+ if (!el) return;
9348
+ const pubkey = state.simulation.identity.pubkey || signerPubkey;
9349
+ el.textContent = `pubkey ${pubkey} \xB7 every sign/publish request prompts`;
9350
+ }
9351
+
9352
+ // src/browser-host.ts
9353
+ var bridgeRef = null;
9354
+ function readConfig() {
9355
+ const script = document.getElementById("kehto-paja-config");
9356
+ if (!script?.textContent) {
9357
+ throw new Error("Missing Kehto Paja config.");
9358
+ }
9359
+ return JSON.parse(script.textContent);
9360
+ }
9361
+ async function readLatestConfig(fallback) {
9362
+ try {
9363
+ const response = await fetch("/__kehto/config.json", { cache: "no-store" });
9364
+ if (!response.ok) return fallback;
9365
+ return await response.json();
9366
+ } catch (error) {
9367
+ console.warn("[paja] config refresh failed; using embedded config", error);
9368
+ return fallback;
9369
+ }
9370
+ }
9371
+ function setTargetUrlDisplay(config, frame) {
9372
+ const targetEl = document.querySelector(".target");
9373
+ if (targetEl) {
9374
+ targetEl.textContent = config.target.url;
9375
+ targetEl.setAttribute("title", config.target.url);
9376
+ }
9377
+ frame.dataset.targetUrl = config.target.url;
9378
+ }
9379
+ function setStatus(state, status) {
9380
+ state.status = status;
9381
+ const statusEl = document.getElementById("lifecycle-status");
9382
+ if (statusEl) statusEl.textContent = status;
9383
+ }
9384
+ function setSimulationStatus(state) {
9385
+ const statusEl = document.getElementById("simulation-status");
9386
+ if (statusEl) statusEl.textContent = summarizePajaSimulation(state.simulation);
9387
+ const themeSelect = document.getElementById("simulation-theme");
9388
+ if (themeSelect instanceof HTMLSelectElement) themeSelect.value = state.simulation.theme.mode;
9389
+ renderPajaDevtools(state, { bridge: bridgeRef, signerPubkey: PAJA_DEV_SIGNER_PUBKEY });
9390
+ }
9391
+ function getFrame() {
9392
+ const frame = document.getElementById("napplet-frame");
9393
+ if (!(frame instanceof HTMLIFrameElement)) {
9394
+ throw new Error("Missing Kehto Paja iframe.");
9395
+ }
9396
+ frame.sandbox.add("allow-scripts");
9397
+ frame.sandbox.remove("allow-same-origin");
9398
+ return frame;
9399
+ }
9400
+ function confirmPajaRequest(state, request) {
9401
+ const event = request.event;
9402
+ const kind = typeof event.kind === "number" ? event.kind : "unknown";
9403
+ const content = typeof event.content === "string" && event.content.length > 0 ? `
9404
+
9405
+ ${event.content.slice(0, 240)}` : "";
9406
+ const allowed = window.confirm(`Paja ${request.action} request
9407
+ kind: ${kind}${content}`);
9408
+ appendPajaMessageLog(state, "paja", {
9409
+ type: `paja.${request.action}.${allowed ? "confirmed" : "denied"}`,
9410
+ kind
9411
+ });
9412
+ return allowed;
9413
+ }
9414
+ function getTargetIdentity2(config) {
9415
+ return {
9416
+ pubkey: "",
9417
+ dTag: config.window.dTag,
9418
+ aggregateHash: config.window.aggregateHash
9419
+ };
9420
+ }
7485
9421
  function registerFrameForGeneration(bridge, frame, config, generation) {
7486
9422
  const win = frame.contentWindow;
7487
9423
  if (!win) return null;
@@ -7490,6 +9426,15 @@ function registerFrameForGeneration(bridge, frame, config, generation) {
7490
9426
  dTag: config.window.dTag,
7491
9427
  aggregateHash: config.window.aggregateHash
7492
9428
  });
9429
+ bridge.runtime.sessionRegistry.register(windowId, {
9430
+ ...getTargetIdentity2(config),
9431
+ windowId,
9432
+ origin: "null",
9433
+ type: "napplet",
9434
+ registeredAt: Date.now(),
9435
+ instanceId: `${windowId}:${Date.now()}`,
9436
+ provenance: "nip-5d"
9437
+ });
7493
9438
  return windowId;
7494
9439
  }
7495
9440
  function navigateFrame(bridge, frame, config, generation) {
@@ -7497,16 +9442,20 @@ function navigateFrame(bridge, frame, config, generation) {
7497
9442
  frame.src = config.target.url;
7498
9443
  return windowId;
7499
9444
  }
7500
- function installPajaHost() {
7501
- const config = readConfig();
9445
+ async function installPajaHost() {
9446
+ const config = await readLatestConfig(readConfig());
7502
9447
  const frame = getFrame();
9448
+ setTargetUrlDisplay(config, frame);
7503
9449
  let currentSimulation = config.simulation;
7504
9450
  const getSimulation = () => currentSimulation;
7505
9451
  let themeService = null;
9452
+ let stateRef = null;
7506
9453
  const adapter = createPajaAdapter(config, getSimulation, (theme) => {
7507
9454
  themeService = theme;
7508
- });
9455
+ }, (request) => confirmPajaRequest(stateRef, request));
7509
9456
  const bridge = createShellBridge(adapter);
9457
+ bridgeRef = bridge;
9458
+ installPajaOriginRegistryProxy(originRegistry, () => stateRef);
7510
9459
  const capabilities = buildShellCapabilities(adapter);
7511
9460
  const services = Object.keys(adapter.services ?? {}).sort();
7512
9461
  let currentWindowId = null;
@@ -7518,6 +9467,8 @@ function installPajaHost() {
7518
9467
  simulation: currentSimulation,
7519
9468
  generation: 0,
7520
9469
  status: "booting",
9470
+ messageFilter: "",
9471
+ messageLog: [],
7521
9472
  reload() {
7522
9473
  if (currentWindowId) {
7523
9474
  bridge.runtime.destroyWindow(currentWindowId);
@@ -7541,21 +9492,63 @@ function installPajaHost() {
7541
9492
  themeService?.publishTheme(createDevTheme(currentSimulation.theme.mode, currentSimulation.theme.values));
7542
9493
  setSimulationStatus(this);
7543
9494
  },
9495
+ setDomainEnabled(domain, enabled) {
9496
+ currentSimulation = {
9497
+ ...currentSimulation,
9498
+ capabilities: {
9499
+ domains: {
9500
+ ...currentSimulation.capabilities.domains,
9501
+ [domain]: enabled
9502
+ },
9503
+ disabledDomains: PAJA_SIMULATION_DOMAINS.filter(
9504
+ (entry) => entry === domain ? !enabled : !currentSimulation.capabilities.domains[entry]
9505
+ )
9506
+ }
9507
+ };
9508
+ this.simulation = currentSimulation;
9509
+ this.services = Object.keys(adapter.services ?? {}).filter((name) => currentSimulation.capabilities.domains[name] !== false).sort();
9510
+ setSimulationStatus(this);
9511
+ appendPajaMessageLog(this, "paja", { type: `paja.interface.${enabled ? "enabled" : "disabled"}`, domain });
9512
+ this.reload();
9513
+ },
9514
+ setAclCapability(capability, enabled) {
9515
+ const identity = getTargetIdentity2(config);
9516
+ if (enabled) bridge.runtime.aclState.grant(identity.pubkey, identity.dTag, identity.aggregateHash, capability);
9517
+ else bridge.runtime.aclState.revoke(identity.pubkey, identity.dTag, identity.aggregateHash, capability);
9518
+ bridge.runtime.aclState.persist();
9519
+ appendPajaMessageLog(this, "paja", { type: `paja.acl.${enabled ? "grant" : "revoke"}`, capability });
9520
+ renderPajaDevtools(this, { bridge, signerPubkey: PAJA_DEV_SIGNER_PUBKEY });
9521
+ },
9522
+ clearLog() {
9523
+ this.messageLog.length = 0;
9524
+ renderPajaMessageLog(this);
9525
+ },
7544
9526
  getState() {
7545
9527
  return {
7546
9528
  generation: this.generation,
7547
9529
  status: this.status,
7548
9530
  iframeCount: document.querySelectorAll("iframe").length,
7549
9531
  initSent: initReceivedGeneration === this.generation,
7550
- services,
7551
- simulation: currentSimulation
9532
+ services: this.services,
9533
+ simulation: currentSimulation,
9534
+ messageLog: [...this.messageLog]
7552
9535
  };
7553
9536
  }
7554
9537
  };
9538
+ stateRef = state;
7555
9539
  window.__KEHTO_PAJA__ = state;
7556
9540
  window.addEventListener("message", (event) => {
7557
9541
  if (event.source !== frame.contentWindow) return;
7558
- bridge.handleMessage(event);
9542
+ appendPajaMessageLog(state, "napplet->shell", event.data, currentWindowId ?? void 0);
9543
+ const proxiedSource = createPajaPostMessageProxy(event.source, state, currentWindowId ?? void 0);
9544
+ const syntheticEvent = new Proxy(event, {
9545
+ get(target, prop) {
9546
+ if (prop === "source") return proxiedSource;
9547
+ const val = Reflect.get(target, prop, target);
9548
+ return typeof val === "function" ? val.bind(target) : val;
9549
+ }
9550
+ });
9551
+ bridge.handleMessage(syntheticEvent);
7559
9552
  const data = event.data;
7560
9553
  if (data && typeof data === "object" && data.type === "shell.ready") {
7561
9554
  initReceivedGeneration = state.generation;
@@ -7580,12 +9573,25 @@ function installPajaHost() {
7580
9573
  state.setThemeMode(target.value);
7581
9574
  }
7582
9575
  });
9576
+ document.getElementById("message-filter")?.addEventListener("input", (event) => {
9577
+ const target = event.target;
9578
+ if (!(target instanceof HTMLInputElement)) return;
9579
+ state.messageFilter = target.value;
9580
+ renderPajaMessageLog(state);
9581
+ });
9582
+ document.getElementById("clear-log")?.addEventListener("click", () => {
9583
+ state.clearLog();
9584
+ });
7583
9585
  setStatus(state, "booting");
7584
9586
  setSimulationStatus(state);
7585
9587
  currentWindowId = navigateFrame(bridge, frame, config, state.generation);
7586
9588
  }
7587
9589
  try {
7588
- installPajaHost();
9590
+ void installPajaHost().catch((error) => {
9591
+ const statusEl = document.getElementById("lifecycle-status");
9592
+ if (statusEl) statusEl.textContent = "error";
9593
+ console.error(error);
9594
+ });
7589
9595
  } catch (error) {
7590
9596
  const statusEl = document.getElementById("lifecycle-status");
7591
9597
  if (statusEl) statusEl.textContent = "error";
@@ -7598,5 +9604,12 @@ try {
7598
9604
 
7599
9605
  @scure/base/index.js:
7600
9606
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
9607
+
9608
+ @noble/curves/utils.js:
9609
+ @noble/curves/abstract/modular.js:
9610
+ @noble/curves/abstract/curve.js:
9611
+ @noble/curves/abstract/weierstrass.js:
9612
+ @noble/curves/secp256k1.js:
9613
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7601
9614
  */
7602
9615
  //# sourceMappingURL=browser-host.js.map