@kangentic/protocol 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4,64 +4,116 @@ function encodeProtocolVersion(version = PROTOCOL_VERSION) {
4
4
  return new TextEncoder().encode(`kangentic-bridge-v${version}`);
5
5
  }
6
6
 
7
+ // ../../node_modules/@noble/hashes/_u64.js
8
+ var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
9
+ var _32n = /* @__PURE__ */ BigInt(32);
10
+ function fromBig(n, le = false) {
11
+ if (le)
12
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
13
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
14
+ }
15
+ function split(lst, le = false) {
16
+ const len = lst.length;
17
+ let Ah = new Uint32Array(len);
18
+ let Al = new Uint32Array(len);
19
+ for (let i2 = 0; i2 < len; i2++) {
20
+ const { h, l } = fromBig(lst[i2], le);
21
+ [Ah[i2], Al[i2]] = [h, l];
22
+ }
23
+ return [Ah, Al];
24
+ }
25
+ var fromNumH = (n) => n / 2 ** 32 | 0;
26
+ var fromNumL = (n) => n >>> 0;
27
+ function setU64FromNum(view, byteOffset, n, isLE3) {
28
+ const h = fromNumH(n);
29
+ const l = fromNumL(n);
30
+ view.setUint32(byteOffset, isLE3 ? l : h, isLE3);
31
+ view.setUint32(byteOffset + 4, isLE3 ? h : l, isLE3);
32
+ }
33
+ var shrSH = (h, _l, s) => h >>> s;
34
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
35
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
36
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
37
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
38
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
39
+ function add(Ah, Al, Bh, Bl) {
40
+ const l = (Al >>> 0) + (Bl >>> 0);
41
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
42
+ }
43
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
44
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
45
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
46
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
47
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
48
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
49
+
7
50
  // ../../node_modules/@noble/hashes/utils.js
8
51
  function isBytes(a) {
9
52
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
10
53
  }
54
+ var atitle = (title) => title ? `"${title}" ` : "";
11
55
  function anumber(n, title = "") {
12
- if (typeof n !== "number") {
13
- const prefix = title && `"${title}" `;
14
- throw new TypeError(`${prefix}expected number, got ${typeof n}`);
15
- }
16
- if (!Number.isSafeInteger(n) || n < 0) {
17
- const prefix = title && `"${title}" `;
18
- throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
19
- }
56
+ if (typeof n !== "number")
57
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
58
+ if (!Number.isSafeInteger(n) || n < 0)
59
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
60
+ return n;
20
61
  }
21
62
  function abytes(value, length, title = "") {
63
+ if (isBytes(value) && (length === void 0 || value.length === length))
64
+ return value;
65
+ if (length !== void 0)
66
+ anumber(length, "length");
22
67
  const bytes = isBytes(value);
23
- const len = value?.length;
24
- const needsLen = length !== void 0;
25
- if (!bytes || needsLen && len !== length) {
26
- const prefix = title && `"${title}" `;
27
- const ofLen = needsLen ? ` of length ${length}` : "";
28
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
29
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
30
- if (!bytes)
31
- throw new TypeError(message);
32
- throw new RangeError(message);
33
- }
34
- return value;
68
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
69
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
70
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
71
+ if (!bytes)
72
+ throw new TypeError(message);
73
+ throw new RangeError(message);
74
+ }
75
+ function copyBytes(bytes) {
76
+ return Uint8Array.from(abytes(bytes));
35
77
  }
36
78
  function ahash(h) {
37
79
  if (typeof h !== "function" || typeof h.create !== "function")
38
- throw new TypeError("Hash must wrapped by utils.createHasher");
80
+ throw new TypeError("expected hash wrapped by utils.createHasher");
39
81
  anumber(h.outputLen);
40
82
  anumber(h.blockLen);
41
- if (h.outputLen < 1)
42
- throw new Error('"outputLen" must be >= 1');
43
- if (h.blockLen < 1)
44
- throw new Error('"blockLen" must be >= 1');
83
+ if (h.outputLen < 1 || h.blockLen < 1)
84
+ throw new Error("hash blockLen / outputLen must be >= 1");
45
85
  }
86
+ var aobject = (value, label) => {
87
+ if (value === null || typeof value !== "object" || Array.isArray(value))
88
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
89
+ };
90
+ var aopts = (value, label) => {
91
+ aobject(value, label);
92
+ const proto = Object.getPrototypeOf(value);
93
+ if (proto !== Object.prototype && proto !== null)
94
+ throw new TypeError(`"${label}" expected plain object`);
95
+ if (Object.hasOwn(value, "__proto__"))
96
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
97
+ };
46
98
  function aexists(instance, checkFinished = true) {
47
99
  if (instance.destroyed)
48
- throw new Error("Hash instance has been destroyed");
100
+ throw new Error("hash was destroyed");
49
101
  if (checkFinished && instance.finished)
50
- throw new Error("Hash#digest() has already been called");
102
+ throw new Error("digest() was already called");
51
103
  }
52
104
  function aoutput(out, instance) {
53
- abytes(out, void 0, "digestInto() output");
105
+ abytes(out, void 0, "output");
54
106
  const min = instance.outputLen;
55
- if (out.length < min) {
56
- throw new RangeError('"digestInto() output" expected to be of length >=' + min);
107
+ if (!(out.length >= min)) {
108
+ throw new RangeError('"output" expected length >= ' + min);
57
109
  }
58
110
  }
59
111
  function u32(arr) {
60
112
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
61
113
  }
62
114
  function clean(...arrays) {
63
- for (let i = 0; i < arrays.length; i++) {
64
- arrays[i].fill(0);
115
+ for (let i2 = 0; i2 < arrays.length; i2++) {
116
+ arrays[i2].fill(0);
65
117
  }
66
118
  }
67
119
  function createView(arr) {
@@ -76,8 +128,8 @@ function byteSwap(word) {
76
128
  }
77
129
  var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0;
78
130
  function byteSwap32(arr) {
79
- for (let i = 0; i < arr.length; i++) {
80
- arr[i] = byteSwap(arr[i]);
131
+ for (let i2 = 0; i2 < arr.length; i2++) {
132
+ arr[i2] = byteSwap(arr[i2]);
81
133
  }
82
134
  return arr;
83
135
  }
@@ -86,26 +138,19 @@ var hasHexBuiltin = /* @__PURE__ */ (() => (
86
138
  // @ts-ignore
87
139
  typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
88
140
  ))();
89
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
141
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0"));
90
142
  function bytesToHex(bytes) {
91
143
  abytes(bytes);
92
144
  if (hasHexBuiltin)
93
145
  return bytes.toHex();
94
146
  let hex = "";
95
- for (let i = 0; i < bytes.length; i++) {
96
- hex += hexes[bytes[i]];
147
+ for (let i2 = 0; i2 < bytes.length; i2++) {
148
+ hex += hexes[bytes[i2]];
97
149
  }
98
150
  return hex;
99
151
  }
100
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
101
152
  function asciiToBase16(ch) {
102
- if (ch >= asciis._0 && ch <= asciis._9)
103
- return ch - asciis._0;
104
- if (ch >= asciis.A && ch <= asciis.F)
105
- return ch - (asciis.A - 10);
106
- if (ch >= asciis.a && ch <= asciis.f)
107
- return ch - (asciis.a - 10);
108
- return;
153
+ return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
109
154
  }
110
155
  function hexToBytes(hex) {
111
156
  if (typeof hex !== "string")
@@ -137,20 +182,30 @@ function hexToBytes(hex) {
137
182
  }
138
183
  function concatBytes(...arrays) {
139
184
  let sum = 0;
140
- for (let i = 0; i < arrays.length; i++) {
141
- const a = arrays[i];
185
+ for (let i2 = 0; i2 < arrays.length; i2++) {
186
+ const a = arrays[i2];
142
187
  abytes(a);
143
188
  sum += a.length;
144
189
  }
145
190
  const res = new Uint8Array(sum);
146
- for (let i = 0, pad = 0; i < arrays.length; i++) {
147
- const a = arrays[i];
191
+ for (let i2 = 0, pad = 0; i2 < arrays.length; i2++) {
192
+ const a = arrays[i2];
148
193
  res.set(a, pad);
149
194
  pad += a.length;
150
195
  }
151
196
  return res;
152
197
  }
198
+ function checkOpts(defaults, opts, title = "opts") {
199
+ aopts(defaults, "defaults");
200
+ if (opts !== void 0)
201
+ aopts(opts, title);
202
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
203
+ return merged;
204
+ }
153
205
  function createHasher(hashCons, info = {}) {
206
+ if (typeof hashCons !== "function")
207
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
208
+ info = checkOpts({}, info, "info");
154
209
  const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
155
210
  const tmp = hashCons(void 0);
156
211
  hashC.outputLen = tmp.outputLen;
@@ -202,24 +257,28 @@ var HashMD = class {
202
257
  abytes(data);
203
258
  const { view, buffer, blockLen } = this;
204
259
  const len = data.length;
260
+ let processed = false;
205
261
  for (let pos = 0; pos < len; ) {
206
262
  const take = Math.min(blockLen - this.pos, len - pos);
207
263
  if (take === blockLen) {
208
264
  const dataView = createView(data);
209
265
  for (; blockLen <= len - pos; pos += blockLen)
210
266
  this.process(dataView, pos);
267
+ processed = true;
211
268
  continue;
212
269
  }
213
- buffer.set(data.subarray(pos, pos + take), this.pos);
270
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
214
271
  this.pos += take;
215
272
  pos += take;
216
273
  if (this.pos === blockLen) {
217
274
  this.process(view, 0);
218
275
  this.pos = 0;
276
+ processed = true;
219
277
  }
220
278
  }
221
279
  this.length += data.length;
222
- this.roundClean();
280
+ if (processed)
281
+ this.roundClean();
223
282
  return this;
224
283
  }
225
284
  digestInto(out) {
@@ -229,25 +288,22 @@ var HashMD = class {
229
288
  const { buffer, view, blockLen, isLE: isLE3 } = this;
230
289
  let { pos } = this;
231
290
  buffer[pos++] = 128;
232
- clean(this.buffer.subarray(pos));
291
+ buffer.fill(0, pos);
233
292
  if (this.padOffset > blockLen - pos) {
234
293
  this.process(view, 0);
235
- pos = 0;
294
+ buffer.fill(0);
236
295
  }
237
- for (let i = pos; i < blockLen; i++)
238
- buffer[i] = 0;
239
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE3);
296
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE3);
240
297
  this.process(view, 0);
241
- const oview = createView(out);
298
+ this.roundClean();
299
+ const oview = out === buffer ? view : createView(out);
242
300
  const len = this.outputLen;
243
- if (len % 4)
244
- throw new Error("_sha2: outputLen must be aligned to 32bit");
245
301
  const outLen = len / 4;
246
302
  const state = this.get();
247
- if (outLen > state.length)
248
- throw new Error("_sha2: outputLen bigger than state");
249
- for (let i = 0; i < outLen; i++)
250
- oview.setUint32(4 * i, state[i], isLE3);
303
+ if (len % 4 || outLen > state.length)
304
+ throw new Error("invalid outputLen");
305
+ for (let i2 = 0; i2 < outLen; i2++)
306
+ oview.setUint32(4 * i2, state[i2], isLE3);
251
307
  }
252
308
  digest() {
253
309
  const { buffer, outputLen } = this;
@@ -256,15 +312,13 @@ var HashMD = class {
256
312
  this.destroy();
257
313
  return res;
258
314
  }
259
- _cloneInto(to) {
260
- to ||= new this.constructor();
261
- to.set(...this.get());
262
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
315
+ _cloneIntoMeta(to) {
316
+ const { buffer, length, finished, destroyed, pos } = this;
263
317
  to.destroyed = destroyed;
264
318
  to.finished = finished;
265
319
  to.length = length;
266
320
  to.pos = pos;
267
- if (length % blockLen)
321
+ if (pos)
268
322
  to.buffer.set(buffer);
269
323
  return to;
270
324
  }
@@ -301,41 +355,6 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
301
355
  327033209
302
356
  ]);
303
357
 
304
- // ../../node_modules/@noble/hashes/_u64.js
305
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
306
- var _32n = /* @__PURE__ */ BigInt(32);
307
- function fromBig(n, le = false) {
308
- if (le)
309
- return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
310
- return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
311
- }
312
- function split(lst, le = false) {
313
- const len = lst.length;
314
- let Ah = new Uint32Array(len);
315
- let Al = new Uint32Array(len);
316
- for (let i = 0; i < len; i++) {
317
- const { h, l } = fromBig(lst[i], le);
318
- [Ah[i], Al[i]] = [h, l];
319
- }
320
- return [Ah, Al];
321
- }
322
- var shrSH = (h, _l, s) => h >>> s;
323
- var shrSL = (h, l, s) => h << 32 - s | l >>> s;
324
- var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
325
- var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
326
- var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
327
- var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
328
- function add(Ah, Al, Bh, Bl) {
329
- const l = (Al >>> 0) + (Bl >>> 0);
330
- return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
331
- }
332
- var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
333
- var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
334
- var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
335
- var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
336
- var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
337
- var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
338
-
339
358
  // ../../node_modules/@noble/hashes/sha2.js
340
359
  var K512 = /* @__PURE__ */ (() => split([
341
360
  "0x428a2f98d728ae22",
@@ -424,8 +443,45 @@ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
424
443
  var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
425
444
  var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
426
445
  var SHA2_64B = class extends HashMD {
427
- constructor(outputLen) {
446
+ // We cannot use array here since array allows indexing by variable
447
+ // which means optimizer/compiler cannot use registers.
448
+ // h -- high 32 bits, l -- low 32 bits
449
+ // Numeric initializers matter: starting the fields as `undefined` changes
450
+ // V8's field representation and slows hashing down (measured on sha256).
451
+ Ah = 0;
452
+ Al = 0;
453
+ Bh = 0;
454
+ Bl = 0;
455
+ Ch = 0;
456
+ Cl = 0;
457
+ Dh = 0;
458
+ Dl = 0;
459
+ Eh = 0;
460
+ El = 0;
461
+ Fh = 0;
462
+ Fl = 0;
463
+ Gh = 0;
464
+ Gl = 0;
465
+ Hh = 0;
466
+ Hl = 0;
467
+ constructor(outputLen, IV) {
428
468
  super(128, outputLen, 16, false);
469
+ this.Ah = IV[0] | 0;
470
+ this.Al = IV[1] | 0;
471
+ this.Bh = IV[2] | 0;
472
+ this.Bl = IV[3] | 0;
473
+ this.Ch = IV[4] | 0;
474
+ this.Cl = IV[5] | 0;
475
+ this.Dh = IV[6] | 0;
476
+ this.Dl = IV[7] | 0;
477
+ this.Eh = IV[8] | 0;
478
+ this.El = IV[9] | 0;
479
+ this.Fh = IV[10] | 0;
480
+ this.Fl = IV[11] | 0;
481
+ this.Gh = IV[12] | 0;
482
+ this.Gl = IV[13] | 0;
483
+ this.Hh = IV[14] | 0;
484
+ this.Hl = IV[15] | 0;
429
485
  }
430
486
  // prettier-ignore
431
487
  get() {
@@ -451,33 +507,37 @@ var SHA2_64B = class extends HashMD {
451
507
  this.Hh = Hh | 0;
452
508
  this.Hl = Hl | 0;
453
509
  }
510
+ _cloneInto(to) {
511
+ (to ||= new this.constructor()).set(...this.get());
512
+ return this._cloneIntoMeta(to);
513
+ }
454
514
  process(view, offset) {
455
- for (let i = 0; i < 16; i++, offset += 4) {
456
- SHA512_W_H[i] = view.getUint32(offset);
457
- SHA512_W_L[i] = view.getUint32(offset += 4);
515
+ for (let i2 = 0; i2 < 16; i2++, offset += 4) {
516
+ SHA512_W_H[i2] = view.getUint32(offset);
517
+ SHA512_W_L[i2] = view.getUint32(offset += 4);
458
518
  }
459
- for (let i = 16; i < 80; i++) {
460
- const W15h = SHA512_W_H[i - 15] | 0;
461
- const W15l = SHA512_W_L[i - 15] | 0;
519
+ for (let i2 = 16; i2 < 80; i2++) {
520
+ const W15h = SHA512_W_H[i2 - 15] | 0;
521
+ const W15l = SHA512_W_L[i2 - 15] | 0;
462
522
  const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
463
523
  const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
464
- const W2h = SHA512_W_H[i - 2] | 0;
465
- const W2l = SHA512_W_L[i - 2] | 0;
524
+ const W2h = SHA512_W_H[i2 - 2] | 0;
525
+ const W2l = SHA512_W_L[i2 - 2] | 0;
466
526
  const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
467
527
  const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
468
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
469
- const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
470
- SHA512_W_H[i] = SUMh | 0;
471
- SHA512_W_L[i] = SUMl | 0;
528
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i2 - 7], SHA512_W_L[i2 - 16]);
529
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i2 - 7], SHA512_W_H[i2 - 16]);
530
+ SHA512_W_H[i2] = SUMh | 0;
531
+ SHA512_W_L[i2] = SUMl | 0;
472
532
  }
473
533
  let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
474
- for (let i = 0; i < 80; i++) {
534
+ for (let i2 = 0; i2 < 80; i2++) {
475
535
  const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
476
536
  const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
477
537
  const CHIh = Eh & Fh ^ ~Eh & Gh;
478
538
  const CHIl = El & Fl ^ ~El & Gl;
479
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
480
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
539
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i2], SHA512_W_L[i2]);
540
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i2], SHA512_W_H[i2]);
481
541
  const T1l = T1ll | 0;
482
542
  const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
483
543
  const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
@@ -520,24 +580,8 @@ var SHA2_64B = class extends HashMD {
520
580
  }
521
581
  };
522
582
  var _SHA512 = class extends SHA2_64B {
523
- Ah = SHA512_IV[0] | 0;
524
- Al = SHA512_IV[1] | 0;
525
- Bh = SHA512_IV[2] | 0;
526
- Bl = SHA512_IV[3] | 0;
527
- Ch = SHA512_IV[4] | 0;
528
- Cl = SHA512_IV[5] | 0;
529
- Dh = SHA512_IV[6] | 0;
530
- Dl = SHA512_IV[7] | 0;
531
- Eh = SHA512_IV[8] | 0;
532
- El = SHA512_IV[9] | 0;
533
- Fh = SHA512_IV[10] | 0;
534
- Fl = SHA512_IV[11] | 0;
535
- Gh = SHA512_IV[12] | 0;
536
- Gl = SHA512_IV[13] | 0;
537
- Hh = SHA512_IV[14] | 0;
538
- Hl = SHA512_IV[15] | 0;
539
583
  constructor() {
540
- super(64);
584
+ super(64, SHA512_IV);
541
585
  }
542
586
  };
543
587
  var sha512 = /* @__PURE__ */ createHasher(
@@ -546,8 +590,26 @@ var sha512 = /* @__PURE__ */ createHasher(
546
590
  );
547
591
 
548
592
  // ../../node_modules/@noble/curves/utils.js
593
+ function aarray(item, title, inner = () => {
594
+ }) {
595
+ if (!Array.isArray(item))
596
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
597
+ for (let i2 = 0; i2 < item.length; i2++)
598
+ inner(item[i2], `${title}[${i2}]`);
599
+ return item;
600
+ }
549
601
  var abytes2 = (value, length, title) => abytes(value, length, title);
550
602
  var anumber2 = anumber;
603
+ function aobject2(value, title = "object") {
604
+ if (value === null || typeof value !== "object" || Array.isArray(value))
605
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
606
+ return value;
607
+ }
608
+ function afunction(value, title) {
609
+ if (typeof value !== "function")
610
+ throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
611
+ return value;
612
+ }
551
613
  var bytesToHex2 = bytesToHex;
552
614
  var concatBytes2 = (...arrays) => concatBytes(...arrays);
553
615
  var hexToBytes2 = (hex) => hexToBytes(hex);
@@ -555,11 +617,10 @@ var isBytes2 = isBytes;
555
617
  var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
556
618
  var _0n = /* @__PURE__ */ BigInt(0);
557
619
  var _1n = /* @__PURE__ */ BigInt(1);
620
+ var atitle2 = (title) => title ? `"${title}" ` : "";
558
621
  function abool(value, title = "") {
559
- if (typeof value !== "boolean") {
560
- const prefix = title && `"${title}" `;
561
- throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
562
- }
622
+ if (typeof value !== "boolean")
623
+ throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
563
624
  return value;
564
625
  }
565
626
  function abignumber(n) {
@@ -589,46 +650,28 @@ function bytesToNumberBE(bytes) {
589
650
  return hexToNumber(bytesToHex(bytes));
590
651
  }
591
652
  function bytesToNumberLE(bytes) {
592
- return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
653
+ return hexToNumber(bytesToHex(copyBytes2(abytes(bytes)).reverse()));
593
654
  }
594
655
  function numberToBytesBE(n, len) {
595
656
  anumber(len);
596
657
  if (len === 0)
597
- throw new RangeError("zero length");
658
+ throw new Error("zero output length is invalid");
598
659
  n = abignumber(n);
660
+ const expectedLen = len * 2;
599
661
  const hex = n.toString(16);
600
- if (hex.length > len * 2)
601
- throw new RangeError("number too large");
602
- return hexToBytes(hex.padStart(len * 2, "0"));
662
+ if (hex.length > expectedLen)
663
+ throw new RangeError("number is too large");
664
+ return hexToBytes(hex.padStart(expectedLen, "0"));
603
665
  }
604
666
  function numberToBytesLE(n, len) {
605
667
  return numberToBytesBE(n, len).reverse();
606
668
  }
607
- function equalBytes(a, b) {
608
- a = abytes2(a);
609
- b = abytes2(b);
610
- if (a.length !== b.length)
611
- return false;
612
- let diff = 0;
613
- for (let i = 0; i < a.length; i++)
614
- diff |= a[i] ^ b[i];
615
- return diff === 0;
616
- }
617
- function copyBytes(bytes) {
669
+ function copyBytes2(bytes) {
618
670
  return Uint8Array.from(abytes2(bytes));
619
671
  }
620
- function asciiToBytes(ascii) {
621
- if (typeof ascii !== "string")
622
- throw new TypeError("ascii string expected, got " + typeof ascii);
623
- return Uint8Array.from(ascii, (c, i) => {
624
- const charCode = c.charCodeAt(0);
625
- if (c.length !== 1 || charCode > 127) {
626
- throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
627
- }
628
- return charCode;
629
- });
672
+ function isPosBig(n) {
673
+ return typeof n === "bigint" && _0n <= n;
630
674
  }
631
- var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
632
675
  function inRange(n, min, max2) {
633
676
  return isPosBig(n) && isPosBig(min) && isPosBig(max2) && min <= n && n < max2;
634
677
  }
@@ -639,32 +682,32 @@ function aInRange(title, n, min, max2) {
639
682
  function bitLen(n) {
640
683
  if (n < _0n)
641
684
  throw new Error("expected non-negative bigint, got " + n);
642
- let len;
643
- for (len = 0; n > _0n; n >>= _1n, len += 1)
644
- ;
645
- return len;
685
+ return n === _0n ? 0 : n.toString(2).length;
646
686
  }
647
- var bitMask = (n) => (_1n << BigInt(n)) - _1n;
648
- function validateObject(object, fields = {}, optFields = {}) {
649
- if (Object.prototype.toString.call(object) !== "[object Object]")
650
- throw new TypeError("expected valid options object");
687
+ var bitMask = (n) => {
688
+ asafenumber(n, "n");
689
+ return (_1n << BigInt(n)) - _1n;
690
+ };
691
+ function validateObject(object, fields = {}, optFields = {}, title = "object") {
692
+ aobject2(object, title);
693
+ aobject2(fields, "fields");
694
+ aobject2(optFields, "optFields");
651
695
  function checkField(fieldName, expectedType, isOpt) {
652
- if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
653
- throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
696
+ const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
654
697
  const val = object[fieldName];
698
+ if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
699
+ throw new TypeError(`${label} is invalid: expected own property`);
700
+ }
655
701
  if (isOpt && val === void 0)
656
702
  return;
657
703
  const current = typeof val;
658
704
  if (current !== expectedType || val === null)
659
- throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
705
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
660
706
  }
661
707
  const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
662
708
  iter(fields, false);
663
709
  iter(optFields, true);
664
710
  }
665
- var notImplemented = () => {
666
- throw new Error("not implemented");
667
- };
668
711
 
669
712
  // ../../node_modules/@noble/curves/abstract/modular.js
670
713
  var _0n2 = /* @__PURE__ */ BigInt(0);
@@ -676,17 +719,67 @@ var _5n = /* @__PURE__ */ BigInt(5);
676
719
  var _7n = /* @__PURE__ */ BigInt(7);
677
720
  var _8n = /* @__PURE__ */ BigInt(8);
678
721
  var _9n = /* @__PURE__ */ BigInt(9);
722
+ var _15n = /* @__PURE__ */ BigInt(15);
679
723
  var _16n = /* @__PURE__ */ BigInt(16);
724
+ var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
680
725
  function mod(a, b) {
681
726
  if (b <= _0n2)
682
727
  throw new Error("mod: expected positive modulus, got " + b);
683
728
  const result = a % b;
684
729
  return result >= _0n2 ? result : b + result;
685
730
  }
686
- function pow2(x, power, modulo) {
731
+ function pow(num, power, modulo) {
732
+ if (modulo <= _1n2)
733
+ throw new Error("pow: expected modulus > 1, got " + modulo);
734
+ if (typeof power !== "bigint")
735
+ throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
736
+ if (power < _0n2)
737
+ throw new Error("invalid exponent, negatives unsupported");
738
+ if (power === _0n2)
739
+ return _1n2;
740
+ if (power === _1n2)
741
+ return num;
742
+ let d = num % modulo;
743
+ if (d < _0n2)
744
+ d += modulo;
745
+ if (power < POW_WINDOWED_MIN) {
746
+ let p2 = _1n2;
747
+ while (power > _0n2) {
748
+ if (power & _1n2)
749
+ p2 = p2 * d % modulo;
750
+ d = d * d % modulo;
751
+ power >>= _1n2;
752
+ }
753
+ return p2;
754
+ }
755
+ const digits = [];
756
+ while (power > _0n2) {
757
+ digits.push(Number(power & _15n));
758
+ power >>= _4n;
759
+ }
760
+ const table = new Array(16);
761
+ table[0] = _1n2;
762
+ table[1] = d;
763
+ for (let i2 = 2; i2 < 16; i2++)
764
+ table[i2] = table[i2 - 1] * d % modulo;
765
+ let p = table[digits[digits.length - 1]];
766
+ for (let w = digits.length - 2; w >= 0; w--) {
767
+ p = p * p % modulo;
768
+ p = p * p % modulo;
769
+ p = p * p % modulo;
770
+ p = p * p % modulo;
771
+ const digit = digits[w];
772
+ if (digit !== 0)
773
+ p = p * table[digit] % modulo;
774
+ }
775
+ return p;
776
+ }
777
+ function pow2(x2, power, modulo) {
778
+ if (modulo <= _1n2)
779
+ throw new Error("pow2: expected modulus > 1, got " + modulo);
687
780
  if (power < _0n2)
688
781
  throw new Error("pow2: expected non-negative exponent, got " + power);
689
- let res = x;
782
+ let res = x2;
690
783
  while (power-- > _0n2) {
691
784
  res *= res;
692
785
  res %= modulo;
@@ -696,28 +789,31 @@ function pow2(x, power, modulo) {
696
789
  function invert(number, modulo) {
697
790
  if (number === _0n2)
698
791
  throw new Error("invert: expected non-zero number");
699
- if (modulo <= _0n2)
700
- throw new Error("invert: expected positive modulus, got " + modulo);
792
+ if (modulo <= _1n2)
793
+ throw new Error("invert: expected modulus > 1, got " + modulo);
701
794
  let a = mod(number, modulo);
702
795
  let b = modulo;
703
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
796
+ let x2 = _0n2, u = _1n2;
704
797
  while (a !== _0n2) {
705
798
  const q = b / a;
706
799
  const r = b - a * q;
707
- const m = x - u * q;
708
- const n = y - v * q;
709
- b = a, a = r, x = u, y = v, u = m, v = n;
800
+ const m = x2 - u * q;
801
+ b = a, a = r, x2 = u, u = m;
710
802
  }
711
803
  const gcd = b;
712
804
  if (gcd !== _1n2)
713
805
  throw new Error("invert: does not exist");
714
- return mod(x, modulo);
806
+ return mod(x2, modulo);
715
807
  }
716
808
  function assertIsSquare(Fp2, root, n) {
717
809
  const F = Fp2;
718
810
  if (!F.eql(F.sqr(root), n))
719
811
  throw new Error("Cannot find square root");
720
812
  }
813
+ function aoddModulus(order, fnName) {
814
+ if ((order & _1n2) === _0n2)
815
+ throw new Error(fnName + ": expected odd modulus, got " + order);
816
+ }
721
817
  function sqrt3mod4(Fp2, n) {
722
818
  const F = Fp2;
723
819
  const p1div4 = (F.ORDER + _1n2) / _4n;
@@ -731,8 +827,8 @@ function sqrt5mod8(Fp2, n) {
731
827
  const n2 = F.mul(n, _2n);
732
828
  const v = F.pow(n2, p5div8);
733
829
  const nv = F.mul(n, v);
734
- const i = F.mul(F.mul(nv, _2n), v);
735
- const root = F.mul(nv, F.sub(i, F.ONE));
830
+ const i2 = F.mul(F.mul(nv, _2n), v);
831
+ const root = F.mul(nv, F.sub(i2, F.ONE));
736
832
  assertIsSquare(F, root, n);
737
833
  return root;
738
834
  }
@@ -762,6 +858,7 @@ function sqrt9mod16(P) {
762
858
  function tonelliShanks(P) {
763
859
  if (P < _3n)
764
860
  throw new Error("sqrt is not defined for small field");
861
+ aoddModulus(P, "tonelliShanks");
765
862
  let Q = P - _1n2;
766
863
  let S = 0;
767
864
  while (Q % _2n === _0n2) {
@@ -790,18 +887,18 @@ function tonelliShanks(P) {
790
887
  let R = F.pow(n, Q1div2);
791
888
  while (!F.eql(t, F.ONE)) {
792
889
  if (F.is0(t))
793
- return F.ZERO;
794
- let i = 1;
890
+ throw new Error("Cannot find square root: probably non-prime P");
891
+ let i2 = 1;
795
892
  let t_tmp = F.sqr(t);
796
893
  while (!F.eql(t_tmp, F.ONE)) {
797
- i++;
894
+ i2++;
798
895
  t_tmp = F.sqr(t_tmp);
799
- if (i === M)
896
+ if (i2 === M)
800
897
  throw new Error("Cannot find square root");
801
898
  }
802
- const exponent = _1n2 << BigInt(M - i - 1);
899
+ const exponent = _1n2 << BigInt(M - i2 - 1);
803
900
  const b = F.pow(c, exponent);
804
- M = i;
901
+ M = i2;
805
902
  c = F.sqr(b);
806
903
  t = F.mul(t, c);
807
904
  R = F.mul(R, b);
@@ -810,6 +907,7 @@ function tonelliShanks(P) {
810
907
  };
811
908
  }
812
909
  function FpSqrt(P) {
910
+ aoddModulus(P, "Fp.sqrt");
813
911
  if (P % _4n === _3n)
814
912
  return sqrt3mod4;
815
913
  if (P % _8n === _5n)
@@ -839,62 +937,44 @@ var FIELD_FIELDS = [
839
937
  "sqrN"
840
938
  ];
841
939
  function validateField(field) {
842
- const initial = {
843
- ORDER: "bigint",
844
- BYTES: "number",
845
- BITS: "number"
846
- };
847
- const opts = FIELD_FIELDS.reduce((map, val) => {
848
- map[val] = "function";
849
- return map;
850
- }, initial);
851
- validateObject(field, opts);
940
+ aobject2(field, "field");
941
+ if (typeof field.ORDER !== "bigint")
942
+ throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
852
943
  asafenumber(field.BYTES, "BYTES");
853
944
  asafenumber(field.BITS, "BITS");
945
+ for (const name of FIELD_FIELDS)
946
+ afunction(field[name], "field." + name);
854
947
  if (field.BYTES < 1 || field.BITS < 1)
855
948
  throw new Error("invalid field: expected BYTES/BITS > 0");
856
949
  if (field.ORDER <= _1n2)
857
950
  throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
858
951
  return field;
859
952
  }
860
- function FpPow(Fp2, num, power) {
861
- const F = Fp2;
862
- if (power < _0n2)
863
- throw new Error("invalid exponent, negatives unsupported");
864
- if (power === _0n2)
865
- return F.ONE;
866
- if (power === _1n2)
867
- return num;
868
- let p = F.ONE;
869
- let d = num;
870
- while (power > _0n2) {
871
- if (power & _1n2)
872
- p = F.mul(p, d);
873
- d = F.sqr(d);
874
- power >>= _1n2;
875
- }
876
- return p;
877
- }
878
953
  function FpInvertBatch(Fp2, nums, passZero = false) {
954
+ validateField(Fp2);
955
+ aarray(nums, "nums");
956
+ abool(passZero, "passZero");
879
957
  const F = Fp2;
880
958
  const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
881
- const multipliedAcc = nums.reduce((acc, num, i) => {
959
+ const multipliedAcc = nums.reduce((acc, num, i2) => {
882
960
  if (F.is0(num))
883
961
  return acc;
884
- inverted[i] = acc;
962
+ inverted[i2] = acc;
885
963
  return F.mul(acc, num);
886
964
  }, F.ONE);
887
965
  const invertedAcc = F.inv(multipliedAcc);
888
- nums.reduceRight((acc, num, i) => {
966
+ nums.reduceRight((acc, num, i2) => {
889
967
  if (F.is0(num))
890
968
  return acc;
891
- inverted[i] = F.mul(acc, inverted[i]);
969
+ inverted[i2] = F.mul(acc, inverted[i2]);
892
970
  return F.mul(acc, num);
893
971
  }, invertedAcc);
894
972
  return inverted;
895
973
  }
896
974
  function FpLegendre(Fp2, n) {
975
+ validateField(Fp2);
897
976
  const F = Fp2;
977
+ aoddModulus(F.ORDER, "FpLegendre");
898
978
  const p1mod2 = (F.ORDER - _1n2) / _2n;
899
979
  const powered = F.pow(n, p1mod2);
900
980
  const yes = F.eql(powered, F.ONE);
@@ -913,7 +993,7 @@ function nLength(n, nBitLength) {
913
993
  throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
914
994
  const bits2 = bitLen(n);
915
995
  if (nBitLength !== void 0 && nBitLength < bits2)
916
- throw new Error(`invalid n length: expected bit length (${bits2}) >= n.length (${nBitLength})`);
996
+ throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits2})`);
917
997
  const _nBitLength = nBitLength !== void 0 ? nBitLength : bits2;
918
998
  const nByteLength = Math.ceil(_nBitLength / 8);
919
999
  return { nBitLength: _nBitLength, nByteLength };
@@ -990,7 +1070,7 @@ var _Field = class {
990
1070
  return mod(lhs * rhs, this.ORDER);
991
1071
  }
992
1072
  pow(num, power) {
993
- return FpPow(this, num, power);
1073
+ return pow(num, power, this.ORDER);
994
1074
  }
995
1075
  div(lhs, rhs) {
996
1076
  return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
@@ -1044,7 +1124,7 @@ var _Field = class {
1044
1124
  }
1045
1125
  // TODO: we don't need it here, move out to separate fn
1046
1126
  invertBatch(lst) {
1047
- return FpInvertBatch(this, lst);
1127
+ return FpInvertBatch(this, lst, true);
1048
1128
  }
1049
1129
  // We can't move this out because Fp6, Fp12 implement it
1050
1130
  // and it's unclear what to return in there.
@@ -1053,192 +1133,357 @@ var _Field = class {
1053
1133
  return condition ? b : a;
1054
1134
  }
1055
1135
  };
1056
- Object.freeze(_Field.prototype);
1057
1136
  function Field(ORDER, opts = {}) {
1137
+ Object.freeze(_Field.prototype);
1058
1138
  return new _Field(ORDER, opts);
1059
1139
  }
1060
1140
 
1061
1141
  // ../../node_modules/@noble/curves/abstract/curve.js
1062
1142
  var _0n3 = /* @__PURE__ */ BigInt(0);
1063
1143
  var _1n3 = /* @__PURE__ */ BigInt(1);
1064
- function negateCt(condition, item) {
1065
- const neg = item.negate();
1066
- return condition ? neg : item;
1144
+ var _4n2 = /* @__PURE__ */ BigInt(4);
1145
+ var BLIND_BYTES = 16;
1146
+ var BLIND_BITS = 128;
1147
+ var FW_WINDOW = 5;
1148
+ var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
1149
+ function validatePointCons(Point) {
1150
+ const pc = Point;
1151
+ if (typeof pc !== "function")
1152
+ throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
1153
+ afunction(pc.fromAffine, "Point.fromAffine");
1154
+ afunction(pc.fromBytes, "Point.fromBytes");
1155
+ afunction(pc.fromHex, "Point.fromHex");
1156
+ aobject2(pc.BASE, "Point.BASE");
1157
+ aobject2(pc.ZERO, "Point.ZERO");
1158
+ validateField(pc.Fp);
1159
+ validateField(pc.Fn);
1067
1160
  }
1068
1161
  function normalizeZ(c, points) {
1162
+ validatePointCons(c);
1163
+ validateMSMPoints(points, c);
1069
1164
  const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1070
- return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1071
- }
1072
- function validateW(W, bits2) {
1073
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits2)
1074
- throw new Error("invalid window size, expected [1.." + bits2 + "], got W=" + W);
1075
- }
1076
- function calcWOpts(W, scalarBits) {
1077
- validateW(W, scalarBits);
1078
- const windows = Math.ceil(scalarBits / W) + 1;
1079
- const windowSize = 2 ** (W - 1);
1080
- const maxNumber = 2 ** W;
1081
- const mask = bitMask(W);
1082
- const shiftBy = BigInt(W);
1083
- return { windows, windowSize, mask, maxNumber, shiftBy };
1084
- }
1085
- function calcOffsets(n, window, wOpts) {
1086
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1087
- let wbits2 = Number(n & mask);
1088
- let nextN = n >> shiftBy;
1089
- if (wbits2 > windowSize) {
1090
- wbits2 -= maxNumber;
1091
- nextN += _1n3;
1092
- }
1093
- const offsetStart = window * windowSize;
1094
- const offset = offsetStart + Math.abs(wbits2) - 1;
1095
- const isZero = wbits2 === 0;
1096
- const isNeg = wbits2 < 0;
1097
- const isNegF = window % 2 !== 0;
1098
- const offsetF = offsetStart;
1099
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1100
- }
1101
- var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1165
+ return points.map((p, i2) => c.fromAffine(p.toAffine(invertedZs[i2])));
1166
+ }
1167
+ function validateW(W, bits2, min = 1) {
1168
+ if (!Number.isSafeInteger(W) || W < min || W > bits2)
1169
+ throw new Error("invalid window size, expected [" + min + ".." + bits2 + "], got W=" + W);
1170
+ }
1171
+ function validateTableBytes(numPoints, fpBytes) {
1172
+ const bytes = numPoints * (4 * fpBytes + 128);
1173
+ if (bytes > TABLE_BYTES_MAX)
1174
+ throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
1175
+ }
1176
+ function probeRandomBytes(randomBytes5, length) {
1177
+ if (randomBytes5 === void 0)
1178
+ return void 0;
1179
+ afunction(randomBytes5, "randomBytes");
1180
+ try {
1181
+ const probe = randomBytes5(length);
1182
+ if (!isBytes2(probe) || probe.length !== length)
1183
+ return void 0;
1184
+ } catch {
1185
+ return void 0;
1186
+ }
1187
+ return randomBytes5;
1188
+ }
1189
+ function validateMSMPoints(points, c) {
1190
+ aarray(points, "points");
1191
+ points.forEach((p, i2) => {
1192
+ if (!(p instanceof c))
1193
+ throw new Error("invalid point at index " + i2);
1194
+ });
1195
+ }
1196
+ function validateMSMScalars(scalars, field, maxScalar) {
1197
+ if (!Array.isArray(scalars))
1198
+ throw new Error("array of scalars expected");
1199
+ scalars.forEach((s, i2) => {
1200
+ const ok = maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar;
1201
+ if (!ok)
1202
+ throw new Error("invalid scalar at index " + i2);
1203
+ });
1204
+ }
1102
1205
  var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1103
- function getW(P) {
1206
+ function getWindowSize(P) {
1104
1207
  return pointWindowSizes.get(P) || 1;
1105
1208
  }
1106
- function assert0(n) {
1209
+ function oddMultiples(p, size) {
1210
+ const dbl = p.double();
1211
+ const t = [p];
1212
+ for (let j = 1; j < size; j++)
1213
+ t.push(t[j - 1].add(dbl));
1214
+ return t;
1215
+ }
1216
+ function wnafDigits(n, W) {
1217
+ const size = 2 ** W;
1218
+ const half = size / 2;
1219
+ const mask = BigInt(size - 1);
1220
+ const d = [];
1221
+ while (n > _0n3) {
1222
+ let w = 0;
1223
+ if (n & _1n3) {
1224
+ w = Number(n & mask);
1225
+ if (w >= half)
1226
+ w -= size;
1227
+ n -= BigInt(w);
1228
+ }
1229
+ d.push(w);
1230
+ n >>= _1n3;
1231
+ }
1232
+ return d;
1233
+ }
1234
+ function signedWindowDigits(n, W, windows) {
1235
+ const size = 2 ** W;
1236
+ const half = size / 2;
1237
+ const mask = BigInt(size - 1);
1238
+ const shiftBy = BigInt(W);
1239
+ const d = [];
1240
+ for (let w = 0; w < windows; w++) {
1241
+ let v = Number(n & mask);
1242
+ n >>= shiftBy;
1243
+ if (v > half) {
1244
+ v -= size;
1245
+ n += _1n3;
1246
+ }
1247
+ d.push(v);
1248
+ }
1107
1249
  if (n !== _0n3)
1108
- throw new Error("invalid wNAF");
1250
+ throw new Error("invalid wnaf");
1251
+ return d;
1252
+ }
1253
+ function wnafWalk(zero, tables, digits) {
1254
+ let max2 = 0;
1255
+ for (const d of digits)
1256
+ max2 = Math.max(max2, d.length);
1257
+ let acc = zero;
1258
+ for (let bit = max2 - 1; bit >= 0; bit--) {
1259
+ if (bit !== max2 - 1)
1260
+ acc = acc.double();
1261
+ for (let i2 = 0; i2 < digits.length; i2++) {
1262
+ const w = digits[i2][bit];
1263
+ if (w) {
1264
+ const item = tables[i2][Math.abs(w) - 1 >> 1];
1265
+ acc = acc.add(w < 0 ? item.negate() : item);
1266
+ }
1267
+ }
1268
+ }
1269
+ return acc;
1109
1270
  }
1110
- var wNAF = class {
1271
+ var ScalarMultiplier = class {
1272
+ Point;
1111
1273
  BASE;
1112
1274
  ZERO;
1113
- Fn;
1275
+ randomBytes;
1276
+ wnafPrecomputes = /* @__PURE__ */ new WeakMap();
1277
+ baseCanBeBlinded;
1114
1278
  bits;
1115
1279
  // Parametrized with a given Point class (not individual point)
1116
- constructor(Point, bits2) {
1280
+ constructor(Point, randomBytes5) {
1281
+ validatePointCons(Point);
1282
+ this.randomBytes = probeRandomBytes(randomBytes5, BLIND_BYTES);
1283
+ this.Point = Point;
1117
1284
  this.BASE = Point.BASE;
1118
1285
  this.ZERO = Point.ZERO;
1119
- this.Fn = Point.Fn;
1120
- this.bits = bits2;
1121
- }
1122
- // non-const time multiplication ladder
1123
- _unsafeLadder(elm, n, p = this.ZERO) {
1124
- let d = elm;
1125
- while (n > _0n3) {
1126
- if (n & _1n3)
1127
- p = p.add(d);
1128
- d = d.double();
1129
- n >>= _1n3;
1130
- }
1131
- return p;
1286
+ this.bits = Point.Fn.BITS;
1132
1287
  }
1133
1288
  /**
1134
- * Creates a wNAF precomputation window. Used for caching.
1135
- * Default window size is set by `utils.precompute()` and is equal to 8.
1136
- * Number of precomputed points depends on the curve size:
1137
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1138
- * - 𝑊 is the window size
1139
- * - 𝑛 is the bitlength of the curve order.
1140
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1289
+ * Creates a signed fixed-window wNAF precomputation table: for every window w, the
1290
+ * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
1291
+ * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
1292
+ * window absorbs the final carry of signed-digit recoding.
1293
+ * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
1141
1294
  * @param point - Point instance
1142
1295
  * @param W - window size
1143
- * @returns precomputed point tables flattened to a single array
1296
+ * @param bits - scalar bitlength the table must cover
1144
1297
  */
1145
- precomputeWindow(point, W) {
1146
- const { windows, windowSize } = calcWOpts(W, this.bits);
1147
- const points = [];
1148
- let p = point;
1149
- let base = p;
1150
- for (let window = 0; window < windows; window++) {
1151
- base = p;
1152
- points.push(base);
1153
- for (let i = 1; i < windowSize; i++) {
1154
- base = base.add(p);
1155
- points.push(base);
1298
+ buildWnafTable(point, W, bits2) {
1299
+ const windows = Math.ceil(bits2 / W) + 1;
1300
+ const half = 2 ** (W - 1);
1301
+ const comp = [];
1302
+ let base = point;
1303
+ for (let w = 0; w < windows; w++) {
1304
+ let acc = base;
1305
+ for (let i2 = 0; i2 < half; i2++) {
1306
+ comp.push(acc);
1307
+ acc = acc.add(base);
1156
1308
  }
1157
- p = base.double();
1309
+ base = comp[comp.length - 1].double();
1158
1310
  }
1159
- return points;
1311
+ return { W, bits: bits2, windows, comp };
1160
1312
  }
1161
1313
  /**
1162
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1163
- * More compact implementation:
1164
- * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1314
+ * Implements ec multiplication using precomputed signed fixed-window wNAF tables.
1315
+ * Constant-time: fixed window count with one table addition per window — zero digits feed
1316
+ * the fake accumulator — and no doublings; the lookup scans the whole window slice.
1317
+ * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
1318
+ * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
1319
+ * signedWindowDigits throws if `n` exceeds the table.
1165
1320
  * @returns real and fake (for const-time) points
1166
1321
  */
1167
- wNAF(W, precomputes, n) {
1168
- if (!this.Fn.isValid(n))
1169
- throw new Error("invalid scalar");
1322
+ wnafCachedCT(precomputes, n) {
1323
+ const { W, windows, comp } = precomputes;
1324
+ const half = 2 ** (W - 1);
1325
+ const digits = signedWindowDigits(n, W, windows);
1170
1326
  let p = this.ZERO;
1171
1327
  let f = this.BASE;
1172
- const wo = calcWOpts(W, this.bits);
1173
- for (let window = 0; window < wo.windows; window++) {
1174
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1175
- n = nextN;
1176
- if (isZero) {
1177
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
1178
- } else {
1179
- p = p.add(negateCt(isNeg, precomputes[offset]));
1180
- }
1328
+ for (let w = 0; w < windows; w++) {
1329
+ const digit = digits[w];
1330
+ const start = w * half;
1331
+ const idx = Math.abs(digit) - 1;
1332
+ let sel = comp[start];
1333
+ for (let i2 = 1; i2 < half; i2++)
1334
+ sel = i2 === idx ? comp[start + i2] : sel;
1335
+ const neg = sel.negate();
1336
+ if (digit === 0)
1337
+ f = f.add(comp[start]);
1338
+ else
1339
+ p = p.add(digit < 0 ? neg : sel);
1181
1340
  }
1182
- assert0(n);
1183
1341
  return { p, f };
1184
1342
  }
1185
- /**
1186
- * Implements unsafe EC multiplication using precomputed tables
1187
- * and w-ary non-adjacent form.
1188
- * @param acc - accumulator point to add result of multiplication
1189
- * @returns point
1190
- */
1191
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1192
- const wo = calcWOpts(W, this.bits);
1193
- for (let window = 0; window < wo.windows; window++) {
1194
- if (n === _0n3)
1195
- break;
1196
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1197
- n = nextN;
1198
- if (isZero) {
1199
- continue;
1200
- } else {
1201
- const item = precomputes[offset];
1202
- acc = acc.add(isNeg ? item.negate() : item);
1203
- }
1204
- }
1205
- assert0(n);
1206
- return acc;
1207
- }
1208
- getPrecomputes(W, point, transform) {
1209
- let comp = pointPrecomputes.get(point);
1343
+ // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
1344
+ // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
1345
+ // incompatible `transform(...)` layouts and expect a separate cache entry.
1346
+ getWnafPrecomputes(W, point, bits2, transform) {
1347
+ let entries = this.wnafPrecomputes.get(point);
1348
+ let comp = entries?.find((entry) => entry.W === W && entry.bits === bits2);
1210
1349
  if (!comp) {
1211
- comp = this.precomputeWindow(point, W);
1212
- if (W !== 1) {
1213
- if (typeof transform === "function")
1214
- comp = transform(comp);
1215
- pointPrecomputes.set(point, comp);
1350
+ comp = this.buildWnafTable(point, W, bits2);
1351
+ if (typeof transform === "function")
1352
+ comp = { ...comp, comp: transform(comp.comp) };
1353
+ if (!entries) {
1354
+ entries = [];
1355
+ this.wnafPrecomputes.set(point, entries);
1216
1356
  }
1357
+ entries.push(comp);
1217
1358
  }
1218
1359
  return comp;
1219
1360
  }
1220
- cached(point, scalar, transform) {
1221
- const W = getW(point);
1222
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1361
+ assertPoint(point) {
1362
+ if (!(point instanceof this.Point))
1363
+ throw new TypeError('"point" expected Point instance, got type=' + typeof point);
1364
+ }
1365
+ // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
1366
+ // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
1367
+ // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
1368
+ validateMulInput(point, scalar) {
1369
+ this.assertPoint(point);
1370
+ if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
1371
+ throw new Error("invalid scalar");
1223
1372
  }
1224
- unsafe(point, scalar, transform, prev) {
1225
- const W = getW(point);
1373
+ // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
1374
+ // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
1375
+ // multiply. `n` must be < 2^bits.
1376
+ runCT(point, n, bits2, transform) {
1377
+ const W = getWindowSize(point);
1226
1378
  if (W === 1)
1227
- return this._unsafeLadder(point, scalar, prev);
1228
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1379
+ return this.fixedWindowCT(point, n, bits2);
1380
+ return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits2, transform), n);
1381
+ }
1382
+ mulCT(point, scalar, transform) {
1383
+ this.validateMulInput(point, scalar);
1384
+ return this.runCT(point, scalar, this.bits, transform);
1385
+ }
1386
+ mulCTBlinded(point, scalar, transform) {
1387
+ this.validateMulInput(point, scalar);
1388
+ if (this.randomBytes === void 0)
1389
+ throw new Error("randomBytes is required for scalar blinding");
1390
+ const bits2 = this.Point.Fn.BITS + BLIND_BITS;
1391
+ const blind = this.randomBytes(BLIND_BYTES);
1392
+ if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
1393
+ throw new Error("randomBytes returned invalid byte array");
1394
+ blind[0] = blind[0] & 63 | 128;
1395
+ const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
1396
+ return this.runCT(point, n, bits2, transform);
1397
+ }
1398
+ /**
1399
+ * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
1400
+ * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
1401
+ * far cheaper to build for a single use. The point-operation sequence is independent of `n`:
1402
+ * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
1403
+ * every table entry, and one addition (adds the identity when the window digit is 0 — never
1404
+ * skipped).
1405
+ *
1406
+ * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
1407
+ * add), which holds for the Weierstrass/Edwards point types used here. The table is left in
1408
+ * projective form (no normalizeZ): normalizing this small a table costs more than the
1409
+ * mixed-add savings it would buy for a single multiply.
1410
+ * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
1411
+ * (this path needs no fake accumulator — its op-count is already scalar-independent).
1412
+ */
1413
+ fixedWindowCT(point, n, bits2) {
1414
+ const W = FW_WINDOW;
1415
+ const size = 1 << W;
1416
+ const mask = bitMask(W);
1417
+ const table = new Array(size);
1418
+ table[0] = this.ZERO;
1419
+ for (let i2 = 1; i2 < size; i2++)
1420
+ table[i2] = table[i2 - 1].add(point);
1421
+ const windows = Math.ceil(bits2 / W);
1422
+ let acc = this.ZERO;
1423
+ for (let window = windows - 1; window >= 0; window--) {
1424
+ if (window !== windows - 1)
1425
+ for (let d = 0; d < W; d++)
1426
+ acc = acc.double();
1427
+ const digit = Number(n >> BigInt(window * W) & mask);
1428
+ let sel = table[0];
1429
+ for (let i2 = 1; i2 < size; i2++)
1430
+ sel = i2 === digit ? table[i2] : sel;
1431
+ acc = acc.add(sel);
1432
+ }
1433
+ return { p: acc, f: acc };
1229
1434
  }
1230
- // We calculate precomputes for elliptic curve point multiplication
1231
- // using windowed method. This specifies window size and
1232
- // stores precomputed values. Usually only base point would be precomputed.
1233
- createCache(P, W) {
1435
+ shouldBlind(point, cofactor) {
1436
+ if (this.randomBytes === void 0)
1437
+ return false;
1438
+ if (cofactor === _1n3)
1439
+ return true;
1440
+ if (point !== this.BASE)
1441
+ return false;
1442
+ if (this.baseCanBeBlinded === void 0)
1443
+ this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
1444
+ return this.baseCanBeBlinded;
1445
+ }
1446
+ mulSecret(point, scalar, cofactor, transform) {
1447
+ return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
1448
+ }
1449
+ mulUnsafe(point, scalar, transform) {
1450
+ this.assertPoint(point);
1451
+ if (!isPosBig(scalar))
1452
+ throw new Error("invalid scalar");
1453
+ const W = getWindowSize(point);
1454
+ if (W === 1 || scalar >= this.Point.Fn.ORDER)
1455
+ return mulAddUnsafe(this.Point, [point], [scalar], true);
1456
+ const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
1457
+ return this.wnafCachedCT(precomputes, scalar).p;
1458
+ }
1459
+ // Remembers the window size used for precomputed wNAF multiplication of the given point
1460
+ // and drops any previously built tables. Usually only the base point is precomputed.
1461
+ // W=1 resets the point to the un-precomputed (table-less) paths.
1462
+ // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
1463
+ setWindowSize(point, W) {
1464
+ this.assertPoint(point);
1234
1465
  validateW(W, this.bits);
1235
- pointWindowSizes.set(P, W);
1236
- pointPrecomputes.delete(P);
1466
+ const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
1467
+ validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
1468
+ pointWindowSizes.set(point, W);
1469
+ this.wnafPrecomputes.delete(point);
1237
1470
  }
1238
- hasCache(elm) {
1239
- return getW(elm) !== 1;
1471
+ // True when a window size is set: tables themselves are built lazily on first multiply.
1472
+ hasWindowSize(point) {
1473
+ return getWindowSize(point) !== 1;
1240
1474
  }
1241
1475
  };
1476
+ function mulAddUnsafe(c, points, scalars, allowOversized = false) {
1477
+ validatePointCons(c);
1478
+ validateMSMPoints(points, c);
1479
+ abool(allowOversized, "allowOversized");
1480
+ validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
1481
+ if (points.length !== scalars.length)
1482
+ throw new Error("arrays of points and scalars must have equal length");
1483
+ const tables = points.map((p) => oddMultiples(p, 4));
1484
+ const digits = scalars.map((n) => wnafDigits(n, 4));
1485
+ return wnafWalk(c.ZERO, tables, digits);
1486
+ }
1242
1487
  function createField(order, field, isLE3) {
1243
1488
  if (field) {
1244
1489
  if (field.ORDER !== order)
@@ -1250,17 +1495,20 @@ function createField(order, field, isLE3) {
1250
1495
  }
1251
1496
  }
1252
1497
  function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1498
+ if (type !== "weierstrass" && type !== "edwards")
1499
+ throw new Error('expected curve type "weierstrass" or "edwards"');
1253
1500
  if (FpFnLE === void 0)
1254
1501
  FpFnLE = type === "edwards";
1255
1502
  if (!CURVE || typeof CURVE !== "object")
1256
1503
  throw new Error(`expected valid ${type} CURVE object`);
1504
+ validateObject(curveOpts);
1257
1505
  for (const p of ["p", "n", "h"]) {
1258
1506
  const val = CURVE[p];
1259
- if (!(typeof val === "bigint" && val > _0n3))
1507
+ if (!(isPosBig(val) && val !== _0n3))
1260
1508
  throw new Error(`CURVE.${p} must be positive bigint`);
1261
1509
  }
1262
1510
  const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1263
- const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1511
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1264
1512
  const _b2 = type === "weierstrass" ? "b" : "d";
1265
1513
  const params = ["Gx", "Gy", "a", _b2];
1266
1514
  for (const p of params) {
@@ -1268,7 +1516,7 @@ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1268
1516
  throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1269
1517
  }
1270
1518
  CURVE = Object.freeze(Object.assign({}, CURVE));
1271
- return { CURVE, Fp: Fp2, Fn: Fn2 };
1519
+ return { CURVE, Fp: Fp2, Fn };
1272
1520
  }
1273
1521
  function createKeygen(randomSecretKey, getPublicKey) {
1274
1522
  return function keygen(seed) {
@@ -1281,23 +1529,34 @@ function createKeygen(randomSecretKey, getPublicKey) {
1281
1529
  var _0n4 = /* @__PURE__ */ BigInt(0);
1282
1530
  var _1n4 = /* @__PURE__ */ BigInt(1);
1283
1531
  var _2n2 = /* @__PURE__ */ BigInt(2);
1532
+ var _4n3 = /* @__PURE__ */ BigInt(4);
1284
1533
  var _8n2 = /* @__PURE__ */ BigInt(8);
1285
- function isEdValidXY(Fp2, CURVE, x, y) {
1286
- const x2 = Fp2.sqr(x);
1534
+ function isEdValidXY(Fp2, CURVE, x2, y) {
1535
+ const x22 = Fp2.sqr(x2);
1287
1536
  const y2 = Fp2.sqr(y);
1288
- const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
1289
- const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
1537
+ const left = Fp2.add(Fp2.mul(CURVE.a, x22), y2);
1538
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x22, y2)));
1290
1539
  return Fp2.eql(left, right);
1291
1540
  }
1292
1541
  function edwards(params, extraOpts = {}) {
1542
+ validateObject(extraOpts, {}, {}, "extraOpts");
1293
1543
  const opts = extraOpts;
1294
1544
  const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
1295
- const { Fp: Fp2, Fn: Fn2 } = validated;
1545
+ const { Fp: Fp2, Fn } = validated;
1296
1546
  let CURVE = validated.CURVE;
1297
1547
  const { h: cofactor } = CURVE;
1298
- validateObject(opts, {}, { uvRatio: "function" });
1299
- const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
1300
- const modP = (n) => Fp2.create(n);
1548
+ if (FpLegendre(Fp2, CURVE.a) !== 1)
1549
+ throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
1550
+ if (FpLegendre(Fp2, CURVE.d) !== -1)
1551
+ throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
1552
+ validateObject(opts, {}, { uvRatio: "function", randomBytes: "function" });
1553
+ const randomBytes5 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
1554
+ const MASK = _2n2 << BigInt(Fp2.BYTES * 8) - _1n4;
1555
+ function isOdd(n) {
1556
+ if (!Fp2.isOdd)
1557
+ throw new Error("Field does not have .isOdd()");
1558
+ return Fp2.isOdd(n);
1559
+ }
1301
1560
  const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
1302
1561
  try {
1303
1562
  return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
@@ -1307,6 +1566,7 @@ function edwards(params, extraOpts = {}) {
1307
1566
  } : opts.uvRatio;
1308
1567
  if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1309
1568
  throw new Error("bad curve params: generator point");
1569
+ const mulA = Fp2.eql(CURVE.a, Fp2.neg(Fp2.ONE)) ? (x2) => Fp2.neg(x2) : Fp2.eql(CURVE.a, Fp2.ONE) ? (x2) => x2 : (x2) => Fp2.mul(CURVE.a, x2);
1310
1570
  function acoord(title, n, banZero = false) {
1311
1571
  const min = banZero ? _1n4 : _0n4;
1312
1572
  aInRange("coordinate " + title, n, min, MASK);
@@ -1317,15 +1577,10 @@ function edwards(params, extraOpts = {}) {
1317
1577
  throw new Error("EdwardsPoint expected");
1318
1578
  }
1319
1579
  class Point {
1320
- // base / generator point
1321
- static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
1322
- // zero / infinity / identity point
1323
- static ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
1324
- // 0, 1, 1, 0
1325
- // math field
1580
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE, Fp2.mul(CURVE.Gx, CURVE.Gy));
1581
+ static ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ONE, Fp2.ZERO);
1326
1582
  static Fp = Fp2;
1327
- // scalar field
1328
- static Fn = Fn2;
1583
+ static Fn = Fn;
1329
1584
  X;
1330
1585
  Y;
1331
1586
  Z;
@@ -1348,36 +1603,36 @@ function edwards(params, extraOpts = {}) {
1348
1603
  static fromAffine(p) {
1349
1604
  if (p instanceof Point)
1350
1605
  throw new Error("extended point not allowed");
1351
- const { x, y } = p || {};
1352
- acoord("x", x);
1606
+ const { x: x2, y } = p || {};
1607
+ acoord("x", x2);
1353
1608
  acoord("y", y);
1354
- return new Point(x, y, _1n4, modP(x * y));
1609
+ return new Point(x2, y, Fp2.ONE, Fp2.mul(x2, y));
1355
1610
  }
1356
1611
  // Uses algo from RFC8032 5.1.3.
1357
1612
  static fromBytes(bytes, zip215 = false) {
1358
1613
  const len = Fp2.BYTES;
1359
1614
  const { a, d } = CURVE;
1360
- bytes = copyBytes(abytes2(bytes, len, "point"));
1615
+ bytes = copyBytes2(abytes2(bytes, len, "point"));
1361
1616
  abool(zip215, "zip215");
1362
- const normed = copyBytes(bytes);
1617
+ const normed = copyBytes2(bytes);
1363
1618
  const lastByte = bytes[len - 1];
1364
1619
  normed[len - 1] = lastByte & ~128;
1365
1620
  const y = bytesToNumberLE(normed);
1366
1621
  const max2 = zip215 ? MASK : Fp2.ORDER;
1367
1622
  aInRange("point.y", y, _0n4, max2);
1368
- const y2 = modP(y * y);
1369
- const u = modP(y2 - _1n4);
1370
- const v = modP(d * y2 - a);
1371
- let { isValid, value: x } = uvRatio2(u, v);
1623
+ const y2 = Fp2.sqr(y);
1624
+ const u = Fp2.sub(y2, Fp2.ONE);
1625
+ const v = Fp2.sub(Fp2.mulN(d, y2), a);
1626
+ let { isValid, value: x2 } = uvRatio2(u, v);
1372
1627
  if (!isValid)
1373
1628
  throw new Error("bad point: invalid y coordinate");
1374
- const isXOdd = (x & _1n4) === _1n4;
1629
+ const isXOdd = isOdd(x2);
1375
1630
  const isLastByteOdd = (lastByte & 128) !== 0;
1376
- if (!zip215 && x === _0n4 && isLastByteOdd)
1631
+ if (!zip215 && Fp2.is0(x2) && isLastByteOdd)
1377
1632
  throw new Error("bad point: x=0 and x_0=1");
1378
1633
  if (isLastByteOdd !== isXOdd)
1379
- x = modP(-x);
1380
- return Point.fromAffine({ x, y });
1634
+ x2 = Fp2.neg(x2);
1635
+ return Point.fromAffine({ x: x2, y });
1381
1636
  }
1382
1637
  static fromHex(hex, zip215 = false) {
1383
1638
  return Point.fromBytes(hexToBytes2(hex), zip215);
@@ -1388,8 +1643,8 @@ function edwards(params, extraOpts = {}) {
1388
1643
  get y() {
1389
1644
  return this.toAffine().y;
1390
1645
  }
1391
- precompute(windowSize = 8, isLazy = true) {
1392
- wnaf.createCache(this, windowSize);
1646
+ precompute(windowSize = 6, isLazy = true) {
1647
+ wnaf.setWindowSize(this, windowSize);
1393
1648
  if (!isLazy)
1394
1649
  this.multiply(_2n2);
1395
1650
  return this;
@@ -1401,18 +1656,18 @@ function edwards(params, extraOpts = {}) {
1401
1656
  if (p.is0())
1402
1657
  throw new Error("bad point: ZERO");
1403
1658
  const { X, Y, Z, T } = p;
1404
- const X2 = modP(X * X);
1405
- const Y2 = modP(Y * Y);
1406
- const Z2 = modP(Z * Z);
1407
- const Z4 = modP(Z2 * Z2);
1408
- const aX2 = modP(X2 * a);
1409
- const left = modP(Z2 * modP(aX2 + Y2));
1410
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1411
- if (left !== right)
1659
+ const X2 = Fp2.sqr(X);
1660
+ const Y2 = Fp2.sqr(Y);
1661
+ const Z2 = Fp2.sqr(Z);
1662
+ const Z4 = Fp2.sqr(Z2);
1663
+ const aX2 = Fp2.mul(X2, a);
1664
+ const left = Fp2.mul(Fp2.add(aX2, Y2), Z2);
1665
+ const right = Fp2.add(Z4, Fp2.mul(d, Fp2.mul(X2, Y2)));
1666
+ if (!Fp2.eql(left, right))
1412
1667
  throw new Error("bad point: equation left != right (1)");
1413
- const XY = modP(X * Y);
1414
- const ZT = modP(Z * T);
1415
- if (XY !== ZT)
1668
+ const XY = Fp2.mul(X, Y);
1669
+ const ZT = Fp2.mul(Z, T);
1670
+ if (!Fp2.eql(XY, ZT))
1416
1671
  throw new Error("bad point: equation left != right (2)");
1417
1672
  }
1418
1673
  // Compare one point to another.
@@ -1420,37 +1675,36 @@ function edwards(params, extraOpts = {}) {
1420
1675
  aedpoint(other);
1421
1676
  const { X: X1, Y: Y1, Z: Z1 } = this;
1422
1677
  const { X: X2, Y: Y2, Z: Z2 } = other;
1423
- const X1Z2 = modP(X1 * Z2);
1424
- const X2Z1 = modP(X2 * Z1);
1425
- const Y1Z2 = modP(Y1 * Z2);
1426
- const Y2Z1 = modP(Y2 * Z1);
1427
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1678
+ const X1Z2 = Fp2.mul(X1, Z2);
1679
+ const X2Z1 = Fp2.mul(X2, Z1);
1680
+ const Y1Z2 = Fp2.mul(Y1, Z2);
1681
+ const Y2Z1 = Fp2.mul(Y2, Z1);
1682
+ return Fp2.eql(X1Z2, X2Z1) && Fp2.eql(Y1Z2, Y2Z1);
1428
1683
  }
1429
1684
  is0() {
1430
1685
  return this.equals(Point.ZERO);
1431
1686
  }
1432
1687
  negate() {
1433
- return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1688
+ return new Point(Fp2.neg(this.X), this.Y, this.Z, Fp2.neg(this.T));
1434
1689
  }
1435
1690
  // Fast algo for doubling Extended Point.
1436
1691
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1437
1692
  // Cost: 4M + 4S + 1*a + 6add + 1*2.
1438
1693
  double() {
1439
- const { a } = CURVE;
1440
1694
  const { X: X1, Y: Y1, Z: Z1 } = this;
1441
- const A = modP(X1 * X1);
1442
- const B = modP(Y1 * Y1);
1443
- const C = modP(_2n2 * modP(Z1 * Z1));
1444
- const D = modP(a * A);
1445
- const x1y1 = X1 + Y1;
1446
- const E = modP(modP(x1y1 * x1y1) - A - B);
1447
- const G = D + B;
1448
- const F = G - C;
1449
- const H = D - B;
1450
- const X3 = modP(E * F);
1451
- const Y3 = modP(G * H);
1452
- const T3 = modP(E * H);
1453
- const Z3 = modP(F * G);
1695
+ const A = Fp2.sqr(X1);
1696
+ const B = Fp2.sqr(Y1);
1697
+ const C = Fp2.mul(Fp2.sqr(Z1), _2n2);
1698
+ const D = mulA(A);
1699
+ const x1y1 = Fp2.addN(X1, Y1);
1700
+ const E = Fp2.sub(Fp2.subN(Fp2.sqr(x1y1), A), B);
1701
+ const G = Fp2.addN(D, B);
1702
+ const F = Fp2.subN(G, C);
1703
+ const H = Fp2.subN(D, B);
1704
+ const X3 = Fp2.mul(E, F);
1705
+ const Y3 = Fp2.mul(G, H);
1706
+ const T3 = Fp2.mul(E, H);
1707
+ const Z3 = Fp2.mul(F, G);
1454
1708
  return new Point(X3, Y3, Z3, T3);
1455
1709
  }
1456
1710
  // Fast algo for adding 2 Extended Points.
@@ -1458,21 +1712,21 @@ function edwards(params, extraOpts = {}) {
1458
1712
  // Cost: 9M + 1*a + 1*d + 7add.
1459
1713
  add(other) {
1460
1714
  aedpoint(other);
1461
- const { a, d } = CURVE;
1715
+ const { d } = CURVE;
1462
1716
  const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1463
1717
  const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1464
- const A = modP(X1 * X2);
1465
- const B = modP(Y1 * Y2);
1466
- const C = modP(T1 * d * T2);
1467
- const D = modP(Z1 * Z2);
1468
- const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1469
- const F = D - C;
1470
- const G = D + C;
1471
- const H = modP(B - a * A);
1472
- const X3 = modP(E * F);
1473
- const Y3 = modP(G * H);
1474
- const T3 = modP(E * H);
1475
- const Z3 = modP(F * G);
1718
+ const A = Fp2.mul(X1, X2);
1719
+ const B = Fp2.mul(Y1, Y2);
1720
+ const C = Fp2.mul(Fp2.mulN(T1, d), T2);
1721
+ const D = Fp2.mul(Z1, Z2);
1722
+ const E = Fp2.sub(Fp2.subN(Fp2.mulN(Fp2.addN(X1, Y1), Fp2.addN(X2, Y2)), A), B);
1723
+ const F = Fp2.subN(D, C);
1724
+ const G = Fp2.addN(D, C);
1725
+ const H = Fp2.sub(B, mulA(A));
1726
+ const X3 = Fp2.mul(E, F);
1727
+ const Y3 = Fp2.mul(G, H);
1728
+ const T3 = Fp2.mul(E, H);
1729
+ const Z3 = Fp2.mul(F, G);
1476
1730
  return new Point(X3, Y3, Z3, T3);
1477
1731
  }
1478
1732
  subtract(other) {
@@ -1481,10 +1735,10 @@ function edwards(params, extraOpts = {}) {
1481
1735
  }
1482
1736
  // Constant-time multiplication.
1483
1737
  multiply(scalar) {
1484
- if (!Fn2.isValidNot0(scalar))
1738
+ if (!Fn.isValidNot0(scalar))
1485
1739
  throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1486
- const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1487
- return normalizeZ(Point, [p, f])[0];
1740
+ const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
1741
+ return normalize([p, f])[0];
1488
1742
  }
1489
1743
  // Non-constant-time multiplication. Uses double-and-add algorithm.
1490
1744
  // It's faster, but should only be used when you don't care about
@@ -1492,13 +1746,13 @@ function edwards(params, extraOpts = {}) {
1492
1746
  // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
1493
1747
  // n and larger values are rejected instead of being reduced mod n to the identity point.
1494
1748
  multiplyUnsafe(scalar) {
1495
- if (!Fn2.isValid(scalar))
1749
+ if (!Fn.isValid(scalar))
1496
1750
  throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1497
1751
  if (scalar === _0n4)
1498
1752
  return Point.ZERO;
1499
1753
  if (this.is0() || scalar === _1n4)
1500
1754
  return this;
1501
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));
1755
+ return wnaf.mulUnsafe(this, scalar, normalize);
1502
1756
  }
1503
1757
  // Checks if point is of small order.
1504
1758
  // If you add something to small order point, you will have "dirty"
@@ -1510,35 +1764,43 @@ function edwards(params, extraOpts = {}) {
1510
1764
  // Multiplies point by curve order and checks if the result is 0.
1511
1765
  // Returns `false` is the point is dirty.
1512
1766
  isTorsionFree() {
1513
- return wnaf.unsafe(this, CURVE.n).is0();
1767
+ return wnaf.mulUnsafe(this, CURVE.n).is0();
1514
1768
  }
1515
1769
  // Converts Extended point to default (x, y) coordinates.
1516
1770
  // Can accept precomputed Z^-1 - for example, from invertBatch.
1517
1771
  toAffine(invertedZ) {
1518
1772
  const p = this;
1519
1773
  let iz = invertedZ;
1774
+ if (iz != null && typeof iz !== "bigint")
1775
+ throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
1520
1776
  const { X, Y, Z } = p;
1521
1777
  const is0 = p.is0();
1522
1778
  if (iz == null)
1523
- iz = is0 ? _8n2 : Fp2.inv(Z);
1524
- const x = modP(X * iz);
1525
- const y = modP(Y * iz);
1779
+ iz = is0 ? Fp2.create(_8n2) : Fp2.inv(Z);
1780
+ const x2 = Fp2.mul(X, iz);
1781
+ const y = Fp2.mul(Y, iz);
1526
1782
  const zz = Fp2.mul(Z, iz);
1527
1783
  if (is0)
1528
- return { x: _0n4, y: _1n4 };
1529
- if (zz !== _1n4)
1784
+ return { x: Fp2.ZERO, y: Fp2.ONE };
1785
+ if (!Fp2.eql(zz, Fp2.ONE))
1530
1786
  throw new Error("invZ was invalid");
1531
- return { x, y };
1787
+ return { x: x2, y };
1532
1788
  }
1533
1789
  clearCofactor() {
1534
1790
  if (cofactor === _1n4)
1535
1791
  return this;
1792
+ if (cofactor === _2n2)
1793
+ return this.double();
1794
+ if (cofactor === _4n3)
1795
+ return this.double().double();
1796
+ if (cofactor === _8n2)
1797
+ return this.double().double().double();
1536
1798
  return this.multiplyUnsafe(cofactor);
1537
1799
  }
1538
1800
  toBytes() {
1539
- const { x, y } = this.toAffine();
1801
+ const { x: x2, y } = this.toAffine();
1540
1802
  const bytes = Fp2.toBytes(y);
1541
- bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1803
+ bytes[bytes.length - 1] |= isOdd(x2) ? 128 : 0;
1542
1804
  return bytes;
1543
1805
  }
1544
1806
  toHex() {
@@ -1548,94 +1810,16 @@ function edwards(params, extraOpts = {}) {
1548
1810
  return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1549
1811
  }
1550
1812
  }
1551
- const wnaf = new wNAF(Point, Fn2.BITS);
1552
- if (Fn2.BITS >= 8)
1553
- Point.BASE.precompute(8);
1813
+ const normalize = (points) => normalizeZ(Point, points);
1814
+ const wnaf = new ScalarMultiplier(Point, randomBytes5);
1815
+ if (wnaf.bits >= 6)
1816
+ Point.BASE.precompute(6);
1554
1817
  Object.freeze(Point.prototype);
1555
1818
  Object.freeze(Point);
1556
1819
  return Point;
1557
1820
  }
1558
- var PrimeEdwardsPoint = class {
1559
- static BASE;
1560
- static ZERO;
1561
- static Fp;
1562
- static Fn;
1563
- ep;
1564
- /**
1565
- * Wrap one internal Edwards representative directly.
1566
- * This is not a canonical encoding boundary: alternate Edwards
1567
- * representatives may still describe the same abstract wrapper element.
1568
- */
1569
- constructor(ep) {
1570
- this.ep = ep;
1571
- }
1572
- // Static methods that must be implemented by subclasses
1573
- static fromBytes(_bytes) {
1574
- notImplemented();
1575
- }
1576
- static fromHex(_hex) {
1577
- notImplemented();
1578
- }
1579
- get x() {
1580
- return this.toAffine().x;
1581
- }
1582
- get y() {
1583
- return this.toAffine().y;
1584
- }
1585
- // Common implementations
1586
- clearCofactor() {
1587
- return this;
1588
- }
1589
- assertValidity() {
1590
- this.ep.assertValidity();
1591
- }
1592
- /**
1593
- * Return affine coordinates of the current internal Edwards representative.
1594
- * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
1595
- * Equal abstract elements may expose different `x` / `y`; use
1596
- * `toBytes()` / `fromBytes()` for canonical roundtrips.
1597
- */
1598
- toAffine(invertedZ) {
1599
- return this.ep.toAffine(invertedZ);
1600
- }
1601
- toHex() {
1602
- return bytesToHex2(this.toBytes());
1603
- }
1604
- toString() {
1605
- return this.toHex();
1606
- }
1607
- isTorsionFree() {
1608
- return true;
1609
- }
1610
- isSmallOrder() {
1611
- return false;
1612
- }
1613
- add(other) {
1614
- this.assertSame(other);
1615
- return this.init(this.ep.add(other.ep));
1616
- }
1617
- subtract(other) {
1618
- this.assertSame(other);
1619
- return this.init(this.ep.subtract(other.ep));
1620
- }
1621
- multiply(scalar) {
1622
- return this.init(this.ep.multiply(scalar));
1623
- }
1624
- multiplyUnsafe(scalar) {
1625
- return this.init(this.ep.multiplyUnsafe(scalar));
1626
- }
1627
- double() {
1628
- return this.init(this.ep.double());
1629
- }
1630
- negate() {
1631
- return this.init(this.ep.negate());
1632
- }
1633
- precompute(windowSize, isLazy) {
1634
- this.ep.precompute(windowSize, isLazy);
1635
- return this;
1636
- }
1637
- };
1638
1821
  function eddsa(Point, cHash, eddsaOpts = {}) {
1822
+ validatePointCons(Point);
1639
1823
  if (typeof cHash !== "function")
1640
1824
  throw new Error('"hash" function param is required');
1641
1825
  const hash = cHash;
@@ -1646,10 +1830,12 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1646
1830
  domain: "function",
1647
1831
  prehash: "function",
1648
1832
  zip215: "boolean",
1649
- mapToCurve: "function"
1833
+ mapToCurve: "function",
1834
+ toMontgomery: "function",
1835
+ toMontgomerySecret: "function"
1650
1836
  });
1651
1837
  const { prehash } = opts;
1652
- const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
1838
+ const { BASE, Fp: Fp2, Fn } = Point;
1653
1839
  const outputLen = hash.outputLen;
1654
1840
  const expectedLen = 2 * Fp2.BYTES;
1655
1841
  if (outputLen !== void 0) {
@@ -1658,6 +1844,8 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1658
1844
  throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
1659
1845
  }
1660
1846
  const randomBytes5 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
1847
+ const toMontgomery2 = opts.toMontgomery;
1848
+ const toMontgomerySecret2 = opts.toMontgomerySecret;
1661
1849
  const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
1662
1850
  const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
1663
1851
  abool(phflag, "phflag");
@@ -1666,7 +1854,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1666
1854
  return data;
1667
1855
  } : opts.domain;
1668
1856
  function modN_LE(hash2) {
1669
- return Fn2.create(bytesToNumberLE(hash2));
1857
+ return Fn.create(bytesToNumberLE(hash2));
1670
1858
  }
1671
1859
  function getPrivateScalar(key) {
1672
1860
  const len = lengths.secretKey;
@@ -1691,23 +1879,25 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1691
1879
  return modN_LE(hash(domain(msg, abytes2(context, void 0, "context"), !!prehash)));
1692
1880
  }
1693
1881
  function sign(msg, secretKey, options = {}) {
1694
- msg = abytes2(msg, void 0, "message");
1882
+ validateObject(options, {}, {}, "options");
1883
+ msg = copyBytes2(abytes2(msg, void 0, "message"));
1695
1884
  if (prehash)
1696
1885
  msg = prehash(msg);
1697
1886
  const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
1698
1887
  const r = hashDomainToScalar(options.context, prefix, msg);
1699
1888
  const R = BASE.multiply(r).toBytes();
1700
1889
  const k = hashDomainToScalar(options.context, R, pointBytes, msg);
1701
- const s = Fn2.create(r + k * scalar);
1702
- if (!Fn2.isValid(s))
1890
+ const s = Fn.create(r + k * scalar);
1891
+ if (!Fn.isValid(s))
1703
1892
  throw new Error("sign failed: invalid s");
1704
- const rs = concatBytes2(R, Fn2.toBytes(s));
1893
+ const rs = concatBytes2(R, Fn.toBytes(s));
1705
1894
  return abytes2(rs, lengths.signature, "result");
1706
1895
  }
1707
1896
  const verifyOpts = {
1708
1897
  zip215: opts.zip215
1709
1898
  };
1710
1899
  function verify(sig, msg, publicKey, options = verifyOpts) {
1900
+ validateObject(options);
1711
1901
  const { context } = options;
1712
1902
  const zip215 = options.zip215 === void 0 ? !!verifyOpts.zip215 : options.zip215;
1713
1903
  const len = lengths.signature;
@@ -1761,29 +1951,16 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1761
1951
  randomSecretKey,
1762
1952
  isValidSecretKey,
1763
1953
  isValidPublicKey,
1764
- /**
1765
- * Converts ed public key to x public key. Uses formula:
1766
- * - ed25519:
1767
- * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
1768
- * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
1769
- * - ed448:
1770
- * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
1771
- * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
1772
- */
1954
+ /** Converts an Edwards public key to a companion Montgomery public key. */
1773
1955
  toMontgomery(publicKey) {
1774
- const { y } = Point.fromBytes(publicKey);
1775
- const size = lengths.publicKey;
1776
- const is25519 = size === 32;
1777
- if (!is25519 && size !== 57)
1778
- throw new Error("only defined for 25519 and 448");
1779
- const u = is25519 ? Fp2.div(_1n4 + y, _1n4 - y) : Fp2.div(y - _1n4, y + _1n4);
1780
- return Fp2.toBytes(u);
1956
+ if (toMontgomery2 === void 0)
1957
+ throw new Error("Montgomery conversion is not supported for this curve");
1958
+ return toMontgomery2(Point.fromBytes(publicKey));
1781
1959
  },
1782
1960
  toMontgomerySecret(secretKey) {
1783
- const size = lengths.secretKey;
1784
- abytes2(secretKey, size);
1785
- const hashed = hash(secretKey.subarray(0, size));
1786
- return adjustScalarBytes2(hashed).subarray(0, size);
1961
+ if (toMontgomerySecret2 === void 0)
1962
+ throw new Error("Montgomery conversion is not supported for this curve");
1963
+ return toMontgomerySecret2(secretKey);
1787
1964
  }
1788
1965
  };
1789
1966
  Object.freeze(lengths);
@@ -1799,65 +1976,22 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1799
1976
  });
1800
1977
  }
1801
1978
 
1802
- // ../../node_modules/@noble/curves/abstract/hash-to-curve.js
1803
- function i2osp(value, length) {
1804
- asafenumber(value);
1805
- asafenumber(length);
1806
- if (length < 0 || length > 4)
1807
- throw new Error("invalid I2OSP length: " + length);
1808
- if (value < 0 || value > 2 ** (8 * length) - 1)
1809
- throw new Error("invalid I2OSP input: " + value);
1810
- const res = Array.from({ length }).fill(0);
1811
- for (let i = length - 1; i >= 0; i--) {
1812
- res[i] = value & 255;
1813
- value >>>= 8;
1814
- }
1815
- return new Uint8Array(res);
1816
- }
1817
- function strxor(a, b) {
1818
- const arr = new Uint8Array(a.length);
1819
- for (let i = 0; i < a.length; i++) {
1820
- arr[i] = a[i] ^ b[i];
1821
- }
1822
- return arr;
1823
- }
1824
- function normDST(DST) {
1825
- if (!isBytes2(DST) && typeof DST !== "string")
1826
- throw new Error("DST must be Uint8Array or ascii string");
1827
- const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
1828
- if (dst.length === 0)
1829
- throw new Error("DST must be non-empty");
1830
- return dst;
1831
- }
1832
- function expand_message_xmd(msg, DST, lenInBytes, H) {
1833
- abytes2(msg);
1834
- asafenumber(lenInBytes);
1835
- DST = normDST(DST);
1836
- if (DST.length > 255)
1837
- DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
1838
- const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1839
- const ell = Math.ceil(lenInBytes / b_in_bytes);
1840
- if (lenInBytes > 65535 || ell > 255)
1841
- throw new Error("expand_message_xmd: invalid lenInBytes");
1842
- const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
1843
- const Z_pad = new Uint8Array(r_in_bytes);
1844
- const l_i_b_str = i2osp(lenInBytes, 2);
1845
- const b = new Array(ell);
1846
- const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1847
- b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
1848
- for (let i = 1; i < ell; i++) {
1849
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1850
- b[i] = H(concatBytes2(...args));
1851
- }
1852
- const pseudo_random_bytes = concatBytes2(...b);
1853
- return pseudo_random_bytes.slice(0, lenInBytes);
1854
- }
1855
- var _DST_scalar = "HashToScalar-";
1856
-
1857
1979
  // ../../node_modules/@noble/curves/abstract/montgomery.js
1858
- var _0n5 = BigInt(0);
1859
- var _1n5 = BigInt(1);
1860
- var _2n3 = BigInt(2);
1980
+ var _0n5 = /* @__PURE__ */ BigInt(0);
1981
+ var _1n5 = /* @__PURE__ */ BigInt(1);
1982
+ var _2n3 = /* @__PURE__ */ BigInt(2);
1983
+ function cmask(P, swap) {
1984
+ return P + swap - (swap >> _1n5 << _1n5);
1985
+ }
1986
+ function cswap(P) {
1987
+ const offset = BigInt(6) * P;
1988
+ return (mask, x_2, x_3) => {
1989
+ const sum = x_2 + x_3;
1990
+ const d = offset + x_3 - x_2;
1991
+ const a = (d * mask + x_2) % P;
1992
+ return { x_2: a, x_3: sum - a };
1993
+ };
1994
+ }
1861
1995
  function validateOpts(curve) {
1862
1996
  validateObject(curve, {
1863
1997
  P: "bigint",
@@ -1865,23 +1999,26 @@ function validateOpts(curve) {
1865
1999
  adjustScalarBytes: "function",
1866
2000
  powPminus2: "function"
1867
2001
  }, {
1868
- randomBytes: "function"
2002
+ randomBytes: "function",
2003
+ scalarMultBase: "function"
1869
2004
  });
1870
2005
  return Object.freeze({ ...curve });
1871
2006
  }
1872
2007
  function montgomery(curveDef) {
1873
2008
  const CURVE = validateOpts(curveDef);
1874
2009
  const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
2010
+ const mulBaseHook = CURVE.scalarMultBase;
1875
2011
  const is25519 = type === "x25519";
1876
2012
  if (!is25519 && type !== "x448")
1877
2013
  throw new Error("invalid type");
1878
2014
  const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
1879
2015
  const montgomeryBits = is25519 ? 255 : 448;
2016
+ const swap = cswap(P);
1880
2017
  const fieldLen = is25519 ? 32 : 56;
1881
2018
  const Gu = is25519 ? BigInt(9) : BigInt(5);
1882
2019
  const a24 = is25519 ? BigInt(121665) : BigInt(39081);
1883
2020
  const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
1884
- const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
2021
+ const maxAdded = is25519 ? BigInt(8) * (_2n3 ** BigInt(251) - _1n5) : BigInt(4) * (_2n3 ** BigInt(445) - _1n5);
1885
2022
  const maxScalar = minScalar + maxAdded + _1n5;
1886
2023
  const modP = (n) => mod(n, P);
1887
2024
  const GuBytes = encodeU(Gu);
@@ -1889,31 +2026,42 @@ function montgomery(curveDef) {
1889
2026
  return numberToBytesLE(modP(u), fieldLen);
1890
2027
  }
1891
2028
  function decodeU(u) {
1892
- const _u = copyBytes(abytes2(u, fieldLen, "uCoordinate"));
2029
+ const _u = copyBytes2(abytes2(u, fieldLen, "uCoordinate"));
1893
2030
  if (is25519)
1894
2031
  _u[31] &= 127;
1895
2032
  return modP(bytesToNumberLE(_u));
1896
2033
  }
1897
2034
  function decodeScalar(scalar) {
1898
- return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
1899
- }
2035
+ return bytesToNumberLE(adjustScalarBytes2(copyBytes2(abytes2(scalar, fieldLen, "scalar"))));
2036
+ }
2037
+ const lowOrderU = new Set(is25519 ? [
2038
+ _0n5,
2039
+ _1n5,
2040
+ P - _1n5,
2041
+ BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),
2042
+ BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")
2043
+ ] : [_0n5, _1n5, P - _1n5]);
1900
2044
  function scalarMult(scalar, u) {
1901
- const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
2045
+ const pointU = decodeU(u);
2046
+ if (lowOrderU.has(pointU))
2047
+ throw new Error("invalid private or public key received");
2048
+ const pu = montgomeryLadder(pointU, decodeScalar(scalar));
1902
2049
  if (pu === _0n5)
1903
2050
  throw new Error("invalid private or public key received");
1904
2051
  return encodeU(pu);
1905
2052
  }
1906
2053
  function scalarMultBase(scalar) {
1907
- return scalarMult(scalar, GuBytes);
2054
+ if (mulBaseHook === void 0)
2055
+ return scalarMult(scalar, GuBytes);
2056
+ const k = decodeScalar(scalar);
2057
+ aInRange("scalar", k, minScalar, maxScalar);
2058
+ const pu = modP(mulBaseHook(k));
2059
+ if (pu === _0n5)
2060
+ throw new Error("invalid private or public key received");
2061
+ return encodeU(pu);
1908
2062
  }
1909
2063
  const getPublicKey = scalarMultBase;
1910
2064
  const getSharedSecret = scalarMult;
1911
- function cswap(swap, x_2, x_3) {
1912
- const dummy = modP(swap * (x_2 - x_3));
1913
- x_2 = modP(x_2 - dummy);
1914
- x_3 = modP(x_3 + dummy);
1915
- return { x_2, x_3 };
1916
- }
1917
2065
  function montgomeryLadder(u, scalar) {
1918
2066
  aInRange("u", u, _0n5, P);
1919
2067
  aInRange("scalar", scalar, minScalar, maxScalar);
@@ -1923,13 +2071,11 @@ function montgomery(curveDef) {
1923
2071
  let z_2 = _0n5;
1924
2072
  let x_3 = u;
1925
2073
  let z_3 = _1n5;
1926
- let swap = _0n5;
2074
+ const kx = k ^ k >> _1n5;
1927
2075
  for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
1928
- const k_t = k >> t & _1n5;
1929
- swap ^= k_t;
1930
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1931
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1932
- swap = k_t;
2076
+ const mask2 = cmask(P, kx >> t);
2077
+ ({ x_2, x_3 } = swap(mask2, x_2, x_3));
2078
+ ({ x_2: z_2, x_3: z_3 } = swap(mask2, z_2, z_3));
1933
2079
  const A = x_2 + z_2;
1934
2080
  const AA = modP(A * A);
1935
2081
  const B = x_2 - z_2;
@@ -1946,8 +2092,9 @@ function montgomery(curveDef) {
1946
2092
  x_2 = modP(AA * BB);
1947
2093
  z_2 = modP(E * (AA + modP(a24 * E)));
1948
2094
  }
1949
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1950
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
2095
+ const mask = cmask(P, k);
2096
+ ({ x_2, x_3 } = swap(mask, x_2, x_3));
2097
+ ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));
1951
2098
  const z2 = powPminus2(z_2);
1952
2099
  return modP(x_2 * z2);
1953
2100
  }
@@ -1993,13 +2140,13 @@ var ed25519_CURVE = /* @__PURE__ */ (() => ({
1993
2140
  Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
1994
2141
  Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
1995
2142
  }))();
1996
- function ed25519_pow_2_252_3(x) {
2143
+ function ed25519_pow_2_252_3(x2) {
1997
2144
  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
1998
2145
  const P = ed25519_CURVE_p;
1999
- const x2 = x * x % P;
2000
- const b2 = x2 * x % P;
2146
+ const x22 = x2 * x2 % P;
2147
+ const b2 = x22 * x2 % P;
2001
2148
  const b4 = pow2(b2, _2n4, P) * b2 % P;
2002
- const b5 = pow2(b4, _1n6, P) * x % P;
2149
+ const b5 = pow2(b4, _1n6, P) * x2 % P;
2003
2150
  const b10 = pow2(b5, _5n2, P) * b5 % P;
2004
2151
  const b20 = pow2(b10, _10n, P) * b10 % P;
2005
2152
  const b40 = pow2(b20, _20n, P) * b20 % P;
@@ -2007,7 +2154,7 @@ function ed25519_pow_2_252_3(x) {
2007
2154
  const b160 = pow2(b80, _80n, P) * b80 % P;
2008
2155
  const b240 = pow2(b160, _80n, P) * b80 % P;
2009
2156
  const b250 = pow2(b240, _10n, P) * b10 % P;
2010
- const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
2157
+ const pow_p_5_8 = pow2(b250, _2n4, P) * x2 % P;
2011
2158
  return { pow_p_5_8, b2 };
2012
2159
  }
2013
2160
  function adjustScalarBytes(bytes) {
@@ -2021,233 +2168,60 @@ function uvRatio(u, v) {
2021
2168
  const P = ed25519_CURVE_p;
2022
2169
  const v3 = mod(v * v * v, P);
2023
2170
  const v7 = mod(v3 * v3 * v, P);
2024
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2025
- let x = mod(u * v3 * pow, P);
2026
- const vx2 = mod(v * x * x, P);
2027
- const root1 = x;
2028
- const root2 = mod(x * ED25519_SQRT_M1, P);
2171
+ const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2172
+ let x2 = mod(u * v3 * pow3, P);
2173
+ const vx2 = mod(v * x2 * x2, P);
2174
+ const root1 = x2;
2175
+ const root2 = mod(x2 * ED25519_SQRT_M1, P);
2029
2176
  const useRoot1 = vx2 === u;
2030
2177
  const useRoot2 = vx2 === mod(-u, P);
2031
2178
  const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2032
2179
  if (useRoot1)
2033
- x = root1;
2180
+ x2 = root1;
2034
2181
  if (useRoot2 || noRoot)
2035
- x = root2;
2036
- if (isNegativeLE(x, P))
2037
- x = mod(-x, P);
2038
- return { isValid: useRoot1 || useRoot2, value: x };
2182
+ x2 = root2;
2183
+ if (isNegativeLE(x2, P))
2184
+ x2 = mod(-x2, P);
2185
+ return { isValid: useRoot1 || useRoot2, value: x2 };
2039
2186
  }
2040
2187
  var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2041
2188
  var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
2042
- var Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
2189
+ function toMontgomery(point) {
2190
+ const { y } = point;
2191
+ return Fp.toBytes(Fp.div(_1n6 + y, _1n6 - y));
2192
+ }
2193
+ function toMontgomerySecret(secretKey) {
2194
+ const size = ed25519_Point.Fp.BYTES;
2195
+ abytes(secretKey, size);
2196
+ return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);
2197
+ }
2043
2198
  function ed(opts) {
2044
- return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, zip215: true }, opts));
2199
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));
2045
2200
  }
2046
2201
  var ed25519 = /* @__PURE__ */ ed({});
2047
2202
  var x25519 = /* @__PURE__ */ (() => {
2048
2203
  const P = ed25519_CURVE_p;
2204
+ const powPminus2 = (x2) => {
2205
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x2);
2206
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2207
+ };
2049
2208
  return montgomery({
2050
2209
  P,
2051
2210
  type: "x25519",
2052
- powPminus2: (x) => {
2053
- const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
2054
- return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2055
- },
2056
- adjustScalarBytes
2211
+ powPminus2,
2212
+ adjustScalarBytes,
2213
+ // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached
2214
+ // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.
2215
+ // Same construction as libsodium's crypto_scalarmult_curve25519_base.
2216
+ scalarMultBase: (k) => {
2217
+ const kn = mod(k, ed25519_Point.Fn.ORDER);
2218
+ if (kn === _0n6)
2219
+ return _0n6;
2220
+ const p = ed25519_Point.BASE.multiply(kn);
2221
+ return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);
2222
+ }
2057
2223
  });
2058
2224
  })();
2059
- var SQRT_M1 = ED25519_SQRT_M1;
2060
- var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
2061
- var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
2062
- var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
2063
- var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
2064
- var invertSqrt = (number) => uvRatio(_1n6, number);
2065
- var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2066
- var bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
2067
- function calcElligatorRistrettoMap(r0) {
2068
- const { d } = ed25519_CURVE;
2069
- const P = ed25519_CURVE_p;
2070
- const mod2 = (n) => Fp.create(n);
2071
- const r = mod2(SQRT_M1 * r0 * r0);
2072
- const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
2073
- let c = BigInt(-1);
2074
- const D = mod2((c - d * r) * mod2(r + d));
2075
- let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
2076
- let s_ = mod2(s * r0);
2077
- if (!isNegativeLE(s_, P))
2078
- s_ = mod2(-s_);
2079
- if (!Ns_D_is_sq)
2080
- s = s_;
2081
- if (!Ns_D_is_sq)
2082
- c = r;
2083
- const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2084
- const s2 = s * s;
2085
- const W0 = mod2((s + s) * D);
2086
- const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2087
- const W2 = mod2(_1n6 - s2);
2088
- const W3 = mod2(_1n6 + s2);
2089
- return new ed25519_Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2090
- }
2091
- var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2092
- // Do NOT change syntax: the following gymnastics is done,
2093
- // because typescript strips comments, which makes bundlers disable tree-shaking.
2094
- // prettier-ignore
2095
- static BASE = /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.BASE))();
2096
- // prettier-ignore
2097
- static ZERO = /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.ZERO))();
2098
- // prettier-ignore
2099
- static Fp = /* @__PURE__ */ (() => Fp)();
2100
- // prettier-ignore
2101
- static Fn = /* @__PURE__ */ (() => Fn)();
2102
- constructor(ep) {
2103
- super(ep);
2104
- }
2105
- /**
2106
- * Create one Ristretto255 point from affine Edwards coordinates.
2107
- * This wraps the internal Edwards representative directly and is not a
2108
- * canonical ristretto255 decoding path.
2109
- * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
2110
- */
2111
- static fromAffine(ap) {
2112
- return new __RistrettoPoint(ed25519_Point.fromAffine(ap));
2113
- }
2114
- assertSame(other) {
2115
- if (!(other instanceof __RistrettoPoint))
2116
- throw new Error("RistrettoPoint expected");
2117
- }
2118
- init(ep) {
2119
- return new __RistrettoPoint(ep);
2120
- }
2121
- static fromBytes(bytes) {
2122
- abytes(bytes, 32);
2123
- const { a, d } = ed25519_CURVE;
2124
- const P = ed25519_CURVE_p;
2125
- const mod2 = (n) => Fp.create(n);
2126
- const s = bytes255ToNumberLE(bytes);
2127
- if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2128
- throw new Error("invalid ristretto255 encoding 1");
2129
- const s2 = mod2(s * s);
2130
- const u1 = mod2(_1n6 + a * s2);
2131
- const u2 = mod2(_1n6 - a * s2);
2132
- const u1_2 = mod2(u1 * u1);
2133
- const u2_2 = mod2(u2 * u2);
2134
- const v = mod2(a * d * u1_2 - u2_2);
2135
- const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2136
- const Dx = mod2(I * u2);
2137
- const Dy = mod2(I * Dx * v);
2138
- let x = mod2((s + s) * Dx);
2139
- if (isNegativeLE(x, P))
2140
- x = mod2(-x);
2141
- const y = mod2(u1 * Dy);
2142
- const t = mod2(x * y);
2143
- if (!isValid || isNegativeLE(t, P) || y === _0n6)
2144
- throw new Error("invalid ristretto255 encoding 2");
2145
- return new __RistrettoPoint(new ed25519_Point(x, y, _1n6, t));
2146
- }
2147
- /**
2148
- * Converts ristretto-encoded string to ristretto point.
2149
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2150
- * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2151
- */
2152
- static fromHex(hex) {
2153
- return __RistrettoPoint.fromBytes(hexToBytes(hex));
2154
- }
2155
- /**
2156
- * Encodes ristretto point to Uint8Array.
2157
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2158
- */
2159
- toBytes() {
2160
- let { X, Y, Z, T } = this.ep;
2161
- const P = ed25519_CURVE_p;
2162
- const mod2 = (n) => Fp.create(n);
2163
- const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2164
- const u2 = mod2(X * Y);
2165
- const u2sq = mod2(u2 * u2);
2166
- const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2167
- const D1 = mod2(invsqrt * u1);
2168
- const D2 = mod2(invsqrt * u2);
2169
- const zInv = mod2(D1 * D2 * T);
2170
- let D;
2171
- if (isNegativeLE(T * zInv, P)) {
2172
- let _x = mod2(Y * SQRT_M1);
2173
- let _y = mod2(X * SQRT_M1);
2174
- X = _x;
2175
- Y = _y;
2176
- D = mod2(D1 * INVSQRT_A_MINUS_D);
2177
- } else {
2178
- D = D2;
2179
- }
2180
- if (isNegativeLE(X * zInv, P))
2181
- Y = mod2(-Y);
2182
- let s = mod2((Z - Y) * D);
2183
- if (isNegativeLE(s, P))
2184
- s = mod2(-s);
2185
- return Fp.toBytes(s);
2186
- }
2187
- /**
2188
- * Compares two Ristretto points.
2189
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2190
- */
2191
- equals(other) {
2192
- this.assertSame(other);
2193
- const { X: X1, Y: Y1 } = this.ep;
2194
- const { X: X2, Y: Y2 } = other.ep;
2195
- const mod2 = (n) => Fp.create(n);
2196
- const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2197
- const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2198
- return one || two;
2199
- }
2200
- is0() {
2201
- return this.equals(__RistrettoPoint.ZERO);
2202
- }
2203
- };
2204
- Object.freeze(_RistrettoPoint.BASE);
2205
- Object.freeze(_RistrettoPoint.ZERO);
2206
- Object.freeze(_RistrettoPoint.prototype);
2207
- Object.freeze(_RistrettoPoint);
2208
- var ristretto255_hasher = Object.freeze({
2209
- Point: _RistrettoPoint,
2210
- /**
2211
- * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
2212
- * * There are no test vectors
2213
- * * encodeToCurve / mapToCurve is undefined
2214
- * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!
2215
- * * hashToScalar is undefined too, so we just use OPRF implementation
2216
- * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
2217
- (os2ip -> bytes255ToNumberLE)
2218
- * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
2219
- * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
2220
- version here. Using `bytes255ToNumblerLE` will create a different result
2221
- if we use `bytes255ToNumberLE` as os2ip
2222
- * * current version is closest to spec.
2223
- */
2224
- hashToCurve(msg, options) {
2225
- const DST = options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2226
- const xmd = expand_message_xmd(msg, DST, 64, sha512);
2227
- return ristretto255_hasher.deriveToCurve(xmd);
2228
- },
2229
- hashToScalar(msg, options = { DST: _DST_scalar }) {
2230
- const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2231
- return Fn.create(bytesToNumberLE(xmd));
2232
- },
2233
- /**
2234
- * HashToCurve-like construction based on RFC 9496 (Element Derivation).
2235
- * Converts 64 uniform random bytes into a curve point.
2236
- *
2237
- * WARNING: This represents an older hash-to-curve construction from before
2238
- * RFC 9380 was finalized.
2239
- * It was later reused as a component in the newer
2240
- * `hash_to_ristretto255` function defined in RFC 9380.
2241
- */
2242
- deriveToCurve(bytes) {
2243
- abytes(bytes, 64);
2244
- const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2245
- const R1 = calcElligatorRistrettoMap(r1);
2246
- const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2247
- const R2 = calcElligatorRistrettoMap(r2);
2248
- return new _RistrettoPoint(R1.add(R2));
2249
- }
2250
- });
2251
2225
 
2252
2226
  // ../../node_modules/@noble/hashes/_blake.js
2253
2227
  var BSIGMA = /* @__PURE__ */ Uint8Array.from([
@@ -2509,15 +2483,15 @@ var BSIGMA = /* @__PURE__ */ Uint8Array.from([
2509
2483
  1,
2510
2484
  9
2511
2485
  ]);
2512
- function G1s(a, b, c, d, x) {
2513
- a = a + b + x | 0;
2486
+ function G1s(a, b, c, d, x2) {
2487
+ a = a + b + x2 | 0;
2514
2488
  d = rotr(d ^ a, 16);
2515
2489
  c = c + d | 0;
2516
2490
  b = rotr(b ^ c, 12);
2517
2491
  return { a, b, c, d };
2518
2492
  }
2519
- function G2s(a, b, c, d, x) {
2520
- a = a + b + x | 0;
2493
+ function G2s(a, b, c, d, x2) {
2494
+ a = a + b + x2 | 0;
2521
2495
  d = rotr(d ^ a, 8);
2522
2496
  c = c + d | 0;
2523
2497
  b = rotr(b ^ c, 7);
@@ -2528,7 +2502,7 @@ function G2s(a, b, c, d, x) {
2528
2502
  function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
2529
2503
  anumber(keyLen);
2530
2504
  if (outputLen <= 0 || outputLen > keyLen)
2531
- throw new Error("outputLen bigger than keyLen");
2505
+ throw new Error('"dkLen" must be 1..' + keyLen + ", got " + outputLen);
2532
2506
  const { key, salt, personalization } = opts;
2533
2507
  if (key !== void 0 && (key.length < 1 || key.length > keyLen))
2534
2508
  throw new Error('"key" expected to be undefined or of length=1..' + keyLen);
@@ -2581,7 +2555,7 @@ var _BLAKE2 = class {
2581
2555
  swap32IfBE(data32);
2582
2556
  continue;
2583
2557
  }
2584
- buffer.set(data.subarray(pos, pos + take), this.pos);
2558
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
2585
2559
  this.pos += take;
2586
2560
  this.length += take;
2587
2561
  pos += take;
@@ -2591,26 +2565,26 @@ var _BLAKE2 = class {
2591
2565
  digestInto(out) {
2592
2566
  aexists(this);
2593
2567
  aoutput(out, this);
2568
+ if (out.byteOffset & 3)
2569
+ throw new RangeError('"output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
2594
2570
  const { pos, buffer32 } = this;
2595
2571
  this.finished = true;
2596
- clean(this.buffer.subarray(pos));
2572
+ this.buffer.fill(0, pos);
2597
2573
  swap32IfBE(buffer32);
2598
2574
  this.compress(buffer32, 0, true);
2599
2575
  swap32IfBE(buffer32);
2600
- if (out.byteOffset & 3)
2601
- throw new RangeError('"digestInto() output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
2602
2576
  const state = this.get();
2603
- const out32 = u32(out);
2577
+ const out32 = out === this.buffer ? buffer32 : u32(out);
2604
2578
  const full = Math.floor(this.outputLen / 4);
2605
- for (let i = 0; i < full; i++)
2606
- out32[i] = swap8IfBE(state[i]);
2579
+ for (let i2 = 0; i2 < full; i2++)
2580
+ out32[i2] = swap8IfBE(state[i2]);
2607
2581
  const tail = this.outputLen % 4;
2608
2582
  if (!tail)
2609
2583
  return;
2610
2584
  const off = full * 4;
2611
2585
  const word = state[full];
2612
- for (let i = 0; i < tail; i++)
2613
- out[off + i] = word >>> 8 * i;
2586
+ for (let i2 = 0; i2 < tail; i2++)
2587
+ out[off + i2] = word >>> 8 * i2;
2614
2588
  }
2615
2589
  digest() {
2616
2590
  const { buffer, outputLen } = this;
@@ -2635,9 +2609,9 @@ var _BLAKE2 = class {
2635
2609
  return this._cloneInto();
2636
2610
  }
2637
2611
  };
2638
- function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
2612
+ function _compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
2639
2613
  let j = 0;
2640
- for (let i = 0; i < rounds; i++) {
2614
+ for (let i2 = 0; i2 < rounds; i2++) {
2641
2615
  ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
2642
2616
  ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
2643
2617
  ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
@@ -2669,6 +2643,7 @@ var _BLAKE2s = class extends _BLAKE2 {
2669
2643
  v6 = B2S_IV[6] | 0;
2670
2644
  v7 = B2S_IV[7] | 0;
2671
2645
  constructor(opts = {}) {
2646
+ opts = checkOpts({}, opts);
2672
2647
  const olen = opts.dkLen === void 0 ? 32 : opts.dkLen;
2673
2648
  super(64, olen);
2674
2649
  checkBlake2Opts(olen, opts, 32, 8, 8);
@@ -2681,13 +2656,13 @@ var _BLAKE2s = class extends _BLAKE2 {
2681
2656
  this.v0 ^= this.outputLen | keyLength << 8 | 1 << 16 | 1 << 24;
2682
2657
  if (salt !== void 0) {
2683
2658
  abytes(salt, void 0, "salt");
2684
- const slt = u32(salt);
2659
+ const slt = u32(copyBytes(salt));
2685
2660
  this.v4 ^= swap8IfBE(slt[0]);
2686
2661
  this.v5 ^= swap8IfBE(slt[1]);
2687
2662
  }
2688
2663
  if (personalization !== void 0) {
2689
2664
  abytes(personalization, void 0, "personalization");
2690
- const pers = u32(personalization);
2665
+ const pers = u32(copyBytes(personalization));
2691
2666
  this.v6 ^= swap8IfBE(pers[0]);
2692
2667
  this.v7 ^= swap8IfBE(pers[1]);
2693
2668
  }
@@ -2695,6 +2670,7 @@ var _BLAKE2s = class extends _BLAKE2 {
2695
2670
  const tmp = new Uint8Array(this.blockLen);
2696
2671
  tmp.set(key);
2697
2672
  this.update(tmp);
2673
+ clean(tmp);
2698
2674
  }
2699
2675
  }
2700
2676
  get() {
@@ -2713,8 +2689,9 @@ var _BLAKE2s = class extends _BLAKE2 {
2713
2689
  this.v7 = v7 | 0;
2714
2690
  }
2715
2691
  compress(msg, offset, isLast) {
2716
- const { h, l } = fromBig(BigInt(this.length));
2717
- const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);
2692
+ const l = fromNumL(this.length);
2693
+ const h = fromNumH(this.length);
2694
+ const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);
2718
2695
  this.v0 ^= v0 ^ v8;
2719
2696
  this.v1 ^= v1 ^ v9;
2720
2697
  this.v2 ^= v2 ^ v10;
@@ -2746,18 +2723,18 @@ var _HMAC = class {
2746
2723
  abytes(key, void 0, "key");
2747
2724
  this.iHash = hash.create();
2748
2725
  if (typeof this.iHash.update !== "function")
2749
- throw new Error("Expected instance of class which extends utils.Hash");
2726
+ throw new Error("expected Hash instance");
2750
2727
  this.blockLen = this.iHash.blockLen;
2751
2728
  this.outputLen = this.iHash.outputLen;
2752
2729
  const blockLen = this.blockLen;
2753
2730
  const pad = new Uint8Array(blockLen);
2754
2731
  pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2755
- for (let i = 0; i < pad.length; i++)
2756
- pad[i] ^= 54;
2732
+ for (let i2 = 0; i2 < pad.length; i2++)
2733
+ pad[i2] ^= 54;
2757
2734
  this.iHash.update(pad);
2758
2735
  this.oHash = hash.create();
2759
- for (let i = 0; i < pad.length; i++)
2760
- pad[i] ^= 54 ^ 92;
2736
+ for (let i2 = 0; i2 < pad.length; i2++)
2737
+ pad[i2] ^= 54 ^ 92;
2761
2738
  this.oHash.update(pad);
2762
2739
  clean(pad);
2763
2740
  }
@@ -2783,12 +2760,13 @@ var _HMAC = class {
2783
2760
  }
2784
2761
  _cloneInto(to) {
2785
2762
  to ||= Object.create(Object.getPrototypeOf(this), {});
2786
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
2763
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;
2787
2764
  to = to;
2788
2765
  to.finished = finished;
2789
2766
  to.destroyed = destroyed;
2790
2767
  to.blockLen = blockLen;
2791
2768
  to.outputLen = outputLen;
2769
+ to.canXOF = canXOF;
2792
2770
  to.oHash = oHash._cloneInto(to.oHash);
2793
2771
  to.iHash = iHash._cloneInto(to.iHash);
2794
2772
  return to;
@@ -2809,15 +2787,9 @@ var hmac = /* @__PURE__ */ (() => {
2809
2787
  })();
2810
2788
 
2811
2789
  // ../../node_modules/@noble/hashes/hkdf.js
2812
- function extract(hash, ikm, salt) {
2813
- ahash(hash);
2814
- if (salt === void 0)
2815
- salt = new Uint8Array(hash.outputLen);
2816
- return hmac(hash, salt, ikm);
2817
- }
2818
2790
  var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
2819
2791
  var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
2820
- function expand(hash, prk, info, length = 32) {
2792
+ function expand(hash, prk, info, length = 32, _recycled) {
2821
2793
  ahash(hash);
2822
2794
  anumber(length, "length");
2823
2795
  abytes(prk, void 0, "prk");
@@ -2831,99 +2803,144 @@ function expand(hash, prk, info, length = 32) {
2831
2803
  info = EMPTY_BUFFER;
2832
2804
  else
2833
2805
  abytes(info, void 0, "info");
2834
- const okm = new Uint8Array(blocks * olen);
2835
- const HMAC = hmac.create(hash, prk);
2836
- const HMACTmp = HMAC._cloneInto();
2837
- const T = new Uint8Array(HMAC.outputLen);
2838
- for (let counter = 0; counter < blocks; counter++) {
2806
+ if (!blocks) {
2807
+ if (_recycled)
2808
+ clean(prk);
2809
+ return new Uint8Array();
2810
+ }
2811
+ const okm = _recycled && blocks === 1 ? prk : new Uint8Array(blocks * olen);
2812
+ const { iHash, oHash } = hmac.create(hash, prk);
2813
+ const T = _recycled ? prk : new Uint8Array(olen);
2814
+ const worker = blocks > 1 ? _recycled?.iHash || hash.create() : void 0;
2815
+ for (let counter = 0; counter < blocks - 1; counter++) {
2839
2816
  HKDF_COUNTER[0] = counter + 1;
2840
- HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
2817
+ const iWork = iHash._cloneInto(worker);
2818
+ if (counter)
2819
+ iWork.update(T);
2820
+ iWork.update(info).update(HKDF_COUNTER).digestInto(T);
2821
+ oHash._cloneInto(worker).update(T).digestInto(T);
2841
2822
  okm.set(T, olen * counter);
2842
- HMAC._cloneInto(HMACTmp);
2843
2823
  }
2844
- HMAC.destroy();
2845
- HMACTmp.destroy();
2846
- clean(T, HKDF_COUNTER);
2847
- return okm.slice(0, length);
2824
+ HKDF_COUNTER[0] = blocks;
2825
+ if (blocks > 1)
2826
+ iHash.update(T);
2827
+ iHash.update(info).update(HKDF_COUNTER).digestInto(T);
2828
+ oHash.update(T).digestInto(T);
2829
+ okm.set(T, olen * (blocks - 1));
2830
+ iHash.destroy();
2831
+ oHash.destroy();
2832
+ worker?.destroy();
2833
+ if (T !== okm)
2834
+ clean(T);
2835
+ clean(HKDF_COUNTER);
2836
+ if (length === okm.length)
2837
+ return okm;
2838
+ const res = okm.slice(0, length);
2839
+ clean(okm);
2840
+ return res;
2848
2841
  }
2849
- var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
2842
+ var hkdf = (hash, ikm, salt, info, length) => {
2843
+ ahash(hash);
2844
+ if (salt === void 0)
2845
+ salt = new Uint8Array(hash.outputLen);
2846
+ const HMAC = hmac.create(hash, salt).update(ikm);
2847
+ return expand(hash, HMAC.digest(), info, length, HMAC);
2848
+ };
2850
2849
 
2851
2850
  // ../../node_modules/@noble/ciphers/utils.js
2852
2851
  function isBytes3(a) {
2853
2852
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
2854
2853
  }
2855
- function abool2(b) {
2856
- if (typeof b !== "boolean")
2857
- throw new TypeError(`boolean expected, not ${b}`);
2854
+ var atitle3 = (title) => title ? `"${title}" ` : "";
2855
+ function abool2(value, title = "") {
2856
+ if (typeof value !== "boolean")
2857
+ throw new TypeError(atitle3(title) + "expected boolean, got type=" + typeof value);
2858
+ return value;
2858
2859
  }
2859
- function anumber3(n) {
2860
+ function anumber3(n, title = "") {
2860
2861
  if (typeof n !== "number")
2861
- throw new TypeError("number expected, got " + typeof n);
2862
+ throw new TypeError(atitle3(title) + "expected number, got " + typeof n);
2862
2863
  if (!Number.isSafeInteger(n) || n < 0)
2863
- throw new RangeError("positive integer expected, got " + n);
2864
+ throw new RangeError(atitle3(title) + "expected integer >= 0, got " + n);
2865
+ return n;
2864
2866
  }
2865
2867
  function abytes3(value, length, title = "") {
2868
+ if (isBytes3(value) && (length === void 0 || value.length === length))
2869
+ return value;
2870
+ if (length !== void 0)
2871
+ anumber3(length, "length");
2866
2872
  const bytes = isBytes3(value);
2867
- const len = value?.length;
2868
- const needsLen = length !== void 0;
2869
- if (!bytes || needsLen && len !== length) {
2870
- const prefix = title && `"${title}" `;
2871
- const ofLen = needsLen ? ` of length ${length}` : "";
2872
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
2873
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
2874
- if (!bytes)
2875
- throw new TypeError(message);
2876
- throw new RangeError(message);
2877
- }
2878
- return value;
2879
- }
2873
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
2874
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
2875
+ const message = atitle3(title) + "expected Uint8Array" + ofLen + ", got " + got;
2876
+ if (!bytes)
2877
+ throw new TypeError(message);
2878
+ throw new RangeError(message);
2879
+ }
2880
+ var aobject3 = (value, label) => {
2881
+ if (value === null || typeof value !== "object" || Array.isArray(value))
2882
+ throw new TypeError(label === "object" ? "expected valid options object" : `"${label}" expected object, got type=${typeof value}`);
2883
+ };
2880
2884
  function aexists2(instance, checkFinished = true) {
2881
2885
  if (instance.destroyed)
2882
- throw new Error("Hash instance has been destroyed");
2886
+ throw new Error("hash was destroyed");
2883
2887
  if (checkFinished && instance.finished)
2884
- throw new Error("Hash#digest() has already been called");
2888
+ throw new Error("digest() was already called");
2885
2889
  }
2886
- function aoutput2(out, instance, onlyAligned = false) {
2890
+ function aoutput2(out, instance) {
2887
2891
  abytes3(out, void 0, "output");
2888
2892
  const min = instance.outputLen;
2889
- if (out.length < min) {
2890
- throw new RangeError("digestInto() expects output buffer of length at least " + min);
2893
+ if (!(out.length >= min)) {
2894
+ throw new RangeError('"output" expected length >= ' + min);
2891
2895
  }
2892
- if (onlyAligned && !isAligned32(out))
2893
- throw new Error("invalid output, must be aligned");
2894
2896
  }
2895
2897
  function u322(arr) {
2896
2898
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
2897
2899
  }
2898
2900
  function clean2(...arrays) {
2899
- for (let i = 0; i < arrays.length; i++) {
2900
- arrays[i].fill(0);
2901
+ for (let i2 = 0; i2 < arrays.length; i2++) {
2902
+ arrays[i2].fill(0);
2901
2903
  }
2902
2904
  }
2903
2905
  function createView2(arr) {
2904
2906
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2905
2907
  }
2906
2908
  var isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
2907
- var byteSwap2 = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
2908
- var swap8IfBE2 = isLE2 ? (n) => n : (n) => byteSwap2(n) >>> 0;
2909
- var byteSwap322 = (arr) => {
2910
- for (let i = 0; i < arr.length; i++)
2911
- arr[i] = byteSwap2(arr[i]);
2909
+ function byteSwap2(word) {
2910
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
2911
+ }
2912
+ function byteSwap322(arr) {
2913
+ for (let i2 = 0; i2 < arr.length; i2++) {
2914
+ arr[i2] = byteSwap2(arr[i2]);
2915
+ }
2912
2916
  return arr;
2913
- };
2917
+ }
2914
2918
  var swap32IfBE2 = isLE2 ? (u) => u : byteSwap322;
2915
- function checkOpts(defaults, opts) {
2916
- if (opts == null || typeof opts !== "object")
2917
- throw new Error("options must be defined");
2919
+ function overlapBytes(a, b) {
2920
+ if (!a.byteLength || !b.byteLength)
2921
+ return false;
2922
+ return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
2923
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
2924
+ b.byteOffset < a.byteOffset + a.byteLength;
2925
+ }
2926
+ function complexOverlapBytes(input, output) {
2927
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
2928
+ throw new Error("complex overlap of input and output is not supported");
2929
+ }
2930
+ function checkOpts2(defaults, opts) {
2931
+ aobject3(defaults, "defaults");
2932
+ aobject3(opts, "opts");
2918
2933
  const merged = Object.assign(defaults, opts);
2919
2934
  return merged;
2920
2935
  }
2921
- function equalBytes2(a, b) {
2936
+ function equalBytes(a, b) {
2937
+ a = abytes3(a);
2938
+ b = abytes3(b);
2922
2939
  if (a.length !== b.length)
2923
2940
  return false;
2924
2941
  let diff = 0;
2925
- for (let i = 0; i < a.length; i++)
2926
- diff |= a[i] ^ b[i];
2942
+ for (let i2 = 0; i2 < a.length; i2++)
2943
+ diff |= a[i2] ^ b[i2];
2927
2944
  return diff === 0;
2928
2945
  }
2929
2946
  function wrapMacConstructor(keyLen, macCons, fromMsg) {
@@ -2944,8 +2961,14 @@ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
2944
2961
  abytes3(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce");
2945
2962
  }
2946
2963
  const tagl = params.tagLength;
2947
- if (tagl && args[1] !== void 0)
2948
- abytes3(args[1], void 0, "AAD");
2964
+ const aadStart = params.nonceLength !== void 0 ? 1 : 0;
2965
+ if (!params.withAAD) {
2966
+ for (let i2 = aadStart; i2 < args.length; i2++)
2967
+ if (isBytes3(args[i2]))
2968
+ throw new Error("AAD not supported");
2969
+ }
2970
+ if (params.withAAD && args[aadStart] !== void 0)
2971
+ abytes3(args[aadStart], void 0, "AAD");
2949
2972
  const cipher = constructor(key, ...args);
2950
2973
  const checkOutput = (fnLength, output) => {
2951
2974
  if (output !== void 0) {
@@ -2960,14 +2983,14 @@ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
2960
2983
  if (called)
2961
2984
  throw new Error("cannot encrypt() twice with same key + nonce");
2962
2985
  called = true;
2963
- abytes3(data);
2986
+ abytes3(data, void 0, "data");
2964
2987
  checkOutput(cipher.encrypt.length, output);
2965
2988
  return cipher.encrypt(data, output);
2966
2989
  },
2967
2990
  decrypt(data, output) {
2968
- abytes3(data);
2991
+ abytes3(data, void 0, "data");
2969
2992
  if (tagl && data.length < tagl)
2970
- throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl);
2993
+ throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
2971
2994
  checkOutput(cipher.decrypt.length, output);
2972
2995
  return cipher.decrypt(data, output);
2973
2996
  }
@@ -2980,9 +3003,7 @@ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
2980
3003
  function getOutput(expectedLength, out, onlyAligned = true) {
2981
3004
  if (out === void 0)
2982
3005
  return new Uint8Array(expectedLength);
2983
- abytes3(out, void 0, "output");
2984
- if (out.length !== expectedLength)
2985
- throw new Error('"output" expected Uint8Array of length ' + expectedLength + ", got: " + out.length);
3006
+ abytes3(out, expectedLength, "output");
2986
3007
  if (onlyAligned && !isAligned32(out))
2987
3008
  throw new Error("invalid output, must be aligned");
2988
3009
  return out;
@@ -3000,7 +3021,7 @@ function u64Lengths(dataLength, aadLength, isLE3) {
3000
3021
  function isAligned32(bytes) {
3001
3022
  return bytes.byteOffset % 4 === 0;
3002
3023
  }
3003
- function copyBytes2(bytes) {
3024
+ function copyBytes3(bytes) {
3004
3025
  return Uint8Array.from(abytes3(bytes));
3005
3026
  }
3006
3027
 
@@ -3061,7 +3082,7 @@ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
3061
3082
  }
3062
3083
  }
3063
3084
  function createCipher(core, opts) {
3064
- const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
3085
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts2({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
3065
3086
  if (typeof core !== "function")
3066
3087
  throw new Error("core must be a function");
3067
3088
  anumber3(counterLength);
@@ -3073,7 +3094,10 @@ function createCipher(core, opts) {
3073
3094
  abytes3(nonce, void 0, "nonce");
3074
3095
  abytes3(data, void 0, "data");
3075
3096
  const len = data.length;
3097
+ const hasOutput = output !== void 0;
3076
3098
  output = getOutput(len, output, false);
3099
+ if (hasOutput)
3100
+ complexOverlapBytes(data, output);
3077
3101
  anumber3(counter);
3078
3102
  if (counter < 0 || counter >= MAX_COUNTER)
3079
3103
  throw new Error("arx: counter overflow");
@@ -3082,7 +3106,7 @@ function createCipher(core, opts) {
3082
3106
  let k;
3083
3107
  let sigma;
3084
3108
  if (l === 32) {
3085
- toClean.push(k = copyBytes2(key));
3109
+ toClean.push(k = copyBytes3(key));
3086
3110
  sigma = sigma32_32;
3087
3111
  } else if (l === 16 && allowShortKeys) {
3088
3112
  k = new Uint8Array(32);
@@ -3095,11 +3119,11 @@ function createCipher(core, opts) {
3095
3119
  throw new Error("invalid key size");
3096
3120
  }
3097
3121
  if (!isLE2 || !isAligned32(nonce))
3098
- toClean.push(nonce = copyBytes2(nonce));
3122
+ toClean.push(nonce = copyBytes3(nonce));
3099
3123
  let k32 = u322(k);
3100
3124
  if (extendNonceFn) {
3101
3125
  if (nonce.length !== 24)
3102
- throw new Error(`arx: extended nonce must be 24 bytes`);
3126
+ throw new Error("arx: extended nonce must be 24 bytes");
3103
3127
  const n16 = nonce.subarray(0, 16);
3104
3128
  if (isLE2)
3105
3129
  extendNonceFn(sigma, k32, u322(n16), k32);
@@ -3132,8 +3156,8 @@ function createCipher(core, opts) {
3132
3156
  }
3133
3157
 
3134
3158
  // ../../node_modules/@noble/ciphers/_poly1305.js
3135
- function u8to16(a, i) {
3136
- return a[i++] & 255 | (a[i++] & 255) << 8;
3159
+ function u8to16(a, i2) {
3160
+ return a[i2++] & 255 | (a[i2++] & 255) << 8;
3137
3161
  }
3138
3162
  var Poly1305 = class {
3139
3163
  blockLen = 16;
@@ -3148,7 +3172,7 @@ var Poly1305 = class {
3148
3172
  destroyed = false;
3149
3173
  // Can be speed-up using BigUint64Array, at the cost of complexity
3150
3174
  constructor(key) {
3151
- key = copyBytes2(abytes3(key, 32, "key"));
3175
+ key = copyBytes3(abytes3(key, 32, "key"));
3152
3176
  const t0 = u8to16(key, 0);
3153
3177
  const t1 = u8to16(key, 2);
3154
3178
  const t2 = u8to16(key, 4);
@@ -3167,8 +3191,8 @@ var Poly1305 = class {
3167
3191
  this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
3168
3192
  this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
3169
3193
  this.r[9] = t7 >>> 5 & 127;
3170
- for (let i = 0; i < 8; i++)
3171
- this.pad[i] = u8to16(key, 16 + 2 * i);
3194
+ for (let i2 = 0; i2 < 8; i2++)
3195
+ this.pad[i2] = u8to16(key, 16 + 2 * i2);
3172
3196
  }
3173
3197
  process(data, offset, isLast = false) {
3174
3198
  const hibit = isLast ? 0 : 1 << 11;
@@ -3283,10 +3307,10 @@ var Poly1305 = class {
3283
3307
  const g = new Uint16Array(10);
3284
3308
  let c = h[1] >>> 13;
3285
3309
  h[1] &= 8191;
3286
- for (let i = 2; i < 10; i++) {
3287
- h[i] += c;
3288
- c = h[i] >>> 13;
3289
- h[i] &= 8191;
3310
+ for (let i2 = 2; i2 < 10; i2++) {
3311
+ h[i2] += c;
3312
+ c = h[i2] >>> 13;
3313
+ h[i2] &= 8191;
3290
3314
  }
3291
3315
  h[0] += c * 5;
3292
3316
  c = h[0] >>> 13;
@@ -3298,18 +3322,18 @@ var Poly1305 = class {
3298
3322
  g[0] = h[0] + 5;
3299
3323
  c = g[0] >>> 13;
3300
3324
  g[0] &= 8191;
3301
- for (let i = 1; i < 10; i++) {
3302
- g[i] = h[i] + c;
3303
- c = g[i] >>> 13;
3304
- g[i] &= 8191;
3325
+ for (let i2 = 1; i2 < 10; i2++) {
3326
+ g[i2] = h[i2] + c;
3327
+ c = g[i2] >>> 13;
3328
+ g[i2] &= 8191;
3305
3329
  }
3306
3330
  g[9] -= 1 << 13;
3307
3331
  let mask = (c ^ 1) - 1;
3308
- for (let i = 0; i < 10; i++)
3309
- g[i] &= mask;
3332
+ for (let i2 = 0; i2 < 10; i2++)
3333
+ g[i2] &= mask;
3310
3334
  mask = ~mask;
3311
- for (let i = 0; i < 10; i++)
3312
- h[i] = h[i] & mask | g[i];
3335
+ for (let i2 = 0; i2 < 10; i2++)
3336
+ h[i2] = h[i2] & mask | g[i2];
3313
3337
  h[0] = (h[0] | h[1] << 13) & 65535;
3314
3338
  h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
3315
3339
  h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
@@ -3320,16 +3344,16 @@ var Poly1305 = class {
3320
3344
  h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
3321
3345
  let f = h[0] + pad[0];
3322
3346
  h[0] = f & 65535;
3323
- for (let i = 1; i < 8; i++) {
3324
- f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
3325
- h[i] = f & 65535;
3347
+ for (let i2 = 1; i2 < 8; i2++) {
3348
+ f = (h[i2] + pad[i2] | 0) + (f >>> 16) | 0;
3349
+ h[i2] = f & 65535;
3326
3350
  }
3327
3351
  clean2(g);
3328
3352
  }
3329
3353
  update(data) {
3330
3354
  aexists2(this);
3331
3355
  abytes3(data);
3332
- data = copyBytes2(data);
3356
+ data = copyBytes3(data);
3333
3357
  const { buffer, blockLen } = this;
3334
3358
  const len = data.length;
3335
3359
  for (let pos = 0; pos < len; ) {
@@ -3367,9 +3391,9 @@ var Poly1305 = class {
3367
3391
  }
3368
3392
  this.finalize();
3369
3393
  let opos = 0;
3370
- for (let i = 0; i < 8; i++) {
3371
- out[opos++] = h[i] >>> 0;
3372
- out[opos++] = h[i] >>> 8;
3394
+ for (let i2 = 0; i2 < 8; i2++) {
3395
+ out[opos++] = h[i2] >>> 0;
3396
+ out[opos++] = h[i2] >>> 8;
3373
3397
  }
3374
3398
  }
3375
3399
  digest() {
@@ -3470,84 +3494,25 @@ function chachaCore(s, k, n, out, cnt, rounds = 20) {
3470
3494
  out[oi++] = y14 + x14 | 0;
3471
3495
  out[oi++] = y15 + x15 | 0;
3472
3496
  }
3473
- function hchacha(s, k, i, out) {
3474
- let x00 = swap8IfBE2(s[0]), x01 = swap8IfBE2(s[1]), x02 = swap8IfBE2(s[2]), x03 = swap8IfBE2(s[3]), x04 = swap8IfBE2(k[0]), x05 = swap8IfBE2(k[1]), x06 = swap8IfBE2(k[2]), x07 = swap8IfBE2(k[3]), x08 = swap8IfBE2(k[4]), x09 = swap8IfBE2(k[5]), x10 = swap8IfBE2(k[6]), x11 = swap8IfBE2(k[7]), x12 = swap8IfBE2(i[0]), x13 = swap8IfBE2(i[1]), x14 = swap8IfBE2(i[2]), x15 = swap8IfBE2(i[3]);
3475
- for (let r = 0; r < 20; r += 2) {
3476
- x00 = x00 + x04 | 0;
3477
- x12 = rotl(x12 ^ x00, 16);
3478
- x08 = x08 + x12 | 0;
3479
- x04 = rotl(x04 ^ x08, 12);
3480
- x00 = x00 + x04 | 0;
3481
- x12 = rotl(x12 ^ x00, 8);
3482
- x08 = x08 + x12 | 0;
3483
- x04 = rotl(x04 ^ x08, 7);
3484
- x01 = x01 + x05 | 0;
3485
- x13 = rotl(x13 ^ x01, 16);
3486
- x09 = x09 + x13 | 0;
3487
- x05 = rotl(x05 ^ x09, 12);
3488
- x01 = x01 + x05 | 0;
3489
- x13 = rotl(x13 ^ x01, 8);
3490
- x09 = x09 + x13 | 0;
3491
- x05 = rotl(x05 ^ x09, 7);
3492
- x02 = x02 + x06 | 0;
3493
- x14 = rotl(x14 ^ x02, 16);
3494
- x10 = x10 + x14 | 0;
3495
- x06 = rotl(x06 ^ x10, 12);
3496
- x02 = x02 + x06 | 0;
3497
- x14 = rotl(x14 ^ x02, 8);
3498
- x10 = x10 + x14 | 0;
3499
- x06 = rotl(x06 ^ x10, 7);
3500
- x03 = x03 + x07 | 0;
3501
- x15 = rotl(x15 ^ x03, 16);
3502
- x11 = x11 + x15 | 0;
3503
- x07 = rotl(x07 ^ x11, 12);
3504
- x03 = x03 + x07 | 0;
3505
- x15 = rotl(x15 ^ x03, 8);
3506
- x11 = x11 + x15 | 0;
3507
- x07 = rotl(x07 ^ x11, 7);
3508
- x00 = x00 + x05 | 0;
3509
- x15 = rotl(x15 ^ x00, 16);
3510
- x10 = x10 + x15 | 0;
3511
- x05 = rotl(x05 ^ x10, 12);
3512
- x00 = x00 + x05 | 0;
3513
- x15 = rotl(x15 ^ x00, 8);
3514
- x10 = x10 + x15 | 0;
3515
- x05 = rotl(x05 ^ x10, 7);
3516
- x01 = x01 + x06 | 0;
3517
- x12 = rotl(x12 ^ x01, 16);
3518
- x11 = x11 + x12 | 0;
3519
- x06 = rotl(x06 ^ x11, 12);
3520
- x01 = x01 + x06 | 0;
3521
- x12 = rotl(x12 ^ x01, 8);
3522
- x11 = x11 + x12 | 0;
3523
- x06 = rotl(x06 ^ x11, 7);
3524
- x02 = x02 + x07 | 0;
3525
- x13 = rotl(x13 ^ x02, 16);
3526
- x08 = x08 + x13 | 0;
3527
- x07 = rotl(x07 ^ x08, 12);
3528
- x02 = x02 + x07 | 0;
3529
- x13 = rotl(x13 ^ x02, 8);
3530
- x08 = x08 + x13 | 0;
3531
- x07 = rotl(x07 ^ x08, 7);
3532
- x03 = x03 + x04 | 0;
3533
- x14 = rotl(x14 ^ x03, 16);
3534
- x09 = x09 + x14 | 0;
3535
- x04 = rotl(x04 ^ x09, 12);
3536
- x03 = x03 + x04 | 0;
3537
- x14 = rotl(x14 ^ x03, 8);
3538
- x09 = x09 + x14 | 0;
3539
- x04 = rotl(x04 ^ x09, 7);
3540
- }
3497
+ function hchacha(s, k, i2, out) {
3498
+ const s2 = isLE2 ? s : swap32IfBE2(s.slice(0, 4));
3499
+ const k2 = isLE2 ? k : swap32IfBE2(k.slice(0, 8));
3500
+ const i22 = isLE2 ? i2 : swap32IfBE2(i2.slice(0, 4));
3501
+ const t = new Uint32Array(16);
3502
+ chachaCore(s2, k2, i22.subarray(1), t, i22[0]);
3541
3503
  let oi = 0;
3542
- out[oi++] = x00;
3543
- out[oi++] = x01;
3544
- out[oi++] = x02;
3545
- out[oi++] = x03;
3546
- out[oi++] = x12;
3547
- out[oi++] = x13;
3548
- out[oi++] = x14;
3549
- out[oi++] = x15;
3504
+ out[oi++] = t[0] - s2[0] | 0;
3505
+ out[oi++] = t[1] - s2[1] | 0;
3506
+ out[oi++] = t[2] - s2[2] | 0;
3507
+ out[oi++] = t[3] - s2[3] | 0;
3508
+ out[oi++] = t[12] - i22[0] | 0;
3509
+ out[oi++] = t[13] - i22[1] | 0;
3510
+ out[oi++] = t[14] - i22[2] | 0;
3511
+ out[oi++] = t[15] - i22[3] | 0;
3550
3512
  swap32IfBE2(out);
3513
+ if (!isLE2)
3514
+ clean2(s2, k2, i22);
3515
+ clean2(t);
3551
3516
  }
3552
3517
  var chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
3553
3518
  counterRight: false,
@@ -3601,7 +3566,7 @@ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
3601
3566
  const data = ciphertext.subarray(0, -tagLength);
3602
3567
  const passedTag = ciphertext.subarray(-tagLength);
3603
3568
  const tag = computeTag(xorStream, key, nonce, data, AAD);
3604
- if (!equalBytes2(passedTag, tag)) {
3569
+ if (!equalBytes(passedTag, tag)) {
3605
3570
  clean2(tag);
3606
3571
  throw new Error("invalid tag");
3607
3572
  }
@@ -3613,11 +3578,11 @@ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
3613
3578
  };
3614
3579
  };
3615
3580
  var chacha20poly1305 = /* @__PURE__ */ wrapCipher(
3616
- { blockSize: 64, nonceLength: 12, tagLength: 16 },
3581
+ { blockSize: 64, nonceLength: 12, tagLength: 16, withAAD: true },
3617
3582
  /* @__PURE__ */ _poly1305_aead(chacha20)
3618
3583
  );
3619
3584
  var xchacha20poly1305 = /* @__PURE__ */ wrapCipher(
3620
- { blockSize: 64, nonceLength: 24, tagLength: 16 },
3585
+ { blockSize: 64, nonceLength: 24, tagLength: 16, withAAD: true },
3621
3586
  /* @__PURE__ */ _poly1305_aead(xchacha20)
3622
3587
  );
3623
3588
 
@@ -3668,8 +3633,8 @@ function hashBlake2s(data) {
3668
3633
  function noiseHkdf(chainingKey, inputKeyMaterial, numOutputs) {
3669
3634
  const output = hkdf(blake2s, inputKeyMaterial, chainingKey, new Uint8Array(0), numOutputs * HASH_LENGTH);
3670
3635
  const chunks = [];
3671
- for (let i = 0; i < numOutputs; i++) {
3672
- chunks.push(output.subarray(i * HASH_LENGTH, (i + 1) * HASH_LENGTH));
3636
+ for (let i2 = 0; i2 < numOutputs; i2++) {
3637
+ chunks.push(output.subarray(i2 * HASH_LENGTH, (i2 + 1) * HASH_LENGTH));
3673
3638
  }
3674
3639
  return chunks;
3675
3640
  }
@@ -3704,7 +3669,7 @@ function xaeadDecrypt(key, nonce, associatedData, ciphertext) {
3704
3669
  const cipher = xchacha20poly1305(key, nonce, associatedData);
3705
3670
  return cipher.decrypt(ciphertext);
3706
3671
  }
3707
- function concatBytes4(...arrays) {
3672
+ function concatBytes3(...arrays) {
3708
3673
  const total = arrays.reduce((sum, arr) => sum + arr.length, 0);
3709
3674
  const result = new Uint8Array(total);
3710
3675
  let offset = 0;
@@ -3751,7 +3716,7 @@ var SymmetricState = class {
3751
3716
  hash;
3752
3717
  constructor(protocolName) {
3753
3718
  if (protocolName.length <= HASH_LENGTH) {
3754
- this.hash = concatBytes4(protocolName, new Uint8Array(HASH_LENGTH - protocolName.length));
3719
+ this.hash = concatBytes3(protocolName, new Uint8Array(HASH_LENGTH - protocolName.length));
3755
3720
  } else {
3756
3721
  this.hash = hashBlake2s(protocolName);
3757
3722
  }
@@ -3764,7 +3729,7 @@ var SymmetricState = class {
3764
3729
  this.cipherState.initializeKey(tempKey);
3765
3730
  }
3766
3731
  mixHash(data) {
3767
- this.hash = hashBlake2s(concatBytes4(this.hash, data));
3732
+ this.hash = hashBlake2s(concatBytes3(this.hash, data));
3768
3733
  }
3769
3734
  /** Processes a "psk" token: MixKeyAndHash(psk) per Noise section 9. */
3770
3735
  mixKeyAndHash(inputKeyMaterial) {
@@ -3924,7 +3889,7 @@ var HandshakeState = class {
3924
3889
  }
3925
3890
  }
3926
3891
  buffers.push(this.symmetricState.encryptAndHash(payload));
3927
- return { message: concatBytes4(...buffers), split: this.maybeSplit() };
3892
+ return { message: concatBytes3(...buffers), split: this.maybeSplit() };
3928
3893
  }
3929
3894
  readMessage(message) {
3930
3895
  const tokens = this.nextTokens();
@@ -4054,7 +4019,7 @@ var SecretstreamState = class {
4054
4019
  const associatedData = Uint8Array.of(tag);
4055
4020
  const ciphertext = xaeadEncrypt(this.key, this.nonceForCounter(this.counter), associatedData, plaintext);
4056
4021
  this.counter += 1n;
4057
- return concatBytes4(associatedData, ciphertext);
4022
+ return concatBytes3(associatedData, ciphertext);
4058
4023
  }
4059
4024
  /**
4060
4025
  * Decrypts one frame and advances this direction's counter. Throws if
@@ -4164,8 +4129,8 @@ function deriveShortAuthenticationString(handshakeHash) {
4164
4129
  const digitsValue = digitsRaw % 1e6;
4165
4130
  const digits = digitsValue.toString(10).padStart(6, "0");
4166
4131
  const emoji = [];
4167
- for (let i = 0; i < 5; i++) {
4168
- emoji.push(SAS_EMOJI_TABLE[bytes[4 + i] % SAS_EMOJI_TABLE.length]);
4132
+ for (let i2 = 0; i2 < 5; i2++) {
4133
+ emoji.push(SAS_EMOJI_TABLE[bytes[4 + i2] % SAS_EMOJI_TABLE.length]);
4169
4134
  }
4170
4135
  return { digits, emoji };
4171
4136
  }
@@ -4174,7 +4139,7 @@ function deriveShortAuthenticationString(handshakeHash) {
4174
4139
  var SESSION_SLOT_LABEL = "kangentic-session-slot-v1";
4175
4140
  var SESSION_SLOT_LENGTH = 16;
4176
4141
  function deriveSessionSlotId(desktopStaticPublicKey, phoneStaticPublicKey) {
4177
- const material = concatBytes4(desktopStaticPublicKey, phoneStaticPublicKey);
4142
+ const material = concatBytes3(desktopStaticPublicKey, phoneStaticPublicKey);
4178
4143
  return bytesToHex(deriveLabeledKey(material, SESSION_SLOT_LABEL, SESSION_SLOT_LENGTH));
4179
4144
  }
4180
4145
  var PAIRING_SLOT_LABEL = "kangentic-pairing-slot-v1";
@@ -4261,13 +4226,13 @@ var fdeb = new u8([
4261
4226
  var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
4262
4227
  var freb = function(eb, start) {
4263
4228
  var b = new u16(31);
4264
- for (var i = 0; i < 31; ++i) {
4265
- b[i] = start += 1 << eb[i - 1];
4229
+ for (var i2 = 0; i2 < 31; ++i2) {
4230
+ b[i2] = start += 1 << eb[i2 - 1];
4266
4231
  }
4267
4232
  var r = new i32(b[30]);
4268
- for (var i = 1; i < 30; ++i) {
4269
- for (var j = b[i]; j < b[i + 1]; ++j) {
4270
- r[j] = j - b[i] << 5 | i;
4233
+ for (var i2 = 1; i2 < 30; ++i2) {
4234
+ for (var j = b[i2]; j < b[i2 + 1]; ++j) {
4235
+ r[j] = j - b[i2] << 5 | i2;
4271
4236
  }
4272
4237
  }
4273
4238
  return { b, r };
@@ -4290,25 +4255,25 @@ var x;
4290
4255
  var i;
4291
4256
  var hMap = (function(cd, mb, r) {
4292
4257
  var s = cd.length;
4293
- var i = 0;
4258
+ var i2 = 0;
4294
4259
  var l = new u16(mb);
4295
- for (; i < s; ++i) {
4296
- if (cd[i])
4297
- ++l[cd[i] - 1];
4260
+ for (; i2 < s; ++i2) {
4261
+ if (cd[i2])
4262
+ ++l[cd[i2] - 1];
4298
4263
  }
4299
4264
  var le = new u16(mb);
4300
- for (i = 1; i < mb; ++i) {
4301
- le[i] = le[i - 1] + l[i - 1] << 1;
4265
+ for (i2 = 1; i2 < mb; ++i2) {
4266
+ le[i2] = le[i2 - 1] + l[i2 - 1] << 1;
4302
4267
  }
4303
4268
  var co;
4304
4269
  if (r) {
4305
4270
  co = new u16(1 << mb);
4306
4271
  var rvb = 15 - mb;
4307
- for (i = 0; i < s; ++i) {
4308
- if (cd[i]) {
4309
- var sv = i << 4 | cd[i];
4310
- var r_1 = mb - cd[i];
4311
- var v = le[cd[i] - 1]++ << r_1;
4272
+ for (i2 = 0; i2 < s; ++i2) {
4273
+ if (cd[i2]) {
4274
+ var sv = i2 << 4 | cd[i2];
4275
+ var r_1 = mb - cd[i2];
4276
+ var v = le[cd[i2] - 1]++ << r_1;
4312
4277
  for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
4313
4278
  co[rev[v] >> rvb] = sv;
4314
4279
  }
@@ -4316,9 +4281,9 @@ var hMap = (function(cd, mb, r) {
4316
4281
  }
4317
4282
  } else {
4318
4283
  co = new u16(s);
4319
- for (i = 0; i < s; ++i) {
4320
- if (cd[i]) {
4321
- co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
4284
+ for (i2 = 0; i2 < s; ++i2) {
4285
+ if (cd[i2]) {
4286
+ co[i2] = rev[le[cd[i2] - 1]++] >> 15 - cd[i2];
4322
4287
  }
4323
4288
  }
4324
4289
  }
@@ -4347,9 +4312,9 @@ var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
4347
4312
  var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
4348
4313
  var max = function(a) {
4349
4314
  var m = a[0];
4350
- for (var i = 1; i < a.length; ++i) {
4351
- if (a[i] > m)
4352
- m = a[i];
4315
+ for (var i2 = 1; i2 < a.length; ++i2) {
4316
+ if (a[i2] > m)
4317
+ m = a[i2];
4353
4318
  }
4354
4319
  return m;
4355
4320
  };
@@ -4442,28 +4407,28 @@ var inflt = function(dat, st, buf, dict) {
4442
4407
  pos += 14;
4443
4408
  var ldt = new u8(tl);
4444
4409
  var clt = new u8(19);
4445
- for (var i = 0; i < hcLen; ++i) {
4446
- clt[clim[i]] = bits(dat, pos + i * 3, 7);
4410
+ for (var i2 = 0; i2 < hcLen; ++i2) {
4411
+ clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
4447
4412
  }
4448
4413
  pos += hcLen * 3;
4449
4414
  var clb = max(clt), clbmsk = (1 << clb) - 1;
4450
4415
  var clm = hMap(clt, clb, 1);
4451
- for (var i = 0; i < tl; ) {
4416
+ for (var i2 = 0; i2 < tl; ) {
4452
4417
  var r = clm[bits(dat, pos, clbmsk)];
4453
4418
  pos += r & 15;
4454
4419
  var s = r >> 4;
4455
4420
  if (s < 16) {
4456
- ldt[i++] = s;
4421
+ ldt[i2++] = s;
4457
4422
  } else {
4458
4423
  var c = 0, n = 0;
4459
4424
  if (s == 16)
4460
- n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
4425
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i2 - 1];
4461
4426
  else if (s == 17)
4462
4427
  n = 3 + bits(dat, pos, 7), pos += 3;
4463
4428
  else if (s == 18)
4464
4429
  n = 11 + bits(dat, pos, 127), pos += 7;
4465
4430
  while (n--)
4466
- ldt[i++] = c;
4431
+ ldt[i2++] = c;
4467
4432
  }
4468
4433
  }
4469
4434
  var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
@@ -4501,8 +4466,8 @@ var inflt = function(dat, st, buf, dict) {
4501
4466
  } else {
4502
4467
  var add2 = sym - 254;
4503
4468
  if (sym > 264) {
4504
- var i = sym - 257, b = fleb[i];
4505
- add2 = bits(dat, pos, (1 << b) - 1) + fl[i];
4469
+ var i2 = sym - 257, b = fleb[i2];
4470
+ add2 = bits(dat, pos, (1 << b) - 1) + fl[i2];
4506
4471
  pos += b;
4507
4472
  }
4508
4473
  var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
@@ -4554,9 +4519,9 @@ var wbits16 = function(d, p, v) {
4554
4519
  };
4555
4520
  var hTree = function(d, mb) {
4556
4521
  var t = [];
4557
- for (var i = 0; i < d.length; ++i) {
4558
- if (d[i])
4559
- t.push({ s: i, f: d[i] });
4522
+ for (var i2 = 0; i2 < d.length; ++i2) {
4523
+ if (d[i2])
4524
+ t.push({ s: i2, f: d[i2] });
4560
4525
  }
4561
4526
  var s = t.length;
4562
4527
  var t2 = t.slice();
@@ -4571,28 +4536,28 @@ var hTree = function(d, mb) {
4571
4536
  return a.f - b.f;
4572
4537
  });
4573
4538
  t.push({ s: -1, f: 25001 });
4574
- var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
4539
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i22 = 2;
4575
4540
  t[0] = { s: -1, f: l.f + r.f, l, r };
4576
4541
  while (i1 != s - 1) {
4577
- l = t[t[i0].f < t[i2].f ? i0++ : i2++];
4578
- r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
4542
+ l = t[t[i0].f < t[i22].f ? i0++ : i22++];
4543
+ r = t[i0 != i1 && t[i0].f < t[i22].f ? i0++ : i22++];
4579
4544
  t[i1++] = { s: -1, f: l.f + r.f, l, r };
4580
4545
  }
4581
4546
  var maxSym = t2[0].s;
4582
- for (var i = 1; i < s; ++i) {
4583
- if (t2[i].s > maxSym)
4584
- maxSym = t2[i].s;
4547
+ for (var i2 = 1; i2 < s; ++i2) {
4548
+ if (t2[i2].s > maxSym)
4549
+ maxSym = t2[i2].s;
4585
4550
  }
4586
4551
  var tr = new u16(maxSym + 1);
4587
4552
  var mbt = ln(t[i1 - 1], tr, 0);
4588
4553
  if (mbt > mb) {
4589
- var i = 0, dt = 0;
4554
+ var i2 = 0, dt = 0;
4590
4555
  var lft = mbt - mb, cst = 1 << lft;
4591
4556
  t2.sort(function(a, b) {
4592
4557
  return tr[b.s] - tr[a.s] || a.f - b.f;
4593
4558
  });
4594
- for (; i < s; ++i) {
4595
- var i2_1 = t2[i].s;
4559
+ for (; i2 < s; ++i2) {
4560
+ var i2_1 = t2[i2].s;
4596
4561
  if (tr[i2_1] > mb) {
4597
4562
  dt += cst - (1 << mbt - tr[i2_1]);
4598
4563
  tr[i2_1] = mb;
@@ -4601,14 +4566,14 @@ var hTree = function(d, mb) {
4601
4566
  }
4602
4567
  dt >>= lft;
4603
4568
  while (dt > 0) {
4604
- var i2_2 = t2[i].s;
4569
+ var i2_2 = t2[i2].s;
4605
4570
  if (tr[i2_2] < mb)
4606
4571
  dt -= 1 << mb - tr[i2_2]++ - 1;
4607
4572
  else
4608
- ++i;
4573
+ ++i2;
4609
4574
  }
4610
- for (; i >= 0 && dt; --i) {
4611
- var i2_3 = t2[i].s;
4575
+ for (; i2 >= 0 && dt; --i2) {
4576
+ var i2_3 = t2[i2].s;
4612
4577
  if (tr[i2_3] == mb) {
4613
4578
  --tr[i2_3];
4614
4579
  ++dt;
@@ -4630,8 +4595,8 @@ var lc = function(c) {
4630
4595
  var w = function(v) {
4631
4596
  cl[cli++] = v;
4632
4597
  };
4633
- for (var i = 1; i <= s; ++i) {
4634
- if (c[i] == cln && i != s)
4598
+ for (var i2 = 1; i2 <= s; ++i2) {
4599
+ if (c[i2] == cln && i2 != s)
4635
4600
  ++cls;
4636
4601
  else {
4637
4602
  if (!cln && cls > 2) {
@@ -4651,15 +4616,15 @@ var lc = function(c) {
4651
4616
  while (cls--)
4652
4617
  w(cln);
4653
4618
  cls = 1;
4654
- cln = c[i];
4619
+ cln = c[i2];
4655
4620
  }
4656
4621
  }
4657
4622
  return { c: cl.subarray(0, cli), n: s };
4658
4623
  };
4659
4624
  var clen = function(cf, cl) {
4660
4625
  var l = 0;
4661
- for (var i = 0; i < cl.length; ++i)
4662
- l += cf[i] * cl[i];
4626
+ for (var i2 = 0; i2 < cl.length; ++i2)
4627
+ l += cf[i2] * cl[i2];
4663
4628
  return l;
4664
4629
  };
4665
4630
  var wfblk = function(out, pos, dat) {
@@ -4669,8 +4634,8 @@ var wfblk = function(out, pos, dat) {
4669
4634
  out[o + 1] = s >> 8;
4670
4635
  out[o + 2] = out[o] ^ 255;
4671
4636
  out[o + 3] = out[o + 1] ^ 255;
4672
- for (var i = 0; i < s; ++i)
4673
- out[o + i + 4] = dat[i];
4637
+ for (var i2 = 0; i2 < s; ++i2)
4638
+ out[o + i2 + 4] = dat[i2];
4674
4639
  return (o + 4 + s) * 8;
4675
4640
  };
4676
4641
  var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
@@ -4681,10 +4646,10 @@ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
4681
4646
  var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
4682
4647
  var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
4683
4648
  var lcfreq = new u16(19);
4684
- for (var i = 0; i < lclt.length; ++i)
4685
- ++lcfreq[lclt[i] & 31];
4686
- for (var i = 0; i < lcdt.length; ++i)
4687
- ++lcfreq[lcdt[i] & 31];
4649
+ for (var i2 = 0; i2 < lclt.length; ++i2)
4650
+ ++lcfreq[lclt[i2] & 31];
4651
+ for (var i2 = 0; i2 < lcdt.length; ++i2)
4652
+ ++lcfreq[lcdt[i2] & 31];
4688
4653
  var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
4689
4654
  var nlcc = 19;
4690
4655
  for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
@@ -4703,24 +4668,24 @@ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
4703
4668
  wbits(out, p + 5, ndc - 1);
4704
4669
  wbits(out, p + 10, nlcc - 4);
4705
4670
  p += 14;
4706
- for (var i = 0; i < nlcc; ++i)
4707
- wbits(out, p + 3 * i, lct[clim[i]]);
4671
+ for (var i2 = 0; i2 < nlcc; ++i2)
4672
+ wbits(out, p + 3 * i2, lct[clim[i2]]);
4708
4673
  p += 3 * nlcc;
4709
4674
  var lcts = [lclt, lcdt];
4710
4675
  for (var it = 0; it < 2; ++it) {
4711
4676
  var clct = lcts[it];
4712
- for (var i = 0; i < clct.length; ++i) {
4713
- var len = clct[i] & 31;
4677
+ for (var i2 = 0; i2 < clct.length; ++i2) {
4678
+ var len = clct[i2] & 31;
4714
4679
  wbits(out, p, llm[len]), p += lct[len];
4715
4680
  if (len > 15)
4716
- wbits(out, p, clct[i] >> 5 & 127), p += clct[i] >> 12;
4681
+ wbits(out, p, clct[i2] >> 5 & 127), p += clct[i2] >> 12;
4717
4682
  }
4718
4683
  }
4719
4684
  } else {
4720
4685
  lm = flm, ll = flt, dm = fdm, dl = fdt;
4721
4686
  }
4722
- for (var i = 0; i < li; ++i) {
4723
- var sym = syms[i];
4687
+ for (var i2 = 0; i2 < li; ++i2) {
4688
+ var sym = syms[i2];
4724
4689
  if (sym > 255) {
4725
4690
  var len = sym >> 18 & 31;
4726
4691
  wbits16(out, p, lm[len + 257]), p += ll[len + 257];
@@ -4753,36 +4718,36 @@ var dflt = function(dat, lvl, plvl, pre, post, st) {
4753
4718
  var msk_1 = (1 << plvl) - 1;
4754
4719
  var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
4755
4720
  var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
4756
- var hsh = function(i2) {
4757
- return (dat[i2] ^ dat[i2 + 1] << bs1_1 ^ dat[i2 + 2] << bs2_1) & msk_1;
4721
+ var hsh = function(i3) {
4722
+ return (dat[i3] ^ dat[i3 + 1] << bs1_1 ^ dat[i3 + 2] << bs2_1) & msk_1;
4758
4723
  };
4759
4724
  var syms = new i32(25e3);
4760
4725
  var lf = new u16(288), df = new u16(32);
4761
- var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
4762
- for (; i + 2 < s; ++i) {
4763
- var hv = hsh(i);
4764
- var imod = i & 32767, pimod = head[hv];
4726
+ var lc_1 = 0, eb = 0, i2 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
4727
+ for (; i2 + 2 < s; ++i2) {
4728
+ var hv = hsh(i2);
4729
+ var imod = i2 & 32767, pimod = head[hv];
4765
4730
  prev[imod] = pimod;
4766
4731
  head[hv] = imod;
4767
- if (wi <= i) {
4768
- var rem = s - i;
4732
+ if (wi <= i2) {
4733
+ var rem = s - i2;
4769
4734
  if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
4770
- pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
4771
- li = lc_1 = eb = 0, bs = i;
4735
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i2 - bs, pos);
4736
+ li = lc_1 = eb = 0, bs = i2;
4772
4737
  for (var j = 0; j < 286; ++j)
4773
4738
  lf[j] = 0;
4774
4739
  for (var j = 0; j < 30; ++j)
4775
4740
  df[j] = 0;
4776
4741
  }
4777
4742
  var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
4778
- if (rem > 2 && hv == hsh(i - dif)) {
4743
+ if (rem > 2 && hv == hsh(i2 - dif)) {
4779
4744
  var maxn = Math.min(n, rem) - 1;
4780
- var maxd = Math.min(32767, i);
4745
+ var maxd = Math.min(32767, i2);
4781
4746
  var ml = Math.min(258, rem);
4782
4747
  while (dif <= maxd && --ch_1 && imod != pimod) {
4783
- if (dat[i + l] == dat[i + l - dif]) {
4748
+ if (dat[i2 + l] == dat[i2 + l - dif]) {
4784
4749
  var nl = 0;
4785
- for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
4750
+ for (; nl < ml && dat[i2 + nl] == dat[i2 + nl - dif]; ++nl)
4786
4751
  ;
4787
4752
  if (nl > l) {
4788
4753
  l = nl, d = dif;
@@ -4791,7 +4756,7 @@ var dflt = function(dat, lvl, plvl, pre, post, st) {
4791
4756
  var mmd = Math.min(dif, nl - 2);
4792
4757
  var md = 0;
4793
4758
  for (var j = 0; j < mmd; ++j) {
4794
- var ti = i - dif + j & 32767;
4759
+ var ti = i2 - dif + j & 32767;
4795
4760
  var pti = prev[ti];
4796
4761
  var cd = ti - pti & 32767;
4797
4762
  if (cd > md)
@@ -4809,32 +4774,32 @@ var dflt = function(dat, lvl, plvl, pre, post, st) {
4809
4774
  eb += fleb[lin] + fdeb[din];
4810
4775
  ++lf[257 + lin];
4811
4776
  ++df[din];
4812
- wi = i + l;
4777
+ wi = i2 + l;
4813
4778
  ++lc_1;
4814
4779
  } else {
4815
- syms[li++] = dat[i];
4816
- ++lf[dat[i]];
4780
+ syms[li++] = dat[i2];
4781
+ ++lf[dat[i2]];
4817
4782
  }
4818
4783
  }
4819
4784
  }
4820
- for (i = Math.max(i, wi); i < s; ++i) {
4821
- syms[li++] = dat[i];
4822
- ++lf[dat[i]];
4785
+ for (i2 = Math.max(i2, wi); i2 < s; ++i2) {
4786
+ syms[li++] = dat[i2];
4787
+ ++lf[dat[i2]];
4823
4788
  }
4824
- pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
4789
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i2 - bs, pos);
4825
4790
  if (!lst) {
4826
4791
  st.r = pos & 7 | w[pos / 8 | 0] << 3;
4827
4792
  pos -= 7;
4828
- st.h = head, st.p = prev, st.i = i, st.w = wi;
4793
+ st.h = head, st.p = prev, st.i = i2, st.w = wi;
4829
4794
  }
4830
4795
  } else {
4831
- for (var i = st.w || 0; i < s + lst; i += 65535) {
4832
- var e = i + 65535;
4796
+ for (var i2 = st.w || 0; i2 < s + lst; i2 += 65535) {
4797
+ var e = i2 + 65535;
4833
4798
  if (e >= s) {
4834
4799
  w[pos / 8 | 0] = lst;
4835
4800
  e = s;
4836
4801
  }
4837
- pos = wfblk(w, pos + 1, dat.subarray(i, e));
4802
+ pos = wfblk(w, pos + 1, dat.subarray(i2, e));
4838
4803
  }
4839
4804
  st.i = s;
4840
4805
  }
@@ -4879,7 +4844,8 @@ var CAPABILITY_VERBS = [
4879
4844
  "interactive-terminal",
4880
4845
  "board-tool-read",
4881
4846
  "board-tool-write",
4882
- "register-push"
4847
+ "register-push",
4848
+ "start-session"
4883
4849
  ];
4884
4850
  function isCapabilityVerb(value) {
4885
4851
  return CAPABILITY_VERBS.includes(value);
@@ -4915,6 +4881,23 @@ var COMPRESSION_THRESHOLD = 4 * 1024;
4915
4881
  var FRAME_FORMAT_DEFLATE = 1;
4916
4882
  var JSON_OPEN_BRACE = 123;
4917
4883
  var DEFLATE_HEADER_LENGTH = 5;
4884
+ var UNSUPPORTED_VERB_ERROR_CODE = "unsupported-verb";
4885
+ var UNSUPPORTED_VERB_ERROR_NAME = "UnsupportedVerbError";
4886
+ var UnsupportedVerbError = class extends Error {
4887
+ requestId;
4888
+ verb;
4889
+ constructor(requestId, verb) {
4890
+ super(`capability-request has an unsupported "verb": ${verb}`);
4891
+ this.name = UNSUPPORTED_VERB_ERROR_NAME;
4892
+ this.requestId = requestId;
4893
+ this.verb = verb;
4894
+ }
4895
+ };
4896
+ function isUnsupportedVerbError(error) {
4897
+ if (!(error instanceof Error) || error.name !== UNSUPPORTED_VERB_ERROR_NAME) return false;
4898
+ const candidate = error;
4899
+ return typeof candidate.requestId === "string" && typeof candidate.verb === "string";
4900
+ }
4918
4901
  function encodeMessage(message) {
4919
4902
  const json = new TextEncoder().encode(JSON.stringify(message));
4920
4903
  if (json.length > MAX_DECODED_LENGTH) {
@@ -4993,8 +4976,9 @@ function validateBridgeMessage(value) {
4993
4976
  return { type: "heartbeat" };
4994
4977
  case "capability-request": {
4995
4978
  if (typeof value.requestId !== "string") throw new Error('capability-request missing "requestId"');
4996
- if (typeof value.verb !== "string" || !isCapabilityVerb(value.verb)) throw new Error('capability-request has an invalid "verb"');
4979
+ if (typeof value.verb !== "string") throw new Error('capability-request has an invalid "verb"');
4997
4980
  if (!isJsonValue(value.payload)) throw new Error('capability-request has a non-JSON "payload"');
4981
+ if (!isCapabilityVerb(value.verb)) throw new UnsupportedVerbError(value.requestId, value.verb);
4998
4982
  return { type: "capability-request", requestId: value.requestId, verb: value.verb, payload: value.payload };
4999
4983
  }
5000
4984
  case "capability-response": {
@@ -5002,12 +4986,14 @@ function validateBridgeMessage(value) {
5002
4986
  if (typeof value.ok !== "boolean") throw new Error('capability-response missing "ok"');
5003
4987
  if (value.payload !== void 0 && !isJsonValue(value.payload)) throw new Error('capability-response has a non-JSON "payload"');
5004
4988
  if (value.error !== void 0 && typeof value.error !== "string") throw new Error('capability-response has a non-string "error"');
4989
+ if (value.code !== void 0 && typeof value.code !== "string") throw new Error('capability-response has a non-string "code"');
5005
4990
  return {
5006
4991
  type: "capability-response",
5007
4992
  requestId: value.requestId,
5008
4993
  ok: value.ok,
5009
4994
  payload: value.payload,
5010
- error: value.error
4995
+ error: value.error,
4996
+ code: value.code
5011
4997
  };
5012
4998
  }
5013
4999
  case "event": {
@@ -5042,20 +5028,20 @@ function unwrapSessionFrame(frame) {
5042
5028
  // src/wire/base64url.ts
5043
5029
  var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
5044
5030
  var DECODE_MAP = {};
5045
- for (let i = 0; i < ALPHABET.length; i++) DECODE_MAP[ALPHABET[i]] = i;
5031
+ for (let i2 = 0; i2 < ALPHABET.length; i2++) DECODE_MAP[ALPHABET[i2]] = i2;
5046
5032
  function base64UrlEncode(bytes) {
5047
5033
  let result = "";
5048
- let i = 0;
5049
- for (; i + 2 < bytes.length; i += 3) {
5050
- const chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
5034
+ let i2 = 0;
5035
+ for (; i2 + 2 < bytes.length; i2 += 3) {
5036
+ const chunk = bytes[i2] << 16 | bytes[i2 + 1] << 8 | bytes[i2 + 2];
5051
5037
  result += ALPHABET[chunk >> 18 & 63] + ALPHABET[chunk >> 12 & 63] + ALPHABET[chunk >> 6 & 63] + ALPHABET[chunk & 63];
5052
5038
  }
5053
- const remaining = bytes.length - i;
5039
+ const remaining = bytes.length - i2;
5054
5040
  if (remaining === 1) {
5055
- const chunk = bytes[i] << 16;
5041
+ const chunk = bytes[i2] << 16;
5056
5042
  result += ALPHABET[chunk >> 18 & 63] + ALPHABET[chunk >> 12 & 63];
5057
5043
  } else if (remaining === 2) {
5058
- const chunk = bytes[i] << 16 | bytes[i + 1] << 8;
5044
+ const chunk = bytes[i2] << 16 | bytes[i2 + 1] << 8;
5059
5045
  result += ALPHABET[chunk >> 18 & 63] + ALPHABET[chunk >> 12 & 63] + ALPHABET[chunk >> 6 & 63];
5060
5046
  }
5061
5047
  return result;
@@ -5112,7 +5098,7 @@ function sealPushEnvelope(pushKey, recipientStaticPublicKey, plaintext) {
5112
5098
  const nonce = randomBytes4(XCHACHA_NONCE_LENGTH);
5113
5099
  const encodedPlaintext = new TextEncoder().encode(JSON.stringify(plaintext));
5114
5100
  const ciphertext = xaeadEncrypt(pushKey, nonce, recipientStaticPublicKey, encodedPlaintext);
5115
- return base64UrlEncode(concatBytes4(nonce, ciphertext));
5101
+ return base64UrlEncode(concatBytes3(nonce, ciphertext));
5116
5102
  }
5117
5103
  function openPushEnvelope(pushKey, recipientStaticPublicKey, blob) {
5118
5104
  const bytes = base64UrlDecode(blob);
@@ -5635,6 +5621,23 @@ function parseMoveTaskRequestPayload(payload) {
5635
5621
  projectId: payload.projectId
5636
5622
  };
5637
5623
  }
5624
+ function parseStartSessionRequestPayload(payload) {
5625
+ if (!isRecord(payload)) throw new Error("start-session payload must be an object");
5626
+ if (typeof payload.taskId !== "string") throw new Error('start-session payload missing "taskId"');
5627
+ if (typeof payload.projectId !== "string") throw new Error('start-session payload missing "projectId"');
5628
+ return {
5629
+ taskId: payload.taskId,
5630
+ projectId: payload.projectId
5631
+ };
5632
+ }
5633
+ function parseStartSessionResponsePayload(payload) {
5634
+ if (!isRecord(payload)) throw new Error("start-session response must be an object");
5635
+ if (typeof payload.ok !== "boolean") throw new Error('start-session response missing "ok"');
5636
+ if (payload.outcome !== "starting" && payload.outcome !== "live") {
5637
+ throw new Error('start-session response has an invalid "outcome"');
5638
+ }
5639
+ return { ok: payload.ok, outcome: payload.outcome };
5640
+ }
5638
5641
  function parseAnswerPermissionPromptRequestPayload(payload) {
5639
5642
  if (!isRecord(payload)) throw new Error("answer-permission-prompt payload must be an object");
5640
5643
  if (typeof payload.sessionId !== "string") throw new Error('answer-permission-prompt payload missing "sessionId"');
@@ -5730,6 +5733,8 @@ function parseCapabilityRequestPayload(verb, payload) {
5730
5733
  return parseBoardToolRequestPayload(payload);
5731
5734
  case "register-push":
5732
5735
  return parseRegisterPushRequestPayload(payload);
5736
+ case "start-session":
5737
+ return parseStartSessionRequestPayload(payload);
5733
5738
  default: {
5734
5739
  const exhaustiveCheck = verb;
5735
5740
  throw new Error(`Unknown capability verb: ${String(exhaustiveCheck)}`);
@@ -5795,7 +5800,7 @@ function encodePairingQrPayload(payload) {
5795
5800
  }
5796
5801
  const expiresAtBytes = new TextEncoder().encode(payload.expiresAt);
5797
5802
  const protocolVersionBytes = new TextEncoder().encode(payload.protocolVersion);
5798
- const body = concatBytes4(
5803
+ const body = concatBytes3(
5799
5804
  Uint8Array.of(PAYLOAD_VERSION),
5800
5805
  payload.desktopStaticPublicKey,
5801
5806
  payload.pairingToken,
@@ -5875,12 +5880,12 @@ function openPairingConfirm(initiatorToResponder, frame) {
5875
5880
  function uint32LengthPrefixed(bytes) {
5876
5881
  const prefix = new Uint8Array(4);
5877
5882
  new DataView(prefix.buffer).setUint32(0, bytes.length, false);
5878
- return concatBytes4(prefix, bytes);
5883
+ return concatBytes3(prefix, bytes);
5879
5884
  }
5880
5885
  function encodeRosterEntryForSigning(entry) {
5881
5886
  const encoder = new TextEncoder();
5882
5887
  const sortedCapabilities = entry.capabilities.slice().sort().join(",");
5883
- return concatBytes4(
5888
+ return concatBytes3(
5884
5889
  uint32LengthPrefixed(encoder.encode(entry.deviceId)),
5885
5890
  uint32LengthPrefixed(entry.staticPublicKey),
5886
5891
  uint32LengthPrefixed(encoder.encode(entry.displayName)),
@@ -5986,7 +5991,11 @@ function parseActivityEventPayload(payload) {
5986
5991
  }
5987
5992
  case "session-ended": {
5988
5993
  if (typeof payload.intentional !== "boolean") throw new Error('session-ended payload is missing "intentional"');
5989
- return { type: "session-ended", intentional: payload.intentional };
5994
+ if (payload.spawnProgressLabel === void 0) {
5995
+ return { type: "session-ended", intentional: payload.intentional };
5996
+ }
5997
+ if (typeof payload.spawnProgressLabel !== "string") throw new Error('session-ended payload has an invalid "spawnProgressLabel"');
5998
+ return { type: "session-ended", intentional: payload.intentional, spawnProgressLabel: payload.spawnProgressLabel };
5990
5999
  }
5991
6000
  case "message-preview": {
5992
6001
  if (typeof payload.text !== "string") throw new Error('message-preview payload is missing "text"');
@@ -6066,6 +6075,8 @@ export {
6066
6075
  PUSH_ENVELOPE_MAX_FUTURE_SKEW_MS,
6067
6076
  SecretstreamState,
6068
6077
  SessionFrameKind,
6078
+ UNSUPPORTED_VERB_ERROR_CODE,
6079
+ UnsupportedVerbError,
6069
6080
  X25519_KEY_LENGTH,
6070
6081
  bytesToHex,
6071
6082
  capabilitySetFromArray,
@@ -6102,6 +6113,7 @@ export {
6102
6113
  isRosterEntryExpired,
6103
6114
  isSecureRelayAddress,
6104
6115
  isTodoRole,
6116
+ isUnsupportedVerbError,
6105
6117
  openPairingConfirm,
6106
6118
  openPushEnvelope,
6107
6119
  parseActivityEventPayload,
@@ -6119,6 +6131,7 @@ export {
6119
6131
  parseSessionEventWire,
6120
6132
  parseSessionSummaryWire,
6121
6133
  parseSessionUsageWire,
6134
+ parseStartSessionResponsePayload,
6122
6135
  parseTerminalDimensionsWire,
6123
6136
  parseTranscriptEntriesWire,
6124
6137
  parseTranscriptEventPayload,