@kangentic/protocol 0.14.0 → 0.16.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.cjs CHANGED
@@ -41,6 +41,8 @@ __export(index_exports, {
41
41
  PUSH_ENVELOPE_MAX_FUTURE_SKEW_MS: () => PUSH_ENVELOPE_MAX_FUTURE_SKEW_MS,
42
42
  SecretstreamState: () => SecretstreamState,
43
43
  SessionFrameKind: () => SessionFrameKind,
44
+ UNSUPPORTED_VERB_ERROR_CODE: () => UNSUPPORTED_VERB_ERROR_CODE,
45
+ UnsupportedVerbError: () => UnsupportedVerbError,
44
46
  X25519_KEY_LENGTH: () => X25519_KEY_LENGTH,
45
47
  bytesToHex: () => bytesToHex,
46
48
  capabilitySetFromArray: () => capabilitySetFromArray,
@@ -73,10 +75,12 @@ __export(index_exports, {
73
75
  isDoneRole: () => isDoneRole,
74
76
  isJsonValue: () => isJsonValue,
75
77
  isPushCategory: () => isPushCategory,
78
+ isReadStreamSessionStatusWire: () => isReadStreamSessionStatusWire,
76
79
  isRecord: () => isRecord,
77
80
  isRosterEntryExpired: () => isRosterEntryExpired,
78
81
  isSecureRelayAddress: () => isSecureRelayAddress,
79
82
  isTodoRole: () => isTodoRole,
83
+ isUnsupportedVerbError: () => isUnsupportedVerbError,
80
84
  openPairingConfirm: () => openPairingConfirm,
81
85
  openPushEnvelope: () => openPushEnvelope,
82
86
  parseActivityEventPayload: () => parseActivityEventPayload,
@@ -94,6 +98,7 @@ __export(index_exports, {
94
98
  parseSessionEventWire: () => parseSessionEventWire,
95
99
  parseSessionSummaryWire: () => parseSessionSummaryWire,
96
100
  parseSessionUsageWire: () => parseSessionUsageWire,
101
+ parseStartSessionResponsePayload: () => parseStartSessionResponsePayload,
97
102
  parseTerminalDimensionsWire: () => parseTerminalDimensionsWire,
98
103
  parseTranscriptEntriesWire: () => parseTranscriptEntriesWire,
99
104
  parseTranscriptEventPayload: () => parseTranscriptEventPayload,
@@ -116,64 +121,116 @@ function encodeProtocolVersion(version = PROTOCOL_VERSION) {
116
121
  return new TextEncoder().encode(`kangentic-bridge-v${version}`);
117
122
  }
118
123
 
124
+ // ../../node_modules/@noble/hashes/_u64.js
125
+ var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
126
+ var _32n = /* @__PURE__ */ BigInt(32);
127
+ function fromBig(n, le = false) {
128
+ if (le)
129
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
130
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
131
+ }
132
+ function split(lst, le = false) {
133
+ const len = lst.length;
134
+ let Ah = new Uint32Array(len);
135
+ let Al = new Uint32Array(len);
136
+ for (let i2 = 0; i2 < len; i2++) {
137
+ const { h, l } = fromBig(lst[i2], le);
138
+ [Ah[i2], Al[i2]] = [h, l];
139
+ }
140
+ return [Ah, Al];
141
+ }
142
+ var fromNumH = (n) => n / 2 ** 32 | 0;
143
+ var fromNumL = (n) => n >>> 0;
144
+ function setU64FromNum(view, byteOffset, n, isLE3) {
145
+ const h = fromNumH(n);
146
+ const l = fromNumL(n);
147
+ view.setUint32(byteOffset, isLE3 ? l : h, isLE3);
148
+ view.setUint32(byteOffset + 4, isLE3 ? h : l, isLE3);
149
+ }
150
+ var shrSH = (h, _l, s) => h >>> s;
151
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
152
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
153
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
154
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
155
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
156
+ function add(Ah, Al, Bh, Bl) {
157
+ const l = (Al >>> 0) + (Bl >>> 0);
158
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
159
+ }
160
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
161
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
162
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
163
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
164
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
165
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
166
+
119
167
  // ../../node_modules/@noble/hashes/utils.js
120
168
  function isBytes(a) {
121
169
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
122
170
  }
171
+ var atitle = (title) => title ? `"${title}" ` : "";
123
172
  function anumber(n, title = "") {
124
- if (typeof n !== "number") {
125
- const prefix = title && `"${title}" `;
126
- throw new TypeError(`${prefix}expected number, got ${typeof n}`);
127
- }
128
- if (!Number.isSafeInteger(n) || n < 0) {
129
- const prefix = title && `"${title}" `;
130
- throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
131
- }
173
+ if (typeof n !== "number")
174
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
175
+ if (!Number.isSafeInteger(n) || n < 0)
176
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
177
+ return n;
132
178
  }
133
179
  function abytes(value, length, title = "") {
180
+ if (isBytes(value) && (length === void 0 || value.length === length))
181
+ return value;
182
+ if (length !== void 0)
183
+ anumber(length, "length");
134
184
  const bytes = isBytes(value);
135
- const len = value?.length;
136
- const needsLen = length !== void 0;
137
- if (!bytes || needsLen && len !== length) {
138
- const prefix = title && `"${title}" `;
139
- const ofLen = needsLen ? ` of length ${length}` : "";
140
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
141
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
142
- if (!bytes)
143
- throw new TypeError(message);
144
- throw new RangeError(message);
145
- }
146
- return value;
185
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
186
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
187
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
188
+ if (!bytes)
189
+ throw new TypeError(message);
190
+ throw new RangeError(message);
191
+ }
192
+ function copyBytes(bytes) {
193
+ return Uint8Array.from(abytes(bytes));
147
194
  }
148
195
  function ahash(h) {
149
196
  if (typeof h !== "function" || typeof h.create !== "function")
150
- throw new TypeError("Hash must wrapped by utils.createHasher");
197
+ throw new TypeError("expected hash wrapped by utils.createHasher");
151
198
  anumber(h.outputLen);
152
199
  anumber(h.blockLen);
153
- if (h.outputLen < 1)
154
- throw new Error('"outputLen" must be >= 1');
155
- if (h.blockLen < 1)
156
- throw new Error('"blockLen" must be >= 1');
200
+ if (h.outputLen < 1 || h.blockLen < 1)
201
+ throw new Error("hash blockLen / outputLen must be >= 1");
157
202
  }
203
+ var aobject = (value, label) => {
204
+ if (value === null || typeof value !== "object" || Array.isArray(value))
205
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
206
+ };
207
+ var aopts = (value, label) => {
208
+ aobject(value, label);
209
+ const proto = Object.getPrototypeOf(value);
210
+ if (proto !== Object.prototype && proto !== null)
211
+ throw new TypeError(`"${label}" expected plain object`);
212
+ if (Object.hasOwn(value, "__proto__"))
213
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
214
+ };
158
215
  function aexists(instance, checkFinished = true) {
159
216
  if (instance.destroyed)
160
- throw new Error("Hash instance has been destroyed");
217
+ throw new Error("hash was destroyed");
161
218
  if (checkFinished && instance.finished)
162
- throw new Error("Hash#digest() has already been called");
219
+ throw new Error("digest() was already called");
163
220
  }
164
221
  function aoutput(out, instance) {
165
- abytes(out, void 0, "digestInto() output");
222
+ abytes(out, void 0, "output");
166
223
  const min = instance.outputLen;
167
- if (out.length < min) {
168
- throw new RangeError('"digestInto() output" expected to be of length >=' + min);
224
+ if (!(out.length >= min)) {
225
+ throw new RangeError('"output" expected length >= ' + min);
169
226
  }
170
227
  }
171
228
  function u32(arr) {
172
229
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
173
230
  }
174
231
  function clean(...arrays) {
175
- for (let i = 0; i < arrays.length; i++) {
176
- arrays[i].fill(0);
232
+ for (let i2 = 0; i2 < arrays.length; i2++) {
233
+ arrays[i2].fill(0);
177
234
  }
178
235
  }
179
236
  function createView(arr) {
@@ -188,8 +245,8 @@ function byteSwap(word) {
188
245
  }
189
246
  var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0;
190
247
  function byteSwap32(arr) {
191
- for (let i = 0; i < arr.length; i++) {
192
- arr[i] = byteSwap(arr[i]);
248
+ for (let i2 = 0; i2 < arr.length; i2++) {
249
+ arr[i2] = byteSwap(arr[i2]);
193
250
  }
194
251
  return arr;
195
252
  }
@@ -198,26 +255,19 @@ var hasHexBuiltin = /* @__PURE__ */ (() => (
198
255
  // @ts-ignore
199
256
  typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
200
257
  ))();
201
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
258
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0"));
202
259
  function bytesToHex(bytes) {
203
260
  abytes(bytes);
204
261
  if (hasHexBuiltin)
205
262
  return bytes.toHex();
206
263
  let hex = "";
207
- for (let i = 0; i < bytes.length; i++) {
208
- hex += hexes[bytes[i]];
264
+ for (let i2 = 0; i2 < bytes.length; i2++) {
265
+ hex += hexes[bytes[i2]];
209
266
  }
210
267
  return hex;
211
268
  }
212
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
213
269
  function asciiToBase16(ch) {
214
- if (ch >= asciis._0 && ch <= asciis._9)
215
- return ch - asciis._0;
216
- if (ch >= asciis.A && ch <= asciis.F)
217
- return ch - (asciis.A - 10);
218
- if (ch >= asciis.a && ch <= asciis.f)
219
- return ch - (asciis.a - 10);
220
- return;
270
+ return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
221
271
  }
222
272
  function hexToBytes(hex) {
223
273
  if (typeof hex !== "string")
@@ -249,20 +299,30 @@ function hexToBytes(hex) {
249
299
  }
250
300
  function concatBytes(...arrays) {
251
301
  let sum = 0;
252
- for (let i = 0; i < arrays.length; i++) {
253
- const a = arrays[i];
302
+ for (let i2 = 0; i2 < arrays.length; i2++) {
303
+ const a = arrays[i2];
254
304
  abytes(a);
255
305
  sum += a.length;
256
306
  }
257
307
  const res = new Uint8Array(sum);
258
- for (let i = 0, pad = 0; i < arrays.length; i++) {
259
- const a = arrays[i];
308
+ for (let i2 = 0, pad = 0; i2 < arrays.length; i2++) {
309
+ const a = arrays[i2];
260
310
  res.set(a, pad);
261
311
  pad += a.length;
262
312
  }
263
313
  return res;
264
314
  }
315
+ function checkOpts(defaults, opts, title = "opts") {
316
+ aopts(defaults, "defaults");
317
+ if (opts !== void 0)
318
+ aopts(opts, title);
319
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
320
+ return merged;
321
+ }
265
322
  function createHasher(hashCons, info = {}) {
323
+ if (typeof hashCons !== "function")
324
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
325
+ info = checkOpts({}, info, "info");
266
326
  const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
267
327
  const tmp = hashCons(void 0);
268
328
  hashC.outputLen = tmp.outputLen;
@@ -314,24 +374,28 @@ var HashMD = class {
314
374
  abytes(data);
315
375
  const { view, buffer, blockLen } = this;
316
376
  const len = data.length;
377
+ let processed = false;
317
378
  for (let pos = 0; pos < len; ) {
318
379
  const take = Math.min(blockLen - this.pos, len - pos);
319
380
  if (take === blockLen) {
320
381
  const dataView = createView(data);
321
382
  for (; blockLen <= len - pos; pos += blockLen)
322
383
  this.process(dataView, pos);
384
+ processed = true;
323
385
  continue;
324
386
  }
325
- buffer.set(data.subarray(pos, pos + take), this.pos);
387
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
326
388
  this.pos += take;
327
389
  pos += take;
328
390
  if (this.pos === blockLen) {
329
391
  this.process(view, 0);
330
392
  this.pos = 0;
393
+ processed = true;
331
394
  }
332
395
  }
333
396
  this.length += data.length;
334
- this.roundClean();
397
+ if (processed)
398
+ this.roundClean();
335
399
  return this;
336
400
  }
337
401
  digestInto(out) {
@@ -341,25 +405,22 @@ var HashMD = class {
341
405
  const { buffer, view, blockLen, isLE: isLE3 } = this;
342
406
  let { pos } = this;
343
407
  buffer[pos++] = 128;
344
- clean(this.buffer.subarray(pos));
408
+ buffer.fill(0, pos);
345
409
  if (this.padOffset > blockLen - pos) {
346
410
  this.process(view, 0);
347
- pos = 0;
411
+ buffer.fill(0);
348
412
  }
349
- for (let i = pos; i < blockLen; i++)
350
- buffer[i] = 0;
351
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE3);
413
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE3);
352
414
  this.process(view, 0);
353
- const oview = createView(out);
415
+ this.roundClean();
416
+ const oview = out === buffer ? view : createView(out);
354
417
  const len = this.outputLen;
355
- if (len % 4)
356
- throw new Error("_sha2: outputLen must be aligned to 32bit");
357
418
  const outLen = len / 4;
358
419
  const state = this.get();
359
- if (outLen > state.length)
360
- throw new Error("_sha2: outputLen bigger than state");
361
- for (let i = 0; i < outLen; i++)
362
- oview.setUint32(4 * i, state[i], isLE3);
420
+ if (len % 4 || outLen > state.length)
421
+ throw new Error("invalid outputLen");
422
+ for (let i2 = 0; i2 < outLen; i2++)
423
+ oview.setUint32(4 * i2, state[i2], isLE3);
363
424
  }
364
425
  digest() {
365
426
  const { buffer, outputLen } = this;
@@ -368,15 +429,13 @@ var HashMD = class {
368
429
  this.destroy();
369
430
  return res;
370
431
  }
371
- _cloneInto(to) {
372
- to ||= new this.constructor();
373
- to.set(...this.get());
374
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
432
+ _cloneIntoMeta(to) {
433
+ const { buffer, length, finished, destroyed, pos } = this;
375
434
  to.destroyed = destroyed;
376
435
  to.finished = finished;
377
436
  to.length = length;
378
437
  to.pos = pos;
379
- if (length % blockLen)
438
+ if (pos)
380
439
  to.buffer.set(buffer);
381
440
  return to;
382
441
  }
@@ -413,41 +472,6 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
413
472
  327033209
414
473
  ]);
415
474
 
416
- // ../../node_modules/@noble/hashes/_u64.js
417
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
418
- var _32n = /* @__PURE__ */ BigInt(32);
419
- function fromBig(n, le = false) {
420
- if (le)
421
- return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
422
- return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
423
- }
424
- function split(lst, le = false) {
425
- const len = lst.length;
426
- let Ah = new Uint32Array(len);
427
- let Al = new Uint32Array(len);
428
- for (let i = 0; i < len; i++) {
429
- const { h, l } = fromBig(lst[i], le);
430
- [Ah[i], Al[i]] = [h, l];
431
- }
432
- return [Ah, Al];
433
- }
434
- var shrSH = (h, _l, s) => h >>> s;
435
- var shrSL = (h, l, s) => h << 32 - s | l >>> s;
436
- var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
437
- var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
438
- var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
439
- var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
440
- function add(Ah, Al, Bh, Bl) {
441
- const l = (Al >>> 0) + (Bl >>> 0);
442
- return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
443
- }
444
- var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
445
- var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
446
- var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
447
- var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
448
- var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
449
- var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
450
-
451
475
  // ../../node_modules/@noble/hashes/sha2.js
452
476
  var K512 = /* @__PURE__ */ (() => split([
453
477
  "0x428a2f98d728ae22",
@@ -536,8 +560,45 @@ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
536
560
  var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
537
561
  var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
538
562
  var SHA2_64B = class extends HashMD {
539
- constructor(outputLen) {
563
+ // We cannot use array here since array allows indexing by variable
564
+ // which means optimizer/compiler cannot use registers.
565
+ // h -- high 32 bits, l -- low 32 bits
566
+ // Numeric initializers matter: starting the fields as `undefined` changes
567
+ // V8's field representation and slows hashing down (measured on sha256).
568
+ Ah = 0;
569
+ Al = 0;
570
+ Bh = 0;
571
+ Bl = 0;
572
+ Ch = 0;
573
+ Cl = 0;
574
+ Dh = 0;
575
+ Dl = 0;
576
+ Eh = 0;
577
+ El = 0;
578
+ Fh = 0;
579
+ Fl = 0;
580
+ Gh = 0;
581
+ Gl = 0;
582
+ Hh = 0;
583
+ Hl = 0;
584
+ constructor(outputLen, IV) {
540
585
  super(128, outputLen, 16, false);
586
+ this.Ah = IV[0] | 0;
587
+ this.Al = IV[1] | 0;
588
+ this.Bh = IV[2] | 0;
589
+ this.Bl = IV[3] | 0;
590
+ this.Ch = IV[4] | 0;
591
+ this.Cl = IV[5] | 0;
592
+ this.Dh = IV[6] | 0;
593
+ this.Dl = IV[7] | 0;
594
+ this.Eh = IV[8] | 0;
595
+ this.El = IV[9] | 0;
596
+ this.Fh = IV[10] | 0;
597
+ this.Fl = IV[11] | 0;
598
+ this.Gh = IV[12] | 0;
599
+ this.Gl = IV[13] | 0;
600
+ this.Hh = IV[14] | 0;
601
+ this.Hl = IV[15] | 0;
541
602
  }
542
603
  // prettier-ignore
543
604
  get() {
@@ -563,33 +624,37 @@ var SHA2_64B = class extends HashMD {
563
624
  this.Hh = Hh | 0;
564
625
  this.Hl = Hl | 0;
565
626
  }
627
+ _cloneInto(to) {
628
+ (to ||= new this.constructor()).set(...this.get());
629
+ return this._cloneIntoMeta(to);
630
+ }
566
631
  process(view, offset) {
567
- for (let i = 0; i < 16; i++, offset += 4) {
568
- SHA512_W_H[i] = view.getUint32(offset);
569
- SHA512_W_L[i] = view.getUint32(offset += 4);
632
+ for (let i2 = 0; i2 < 16; i2++, offset += 4) {
633
+ SHA512_W_H[i2] = view.getUint32(offset);
634
+ SHA512_W_L[i2] = view.getUint32(offset += 4);
570
635
  }
571
- for (let i = 16; i < 80; i++) {
572
- const W15h = SHA512_W_H[i - 15] | 0;
573
- const W15l = SHA512_W_L[i - 15] | 0;
636
+ for (let i2 = 16; i2 < 80; i2++) {
637
+ const W15h = SHA512_W_H[i2 - 15] | 0;
638
+ const W15l = SHA512_W_L[i2 - 15] | 0;
574
639
  const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
575
640
  const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
576
- const W2h = SHA512_W_H[i - 2] | 0;
577
- const W2l = SHA512_W_L[i - 2] | 0;
641
+ const W2h = SHA512_W_H[i2 - 2] | 0;
642
+ const W2l = SHA512_W_L[i2 - 2] | 0;
578
643
  const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
579
644
  const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
580
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
581
- const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
582
- SHA512_W_H[i] = SUMh | 0;
583
- SHA512_W_L[i] = SUMl | 0;
645
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i2 - 7], SHA512_W_L[i2 - 16]);
646
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i2 - 7], SHA512_W_H[i2 - 16]);
647
+ SHA512_W_H[i2] = SUMh | 0;
648
+ SHA512_W_L[i2] = SUMl | 0;
584
649
  }
585
650
  let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
586
- for (let i = 0; i < 80; i++) {
651
+ for (let i2 = 0; i2 < 80; i2++) {
587
652
  const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
588
653
  const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
589
654
  const CHIh = Eh & Fh ^ ~Eh & Gh;
590
655
  const CHIl = El & Fl ^ ~El & Gl;
591
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
592
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
656
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i2], SHA512_W_L[i2]);
657
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i2], SHA512_W_H[i2]);
593
658
  const T1l = T1ll | 0;
594
659
  const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
595
660
  const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
@@ -632,24 +697,8 @@ var SHA2_64B = class extends HashMD {
632
697
  }
633
698
  };
634
699
  var _SHA512 = class extends SHA2_64B {
635
- Ah = SHA512_IV[0] | 0;
636
- Al = SHA512_IV[1] | 0;
637
- Bh = SHA512_IV[2] | 0;
638
- Bl = SHA512_IV[3] | 0;
639
- Ch = SHA512_IV[4] | 0;
640
- Cl = SHA512_IV[5] | 0;
641
- Dh = SHA512_IV[6] | 0;
642
- Dl = SHA512_IV[7] | 0;
643
- Eh = SHA512_IV[8] | 0;
644
- El = SHA512_IV[9] | 0;
645
- Fh = SHA512_IV[10] | 0;
646
- Fl = SHA512_IV[11] | 0;
647
- Gh = SHA512_IV[12] | 0;
648
- Gl = SHA512_IV[13] | 0;
649
- Hh = SHA512_IV[14] | 0;
650
- Hl = SHA512_IV[15] | 0;
651
700
  constructor() {
652
- super(64);
701
+ super(64, SHA512_IV);
653
702
  }
654
703
  };
655
704
  var sha512 = /* @__PURE__ */ createHasher(
@@ -658,8 +707,26 @@ var sha512 = /* @__PURE__ */ createHasher(
658
707
  );
659
708
 
660
709
  // ../../node_modules/@noble/curves/utils.js
710
+ function aarray(item, title, inner = () => {
711
+ }) {
712
+ if (!Array.isArray(item))
713
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
714
+ for (let i2 = 0; i2 < item.length; i2++)
715
+ inner(item[i2], `${title}[${i2}]`);
716
+ return item;
717
+ }
661
718
  var abytes2 = (value, length, title) => abytes(value, length, title);
662
719
  var anumber2 = anumber;
720
+ function aobject2(value, title = "object") {
721
+ if (value === null || typeof value !== "object" || Array.isArray(value))
722
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
723
+ return value;
724
+ }
725
+ function afunction(value, title) {
726
+ if (typeof value !== "function")
727
+ throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
728
+ return value;
729
+ }
663
730
  var bytesToHex2 = bytesToHex;
664
731
  var concatBytes2 = (...arrays) => concatBytes(...arrays);
665
732
  var hexToBytes2 = (hex) => hexToBytes(hex);
@@ -667,11 +734,10 @@ var isBytes2 = isBytes;
667
734
  var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
668
735
  var _0n = /* @__PURE__ */ BigInt(0);
669
736
  var _1n = /* @__PURE__ */ BigInt(1);
737
+ var atitle2 = (title) => title ? `"${title}" ` : "";
670
738
  function abool(value, title = "") {
671
- if (typeof value !== "boolean") {
672
- const prefix = title && `"${title}" `;
673
- throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
674
- }
739
+ if (typeof value !== "boolean")
740
+ throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
675
741
  return value;
676
742
  }
677
743
  function abignumber(n) {
@@ -701,46 +767,28 @@ function bytesToNumberBE(bytes) {
701
767
  return hexToNumber(bytesToHex(bytes));
702
768
  }
703
769
  function bytesToNumberLE(bytes) {
704
- return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
770
+ return hexToNumber(bytesToHex(copyBytes2(abytes(bytes)).reverse()));
705
771
  }
706
772
  function numberToBytesBE(n, len) {
707
773
  anumber(len);
708
774
  if (len === 0)
709
- throw new RangeError("zero length");
775
+ throw new Error("zero output length is invalid");
710
776
  n = abignumber(n);
777
+ const expectedLen = len * 2;
711
778
  const hex = n.toString(16);
712
- if (hex.length > len * 2)
713
- throw new RangeError("number too large");
714
- return hexToBytes(hex.padStart(len * 2, "0"));
779
+ if (hex.length > expectedLen)
780
+ throw new RangeError("number is too large");
781
+ return hexToBytes(hex.padStart(expectedLen, "0"));
715
782
  }
716
783
  function numberToBytesLE(n, len) {
717
784
  return numberToBytesBE(n, len).reverse();
718
785
  }
719
- function equalBytes(a, b) {
720
- a = abytes2(a);
721
- b = abytes2(b);
722
- if (a.length !== b.length)
723
- return false;
724
- let diff = 0;
725
- for (let i = 0; i < a.length; i++)
726
- diff |= a[i] ^ b[i];
727
- return diff === 0;
728
- }
729
- function copyBytes(bytes) {
786
+ function copyBytes2(bytes) {
730
787
  return Uint8Array.from(abytes2(bytes));
731
788
  }
732
- function asciiToBytes(ascii) {
733
- if (typeof ascii !== "string")
734
- throw new TypeError("ascii string expected, got " + typeof ascii);
735
- return Uint8Array.from(ascii, (c, i) => {
736
- const charCode = c.charCodeAt(0);
737
- if (c.length !== 1 || charCode > 127) {
738
- throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
739
- }
740
- return charCode;
741
- });
789
+ function isPosBig(n) {
790
+ return typeof n === "bigint" && _0n <= n;
742
791
  }
743
- var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
744
792
  function inRange(n, min, max2) {
745
793
  return isPosBig(n) && isPosBig(min) && isPosBig(max2) && min <= n && n < max2;
746
794
  }
@@ -751,32 +799,32 @@ function aInRange(title, n, min, max2) {
751
799
  function bitLen(n) {
752
800
  if (n < _0n)
753
801
  throw new Error("expected non-negative bigint, got " + n);
754
- let len;
755
- for (len = 0; n > _0n; n >>= _1n, len += 1)
756
- ;
757
- return len;
802
+ return n === _0n ? 0 : n.toString(2).length;
758
803
  }
759
- var bitMask = (n) => (_1n << BigInt(n)) - _1n;
760
- function validateObject(object, fields = {}, optFields = {}) {
761
- if (Object.prototype.toString.call(object) !== "[object Object]")
762
- throw new TypeError("expected valid options object");
804
+ var bitMask = (n) => {
805
+ asafenumber(n, "n");
806
+ return (_1n << BigInt(n)) - _1n;
807
+ };
808
+ function validateObject(object, fields = {}, optFields = {}, title = "object") {
809
+ aobject2(object, title);
810
+ aobject2(fields, "fields");
811
+ aobject2(optFields, "optFields");
763
812
  function checkField(fieldName, expectedType, isOpt) {
764
- if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
765
- throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
813
+ const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
766
814
  const val = object[fieldName];
815
+ if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
816
+ throw new TypeError(`${label} is invalid: expected own property`);
817
+ }
767
818
  if (isOpt && val === void 0)
768
819
  return;
769
820
  const current = typeof val;
770
821
  if (current !== expectedType || val === null)
771
- throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
822
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
772
823
  }
773
824
  const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
774
825
  iter(fields, false);
775
826
  iter(optFields, true);
776
827
  }
777
- var notImplemented = () => {
778
- throw new Error("not implemented");
779
- };
780
828
 
781
829
  // ../../node_modules/@noble/curves/abstract/modular.js
782
830
  var _0n2 = /* @__PURE__ */ BigInt(0);
@@ -788,17 +836,67 @@ var _5n = /* @__PURE__ */ BigInt(5);
788
836
  var _7n = /* @__PURE__ */ BigInt(7);
789
837
  var _8n = /* @__PURE__ */ BigInt(8);
790
838
  var _9n = /* @__PURE__ */ BigInt(9);
839
+ var _15n = /* @__PURE__ */ BigInt(15);
791
840
  var _16n = /* @__PURE__ */ BigInt(16);
841
+ var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
792
842
  function mod(a, b) {
793
843
  if (b <= _0n2)
794
844
  throw new Error("mod: expected positive modulus, got " + b);
795
845
  const result = a % b;
796
846
  return result >= _0n2 ? result : b + result;
797
847
  }
798
- function pow2(x, power, modulo) {
848
+ function pow(num, power, modulo) {
849
+ if (modulo <= _1n2)
850
+ throw new Error("pow: expected modulus > 1, got " + modulo);
851
+ if (typeof power !== "bigint")
852
+ throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
853
+ if (power < _0n2)
854
+ throw new Error("invalid exponent, negatives unsupported");
855
+ if (power === _0n2)
856
+ return _1n2;
857
+ if (power === _1n2)
858
+ return num;
859
+ let d = num % modulo;
860
+ if (d < _0n2)
861
+ d += modulo;
862
+ if (power < POW_WINDOWED_MIN) {
863
+ let p2 = _1n2;
864
+ while (power > _0n2) {
865
+ if (power & _1n2)
866
+ p2 = p2 * d % modulo;
867
+ d = d * d % modulo;
868
+ power >>= _1n2;
869
+ }
870
+ return p2;
871
+ }
872
+ const digits = [];
873
+ while (power > _0n2) {
874
+ digits.push(Number(power & _15n));
875
+ power >>= _4n;
876
+ }
877
+ const table = new Array(16);
878
+ table[0] = _1n2;
879
+ table[1] = d;
880
+ for (let i2 = 2; i2 < 16; i2++)
881
+ table[i2] = table[i2 - 1] * d % modulo;
882
+ let p = table[digits[digits.length - 1]];
883
+ for (let w = digits.length - 2; w >= 0; w--) {
884
+ p = p * p % modulo;
885
+ p = p * p % modulo;
886
+ p = p * p % modulo;
887
+ p = p * p % modulo;
888
+ const digit = digits[w];
889
+ if (digit !== 0)
890
+ p = p * table[digit] % modulo;
891
+ }
892
+ return p;
893
+ }
894
+ function pow2(x2, power, modulo) {
895
+ if (modulo <= _1n2)
896
+ throw new Error("pow2: expected modulus > 1, got " + modulo);
799
897
  if (power < _0n2)
800
898
  throw new Error("pow2: expected non-negative exponent, got " + power);
801
- let res = x;
899
+ let res = x2;
802
900
  while (power-- > _0n2) {
803
901
  res *= res;
804
902
  res %= modulo;
@@ -808,28 +906,31 @@ function pow2(x, power, modulo) {
808
906
  function invert(number, modulo) {
809
907
  if (number === _0n2)
810
908
  throw new Error("invert: expected non-zero number");
811
- if (modulo <= _0n2)
812
- throw new Error("invert: expected positive modulus, got " + modulo);
909
+ if (modulo <= _1n2)
910
+ throw new Error("invert: expected modulus > 1, got " + modulo);
813
911
  let a = mod(number, modulo);
814
912
  let b = modulo;
815
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
913
+ let x2 = _0n2, u = _1n2;
816
914
  while (a !== _0n2) {
817
915
  const q = b / a;
818
916
  const r = b - a * q;
819
- const m = x - u * q;
820
- const n = y - v * q;
821
- b = a, a = r, x = u, y = v, u = m, v = n;
917
+ const m = x2 - u * q;
918
+ b = a, a = r, x2 = u, u = m;
822
919
  }
823
920
  const gcd = b;
824
921
  if (gcd !== _1n2)
825
922
  throw new Error("invert: does not exist");
826
- return mod(x, modulo);
923
+ return mod(x2, modulo);
827
924
  }
828
925
  function assertIsSquare(Fp2, root, n) {
829
926
  const F = Fp2;
830
927
  if (!F.eql(F.sqr(root), n))
831
928
  throw new Error("Cannot find square root");
832
929
  }
930
+ function aoddModulus(order, fnName) {
931
+ if ((order & _1n2) === _0n2)
932
+ throw new Error(fnName + ": expected odd modulus, got " + order);
933
+ }
833
934
  function sqrt3mod4(Fp2, n) {
834
935
  const F = Fp2;
835
936
  const p1div4 = (F.ORDER + _1n2) / _4n;
@@ -843,8 +944,8 @@ function sqrt5mod8(Fp2, n) {
843
944
  const n2 = F.mul(n, _2n);
844
945
  const v = F.pow(n2, p5div8);
845
946
  const nv = F.mul(n, v);
846
- const i = F.mul(F.mul(nv, _2n), v);
847
- const root = F.mul(nv, F.sub(i, F.ONE));
947
+ const i2 = F.mul(F.mul(nv, _2n), v);
948
+ const root = F.mul(nv, F.sub(i2, F.ONE));
848
949
  assertIsSquare(F, root, n);
849
950
  return root;
850
951
  }
@@ -874,6 +975,7 @@ function sqrt9mod16(P) {
874
975
  function tonelliShanks(P) {
875
976
  if (P < _3n)
876
977
  throw new Error("sqrt is not defined for small field");
978
+ aoddModulus(P, "tonelliShanks");
877
979
  let Q = P - _1n2;
878
980
  let S = 0;
879
981
  while (Q % _2n === _0n2) {
@@ -902,18 +1004,18 @@ function tonelliShanks(P) {
902
1004
  let R = F.pow(n, Q1div2);
903
1005
  while (!F.eql(t, F.ONE)) {
904
1006
  if (F.is0(t))
905
- return F.ZERO;
906
- let i = 1;
1007
+ throw new Error("Cannot find square root: probably non-prime P");
1008
+ let i2 = 1;
907
1009
  let t_tmp = F.sqr(t);
908
1010
  while (!F.eql(t_tmp, F.ONE)) {
909
- i++;
1011
+ i2++;
910
1012
  t_tmp = F.sqr(t_tmp);
911
- if (i === M)
1013
+ if (i2 === M)
912
1014
  throw new Error("Cannot find square root");
913
1015
  }
914
- const exponent = _1n2 << BigInt(M - i - 1);
1016
+ const exponent = _1n2 << BigInt(M - i2 - 1);
915
1017
  const b = F.pow(c, exponent);
916
- M = i;
1018
+ M = i2;
917
1019
  c = F.sqr(b);
918
1020
  t = F.mul(t, c);
919
1021
  R = F.mul(R, b);
@@ -922,6 +1024,7 @@ function tonelliShanks(P) {
922
1024
  };
923
1025
  }
924
1026
  function FpSqrt(P) {
1027
+ aoddModulus(P, "Fp.sqrt");
925
1028
  if (P % _4n === _3n)
926
1029
  return sqrt3mod4;
927
1030
  if (P % _8n === _5n)
@@ -951,62 +1054,44 @@ var FIELD_FIELDS = [
951
1054
  "sqrN"
952
1055
  ];
953
1056
  function validateField(field) {
954
- const initial = {
955
- ORDER: "bigint",
956
- BYTES: "number",
957
- BITS: "number"
958
- };
959
- const opts = FIELD_FIELDS.reduce((map, val) => {
960
- map[val] = "function";
961
- return map;
962
- }, initial);
963
- validateObject(field, opts);
1057
+ aobject2(field, "field");
1058
+ if (typeof field.ORDER !== "bigint")
1059
+ throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
964
1060
  asafenumber(field.BYTES, "BYTES");
965
1061
  asafenumber(field.BITS, "BITS");
1062
+ for (const name of FIELD_FIELDS)
1063
+ afunction(field[name], "field." + name);
966
1064
  if (field.BYTES < 1 || field.BITS < 1)
967
1065
  throw new Error("invalid field: expected BYTES/BITS > 0");
968
1066
  if (field.ORDER <= _1n2)
969
1067
  throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
970
1068
  return field;
971
1069
  }
972
- function FpPow(Fp2, num, power) {
973
- const F = Fp2;
974
- if (power < _0n2)
975
- throw new Error("invalid exponent, negatives unsupported");
976
- if (power === _0n2)
977
- return F.ONE;
978
- if (power === _1n2)
979
- return num;
980
- let p = F.ONE;
981
- let d = num;
982
- while (power > _0n2) {
983
- if (power & _1n2)
984
- p = F.mul(p, d);
985
- d = F.sqr(d);
986
- power >>= _1n2;
987
- }
988
- return p;
989
- }
990
1070
  function FpInvertBatch(Fp2, nums, passZero = false) {
1071
+ validateField(Fp2);
1072
+ aarray(nums, "nums");
1073
+ abool(passZero, "passZero");
991
1074
  const F = Fp2;
992
1075
  const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
993
- const multipliedAcc = nums.reduce((acc, num, i) => {
1076
+ const multipliedAcc = nums.reduce((acc, num, i2) => {
994
1077
  if (F.is0(num))
995
1078
  return acc;
996
- inverted[i] = acc;
1079
+ inverted[i2] = acc;
997
1080
  return F.mul(acc, num);
998
1081
  }, F.ONE);
999
1082
  const invertedAcc = F.inv(multipliedAcc);
1000
- nums.reduceRight((acc, num, i) => {
1083
+ nums.reduceRight((acc, num, i2) => {
1001
1084
  if (F.is0(num))
1002
1085
  return acc;
1003
- inverted[i] = F.mul(acc, inverted[i]);
1086
+ inverted[i2] = F.mul(acc, inverted[i2]);
1004
1087
  return F.mul(acc, num);
1005
1088
  }, invertedAcc);
1006
1089
  return inverted;
1007
1090
  }
1008
1091
  function FpLegendre(Fp2, n) {
1092
+ validateField(Fp2);
1009
1093
  const F = Fp2;
1094
+ aoddModulus(F.ORDER, "FpLegendre");
1010
1095
  const p1mod2 = (F.ORDER - _1n2) / _2n;
1011
1096
  const powered = F.pow(n, p1mod2);
1012
1097
  const yes = F.eql(powered, F.ONE);
@@ -1025,7 +1110,7 @@ function nLength(n, nBitLength) {
1025
1110
  throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
1026
1111
  const bits2 = bitLen(n);
1027
1112
  if (nBitLength !== void 0 && nBitLength < bits2)
1028
- throw new Error(`invalid n length: expected bit length (${bits2}) >= n.length (${nBitLength})`);
1113
+ throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits2})`);
1029
1114
  const _nBitLength = nBitLength !== void 0 ? nBitLength : bits2;
1030
1115
  const nByteLength = Math.ceil(_nBitLength / 8);
1031
1116
  return { nBitLength: _nBitLength, nByteLength };
@@ -1102,7 +1187,7 @@ var _Field = class {
1102
1187
  return mod(lhs * rhs, this.ORDER);
1103
1188
  }
1104
1189
  pow(num, power) {
1105
- return FpPow(this, num, power);
1190
+ return pow(num, power, this.ORDER);
1106
1191
  }
1107
1192
  div(lhs, rhs) {
1108
1193
  return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
@@ -1156,7 +1241,7 @@ var _Field = class {
1156
1241
  }
1157
1242
  // TODO: we don't need it here, move out to separate fn
1158
1243
  invertBatch(lst) {
1159
- return FpInvertBatch(this, lst);
1244
+ return FpInvertBatch(this, lst, true);
1160
1245
  }
1161
1246
  // We can't move this out because Fp6, Fp12 implement it
1162
1247
  // and it's unclear what to return in there.
@@ -1165,192 +1250,357 @@ var _Field = class {
1165
1250
  return condition ? b : a;
1166
1251
  }
1167
1252
  };
1168
- Object.freeze(_Field.prototype);
1169
1253
  function Field(ORDER, opts = {}) {
1254
+ Object.freeze(_Field.prototype);
1170
1255
  return new _Field(ORDER, opts);
1171
1256
  }
1172
1257
 
1173
1258
  // ../../node_modules/@noble/curves/abstract/curve.js
1174
1259
  var _0n3 = /* @__PURE__ */ BigInt(0);
1175
1260
  var _1n3 = /* @__PURE__ */ BigInt(1);
1176
- function negateCt(condition, item) {
1177
- const neg = item.negate();
1178
- return condition ? neg : item;
1261
+ var _4n2 = /* @__PURE__ */ BigInt(4);
1262
+ var BLIND_BYTES = 16;
1263
+ var BLIND_BITS = 128;
1264
+ var FW_WINDOW = 5;
1265
+ var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
1266
+ function validatePointCons(Point) {
1267
+ const pc = Point;
1268
+ if (typeof pc !== "function")
1269
+ throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
1270
+ afunction(pc.fromAffine, "Point.fromAffine");
1271
+ afunction(pc.fromBytes, "Point.fromBytes");
1272
+ afunction(pc.fromHex, "Point.fromHex");
1273
+ aobject2(pc.BASE, "Point.BASE");
1274
+ aobject2(pc.ZERO, "Point.ZERO");
1275
+ validateField(pc.Fp);
1276
+ validateField(pc.Fn);
1179
1277
  }
1180
1278
  function normalizeZ(c, points) {
1279
+ validatePointCons(c);
1280
+ validateMSMPoints(points, c);
1181
1281
  const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1182
- return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1183
- }
1184
- function validateW(W, bits2) {
1185
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits2)
1186
- throw new Error("invalid window size, expected [1.." + bits2 + "], got W=" + W);
1187
- }
1188
- function calcWOpts(W, scalarBits) {
1189
- validateW(W, scalarBits);
1190
- const windows = Math.ceil(scalarBits / W) + 1;
1191
- const windowSize = 2 ** (W - 1);
1192
- const maxNumber = 2 ** W;
1193
- const mask = bitMask(W);
1194
- const shiftBy = BigInt(W);
1195
- return { windows, windowSize, mask, maxNumber, shiftBy };
1196
- }
1197
- function calcOffsets(n, window, wOpts) {
1198
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1199
- let wbits2 = Number(n & mask);
1200
- let nextN = n >> shiftBy;
1201
- if (wbits2 > windowSize) {
1202
- wbits2 -= maxNumber;
1203
- nextN += _1n3;
1204
- }
1205
- const offsetStart = window * windowSize;
1206
- const offset = offsetStart + Math.abs(wbits2) - 1;
1207
- const isZero = wbits2 === 0;
1208
- const isNeg = wbits2 < 0;
1209
- const isNegF = window % 2 !== 0;
1210
- const offsetF = offsetStart;
1211
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1212
- }
1213
- var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1282
+ return points.map((p, i2) => c.fromAffine(p.toAffine(invertedZs[i2])));
1283
+ }
1284
+ function validateW(W, bits2, min = 1) {
1285
+ if (!Number.isSafeInteger(W) || W < min || W > bits2)
1286
+ throw new Error("invalid window size, expected [" + min + ".." + bits2 + "], got W=" + W);
1287
+ }
1288
+ function validateTableBytes(numPoints, fpBytes) {
1289
+ const bytes = numPoints * (4 * fpBytes + 128);
1290
+ if (bytes > TABLE_BYTES_MAX)
1291
+ throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
1292
+ }
1293
+ function probeRandomBytes(randomBytes5, length) {
1294
+ if (randomBytes5 === void 0)
1295
+ return void 0;
1296
+ afunction(randomBytes5, "randomBytes");
1297
+ try {
1298
+ const probe = randomBytes5(length);
1299
+ if (!isBytes2(probe) || probe.length !== length)
1300
+ return void 0;
1301
+ } catch {
1302
+ return void 0;
1303
+ }
1304
+ return randomBytes5;
1305
+ }
1306
+ function validateMSMPoints(points, c) {
1307
+ aarray(points, "points");
1308
+ points.forEach((p, i2) => {
1309
+ if (!(p instanceof c))
1310
+ throw new Error("invalid point at index " + i2);
1311
+ });
1312
+ }
1313
+ function validateMSMScalars(scalars, field, maxScalar) {
1314
+ if (!Array.isArray(scalars))
1315
+ throw new Error("array of scalars expected");
1316
+ scalars.forEach((s, i2) => {
1317
+ const ok = maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar;
1318
+ if (!ok)
1319
+ throw new Error("invalid scalar at index " + i2);
1320
+ });
1321
+ }
1214
1322
  var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1215
- function getW(P) {
1323
+ function getWindowSize(P) {
1216
1324
  return pointWindowSizes.get(P) || 1;
1217
1325
  }
1218
- function assert0(n) {
1326
+ function oddMultiples(p, size) {
1327
+ const dbl = p.double();
1328
+ const t = [p];
1329
+ for (let j = 1; j < size; j++)
1330
+ t.push(t[j - 1].add(dbl));
1331
+ return t;
1332
+ }
1333
+ function wnafDigits(n, W) {
1334
+ const size = 2 ** W;
1335
+ const half = size / 2;
1336
+ const mask = BigInt(size - 1);
1337
+ const d = [];
1338
+ while (n > _0n3) {
1339
+ let w = 0;
1340
+ if (n & _1n3) {
1341
+ w = Number(n & mask);
1342
+ if (w >= half)
1343
+ w -= size;
1344
+ n -= BigInt(w);
1345
+ }
1346
+ d.push(w);
1347
+ n >>= _1n3;
1348
+ }
1349
+ return d;
1350
+ }
1351
+ function signedWindowDigits(n, W, windows) {
1352
+ const size = 2 ** W;
1353
+ const half = size / 2;
1354
+ const mask = BigInt(size - 1);
1355
+ const shiftBy = BigInt(W);
1356
+ const d = [];
1357
+ for (let w = 0; w < windows; w++) {
1358
+ let v = Number(n & mask);
1359
+ n >>= shiftBy;
1360
+ if (v > half) {
1361
+ v -= size;
1362
+ n += _1n3;
1363
+ }
1364
+ d.push(v);
1365
+ }
1219
1366
  if (n !== _0n3)
1220
- throw new Error("invalid wNAF");
1367
+ throw new Error("invalid wnaf");
1368
+ return d;
1369
+ }
1370
+ function wnafWalk(zero, tables, digits) {
1371
+ let max2 = 0;
1372
+ for (const d of digits)
1373
+ max2 = Math.max(max2, d.length);
1374
+ let acc = zero;
1375
+ for (let bit = max2 - 1; bit >= 0; bit--) {
1376
+ if (bit !== max2 - 1)
1377
+ acc = acc.double();
1378
+ for (let i2 = 0; i2 < digits.length; i2++) {
1379
+ const w = digits[i2][bit];
1380
+ if (w) {
1381
+ const item = tables[i2][Math.abs(w) - 1 >> 1];
1382
+ acc = acc.add(w < 0 ? item.negate() : item);
1383
+ }
1384
+ }
1385
+ }
1386
+ return acc;
1221
1387
  }
1222
- var wNAF = class {
1388
+ var ScalarMultiplier = class {
1389
+ Point;
1223
1390
  BASE;
1224
1391
  ZERO;
1225
- Fn;
1392
+ randomBytes;
1393
+ wnafPrecomputes = /* @__PURE__ */ new WeakMap();
1394
+ baseCanBeBlinded;
1226
1395
  bits;
1227
1396
  // Parametrized with a given Point class (not individual point)
1228
- constructor(Point, bits2) {
1397
+ constructor(Point, randomBytes5) {
1398
+ validatePointCons(Point);
1399
+ this.randomBytes = probeRandomBytes(randomBytes5, BLIND_BYTES);
1400
+ this.Point = Point;
1229
1401
  this.BASE = Point.BASE;
1230
1402
  this.ZERO = Point.ZERO;
1231
- this.Fn = Point.Fn;
1232
- this.bits = bits2;
1233
- }
1234
- // non-const time multiplication ladder
1235
- _unsafeLadder(elm, n, p = this.ZERO) {
1236
- let d = elm;
1237
- while (n > _0n3) {
1238
- if (n & _1n3)
1239
- p = p.add(d);
1240
- d = d.double();
1241
- n >>= _1n3;
1242
- }
1243
- return p;
1403
+ this.bits = Point.Fn.BITS;
1244
1404
  }
1245
1405
  /**
1246
- * Creates a wNAF precomputation window. Used for caching.
1247
- * Default window size is set by `utils.precompute()` and is equal to 8.
1248
- * Number of precomputed points depends on the curve size:
1249
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1250
- * - 𝑊 is the window size
1251
- * - 𝑛 is the bitlength of the curve order.
1252
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1406
+ * Creates a signed fixed-window wNAF precomputation table: for every window w, the
1407
+ * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
1408
+ * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
1409
+ * window absorbs the final carry of signed-digit recoding.
1410
+ * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
1253
1411
  * @param point - Point instance
1254
1412
  * @param W - window size
1255
- * @returns precomputed point tables flattened to a single array
1413
+ * @param bits - scalar bitlength the table must cover
1256
1414
  */
1257
- precomputeWindow(point, W) {
1258
- const { windows, windowSize } = calcWOpts(W, this.bits);
1259
- const points = [];
1260
- let p = point;
1261
- let base = p;
1262
- for (let window = 0; window < windows; window++) {
1263
- base = p;
1264
- points.push(base);
1265
- for (let i = 1; i < windowSize; i++) {
1266
- base = base.add(p);
1267
- points.push(base);
1415
+ buildWnafTable(point, W, bits2) {
1416
+ const windows = Math.ceil(bits2 / W) + 1;
1417
+ const half = 2 ** (W - 1);
1418
+ const comp = [];
1419
+ let base = point;
1420
+ for (let w = 0; w < windows; w++) {
1421
+ let acc = base;
1422
+ for (let i2 = 0; i2 < half; i2++) {
1423
+ comp.push(acc);
1424
+ acc = acc.add(base);
1268
1425
  }
1269
- p = base.double();
1426
+ base = comp[comp.length - 1].double();
1270
1427
  }
1271
- return points;
1428
+ return { W, bits: bits2, windows, comp };
1272
1429
  }
1273
1430
  /**
1274
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1275
- * More compact implementation:
1276
- * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1431
+ * Implements ec multiplication using precomputed signed fixed-window wNAF tables.
1432
+ * Constant-time: fixed window count with one table addition per window — zero digits feed
1433
+ * the fake accumulator — and no doublings; the lookup scans the whole window slice.
1434
+ * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
1435
+ * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
1436
+ * signedWindowDigits throws if `n` exceeds the table.
1277
1437
  * @returns real and fake (for const-time) points
1278
1438
  */
1279
- wNAF(W, precomputes, n) {
1280
- if (!this.Fn.isValid(n))
1281
- throw new Error("invalid scalar");
1439
+ wnafCachedCT(precomputes, n) {
1440
+ const { W, windows, comp } = precomputes;
1441
+ const half = 2 ** (W - 1);
1442
+ const digits = signedWindowDigits(n, W, windows);
1282
1443
  let p = this.ZERO;
1283
1444
  let f = this.BASE;
1284
- const wo = calcWOpts(W, this.bits);
1285
- for (let window = 0; window < wo.windows; window++) {
1286
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1287
- n = nextN;
1288
- if (isZero) {
1289
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
1290
- } else {
1291
- p = p.add(negateCt(isNeg, precomputes[offset]));
1292
- }
1445
+ for (let w = 0; w < windows; w++) {
1446
+ const digit = digits[w];
1447
+ const start = w * half;
1448
+ const idx = Math.abs(digit) - 1;
1449
+ let sel = comp[start];
1450
+ for (let i2 = 1; i2 < half; i2++)
1451
+ sel = i2 === idx ? comp[start + i2] : sel;
1452
+ const neg = sel.negate();
1453
+ if (digit === 0)
1454
+ f = f.add(comp[start]);
1455
+ else
1456
+ p = p.add(digit < 0 ? neg : sel);
1293
1457
  }
1294
- assert0(n);
1295
1458
  return { p, f };
1296
1459
  }
1297
- /**
1298
- * Implements unsafe EC multiplication using precomputed tables
1299
- * and w-ary non-adjacent form.
1300
- * @param acc - accumulator point to add result of multiplication
1301
- * @returns point
1302
- */
1303
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1304
- const wo = calcWOpts(W, this.bits);
1305
- for (let window = 0; window < wo.windows; window++) {
1306
- if (n === _0n3)
1307
- break;
1308
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1309
- n = nextN;
1310
- if (isZero) {
1311
- continue;
1312
- } else {
1313
- const item = precomputes[offset];
1314
- acc = acc.add(isNeg ? item.negate() : item);
1315
- }
1316
- }
1317
- assert0(n);
1318
- return acc;
1319
- }
1320
- getPrecomputes(W, point, transform) {
1321
- let comp = pointPrecomputes.get(point);
1460
+ // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
1461
+ // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
1462
+ // incompatible `transform(...)` layouts and expect a separate cache entry.
1463
+ getWnafPrecomputes(W, point, bits2, transform) {
1464
+ let entries = this.wnafPrecomputes.get(point);
1465
+ let comp = entries?.find((entry) => entry.W === W && entry.bits === bits2);
1322
1466
  if (!comp) {
1323
- comp = this.precomputeWindow(point, W);
1324
- if (W !== 1) {
1325
- if (typeof transform === "function")
1326
- comp = transform(comp);
1327
- pointPrecomputes.set(point, comp);
1467
+ comp = this.buildWnafTable(point, W, bits2);
1468
+ if (typeof transform === "function")
1469
+ comp = { ...comp, comp: transform(comp.comp) };
1470
+ if (!entries) {
1471
+ entries = [];
1472
+ this.wnafPrecomputes.set(point, entries);
1328
1473
  }
1474
+ entries.push(comp);
1329
1475
  }
1330
1476
  return comp;
1331
1477
  }
1332
- cached(point, scalar, transform) {
1333
- const W = getW(point);
1334
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1478
+ assertPoint(point) {
1479
+ if (!(point instanceof this.Point))
1480
+ throw new TypeError('"point" expected Point instance, got type=' + typeof point);
1481
+ }
1482
+ // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
1483
+ // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
1484
+ // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
1485
+ validateMulInput(point, scalar) {
1486
+ this.assertPoint(point);
1487
+ if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
1488
+ throw new Error("invalid scalar");
1335
1489
  }
1336
- unsafe(point, scalar, transform, prev) {
1337
- const W = getW(point);
1490
+ // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
1491
+ // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
1492
+ // multiply. `n` must be < 2^bits.
1493
+ runCT(point, n, bits2, transform) {
1494
+ const W = getWindowSize(point);
1338
1495
  if (W === 1)
1339
- return this._unsafeLadder(point, scalar, prev);
1340
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1496
+ return this.fixedWindowCT(point, n, bits2);
1497
+ return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits2, transform), n);
1498
+ }
1499
+ mulCT(point, scalar, transform) {
1500
+ this.validateMulInput(point, scalar);
1501
+ return this.runCT(point, scalar, this.bits, transform);
1502
+ }
1503
+ mulCTBlinded(point, scalar, transform) {
1504
+ this.validateMulInput(point, scalar);
1505
+ if (this.randomBytes === void 0)
1506
+ throw new Error("randomBytes is required for scalar blinding");
1507
+ const bits2 = this.Point.Fn.BITS + BLIND_BITS;
1508
+ const blind = this.randomBytes(BLIND_BYTES);
1509
+ if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
1510
+ throw new Error("randomBytes returned invalid byte array");
1511
+ blind[0] = blind[0] & 63 | 128;
1512
+ const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
1513
+ return this.runCT(point, n, bits2, transform);
1514
+ }
1515
+ /**
1516
+ * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
1517
+ * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
1518
+ * far cheaper to build for a single use. The point-operation sequence is independent of `n`:
1519
+ * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
1520
+ * every table entry, and one addition (adds the identity when the window digit is 0 — never
1521
+ * skipped).
1522
+ *
1523
+ * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
1524
+ * add), which holds for the Weierstrass/Edwards point types used here. The table is left in
1525
+ * projective form (no normalizeZ): normalizing this small a table costs more than the
1526
+ * mixed-add savings it would buy for a single multiply.
1527
+ * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
1528
+ * (this path needs no fake accumulator — its op-count is already scalar-independent).
1529
+ */
1530
+ fixedWindowCT(point, n, bits2) {
1531
+ const W = FW_WINDOW;
1532
+ const size = 1 << W;
1533
+ const mask = bitMask(W);
1534
+ const table = new Array(size);
1535
+ table[0] = this.ZERO;
1536
+ for (let i2 = 1; i2 < size; i2++)
1537
+ table[i2] = table[i2 - 1].add(point);
1538
+ const windows = Math.ceil(bits2 / W);
1539
+ let acc = this.ZERO;
1540
+ for (let window = windows - 1; window >= 0; window--) {
1541
+ if (window !== windows - 1)
1542
+ for (let d = 0; d < W; d++)
1543
+ acc = acc.double();
1544
+ const digit = Number(n >> BigInt(window * W) & mask);
1545
+ let sel = table[0];
1546
+ for (let i2 = 1; i2 < size; i2++)
1547
+ sel = i2 === digit ? table[i2] : sel;
1548
+ acc = acc.add(sel);
1549
+ }
1550
+ return { p: acc, f: acc };
1341
1551
  }
1342
- // We calculate precomputes for elliptic curve point multiplication
1343
- // using windowed method. This specifies window size and
1344
- // stores precomputed values. Usually only base point would be precomputed.
1345
- createCache(P, W) {
1552
+ shouldBlind(point, cofactor) {
1553
+ if (this.randomBytes === void 0)
1554
+ return false;
1555
+ if (cofactor === _1n3)
1556
+ return true;
1557
+ if (point !== this.BASE)
1558
+ return false;
1559
+ if (this.baseCanBeBlinded === void 0)
1560
+ this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
1561
+ return this.baseCanBeBlinded;
1562
+ }
1563
+ mulSecret(point, scalar, cofactor, transform) {
1564
+ return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
1565
+ }
1566
+ mulUnsafe(point, scalar, transform) {
1567
+ this.assertPoint(point);
1568
+ if (!isPosBig(scalar))
1569
+ throw new Error("invalid scalar");
1570
+ const W = getWindowSize(point);
1571
+ if (W === 1 || scalar >= this.Point.Fn.ORDER)
1572
+ return mulAddUnsafe(this.Point, [point], [scalar], true);
1573
+ const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
1574
+ return this.wnafCachedCT(precomputes, scalar).p;
1575
+ }
1576
+ // Remembers the window size used for precomputed wNAF multiplication of the given point
1577
+ // and drops any previously built tables. Usually only the base point is precomputed.
1578
+ // W=1 resets the point to the un-precomputed (table-less) paths.
1579
+ // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
1580
+ setWindowSize(point, W) {
1581
+ this.assertPoint(point);
1346
1582
  validateW(W, this.bits);
1347
- pointWindowSizes.set(P, W);
1348
- pointPrecomputes.delete(P);
1583
+ const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
1584
+ validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
1585
+ pointWindowSizes.set(point, W);
1586
+ this.wnafPrecomputes.delete(point);
1349
1587
  }
1350
- hasCache(elm) {
1351
- return getW(elm) !== 1;
1588
+ // True when a window size is set: tables themselves are built lazily on first multiply.
1589
+ hasWindowSize(point) {
1590
+ return getWindowSize(point) !== 1;
1352
1591
  }
1353
1592
  };
1593
+ function mulAddUnsafe(c, points, scalars, allowOversized = false) {
1594
+ validatePointCons(c);
1595
+ validateMSMPoints(points, c);
1596
+ abool(allowOversized, "allowOversized");
1597
+ validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
1598
+ if (points.length !== scalars.length)
1599
+ throw new Error("arrays of points and scalars must have equal length");
1600
+ const tables = points.map((p) => oddMultiples(p, 4));
1601
+ const digits = scalars.map((n) => wnafDigits(n, 4));
1602
+ return wnafWalk(c.ZERO, tables, digits);
1603
+ }
1354
1604
  function createField(order, field, isLE3) {
1355
1605
  if (field) {
1356
1606
  if (field.ORDER !== order)
@@ -1362,17 +1612,20 @@ function createField(order, field, isLE3) {
1362
1612
  }
1363
1613
  }
1364
1614
  function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1615
+ if (type !== "weierstrass" && type !== "edwards")
1616
+ throw new Error('expected curve type "weierstrass" or "edwards"');
1365
1617
  if (FpFnLE === void 0)
1366
1618
  FpFnLE = type === "edwards";
1367
1619
  if (!CURVE || typeof CURVE !== "object")
1368
1620
  throw new Error(`expected valid ${type} CURVE object`);
1621
+ validateObject(curveOpts);
1369
1622
  for (const p of ["p", "n", "h"]) {
1370
1623
  const val = CURVE[p];
1371
- if (!(typeof val === "bigint" && val > _0n3))
1624
+ if (!(isPosBig(val) && val !== _0n3))
1372
1625
  throw new Error(`CURVE.${p} must be positive bigint`);
1373
1626
  }
1374
1627
  const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1375
- const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1628
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1376
1629
  const _b2 = type === "weierstrass" ? "b" : "d";
1377
1630
  const params = ["Gx", "Gy", "a", _b2];
1378
1631
  for (const p of params) {
@@ -1380,7 +1633,7 @@ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1380
1633
  throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1381
1634
  }
1382
1635
  CURVE = Object.freeze(Object.assign({}, CURVE));
1383
- return { CURVE, Fp: Fp2, Fn: Fn2 };
1636
+ return { CURVE, Fp: Fp2, Fn };
1384
1637
  }
1385
1638
  function createKeygen(randomSecretKey, getPublicKey) {
1386
1639
  return function keygen(seed) {
@@ -1393,23 +1646,34 @@ function createKeygen(randomSecretKey, getPublicKey) {
1393
1646
  var _0n4 = /* @__PURE__ */ BigInt(0);
1394
1647
  var _1n4 = /* @__PURE__ */ BigInt(1);
1395
1648
  var _2n2 = /* @__PURE__ */ BigInt(2);
1649
+ var _4n3 = /* @__PURE__ */ BigInt(4);
1396
1650
  var _8n2 = /* @__PURE__ */ BigInt(8);
1397
- function isEdValidXY(Fp2, CURVE, x, y) {
1398
- const x2 = Fp2.sqr(x);
1651
+ function isEdValidXY(Fp2, CURVE, x2, y) {
1652
+ const x22 = Fp2.sqr(x2);
1399
1653
  const y2 = Fp2.sqr(y);
1400
- const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
1401
- const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
1654
+ const left = Fp2.add(Fp2.mul(CURVE.a, x22), y2);
1655
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x22, y2)));
1402
1656
  return Fp2.eql(left, right);
1403
1657
  }
1404
1658
  function edwards(params, extraOpts = {}) {
1659
+ validateObject(extraOpts, {}, {}, "extraOpts");
1405
1660
  const opts = extraOpts;
1406
1661
  const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
1407
- const { Fp: Fp2, Fn: Fn2 } = validated;
1662
+ const { Fp: Fp2, Fn } = validated;
1408
1663
  let CURVE = validated.CURVE;
1409
1664
  const { h: cofactor } = CURVE;
1410
- validateObject(opts, {}, { uvRatio: "function" });
1411
- const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
1412
- const modP = (n) => Fp2.create(n);
1665
+ if (FpLegendre(Fp2, CURVE.a) !== 1)
1666
+ throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
1667
+ if (FpLegendre(Fp2, CURVE.d) !== -1)
1668
+ throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
1669
+ validateObject(opts, {}, { uvRatio: "function", randomBytes: "function" });
1670
+ const randomBytes5 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
1671
+ const MASK = _2n2 << BigInt(Fp2.BYTES * 8) - _1n4;
1672
+ function isOdd(n) {
1673
+ if (!Fp2.isOdd)
1674
+ throw new Error("Field does not have .isOdd()");
1675
+ return Fp2.isOdd(n);
1676
+ }
1413
1677
  const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
1414
1678
  try {
1415
1679
  return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
@@ -1419,6 +1683,7 @@ function edwards(params, extraOpts = {}) {
1419
1683
  } : opts.uvRatio;
1420
1684
  if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1421
1685
  throw new Error("bad curve params: generator point");
1686
+ 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);
1422
1687
  function acoord(title, n, banZero = false) {
1423
1688
  const min = banZero ? _1n4 : _0n4;
1424
1689
  aInRange("coordinate " + title, n, min, MASK);
@@ -1429,15 +1694,10 @@ function edwards(params, extraOpts = {}) {
1429
1694
  throw new Error("EdwardsPoint expected");
1430
1695
  }
1431
1696
  class Point {
1432
- // base / generator point
1433
- static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
1434
- // zero / infinity / identity point
1435
- static ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
1436
- // 0, 1, 1, 0
1437
- // math field
1697
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE, Fp2.mul(CURVE.Gx, CURVE.Gy));
1698
+ static ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ONE, Fp2.ZERO);
1438
1699
  static Fp = Fp2;
1439
- // scalar field
1440
- static Fn = Fn2;
1700
+ static Fn = Fn;
1441
1701
  X;
1442
1702
  Y;
1443
1703
  Z;
@@ -1460,36 +1720,36 @@ function edwards(params, extraOpts = {}) {
1460
1720
  static fromAffine(p) {
1461
1721
  if (p instanceof Point)
1462
1722
  throw new Error("extended point not allowed");
1463
- const { x, y } = p || {};
1464
- acoord("x", x);
1723
+ const { x: x2, y } = p || {};
1724
+ acoord("x", x2);
1465
1725
  acoord("y", y);
1466
- return new Point(x, y, _1n4, modP(x * y));
1726
+ return new Point(x2, y, Fp2.ONE, Fp2.mul(x2, y));
1467
1727
  }
1468
1728
  // Uses algo from RFC8032 5.1.3.
1469
1729
  static fromBytes(bytes, zip215 = false) {
1470
1730
  const len = Fp2.BYTES;
1471
1731
  const { a, d } = CURVE;
1472
- bytes = copyBytes(abytes2(bytes, len, "point"));
1732
+ bytes = copyBytes2(abytes2(bytes, len, "point"));
1473
1733
  abool(zip215, "zip215");
1474
- const normed = copyBytes(bytes);
1734
+ const normed = copyBytes2(bytes);
1475
1735
  const lastByte = bytes[len - 1];
1476
1736
  normed[len - 1] = lastByte & ~128;
1477
1737
  const y = bytesToNumberLE(normed);
1478
1738
  const max2 = zip215 ? MASK : Fp2.ORDER;
1479
1739
  aInRange("point.y", y, _0n4, max2);
1480
- const y2 = modP(y * y);
1481
- const u = modP(y2 - _1n4);
1482
- const v = modP(d * y2 - a);
1483
- let { isValid, value: x } = uvRatio2(u, v);
1740
+ const y2 = Fp2.sqr(y);
1741
+ const u = Fp2.sub(y2, Fp2.ONE);
1742
+ const v = Fp2.sub(Fp2.mulN(d, y2), a);
1743
+ let { isValid, value: x2 } = uvRatio2(u, v);
1484
1744
  if (!isValid)
1485
1745
  throw new Error("bad point: invalid y coordinate");
1486
- const isXOdd = (x & _1n4) === _1n4;
1746
+ const isXOdd = isOdd(x2);
1487
1747
  const isLastByteOdd = (lastByte & 128) !== 0;
1488
- if (!zip215 && x === _0n4 && isLastByteOdd)
1748
+ if (!zip215 && Fp2.is0(x2) && isLastByteOdd)
1489
1749
  throw new Error("bad point: x=0 and x_0=1");
1490
1750
  if (isLastByteOdd !== isXOdd)
1491
- x = modP(-x);
1492
- return Point.fromAffine({ x, y });
1751
+ x2 = Fp2.neg(x2);
1752
+ return Point.fromAffine({ x: x2, y });
1493
1753
  }
1494
1754
  static fromHex(hex, zip215 = false) {
1495
1755
  return Point.fromBytes(hexToBytes2(hex), zip215);
@@ -1500,8 +1760,8 @@ function edwards(params, extraOpts = {}) {
1500
1760
  get y() {
1501
1761
  return this.toAffine().y;
1502
1762
  }
1503
- precompute(windowSize = 8, isLazy = true) {
1504
- wnaf.createCache(this, windowSize);
1763
+ precompute(windowSize = 6, isLazy = true) {
1764
+ wnaf.setWindowSize(this, windowSize);
1505
1765
  if (!isLazy)
1506
1766
  this.multiply(_2n2);
1507
1767
  return this;
@@ -1513,18 +1773,18 @@ function edwards(params, extraOpts = {}) {
1513
1773
  if (p.is0())
1514
1774
  throw new Error("bad point: ZERO");
1515
1775
  const { X, Y, Z, T } = p;
1516
- const X2 = modP(X * X);
1517
- const Y2 = modP(Y * Y);
1518
- const Z2 = modP(Z * Z);
1519
- const Z4 = modP(Z2 * Z2);
1520
- const aX2 = modP(X2 * a);
1521
- const left = modP(Z2 * modP(aX2 + Y2));
1522
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1523
- if (left !== right)
1776
+ const X2 = Fp2.sqr(X);
1777
+ const Y2 = Fp2.sqr(Y);
1778
+ const Z2 = Fp2.sqr(Z);
1779
+ const Z4 = Fp2.sqr(Z2);
1780
+ const aX2 = Fp2.mul(X2, a);
1781
+ const left = Fp2.mul(Fp2.add(aX2, Y2), Z2);
1782
+ const right = Fp2.add(Z4, Fp2.mul(d, Fp2.mul(X2, Y2)));
1783
+ if (!Fp2.eql(left, right))
1524
1784
  throw new Error("bad point: equation left != right (1)");
1525
- const XY = modP(X * Y);
1526
- const ZT = modP(Z * T);
1527
- if (XY !== ZT)
1785
+ const XY = Fp2.mul(X, Y);
1786
+ const ZT = Fp2.mul(Z, T);
1787
+ if (!Fp2.eql(XY, ZT))
1528
1788
  throw new Error("bad point: equation left != right (2)");
1529
1789
  }
1530
1790
  // Compare one point to another.
@@ -1532,37 +1792,36 @@ function edwards(params, extraOpts = {}) {
1532
1792
  aedpoint(other);
1533
1793
  const { X: X1, Y: Y1, Z: Z1 } = this;
1534
1794
  const { X: X2, Y: Y2, Z: Z2 } = other;
1535
- const X1Z2 = modP(X1 * Z2);
1536
- const X2Z1 = modP(X2 * Z1);
1537
- const Y1Z2 = modP(Y1 * Z2);
1538
- const Y2Z1 = modP(Y2 * Z1);
1539
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1795
+ const X1Z2 = Fp2.mul(X1, Z2);
1796
+ const X2Z1 = Fp2.mul(X2, Z1);
1797
+ const Y1Z2 = Fp2.mul(Y1, Z2);
1798
+ const Y2Z1 = Fp2.mul(Y2, Z1);
1799
+ return Fp2.eql(X1Z2, X2Z1) && Fp2.eql(Y1Z2, Y2Z1);
1540
1800
  }
1541
1801
  is0() {
1542
1802
  return this.equals(Point.ZERO);
1543
1803
  }
1544
1804
  negate() {
1545
- return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1805
+ return new Point(Fp2.neg(this.X), this.Y, this.Z, Fp2.neg(this.T));
1546
1806
  }
1547
1807
  // Fast algo for doubling Extended Point.
1548
1808
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1549
1809
  // Cost: 4M + 4S + 1*a + 6add + 1*2.
1550
1810
  double() {
1551
- const { a } = CURVE;
1552
1811
  const { X: X1, Y: Y1, Z: Z1 } = this;
1553
- const A = modP(X1 * X1);
1554
- const B = modP(Y1 * Y1);
1555
- const C = modP(_2n2 * modP(Z1 * Z1));
1556
- const D = modP(a * A);
1557
- const x1y1 = X1 + Y1;
1558
- const E = modP(modP(x1y1 * x1y1) - A - B);
1559
- const G = D + B;
1560
- const F = G - C;
1561
- const H = D - B;
1562
- const X3 = modP(E * F);
1563
- const Y3 = modP(G * H);
1564
- const T3 = modP(E * H);
1565
- const Z3 = modP(F * G);
1812
+ const A = Fp2.sqr(X1);
1813
+ const B = Fp2.sqr(Y1);
1814
+ const C = Fp2.mul(Fp2.sqr(Z1), _2n2);
1815
+ const D = mulA(A);
1816
+ const x1y1 = Fp2.addN(X1, Y1);
1817
+ const E = Fp2.sub(Fp2.subN(Fp2.sqr(x1y1), A), B);
1818
+ const G = Fp2.addN(D, B);
1819
+ const F = Fp2.subN(G, C);
1820
+ const H = Fp2.subN(D, B);
1821
+ const X3 = Fp2.mul(E, F);
1822
+ const Y3 = Fp2.mul(G, H);
1823
+ const T3 = Fp2.mul(E, H);
1824
+ const Z3 = Fp2.mul(F, G);
1566
1825
  return new Point(X3, Y3, Z3, T3);
1567
1826
  }
1568
1827
  // Fast algo for adding 2 Extended Points.
@@ -1570,21 +1829,21 @@ function edwards(params, extraOpts = {}) {
1570
1829
  // Cost: 9M + 1*a + 1*d + 7add.
1571
1830
  add(other) {
1572
1831
  aedpoint(other);
1573
- const { a, d } = CURVE;
1832
+ const { d } = CURVE;
1574
1833
  const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1575
1834
  const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1576
- const A = modP(X1 * X2);
1577
- const B = modP(Y1 * Y2);
1578
- const C = modP(T1 * d * T2);
1579
- const D = modP(Z1 * Z2);
1580
- const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1581
- const F = D - C;
1582
- const G = D + C;
1583
- const H = modP(B - a * A);
1584
- const X3 = modP(E * F);
1585
- const Y3 = modP(G * H);
1586
- const T3 = modP(E * H);
1587
- const Z3 = modP(F * G);
1835
+ const A = Fp2.mul(X1, X2);
1836
+ const B = Fp2.mul(Y1, Y2);
1837
+ const C = Fp2.mul(Fp2.mulN(T1, d), T2);
1838
+ const D = Fp2.mul(Z1, Z2);
1839
+ const E = Fp2.sub(Fp2.subN(Fp2.mulN(Fp2.addN(X1, Y1), Fp2.addN(X2, Y2)), A), B);
1840
+ const F = Fp2.subN(D, C);
1841
+ const G = Fp2.addN(D, C);
1842
+ const H = Fp2.sub(B, mulA(A));
1843
+ const X3 = Fp2.mul(E, F);
1844
+ const Y3 = Fp2.mul(G, H);
1845
+ const T3 = Fp2.mul(E, H);
1846
+ const Z3 = Fp2.mul(F, G);
1588
1847
  return new Point(X3, Y3, Z3, T3);
1589
1848
  }
1590
1849
  subtract(other) {
@@ -1593,10 +1852,10 @@ function edwards(params, extraOpts = {}) {
1593
1852
  }
1594
1853
  // Constant-time multiplication.
1595
1854
  multiply(scalar) {
1596
- if (!Fn2.isValidNot0(scalar))
1855
+ if (!Fn.isValidNot0(scalar))
1597
1856
  throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1598
- const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1599
- return normalizeZ(Point, [p, f])[0];
1857
+ const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
1858
+ return normalize([p, f])[0];
1600
1859
  }
1601
1860
  // Non-constant-time multiplication. Uses double-and-add algorithm.
1602
1861
  // It's faster, but should only be used when you don't care about
@@ -1604,13 +1863,13 @@ function edwards(params, extraOpts = {}) {
1604
1863
  // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
1605
1864
  // n and larger values are rejected instead of being reduced mod n to the identity point.
1606
1865
  multiplyUnsafe(scalar) {
1607
- if (!Fn2.isValid(scalar))
1866
+ if (!Fn.isValid(scalar))
1608
1867
  throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1609
1868
  if (scalar === _0n4)
1610
1869
  return Point.ZERO;
1611
1870
  if (this.is0() || scalar === _1n4)
1612
1871
  return this;
1613
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));
1872
+ return wnaf.mulUnsafe(this, scalar, normalize);
1614
1873
  }
1615
1874
  // Checks if point is of small order.
1616
1875
  // If you add something to small order point, you will have "dirty"
@@ -1622,35 +1881,43 @@ function edwards(params, extraOpts = {}) {
1622
1881
  // Multiplies point by curve order and checks if the result is 0.
1623
1882
  // Returns `false` is the point is dirty.
1624
1883
  isTorsionFree() {
1625
- return wnaf.unsafe(this, CURVE.n).is0();
1884
+ return wnaf.mulUnsafe(this, CURVE.n).is0();
1626
1885
  }
1627
1886
  // Converts Extended point to default (x, y) coordinates.
1628
1887
  // Can accept precomputed Z^-1 - for example, from invertBatch.
1629
1888
  toAffine(invertedZ) {
1630
1889
  const p = this;
1631
1890
  let iz = invertedZ;
1891
+ if (iz != null && typeof iz !== "bigint")
1892
+ throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
1632
1893
  const { X, Y, Z } = p;
1633
1894
  const is0 = p.is0();
1634
1895
  if (iz == null)
1635
- iz = is0 ? _8n2 : Fp2.inv(Z);
1636
- const x = modP(X * iz);
1637
- const y = modP(Y * iz);
1896
+ iz = is0 ? Fp2.create(_8n2) : Fp2.inv(Z);
1897
+ const x2 = Fp2.mul(X, iz);
1898
+ const y = Fp2.mul(Y, iz);
1638
1899
  const zz = Fp2.mul(Z, iz);
1639
1900
  if (is0)
1640
- return { x: _0n4, y: _1n4 };
1641
- if (zz !== _1n4)
1901
+ return { x: Fp2.ZERO, y: Fp2.ONE };
1902
+ if (!Fp2.eql(zz, Fp2.ONE))
1642
1903
  throw new Error("invZ was invalid");
1643
- return { x, y };
1904
+ return { x: x2, y };
1644
1905
  }
1645
1906
  clearCofactor() {
1646
1907
  if (cofactor === _1n4)
1647
1908
  return this;
1909
+ if (cofactor === _2n2)
1910
+ return this.double();
1911
+ if (cofactor === _4n3)
1912
+ return this.double().double();
1913
+ if (cofactor === _8n2)
1914
+ return this.double().double().double();
1648
1915
  return this.multiplyUnsafe(cofactor);
1649
1916
  }
1650
1917
  toBytes() {
1651
- const { x, y } = this.toAffine();
1918
+ const { x: x2, y } = this.toAffine();
1652
1919
  const bytes = Fp2.toBytes(y);
1653
- bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1920
+ bytes[bytes.length - 1] |= isOdd(x2) ? 128 : 0;
1654
1921
  return bytes;
1655
1922
  }
1656
1923
  toHex() {
@@ -1660,94 +1927,16 @@ function edwards(params, extraOpts = {}) {
1660
1927
  return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1661
1928
  }
1662
1929
  }
1663
- const wnaf = new wNAF(Point, Fn2.BITS);
1664
- if (Fn2.BITS >= 8)
1665
- Point.BASE.precompute(8);
1930
+ const normalize = (points) => normalizeZ(Point, points);
1931
+ const wnaf = new ScalarMultiplier(Point, randomBytes5);
1932
+ if (wnaf.bits >= 6)
1933
+ Point.BASE.precompute(6);
1666
1934
  Object.freeze(Point.prototype);
1667
1935
  Object.freeze(Point);
1668
1936
  return Point;
1669
1937
  }
1670
- var PrimeEdwardsPoint = class {
1671
- static BASE;
1672
- static ZERO;
1673
- static Fp;
1674
- static Fn;
1675
- ep;
1676
- /**
1677
- * Wrap one internal Edwards representative directly.
1678
- * This is not a canonical encoding boundary: alternate Edwards
1679
- * representatives may still describe the same abstract wrapper element.
1680
- */
1681
- constructor(ep) {
1682
- this.ep = ep;
1683
- }
1684
- // Static methods that must be implemented by subclasses
1685
- static fromBytes(_bytes) {
1686
- notImplemented();
1687
- }
1688
- static fromHex(_hex) {
1689
- notImplemented();
1690
- }
1691
- get x() {
1692
- return this.toAffine().x;
1693
- }
1694
- get y() {
1695
- return this.toAffine().y;
1696
- }
1697
- // Common implementations
1698
- clearCofactor() {
1699
- return this;
1700
- }
1701
- assertValidity() {
1702
- this.ep.assertValidity();
1703
- }
1704
- /**
1705
- * Return affine coordinates of the current internal Edwards representative.
1706
- * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
1707
- * Equal abstract elements may expose different `x` / `y`; use
1708
- * `toBytes()` / `fromBytes()` for canonical roundtrips.
1709
- */
1710
- toAffine(invertedZ) {
1711
- return this.ep.toAffine(invertedZ);
1712
- }
1713
- toHex() {
1714
- return bytesToHex2(this.toBytes());
1715
- }
1716
- toString() {
1717
- return this.toHex();
1718
- }
1719
- isTorsionFree() {
1720
- return true;
1721
- }
1722
- isSmallOrder() {
1723
- return false;
1724
- }
1725
- add(other) {
1726
- this.assertSame(other);
1727
- return this.init(this.ep.add(other.ep));
1728
- }
1729
- subtract(other) {
1730
- this.assertSame(other);
1731
- return this.init(this.ep.subtract(other.ep));
1732
- }
1733
- multiply(scalar) {
1734
- return this.init(this.ep.multiply(scalar));
1735
- }
1736
- multiplyUnsafe(scalar) {
1737
- return this.init(this.ep.multiplyUnsafe(scalar));
1738
- }
1739
- double() {
1740
- return this.init(this.ep.double());
1741
- }
1742
- negate() {
1743
- return this.init(this.ep.negate());
1744
- }
1745
- precompute(windowSize, isLazy) {
1746
- this.ep.precompute(windowSize, isLazy);
1747
- return this;
1748
- }
1749
- };
1750
1938
  function eddsa(Point, cHash, eddsaOpts = {}) {
1939
+ validatePointCons(Point);
1751
1940
  if (typeof cHash !== "function")
1752
1941
  throw new Error('"hash" function param is required');
1753
1942
  const hash = cHash;
@@ -1758,10 +1947,12 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1758
1947
  domain: "function",
1759
1948
  prehash: "function",
1760
1949
  zip215: "boolean",
1761
- mapToCurve: "function"
1950
+ mapToCurve: "function",
1951
+ toMontgomery: "function",
1952
+ toMontgomerySecret: "function"
1762
1953
  });
1763
1954
  const { prehash } = opts;
1764
- const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
1955
+ const { BASE, Fp: Fp2, Fn } = Point;
1765
1956
  const outputLen = hash.outputLen;
1766
1957
  const expectedLen = 2 * Fp2.BYTES;
1767
1958
  if (outputLen !== void 0) {
@@ -1770,6 +1961,8 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1770
1961
  throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
1771
1962
  }
1772
1963
  const randomBytes5 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
1964
+ const toMontgomery2 = opts.toMontgomery;
1965
+ const toMontgomerySecret2 = opts.toMontgomerySecret;
1773
1966
  const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
1774
1967
  const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
1775
1968
  abool(phflag, "phflag");
@@ -1778,7 +1971,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1778
1971
  return data;
1779
1972
  } : opts.domain;
1780
1973
  function modN_LE(hash2) {
1781
- return Fn2.create(bytesToNumberLE(hash2));
1974
+ return Fn.create(bytesToNumberLE(hash2));
1782
1975
  }
1783
1976
  function getPrivateScalar(key) {
1784
1977
  const len = lengths.secretKey;
@@ -1803,23 +1996,25 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1803
1996
  return modN_LE(hash(domain(msg, abytes2(context, void 0, "context"), !!prehash)));
1804
1997
  }
1805
1998
  function sign(msg, secretKey, options = {}) {
1806
- msg = abytes2(msg, void 0, "message");
1999
+ validateObject(options, {}, {}, "options");
2000
+ msg = copyBytes2(abytes2(msg, void 0, "message"));
1807
2001
  if (prehash)
1808
2002
  msg = prehash(msg);
1809
2003
  const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
1810
2004
  const r = hashDomainToScalar(options.context, prefix, msg);
1811
2005
  const R = BASE.multiply(r).toBytes();
1812
2006
  const k = hashDomainToScalar(options.context, R, pointBytes, msg);
1813
- const s = Fn2.create(r + k * scalar);
1814
- if (!Fn2.isValid(s))
2007
+ const s = Fn.create(r + k * scalar);
2008
+ if (!Fn.isValid(s))
1815
2009
  throw new Error("sign failed: invalid s");
1816
- const rs = concatBytes2(R, Fn2.toBytes(s));
2010
+ const rs = concatBytes2(R, Fn.toBytes(s));
1817
2011
  return abytes2(rs, lengths.signature, "result");
1818
2012
  }
1819
2013
  const verifyOpts = {
1820
2014
  zip215: opts.zip215
1821
2015
  };
1822
2016
  function verify(sig, msg, publicKey, options = verifyOpts) {
2017
+ validateObject(options);
1823
2018
  const { context } = options;
1824
2019
  const zip215 = options.zip215 === void 0 ? !!verifyOpts.zip215 : options.zip215;
1825
2020
  const len = lengths.signature;
@@ -1873,29 +2068,16 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1873
2068
  randomSecretKey,
1874
2069
  isValidSecretKey,
1875
2070
  isValidPublicKey,
1876
- /**
1877
- * Converts ed public key to x public key. Uses formula:
1878
- * - ed25519:
1879
- * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
1880
- * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
1881
- * - ed448:
1882
- * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
1883
- * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
1884
- */
2071
+ /** Converts an Edwards public key to a companion Montgomery public key. */
1885
2072
  toMontgomery(publicKey) {
1886
- const { y } = Point.fromBytes(publicKey);
1887
- const size = lengths.publicKey;
1888
- const is25519 = size === 32;
1889
- if (!is25519 && size !== 57)
1890
- throw new Error("only defined for 25519 and 448");
1891
- const u = is25519 ? Fp2.div(_1n4 + y, _1n4 - y) : Fp2.div(y - _1n4, y + _1n4);
1892
- return Fp2.toBytes(u);
2073
+ if (toMontgomery2 === void 0)
2074
+ throw new Error("Montgomery conversion is not supported for this curve");
2075
+ return toMontgomery2(Point.fromBytes(publicKey));
1893
2076
  },
1894
2077
  toMontgomerySecret(secretKey) {
1895
- const size = lengths.secretKey;
1896
- abytes2(secretKey, size);
1897
- const hashed = hash(secretKey.subarray(0, size));
1898
- return adjustScalarBytes2(hashed).subarray(0, size);
2078
+ if (toMontgomerySecret2 === void 0)
2079
+ throw new Error("Montgomery conversion is not supported for this curve");
2080
+ return toMontgomerySecret2(secretKey);
1899
2081
  }
1900
2082
  };
1901
2083
  Object.freeze(lengths);
@@ -1911,65 +2093,22 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1911
2093
  });
1912
2094
  }
1913
2095
 
1914
- // ../../node_modules/@noble/curves/abstract/hash-to-curve.js
1915
- function i2osp(value, length) {
1916
- asafenumber(value);
1917
- asafenumber(length);
1918
- if (length < 0 || length > 4)
1919
- throw new Error("invalid I2OSP length: " + length);
1920
- if (value < 0 || value > 2 ** (8 * length) - 1)
1921
- throw new Error("invalid I2OSP input: " + value);
1922
- const res = Array.from({ length }).fill(0);
1923
- for (let i = length - 1; i >= 0; i--) {
1924
- res[i] = value & 255;
1925
- value >>>= 8;
1926
- }
1927
- return new Uint8Array(res);
1928
- }
1929
- function strxor(a, b) {
1930
- const arr = new Uint8Array(a.length);
1931
- for (let i = 0; i < a.length; i++) {
1932
- arr[i] = a[i] ^ b[i];
1933
- }
1934
- return arr;
1935
- }
1936
- function normDST(DST) {
1937
- if (!isBytes2(DST) && typeof DST !== "string")
1938
- throw new Error("DST must be Uint8Array or ascii string");
1939
- const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
1940
- if (dst.length === 0)
1941
- throw new Error("DST must be non-empty");
1942
- return dst;
1943
- }
1944
- function expand_message_xmd(msg, DST, lenInBytes, H) {
1945
- abytes2(msg);
1946
- asafenumber(lenInBytes);
1947
- DST = normDST(DST);
1948
- if (DST.length > 255)
1949
- DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
1950
- const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1951
- const ell = Math.ceil(lenInBytes / b_in_bytes);
1952
- if (lenInBytes > 65535 || ell > 255)
1953
- throw new Error("expand_message_xmd: invalid lenInBytes");
1954
- const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
1955
- const Z_pad = new Uint8Array(r_in_bytes);
1956
- const l_i_b_str = i2osp(lenInBytes, 2);
1957
- const b = new Array(ell);
1958
- const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1959
- b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
1960
- for (let i = 1; i < ell; i++) {
1961
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1962
- b[i] = H(concatBytes2(...args));
1963
- }
1964
- const pseudo_random_bytes = concatBytes2(...b);
1965
- return pseudo_random_bytes.slice(0, lenInBytes);
1966
- }
1967
- var _DST_scalar = "HashToScalar-";
1968
-
1969
2096
  // ../../node_modules/@noble/curves/abstract/montgomery.js
1970
- var _0n5 = BigInt(0);
1971
- var _1n5 = BigInt(1);
1972
- var _2n3 = BigInt(2);
2097
+ var _0n5 = /* @__PURE__ */ BigInt(0);
2098
+ var _1n5 = /* @__PURE__ */ BigInt(1);
2099
+ var _2n3 = /* @__PURE__ */ BigInt(2);
2100
+ function cmask(P, swap) {
2101
+ return P + swap - (swap >> _1n5 << _1n5);
2102
+ }
2103
+ function cswap(P) {
2104
+ const offset = BigInt(6) * P;
2105
+ return (mask, x_2, x_3) => {
2106
+ const sum = x_2 + x_3;
2107
+ const d = offset + x_3 - x_2;
2108
+ const a = (d * mask + x_2) % P;
2109
+ return { x_2: a, x_3: sum - a };
2110
+ };
2111
+ }
1973
2112
  function validateOpts(curve) {
1974
2113
  validateObject(curve, {
1975
2114
  P: "bigint",
@@ -1977,23 +2116,26 @@ function validateOpts(curve) {
1977
2116
  adjustScalarBytes: "function",
1978
2117
  powPminus2: "function"
1979
2118
  }, {
1980
- randomBytes: "function"
2119
+ randomBytes: "function",
2120
+ scalarMultBase: "function"
1981
2121
  });
1982
2122
  return Object.freeze({ ...curve });
1983
2123
  }
1984
2124
  function montgomery(curveDef) {
1985
2125
  const CURVE = validateOpts(curveDef);
1986
2126
  const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
2127
+ const mulBaseHook = CURVE.scalarMultBase;
1987
2128
  const is25519 = type === "x25519";
1988
2129
  if (!is25519 && type !== "x448")
1989
2130
  throw new Error("invalid type");
1990
2131
  const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
1991
2132
  const montgomeryBits = is25519 ? 255 : 448;
2133
+ const swap = cswap(P);
1992
2134
  const fieldLen = is25519 ? 32 : 56;
1993
2135
  const Gu = is25519 ? BigInt(9) : BigInt(5);
1994
2136
  const a24 = is25519 ? BigInt(121665) : BigInt(39081);
1995
2137
  const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
1996
- const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
2138
+ const maxAdded = is25519 ? BigInt(8) * (_2n3 ** BigInt(251) - _1n5) : BigInt(4) * (_2n3 ** BigInt(445) - _1n5);
1997
2139
  const maxScalar = minScalar + maxAdded + _1n5;
1998
2140
  const modP = (n) => mod(n, P);
1999
2141
  const GuBytes = encodeU(Gu);
@@ -2001,31 +2143,42 @@ function montgomery(curveDef) {
2001
2143
  return numberToBytesLE(modP(u), fieldLen);
2002
2144
  }
2003
2145
  function decodeU(u) {
2004
- const _u = copyBytes(abytes2(u, fieldLen, "uCoordinate"));
2146
+ const _u = copyBytes2(abytes2(u, fieldLen, "uCoordinate"));
2005
2147
  if (is25519)
2006
2148
  _u[31] &= 127;
2007
2149
  return modP(bytesToNumberLE(_u));
2008
2150
  }
2009
2151
  function decodeScalar(scalar) {
2010
- return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
2011
- }
2152
+ return bytesToNumberLE(adjustScalarBytes2(copyBytes2(abytes2(scalar, fieldLen, "scalar"))));
2153
+ }
2154
+ const lowOrderU = new Set(is25519 ? [
2155
+ _0n5,
2156
+ _1n5,
2157
+ P - _1n5,
2158
+ BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),
2159
+ BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")
2160
+ ] : [_0n5, _1n5, P - _1n5]);
2012
2161
  function scalarMult(scalar, u) {
2013
- const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
2162
+ const pointU = decodeU(u);
2163
+ if (lowOrderU.has(pointU))
2164
+ throw new Error("invalid private or public key received");
2165
+ const pu = montgomeryLadder(pointU, decodeScalar(scalar));
2014
2166
  if (pu === _0n5)
2015
2167
  throw new Error("invalid private or public key received");
2016
2168
  return encodeU(pu);
2017
2169
  }
2018
2170
  function scalarMultBase(scalar) {
2019
- return scalarMult(scalar, GuBytes);
2171
+ if (mulBaseHook === void 0)
2172
+ return scalarMult(scalar, GuBytes);
2173
+ const k = decodeScalar(scalar);
2174
+ aInRange("scalar", k, minScalar, maxScalar);
2175
+ const pu = modP(mulBaseHook(k));
2176
+ if (pu === _0n5)
2177
+ throw new Error("invalid private or public key received");
2178
+ return encodeU(pu);
2020
2179
  }
2021
2180
  const getPublicKey = scalarMultBase;
2022
2181
  const getSharedSecret = scalarMult;
2023
- function cswap(swap, x_2, x_3) {
2024
- const dummy = modP(swap * (x_2 - x_3));
2025
- x_2 = modP(x_2 - dummy);
2026
- x_3 = modP(x_3 + dummy);
2027
- return { x_2, x_3 };
2028
- }
2029
2182
  function montgomeryLadder(u, scalar) {
2030
2183
  aInRange("u", u, _0n5, P);
2031
2184
  aInRange("scalar", scalar, minScalar, maxScalar);
@@ -2035,13 +2188,11 @@ function montgomery(curveDef) {
2035
2188
  let z_2 = _0n5;
2036
2189
  let x_3 = u;
2037
2190
  let z_3 = _1n5;
2038
- let swap = _0n5;
2191
+ const kx = k ^ k >> _1n5;
2039
2192
  for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
2040
- const k_t = k >> t & _1n5;
2041
- swap ^= k_t;
2042
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
2043
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
2044
- swap = k_t;
2193
+ const mask2 = cmask(P, kx >> t);
2194
+ ({ x_2, x_3 } = swap(mask2, x_2, x_3));
2195
+ ({ x_2: z_2, x_3: z_3 } = swap(mask2, z_2, z_3));
2045
2196
  const A = x_2 + z_2;
2046
2197
  const AA = modP(A * A);
2047
2198
  const B = x_2 - z_2;
@@ -2058,8 +2209,9 @@ function montgomery(curveDef) {
2058
2209
  x_2 = modP(AA * BB);
2059
2210
  z_2 = modP(E * (AA + modP(a24 * E)));
2060
2211
  }
2061
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
2062
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
2212
+ const mask = cmask(P, k);
2213
+ ({ x_2, x_3 } = swap(mask, x_2, x_3));
2214
+ ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));
2063
2215
  const z2 = powPminus2(z_2);
2064
2216
  return modP(x_2 * z2);
2065
2217
  }
@@ -2105,13 +2257,13 @@ var ed25519_CURVE = /* @__PURE__ */ (() => ({
2105
2257
  Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2106
2258
  Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2107
2259
  }))();
2108
- function ed25519_pow_2_252_3(x) {
2260
+ function ed25519_pow_2_252_3(x2) {
2109
2261
  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2110
2262
  const P = ed25519_CURVE_p;
2111
- const x2 = x * x % P;
2112
- const b2 = x2 * x % P;
2263
+ const x22 = x2 * x2 % P;
2264
+ const b2 = x22 * x2 % P;
2113
2265
  const b4 = pow2(b2, _2n4, P) * b2 % P;
2114
- const b5 = pow2(b4, _1n6, P) * x % P;
2266
+ const b5 = pow2(b4, _1n6, P) * x2 % P;
2115
2267
  const b10 = pow2(b5, _5n2, P) * b5 % P;
2116
2268
  const b20 = pow2(b10, _10n, P) * b10 % P;
2117
2269
  const b40 = pow2(b20, _20n, P) * b20 % P;
@@ -2119,7 +2271,7 @@ function ed25519_pow_2_252_3(x) {
2119
2271
  const b160 = pow2(b80, _80n, P) * b80 % P;
2120
2272
  const b240 = pow2(b160, _80n, P) * b80 % P;
2121
2273
  const b250 = pow2(b240, _10n, P) * b10 % P;
2122
- const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
2274
+ const pow_p_5_8 = pow2(b250, _2n4, P) * x2 % P;
2123
2275
  return { pow_p_5_8, b2 };
2124
2276
  }
2125
2277
  function adjustScalarBytes(bytes) {
@@ -2133,233 +2285,60 @@ function uvRatio(u, v) {
2133
2285
  const P = ed25519_CURVE_p;
2134
2286
  const v3 = mod(v * v * v, P);
2135
2287
  const v7 = mod(v3 * v3 * v, P);
2136
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2137
- let x = mod(u * v3 * pow, P);
2138
- const vx2 = mod(v * x * x, P);
2139
- const root1 = x;
2140
- const root2 = mod(x * ED25519_SQRT_M1, P);
2288
+ const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2289
+ let x2 = mod(u * v3 * pow3, P);
2290
+ const vx2 = mod(v * x2 * x2, P);
2291
+ const root1 = x2;
2292
+ const root2 = mod(x2 * ED25519_SQRT_M1, P);
2141
2293
  const useRoot1 = vx2 === u;
2142
2294
  const useRoot2 = vx2 === mod(-u, P);
2143
2295
  const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2144
2296
  if (useRoot1)
2145
- x = root1;
2297
+ x2 = root1;
2146
2298
  if (useRoot2 || noRoot)
2147
- x = root2;
2148
- if (isNegativeLE(x, P))
2149
- x = mod(-x, P);
2150
- return { isValid: useRoot1 || useRoot2, value: x };
2299
+ x2 = root2;
2300
+ if (isNegativeLE(x2, P))
2301
+ x2 = mod(-x2, P);
2302
+ return { isValid: useRoot1 || useRoot2, value: x2 };
2151
2303
  }
2152
2304
  var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2153
2305
  var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
2154
- var Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
2306
+ function toMontgomery(point) {
2307
+ const { y } = point;
2308
+ return Fp.toBytes(Fp.div(_1n6 + y, _1n6 - y));
2309
+ }
2310
+ function toMontgomerySecret(secretKey) {
2311
+ const size = ed25519_Point.Fp.BYTES;
2312
+ abytes(secretKey, size);
2313
+ return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);
2314
+ }
2155
2315
  function ed(opts) {
2156
- return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, zip215: true }, opts));
2316
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));
2157
2317
  }
2158
2318
  var ed25519 = /* @__PURE__ */ ed({});
2159
2319
  var x25519 = /* @__PURE__ */ (() => {
2160
2320
  const P = ed25519_CURVE_p;
2321
+ const powPminus2 = (x2) => {
2322
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x2);
2323
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2324
+ };
2161
2325
  return montgomery({
2162
2326
  P,
2163
2327
  type: "x25519",
2164
- powPminus2: (x) => {
2165
- const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
2166
- return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2167
- },
2168
- adjustScalarBytes
2328
+ powPminus2,
2329
+ adjustScalarBytes,
2330
+ // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached
2331
+ // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.
2332
+ // Same construction as libsodium's crypto_scalarmult_curve25519_base.
2333
+ scalarMultBase: (k) => {
2334
+ const kn = mod(k, ed25519_Point.Fn.ORDER);
2335
+ if (kn === _0n6)
2336
+ return _0n6;
2337
+ const p = ed25519_Point.BASE.multiply(kn);
2338
+ return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);
2339
+ }
2169
2340
  });
2170
2341
  })();
2171
- var SQRT_M1 = ED25519_SQRT_M1;
2172
- var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
2173
- var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
2174
- var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
2175
- var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
2176
- var invertSqrt = (number) => uvRatio(_1n6, number);
2177
- var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2178
- var bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
2179
- function calcElligatorRistrettoMap(r0) {
2180
- const { d } = ed25519_CURVE;
2181
- const P = ed25519_CURVE_p;
2182
- const mod2 = (n) => Fp.create(n);
2183
- const r = mod2(SQRT_M1 * r0 * r0);
2184
- const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
2185
- let c = BigInt(-1);
2186
- const D = mod2((c - d * r) * mod2(r + d));
2187
- let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
2188
- let s_ = mod2(s * r0);
2189
- if (!isNegativeLE(s_, P))
2190
- s_ = mod2(-s_);
2191
- if (!Ns_D_is_sq)
2192
- s = s_;
2193
- if (!Ns_D_is_sq)
2194
- c = r;
2195
- const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2196
- const s2 = s * s;
2197
- const W0 = mod2((s + s) * D);
2198
- const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2199
- const W2 = mod2(_1n6 - s2);
2200
- const W3 = mod2(_1n6 + s2);
2201
- return new ed25519_Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2202
- }
2203
- var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2204
- // Do NOT change syntax: the following gymnastics is done,
2205
- // because typescript strips comments, which makes bundlers disable tree-shaking.
2206
- // prettier-ignore
2207
- static BASE = /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.BASE))();
2208
- // prettier-ignore
2209
- static ZERO = /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.ZERO))();
2210
- // prettier-ignore
2211
- static Fp = /* @__PURE__ */ (() => Fp)();
2212
- // prettier-ignore
2213
- static Fn = /* @__PURE__ */ (() => Fn)();
2214
- constructor(ep) {
2215
- super(ep);
2216
- }
2217
- /**
2218
- * Create one Ristretto255 point from affine Edwards coordinates.
2219
- * This wraps the internal Edwards representative directly and is not a
2220
- * canonical ristretto255 decoding path.
2221
- * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
2222
- */
2223
- static fromAffine(ap) {
2224
- return new __RistrettoPoint(ed25519_Point.fromAffine(ap));
2225
- }
2226
- assertSame(other) {
2227
- if (!(other instanceof __RistrettoPoint))
2228
- throw new Error("RistrettoPoint expected");
2229
- }
2230
- init(ep) {
2231
- return new __RistrettoPoint(ep);
2232
- }
2233
- static fromBytes(bytes) {
2234
- abytes(bytes, 32);
2235
- const { a, d } = ed25519_CURVE;
2236
- const P = ed25519_CURVE_p;
2237
- const mod2 = (n) => Fp.create(n);
2238
- const s = bytes255ToNumberLE(bytes);
2239
- if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2240
- throw new Error("invalid ristretto255 encoding 1");
2241
- const s2 = mod2(s * s);
2242
- const u1 = mod2(_1n6 + a * s2);
2243
- const u2 = mod2(_1n6 - a * s2);
2244
- const u1_2 = mod2(u1 * u1);
2245
- const u2_2 = mod2(u2 * u2);
2246
- const v = mod2(a * d * u1_2 - u2_2);
2247
- const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2248
- const Dx = mod2(I * u2);
2249
- const Dy = mod2(I * Dx * v);
2250
- let x = mod2((s + s) * Dx);
2251
- if (isNegativeLE(x, P))
2252
- x = mod2(-x);
2253
- const y = mod2(u1 * Dy);
2254
- const t = mod2(x * y);
2255
- if (!isValid || isNegativeLE(t, P) || y === _0n6)
2256
- throw new Error("invalid ristretto255 encoding 2");
2257
- return new __RistrettoPoint(new ed25519_Point(x, y, _1n6, t));
2258
- }
2259
- /**
2260
- * Converts ristretto-encoded string to ristretto point.
2261
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2262
- * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2263
- */
2264
- static fromHex(hex) {
2265
- return __RistrettoPoint.fromBytes(hexToBytes(hex));
2266
- }
2267
- /**
2268
- * Encodes ristretto point to Uint8Array.
2269
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2270
- */
2271
- toBytes() {
2272
- let { X, Y, Z, T } = this.ep;
2273
- const P = ed25519_CURVE_p;
2274
- const mod2 = (n) => Fp.create(n);
2275
- const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2276
- const u2 = mod2(X * Y);
2277
- const u2sq = mod2(u2 * u2);
2278
- const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2279
- const D1 = mod2(invsqrt * u1);
2280
- const D2 = mod2(invsqrt * u2);
2281
- const zInv = mod2(D1 * D2 * T);
2282
- let D;
2283
- if (isNegativeLE(T * zInv, P)) {
2284
- let _x = mod2(Y * SQRT_M1);
2285
- let _y = mod2(X * SQRT_M1);
2286
- X = _x;
2287
- Y = _y;
2288
- D = mod2(D1 * INVSQRT_A_MINUS_D);
2289
- } else {
2290
- D = D2;
2291
- }
2292
- if (isNegativeLE(X * zInv, P))
2293
- Y = mod2(-Y);
2294
- let s = mod2((Z - Y) * D);
2295
- if (isNegativeLE(s, P))
2296
- s = mod2(-s);
2297
- return Fp.toBytes(s);
2298
- }
2299
- /**
2300
- * Compares two Ristretto points.
2301
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2302
- */
2303
- equals(other) {
2304
- this.assertSame(other);
2305
- const { X: X1, Y: Y1 } = this.ep;
2306
- const { X: X2, Y: Y2 } = other.ep;
2307
- const mod2 = (n) => Fp.create(n);
2308
- const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2309
- const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2310
- return one || two;
2311
- }
2312
- is0() {
2313
- return this.equals(__RistrettoPoint.ZERO);
2314
- }
2315
- };
2316
- Object.freeze(_RistrettoPoint.BASE);
2317
- Object.freeze(_RistrettoPoint.ZERO);
2318
- Object.freeze(_RistrettoPoint.prototype);
2319
- Object.freeze(_RistrettoPoint);
2320
- var ristretto255_hasher = Object.freeze({
2321
- Point: _RistrettoPoint,
2322
- /**
2323
- * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
2324
- * * There are no test vectors
2325
- * * encodeToCurve / mapToCurve is undefined
2326
- * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!
2327
- * * hashToScalar is undefined too, so we just use OPRF implementation
2328
- * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
2329
- (os2ip -> bytes255ToNumberLE)
2330
- * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
2331
- * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
2332
- version here. Using `bytes255ToNumblerLE` will create a different result
2333
- if we use `bytes255ToNumberLE` as os2ip
2334
- * * current version is closest to spec.
2335
- */
2336
- hashToCurve(msg, options) {
2337
- const DST = options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2338
- const xmd = expand_message_xmd(msg, DST, 64, sha512);
2339
- return ristretto255_hasher.deriveToCurve(xmd);
2340
- },
2341
- hashToScalar(msg, options = { DST: _DST_scalar }) {
2342
- const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2343
- return Fn.create(bytesToNumberLE(xmd));
2344
- },
2345
- /**
2346
- * HashToCurve-like construction based on RFC 9496 (Element Derivation).
2347
- * Converts 64 uniform random bytes into a curve point.
2348
- *
2349
- * WARNING: This represents an older hash-to-curve construction from before
2350
- * RFC 9380 was finalized.
2351
- * It was later reused as a component in the newer
2352
- * `hash_to_ristretto255` function defined in RFC 9380.
2353
- */
2354
- deriveToCurve(bytes) {
2355
- abytes(bytes, 64);
2356
- const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2357
- const R1 = calcElligatorRistrettoMap(r1);
2358
- const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2359
- const R2 = calcElligatorRistrettoMap(r2);
2360
- return new _RistrettoPoint(R1.add(R2));
2361
- }
2362
- });
2363
2342
 
2364
2343
  // ../../node_modules/@noble/hashes/_blake.js
2365
2344
  var BSIGMA = /* @__PURE__ */ Uint8Array.from([
@@ -2621,15 +2600,15 @@ var BSIGMA = /* @__PURE__ */ Uint8Array.from([
2621
2600
  1,
2622
2601
  9
2623
2602
  ]);
2624
- function G1s(a, b, c, d, x) {
2625
- a = a + b + x | 0;
2603
+ function G1s(a, b, c, d, x2) {
2604
+ a = a + b + x2 | 0;
2626
2605
  d = rotr(d ^ a, 16);
2627
2606
  c = c + d | 0;
2628
2607
  b = rotr(b ^ c, 12);
2629
2608
  return { a, b, c, d };
2630
2609
  }
2631
- function G2s(a, b, c, d, x) {
2632
- a = a + b + x | 0;
2610
+ function G2s(a, b, c, d, x2) {
2611
+ a = a + b + x2 | 0;
2633
2612
  d = rotr(d ^ a, 8);
2634
2613
  c = c + d | 0;
2635
2614
  b = rotr(b ^ c, 7);
@@ -2640,7 +2619,7 @@ function G2s(a, b, c, d, x) {
2640
2619
  function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
2641
2620
  anumber(keyLen);
2642
2621
  if (outputLen <= 0 || outputLen > keyLen)
2643
- throw new Error("outputLen bigger than keyLen");
2622
+ throw new Error('"dkLen" must be 1..' + keyLen + ", got " + outputLen);
2644
2623
  const { key, salt, personalization } = opts;
2645
2624
  if (key !== void 0 && (key.length < 1 || key.length > keyLen))
2646
2625
  throw new Error('"key" expected to be undefined or of length=1..' + keyLen);
@@ -2693,7 +2672,7 @@ var _BLAKE2 = class {
2693
2672
  swap32IfBE(data32);
2694
2673
  continue;
2695
2674
  }
2696
- buffer.set(data.subarray(pos, pos + take), this.pos);
2675
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
2697
2676
  this.pos += take;
2698
2677
  this.length += take;
2699
2678
  pos += take;
@@ -2703,26 +2682,26 @@ var _BLAKE2 = class {
2703
2682
  digestInto(out) {
2704
2683
  aexists(this);
2705
2684
  aoutput(out, this);
2685
+ if (out.byteOffset & 3)
2686
+ throw new RangeError('"output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
2706
2687
  const { pos, buffer32 } = this;
2707
2688
  this.finished = true;
2708
- clean(this.buffer.subarray(pos));
2689
+ this.buffer.fill(0, pos);
2709
2690
  swap32IfBE(buffer32);
2710
2691
  this.compress(buffer32, 0, true);
2711
2692
  swap32IfBE(buffer32);
2712
- if (out.byteOffset & 3)
2713
- throw new RangeError('"digestInto() output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
2714
2693
  const state = this.get();
2715
- const out32 = u32(out);
2694
+ const out32 = out === this.buffer ? buffer32 : u32(out);
2716
2695
  const full = Math.floor(this.outputLen / 4);
2717
- for (let i = 0; i < full; i++)
2718
- out32[i] = swap8IfBE(state[i]);
2696
+ for (let i2 = 0; i2 < full; i2++)
2697
+ out32[i2] = swap8IfBE(state[i2]);
2719
2698
  const tail = this.outputLen % 4;
2720
2699
  if (!tail)
2721
2700
  return;
2722
2701
  const off = full * 4;
2723
2702
  const word = state[full];
2724
- for (let i = 0; i < tail; i++)
2725
- out[off + i] = word >>> 8 * i;
2703
+ for (let i2 = 0; i2 < tail; i2++)
2704
+ out[off + i2] = word >>> 8 * i2;
2726
2705
  }
2727
2706
  digest() {
2728
2707
  const { buffer, outputLen } = this;
@@ -2747,9 +2726,9 @@ var _BLAKE2 = class {
2747
2726
  return this._cloneInto();
2748
2727
  }
2749
2728
  };
2750
- function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
2729
+ function _compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
2751
2730
  let j = 0;
2752
- for (let i = 0; i < rounds; i++) {
2731
+ for (let i2 = 0; i2 < rounds; i2++) {
2753
2732
  ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
2754
2733
  ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
2755
2734
  ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
@@ -2781,6 +2760,7 @@ var _BLAKE2s = class extends _BLAKE2 {
2781
2760
  v6 = B2S_IV[6] | 0;
2782
2761
  v7 = B2S_IV[7] | 0;
2783
2762
  constructor(opts = {}) {
2763
+ opts = checkOpts({}, opts);
2784
2764
  const olen = opts.dkLen === void 0 ? 32 : opts.dkLen;
2785
2765
  super(64, olen);
2786
2766
  checkBlake2Opts(olen, opts, 32, 8, 8);
@@ -2793,13 +2773,13 @@ var _BLAKE2s = class extends _BLAKE2 {
2793
2773
  this.v0 ^= this.outputLen | keyLength << 8 | 1 << 16 | 1 << 24;
2794
2774
  if (salt !== void 0) {
2795
2775
  abytes(salt, void 0, "salt");
2796
- const slt = u32(salt);
2776
+ const slt = u32(copyBytes(salt));
2797
2777
  this.v4 ^= swap8IfBE(slt[0]);
2798
2778
  this.v5 ^= swap8IfBE(slt[1]);
2799
2779
  }
2800
2780
  if (personalization !== void 0) {
2801
2781
  abytes(personalization, void 0, "personalization");
2802
- const pers = u32(personalization);
2782
+ const pers = u32(copyBytes(personalization));
2803
2783
  this.v6 ^= swap8IfBE(pers[0]);
2804
2784
  this.v7 ^= swap8IfBE(pers[1]);
2805
2785
  }
@@ -2807,6 +2787,7 @@ var _BLAKE2s = class extends _BLAKE2 {
2807
2787
  const tmp = new Uint8Array(this.blockLen);
2808
2788
  tmp.set(key);
2809
2789
  this.update(tmp);
2790
+ clean(tmp);
2810
2791
  }
2811
2792
  }
2812
2793
  get() {
@@ -2825,8 +2806,9 @@ var _BLAKE2s = class extends _BLAKE2 {
2825
2806
  this.v7 = v7 | 0;
2826
2807
  }
2827
2808
  compress(msg, offset, isLast) {
2828
- const { h, l } = fromBig(BigInt(this.length));
2829
- 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]);
2809
+ const l = fromNumL(this.length);
2810
+ const h = fromNumH(this.length);
2811
+ 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]);
2830
2812
  this.v0 ^= v0 ^ v8;
2831
2813
  this.v1 ^= v1 ^ v9;
2832
2814
  this.v2 ^= v2 ^ v10;
@@ -2858,18 +2840,18 @@ var _HMAC = class {
2858
2840
  abytes(key, void 0, "key");
2859
2841
  this.iHash = hash.create();
2860
2842
  if (typeof this.iHash.update !== "function")
2861
- throw new Error("Expected instance of class which extends utils.Hash");
2843
+ throw new Error("expected Hash instance");
2862
2844
  this.blockLen = this.iHash.blockLen;
2863
2845
  this.outputLen = this.iHash.outputLen;
2864
2846
  const blockLen = this.blockLen;
2865
2847
  const pad = new Uint8Array(blockLen);
2866
2848
  pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2867
- for (let i = 0; i < pad.length; i++)
2868
- pad[i] ^= 54;
2849
+ for (let i2 = 0; i2 < pad.length; i2++)
2850
+ pad[i2] ^= 54;
2869
2851
  this.iHash.update(pad);
2870
2852
  this.oHash = hash.create();
2871
- for (let i = 0; i < pad.length; i++)
2872
- pad[i] ^= 54 ^ 92;
2853
+ for (let i2 = 0; i2 < pad.length; i2++)
2854
+ pad[i2] ^= 54 ^ 92;
2873
2855
  this.oHash.update(pad);
2874
2856
  clean(pad);
2875
2857
  }
@@ -2895,12 +2877,13 @@ var _HMAC = class {
2895
2877
  }
2896
2878
  _cloneInto(to) {
2897
2879
  to ||= Object.create(Object.getPrototypeOf(this), {});
2898
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
2880
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;
2899
2881
  to = to;
2900
2882
  to.finished = finished;
2901
2883
  to.destroyed = destroyed;
2902
2884
  to.blockLen = blockLen;
2903
2885
  to.outputLen = outputLen;
2886
+ to.canXOF = canXOF;
2904
2887
  to.oHash = oHash._cloneInto(to.oHash);
2905
2888
  to.iHash = iHash._cloneInto(to.iHash);
2906
2889
  return to;
@@ -2921,15 +2904,9 @@ var hmac = /* @__PURE__ */ (() => {
2921
2904
  })();
2922
2905
 
2923
2906
  // ../../node_modules/@noble/hashes/hkdf.js
2924
- function extract(hash, ikm, salt) {
2925
- ahash(hash);
2926
- if (salt === void 0)
2927
- salt = new Uint8Array(hash.outputLen);
2928
- return hmac(hash, salt, ikm);
2929
- }
2930
2907
  var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
2931
2908
  var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
2932
- function expand(hash, prk, info, length = 32) {
2909
+ function expand(hash, prk, info, length = 32, _recycled) {
2933
2910
  ahash(hash);
2934
2911
  anumber(length, "length");
2935
2912
  abytes(prk, void 0, "prk");
@@ -2943,99 +2920,144 @@ function expand(hash, prk, info, length = 32) {
2943
2920
  info = EMPTY_BUFFER;
2944
2921
  else
2945
2922
  abytes(info, void 0, "info");
2946
- const okm = new Uint8Array(blocks * olen);
2947
- const HMAC = hmac.create(hash, prk);
2948
- const HMACTmp = HMAC._cloneInto();
2949
- const T = new Uint8Array(HMAC.outputLen);
2950
- for (let counter = 0; counter < blocks; counter++) {
2923
+ if (!blocks) {
2924
+ if (_recycled)
2925
+ clean(prk);
2926
+ return new Uint8Array();
2927
+ }
2928
+ const okm = _recycled && blocks === 1 ? prk : new Uint8Array(blocks * olen);
2929
+ const { iHash, oHash } = hmac.create(hash, prk);
2930
+ const T = _recycled ? prk : new Uint8Array(olen);
2931
+ const worker = blocks > 1 ? _recycled?.iHash || hash.create() : void 0;
2932
+ for (let counter = 0; counter < blocks - 1; counter++) {
2951
2933
  HKDF_COUNTER[0] = counter + 1;
2952
- HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
2934
+ const iWork = iHash._cloneInto(worker);
2935
+ if (counter)
2936
+ iWork.update(T);
2937
+ iWork.update(info).update(HKDF_COUNTER).digestInto(T);
2938
+ oHash._cloneInto(worker).update(T).digestInto(T);
2953
2939
  okm.set(T, olen * counter);
2954
- HMAC._cloneInto(HMACTmp);
2955
2940
  }
2956
- HMAC.destroy();
2957
- HMACTmp.destroy();
2958
- clean(T, HKDF_COUNTER);
2959
- return okm.slice(0, length);
2941
+ HKDF_COUNTER[0] = blocks;
2942
+ if (blocks > 1)
2943
+ iHash.update(T);
2944
+ iHash.update(info).update(HKDF_COUNTER).digestInto(T);
2945
+ oHash.update(T).digestInto(T);
2946
+ okm.set(T, olen * (blocks - 1));
2947
+ iHash.destroy();
2948
+ oHash.destroy();
2949
+ worker?.destroy();
2950
+ if (T !== okm)
2951
+ clean(T);
2952
+ clean(HKDF_COUNTER);
2953
+ if (length === okm.length)
2954
+ return okm;
2955
+ const res = okm.slice(0, length);
2956
+ clean(okm);
2957
+ return res;
2960
2958
  }
2961
- var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
2959
+ var hkdf = (hash, ikm, salt, info, length) => {
2960
+ ahash(hash);
2961
+ if (salt === void 0)
2962
+ salt = new Uint8Array(hash.outputLen);
2963
+ const HMAC = hmac.create(hash, salt).update(ikm);
2964
+ return expand(hash, HMAC.digest(), info, length, HMAC);
2965
+ };
2962
2966
 
2963
2967
  // ../../node_modules/@noble/ciphers/utils.js
2964
2968
  function isBytes3(a) {
2965
2969
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
2966
2970
  }
2967
- function abool2(b) {
2968
- if (typeof b !== "boolean")
2969
- throw new TypeError(`boolean expected, not ${b}`);
2971
+ var atitle3 = (title) => title ? `"${title}" ` : "";
2972
+ function abool2(value, title = "") {
2973
+ if (typeof value !== "boolean")
2974
+ throw new TypeError(atitle3(title) + "expected boolean, got type=" + typeof value);
2975
+ return value;
2970
2976
  }
2971
- function anumber3(n) {
2977
+ function anumber3(n, title = "") {
2972
2978
  if (typeof n !== "number")
2973
- throw new TypeError("number expected, got " + typeof n);
2979
+ throw new TypeError(atitle3(title) + "expected number, got " + typeof n);
2974
2980
  if (!Number.isSafeInteger(n) || n < 0)
2975
- throw new RangeError("positive integer expected, got " + n);
2981
+ throw new RangeError(atitle3(title) + "expected integer >= 0, got " + n);
2982
+ return n;
2976
2983
  }
2977
2984
  function abytes3(value, length, title = "") {
2985
+ if (isBytes3(value) && (length === void 0 || value.length === length))
2986
+ return value;
2987
+ if (length !== void 0)
2988
+ anumber3(length, "length");
2978
2989
  const bytes = isBytes3(value);
2979
- const len = value?.length;
2980
- const needsLen = length !== void 0;
2981
- if (!bytes || needsLen && len !== length) {
2982
- const prefix = title && `"${title}" `;
2983
- const ofLen = needsLen ? ` of length ${length}` : "";
2984
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
2985
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
2986
- if (!bytes)
2987
- throw new TypeError(message);
2988
- throw new RangeError(message);
2989
- }
2990
- return value;
2991
- }
2990
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
2991
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
2992
+ const message = atitle3(title) + "expected Uint8Array" + ofLen + ", got " + got;
2993
+ if (!bytes)
2994
+ throw new TypeError(message);
2995
+ throw new RangeError(message);
2996
+ }
2997
+ var aobject3 = (value, label) => {
2998
+ if (value === null || typeof value !== "object" || Array.isArray(value))
2999
+ throw new TypeError(label === "object" ? "expected valid options object" : `"${label}" expected object, got type=${typeof value}`);
3000
+ };
2992
3001
  function aexists2(instance, checkFinished = true) {
2993
3002
  if (instance.destroyed)
2994
- throw new Error("Hash instance has been destroyed");
3003
+ throw new Error("hash was destroyed");
2995
3004
  if (checkFinished && instance.finished)
2996
- throw new Error("Hash#digest() has already been called");
3005
+ throw new Error("digest() was already called");
2997
3006
  }
2998
- function aoutput2(out, instance, onlyAligned = false) {
3007
+ function aoutput2(out, instance) {
2999
3008
  abytes3(out, void 0, "output");
3000
3009
  const min = instance.outputLen;
3001
- if (out.length < min) {
3002
- throw new RangeError("digestInto() expects output buffer of length at least " + min);
3010
+ if (!(out.length >= min)) {
3011
+ throw new RangeError('"output" expected length >= ' + min);
3003
3012
  }
3004
- if (onlyAligned && !isAligned32(out))
3005
- throw new Error("invalid output, must be aligned");
3006
3013
  }
3007
3014
  function u322(arr) {
3008
3015
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3009
3016
  }
3010
3017
  function clean2(...arrays) {
3011
- for (let i = 0; i < arrays.length; i++) {
3012
- arrays[i].fill(0);
3018
+ for (let i2 = 0; i2 < arrays.length; i2++) {
3019
+ arrays[i2].fill(0);
3013
3020
  }
3014
3021
  }
3015
3022
  function createView2(arr) {
3016
3023
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3017
3024
  }
3018
3025
  var isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
3019
- var byteSwap2 = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
3020
- var swap8IfBE2 = isLE2 ? (n) => n : (n) => byteSwap2(n) >>> 0;
3021
- var byteSwap322 = (arr) => {
3022
- for (let i = 0; i < arr.length; i++)
3023
- arr[i] = byteSwap2(arr[i]);
3026
+ function byteSwap2(word) {
3027
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
3028
+ }
3029
+ function byteSwap322(arr) {
3030
+ for (let i2 = 0; i2 < arr.length; i2++) {
3031
+ arr[i2] = byteSwap2(arr[i2]);
3032
+ }
3024
3033
  return arr;
3025
- };
3034
+ }
3026
3035
  var swap32IfBE2 = isLE2 ? (u) => u : byteSwap322;
3027
- function checkOpts(defaults, opts) {
3028
- if (opts == null || typeof opts !== "object")
3029
- throw new Error("options must be defined");
3036
+ function overlapBytes(a, b) {
3037
+ if (!a.byteLength || !b.byteLength)
3038
+ return false;
3039
+ return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
3040
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
3041
+ b.byteOffset < a.byteOffset + a.byteLength;
3042
+ }
3043
+ function complexOverlapBytes(input, output) {
3044
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
3045
+ throw new Error("complex overlap of input and output is not supported");
3046
+ }
3047
+ function checkOpts2(defaults, opts) {
3048
+ aobject3(defaults, "defaults");
3049
+ aobject3(opts, "opts");
3030
3050
  const merged = Object.assign(defaults, opts);
3031
3051
  return merged;
3032
3052
  }
3033
- function equalBytes2(a, b) {
3053
+ function equalBytes(a, b) {
3054
+ a = abytes3(a);
3055
+ b = abytes3(b);
3034
3056
  if (a.length !== b.length)
3035
3057
  return false;
3036
3058
  let diff = 0;
3037
- for (let i = 0; i < a.length; i++)
3038
- diff |= a[i] ^ b[i];
3059
+ for (let i2 = 0; i2 < a.length; i2++)
3060
+ diff |= a[i2] ^ b[i2];
3039
3061
  return diff === 0;
3040
3062
  }
3041
3063
  function wrapMacConstructor(keyLen, macCons, fromMsg) {
@@ -3056,8 +3078,14 @@ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
3056
3078
  abytes3(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce");
3057
3079
  }
3058
3080
  const tagl = params.tagLength;
3059
- if (tagl && args[1] !== void 0)
3060
- abytes3(args[1], void 0, "AAD");
3081
+ const aadStart = params.nonceLength !== void 0 ? 1 : 0;
3082
+ if (!params.withAAD) {
3083
+ for (let i2 = aadStart; i2 < args.length; i2++)
3084
+ if (isBytes3(args[i2]))
3085
+ throw new Error("AAD not supported");
3086
+ }
3087
+ if (params.withAAD && args[aadStart] !== void 0)
3088
+ abytes3(args[aadStart], void 0, "AAD");
3061
3089
  const cipher = constructor(key, ...args);
3062
3090
  const checkOutput = (fnLength, output) => {
3063
3091
  if (output !== void 0) {
@@ -3072,14 +3100,14 @@ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
3072
3100
  if (called)
3073
3101
  throw new Error("cannot encrypt() twice with same key + nonce");
3074
3102
  called = true;
3075
- abytes3(data);
3103
+ abytes3(data, void 0, "data");
3076
3104
  checkOutput(cipher.encrypt.length, output);
3077
3105
  return cipher.encrypt(data, output);
3078
3106
  },
3079
3107
  decrypt(data, output) {
3080
- abytes3(data);
3108
+ abytes3(data, void 0, "data");
3081
3109
  if (tagl && data.length < tagl)
3082
- throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl);
3110
+ throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
3083
3111
  checkOutput(cipher.decrypt.length, output);
3084
3112
  return cipher.decrypt(data, output);
3085
3113
  }
@@ -3092,9 +3120,7 @@ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
3092
3120
  function getOutput(expectedLength, out, onlyAligned = true) {
3093
3121
  if (out === void 0)
3094
3122
  return new Uint8Array(expectedLength);
3095
- abytes3(out, void 0, "output");
3096
- if (out.length !== expectedLength)
3097
- throw new Error('"output" expected Uint8Array of length ' + expectedLength + ", got: " + out.length);
3123
+ abytes3(out, expectedLength, "output");
3098
3124
  if (onlyAligned && !isAligned32(out))
3099
3125
  throw new Error("invalid output, must be aligned");
3100
3126
  return out;
@@ -3112,7 +3138,7 @@ function u64Lengths(dataLength, aadLength, isLE3) {
3112
3138
  function isAligned32(bytes) {
3113
3139
  return bytes.byteOffset % 4 === 0;
3114
3140
  }
3115
- function copyBytes2(bytes) {
3141
+ function copyBytes3(bytes) {
3116
3142
  return Uint8Array.from(abytes3(bytes));
3117
3143
  }
3118
3144
 
@@ -3173,7 +3199,7 @@ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
3173
3199
  }
3174
3200
  }
3175
3201
  function createCipher(core, opts) {
3176
- const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
3202
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts2({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
3177
3203
  if (typeof core !== "function")
3178
3204
  throw new Error("core must be a function");
3179
3205
  anumber3(counterLength);
@@ -3185,7 +3211,10 @@ function createCipher(core, opts) {
3185
3211
  abytes3(nonce, void 0, "nonce");
3186
3212
  abytes3(data, void 0, "data");
3187
3213
  const len = data.length;
3214
+ const hasOutput = output !== void 0;
3188
3215
  output = getOutput(len, output, false);
3216
+ if (hasOutput)
3217
+ complexOverlapBytes(data, output);
3189
3218
  anumber3(counter);
3190
3219
  if (counter < 0 || counter >= MAX_COUNTER)
3191
3220
  throw new Error("arx: counter overflow");
@@ -3194,7 +3223,7 @@ function createCipher(core, opts) {
3194
3223
  let k;
3195
3224
  let sigma;
3196
3225
  if (l === 32) {
3197
- toClean.push(k = copyBytes2(key));
3226
+ toClean.push(k = copyBytes3(key));
3198
3227
  sigma = sigma32_32;
3199
3228
  } else if (l === 16 && allowShortKeys) {
3200
3229
  k = new Uint8Array(32);
@@ -3207,11 +3236,11 @@ function createCipher(core, opts) {
3207
3236
  throw new Error("invalid key size");
3208
3237
  }
3209
3238
  if (!isLE2 || !isAligned32(nonce))
3210
- toClean.push(nonce = copyBytes2(nonce));
3239
+ toClean.push(nonce = copyBytes3(nonce));
3211
3240
  let k32 = u322(k);
3212
3241
  if (extendNonceFn) {
3213
3242
  if (nonce.length !== 24)
3214
- throw new Error(`arx: extended nonce must be 24 bytes`);
3243
+ throw new Error("arx: extended nonce must be 24 bytes");
3215
3244
  const n16 = nonce.subarray(0, 16);
3216
3245
  if (isLE2)
3217
3246
  extendNonceFn(sigma, k32, u322(n16), k32);
@@ -3244,8 +3273,8 @@ function createCipher(core, opts) {
3244
3273
  }
3245
3274
 
3246
3275
  // ../../node_modules/@noble/ciphers/_poly1305.js
3247
- function u8to16(a, i) {
3248
- return a[i++] & 255 | (a[i++] & 255) << 8;
3276
+ function u8to16(a, i2) {
3277
+ return a[i2++] & 255 | (a[i2++] & 255) << 8;
3249
3278
  }
3250
3279
  var Poly1305 = class {
3251
3280
  blockLen = 16;
@@ -3260,7 +3289,7 @@ var Poly1305 = class {
3260
3289
  destroyed = false;
3261
3290
  // Can be speed-up using BigUint64Array, at the cost of complexity
3262
3291
  constructor(key) {
3263
- key = copyBytes2(abytes3(key, 32, "key"));
3292
+ key = copyBytes3(abytes3(key, 32, "key"));
3264
3293
  const t0 = u8to16(key, 0);
3265
3294
  const t1 = u8to16(key, 2);
3266
3295
  const t2 = u8to16(key, 4);
@@ -3279,8 +3308,8 @@ var Poly1305 = class {
3279
3308
  this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
3280
3309
  this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
3281
3310
  this.r[9] = t7 >>> 5 & 127;
3282
- for (let i = 0; i < 8; i++)
3283
- this.pad[i] = u8to16(key, 16 + 2 * i);
3311
+ for (let i2 = 0; i2 < 8; i2++)
3312
+ this.pad[i2] = u8to16(key, 16 + 2 * i2);
3284
3313
  }
3285
3314
  process(data, offset, isLast = false) {
3286
3315
  const hibit = isLast ? 0 : 1 << 11;
@@ -3395,10 +3424,10 @@ var Poly1305 = class {
3395
3424
  const g = new Uint16Array(10);
3396
3425
  let c = h[1] >>> 13;
3397
3426
  h[1] &= 8191;
3398
- for (let i = 2; i < 10; i++) {
3399
- h[i] += c;
3400
- c = h[i] >>> 13;
3401
- h[i] &= 8191;
3427
+ for (let i2 = 2; i2 < 10; i2++) {
3428
+ h[i2] += c;
3429
+ c = h[i2] >>> 13;
3430
+ h[i2] &= 8191;
3402
3431
  }
3403
3432
  h[0] += c * 5;
3404
3433
  c = h[0] >>> 13;
@@ -3410,18 +3439,18 @@ var Poly1305 = class {
3410
3439
  g[0] = h[0] + 5;
3411
3440
  c = g[0] >>> 13;
3412
3441
  g[0] &= 8191;
3413
- for (let i = 1; i < 10; i++) {
3414
- g[i] = h[i] + c;
3415
- c = g[i] >>> 13;
3416
- g[i] &= 8191;
3442
+ for (let i2 = 1; i2 < 10; i2++) {
3443
+ g[i2] = h[i2] + c;
3444
+ c = g[i2] >>> 13;
3445
+ g[i2] &= 8191;
3417
3446
  }
3418
3447
  g[9] -= 1 << 13;
3419
3448
  let mask = (c ^ 1) - 1;
3420
- for (let i = 0; i < 10; i++)
3421
- g[i] &= mask;
3449
+ for (let i2 = 0; i2 < 10; i2++)
3450
+ g[i2] &= mask;
3422
3451
  mask = ~mask;
3423
- for (let i = 0; i < 10; i++)
3424
- h[i] = h[i] & mask | g[i];
3452
+ for (let i2 = 0; i2 < 10; i2++)
3453
+ h[i2] = h[i2] & mask | g[i2];
3425
3454
  h[0] = (h[0] | h[1] << 13) & 65535;
3426
3455
  h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
3427
3456
  h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
@@ -3432,16 +3461,16 @@ var Poly1305 = class {
3432
3461
  h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
3433
3462
  let f = h[0] + pad[0];
3434
3463
  h[0] = f & 65535;
3435
- for (let i = 1; i < 8; i++) {
3436
- f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
3437
- h[i] = f & 65535;
3464
+ for (let i2 = 1; i2 < 8; i2++) {
3465
+ f = (h[i2] + pad[i2] | 0) + (f >>> 16) | 0;
3466
+ h[i2] = f & 65535;
3438
3467
  }
3439
3468
  clean2(g);
3440
3469
  }
3441
3470
  update(data) {
3442
3471
  aexists2(this);
3443
3472
  abytes3(data);
3444
- data = copyBytes2(data);
3473
+ data = copyBytes3(data);
3445
3474
  const { buffer, blockLen } = this;
3446
3475
  const len = data.length;
3447
3476
  for (let pos = 0; pos < len; ) {
@@ -3479,9 +3508,9 @@ var Poly1305 = class {
3479
3508
  }
3480
3509
  this.finalize();
3481
3510
  let opos = 0;
3482
- for (let i = 0; i < 8; i++) {
3483
- out[opos++] = h[i] >>> 0;
3484
- out[opos++] = h[i] >>> 8;
3511
+ for (let i2 = 0; i2 < 8; i2++) {
3512
+ out[opos++] = h[i2] >>> 0;
3513
+ out[opos++] = h[i2] >>> 8;
3485
3514
  }
3486
3515
  }
3487
3516
  digest() {
@@ -3582,84 +3611,25 @@ function chachaCore(s, k, n, out, cnt, rounds = 20) {
3582
3611
  out[oi++] = y14 + x14 | 0;
3583
3612
  out[oi++] = y15 + x15 | 0;
3584
3613
  }
3585
- function hchacha(s, k, i, out) {
3586
- 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]);
3587
- for (let r = 0; r < 20; r += 2) {
3588
- x00 = x00 + x04 | 0;
3589
- x12 = rotl(x12 ^ x00, 16);
3590
- x08 = x08 + x12 | 0;
3591
- x04 = rotl(x04 ^ x08, 12);
3592
- x00 = x00 + x04 | 0;
3593
- x12 = rotl(x12 ^ x00, 8);
3594
- x08 = x08 + x12 | 0;
3595
- x04 = rotl(x04 ^ x08, 7);
3596
- x01 = x01 + x05 | 0;
3597
- x13 = rotl(x13 ^ x01, 16);
3598
- x09 = x09 + x13 | 0;
3599
- x05 = rotl(x05 ^ x09, 12);
3600
- x01 = x01 + x05 | 0;
3601
- x13 = rotl(x13 ^ x01, 8);
3602
- x09 = x09 + x13 | 0;
3603
- x05 = rotl(x05 ^ x09, 7);
3604
- x02 = x02 + x06 | 0;
3605
- x14 = rotl(x14 ^ x02, 16);
3606
- x10 = x10 + x14 | 0;
3607
- x06 = rotl(x06 ^ x10, 12);
3608
- x02 = x02 + x06 | 0;
3609
- x14 = rotl(x14 ^ x02, 8);
3610
- x10 = x10 + x14 | 0;
3611
- x06 = rotl(x06 ^ x10, 7);
3612
- x03 = x03 + x07 | 0;
3613
- x15 = rotl(x15 ^ x03, 16);
3614
- x11 = x11 + x15 | 0;
3615
- x07 = rotl(x07 ^ x11, 12);
3616
- x03 = x03 + x07 | 0;
3617
- x15 = rotl(x15 ^ x03, 8);
3618
- x11 = x11 + x15 | 0;
3619
- x07 = rotl(x07 ^ x11, 7);
3620
- x00 = x00 + x05 | 0;
3621
- x15 = rotl(x15 ^ x00, 16);
3622
- x10 = x10 + x15 | 0;
3623
- x05 = rotl(x05 ^ x10, 12);
3624
- x00 = x00 + x05 | 0;
3625
- x15 = rotl(x15 ^ x00, 8);
3626
- x10 = x10 + x15 | 0;
3627
- x05 = rotl(x05 ^ x10, 7);
3628
- x01 = x01 + x06 | 0;
3629
- x12 = rotl(x12 ^ x01, 16);
3630
- x11 = x11 + x12 | 0;
3631
- x06 = rotl(x06 ^ x11, 12);
3632
- x01 = x01 + x06 | 0;
3633
- x12 = rotl(x12 ^ x01, 8);
3634
- x11 = x11 + x12 | 0;
3635
- x06 = rotl(x06 ^ x11, 7);
3636
- x02 = x02 + x07 | 0;
3637
- x13 = rotl(x13 ^ x02, 16);
3638
- x08 = x08 + x13 | 0;
3639
- x07 = rotl(x07 ^ x08, 12);
3640
- x02 = x02 + x07 | 0;
3641
- x13 = rotl(x13 ^ x02, 8);
3642
- x08 = x08 + x13 | 0;
3643
- x07 = rotl(x07 ^ x08, 7);
3644
- x03 = x03 + x04 | 0;
3645
- x14 = rotl(x14 ^ x03, 16);
3646
- x09 = x09 + x14 | 0;
3647
- x04 = rotl(x04 ^ x09, 12);
3648
- x03 = x03 + x04 | 0;
3649
- x14 = rotl(x14 ^ x03, 8);
3650
- x09 = x09 + x14 | 0;
3651
- x04 = rotl(x04 ^ x09, 7);
3652
- }
3614
+ function hchacha(s, k, i2, out) {
3615
+ const s2 = isLE2 ? s : swap32IfBE2(s.slice(0, 4));
3616
+ const k2 = isLE2 ? k : swap32IfBE2(k.slice(0, 8));
3617
+ const i22 = isLE2 ? i2 : swap32IfBE2(i2.slice(0, 4));
3618
+ const t = new Uint32Array(16);
3619
+ chachaCore(s2, k2, i22.subarray(1), t, i22[0]);
3653
3620
  let oi = 0;
3654
- out[oi++] = x00;
3655
- out[oi++] = x01;
3656
- out[oi++] = x02;
3657
- out[oi++] = x03;
3658
- out[oi++] = x12;
3659
- out[oi++] = x13;
3660
- out[oi++] = x14;
3661
- out[oi++] = x15;
3621
+ out[oi++] = t[0] - s2[0] | 0;
3622
+ out[oi++] = t[1] - s2[1] | 0;
3623
+ out[oi++] = t[2] - s2[2] | 0;
3624
+ out[oi++] = t[3] - s2[3] | 0;
3625
+ out[oi++] = t[12] - i22[0] | 0;
3626
+ out[oi++] = t[13] - i22[1] | 0;
3627
+ out[oi++] = t[14] - i22[2] | 0;
3628
+ out[oi++] = t[15] - i22[3] | 0;
3662
3629
  swap32IfBE2(out);
3630
+ if (!isLE2)
3631
+ clean2(s2, k2, i22);
3632
+ clean2(t);
3663
3633
  }
3664
3634
  var chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
3665
3635
  counterRight: false,
@@ -3713,7 +3683,7 @@ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
3713
3683
  const data = ciphertext.subarray(0, -tagLength);
3714
3684
  const passedTag = ciphertext.subarray(-tagLength);
3715
3685
  const tag = computeTag(xorStream, key, nonce, data, AAD);
3716
- if (!equalBytes2(passedTag, tag)) {
3686
+ if (!equalBytes(passedTag, tag)) {
3717
3687
  clean2(tag);
3718
3688
  throw new Error("invalid tag");
3719
3689
  }
@@ -3725,11 +3695,11 @@ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
3725
3695
  };
3726
3696
  };
3727
3697
  var chacha20poly1305 = /* @__PURE__ */ wrapCipher(
3728
- { blockSize: 64, nonceLength: 12, tagLength: 16 },
3698
+ { blockSize: 64, nonceLength: 12, tagLength: 16, withAAD: true },
3729
3699
  /* @__PURE__ */ _poly1305_aead(chacha20)
3730
3700
  );
3731
3701
  var xchacha20poly1305 = /* @__PURE__ */ wrapCipher(
3732
- { blockSize: 64, nonceLength: 24, tagLength: 16 },
3702
+ { blockSize: 64, nonceLength: 24, tagLength: 16, withAAD: true },
3733
3703
  /* @__PURE__ */ _poly1305_aead(xchacha20)
3734
3704
  );
3735
3705
 
@@ -3780,8 +3750,8 @@ function hashBlake2s(data) {
3780
3750
  function noiseHkdf(chainingKey, inputKeyMaterial, numOutputs) {
3781
3751
  const output = hkdf(blake2s, inputKeyMaterial, chainingKey, new Uint8Array(0), numOutputs * HASH_LENGTH);
3782
3752
  const chunks = [];
3783
- for (let i = 0; i < numOutputs; i++) {
3784
- chunks.push(output.subarray(i * HASH_LENGTH, (i + 1) * HASH_LENGTH));
3753
+ for (let i2 = 0; i2 < numOutputs; i2++) {
3754
+ chunks.push(output.subarray(i2 * HASH_LENGTH, (i2 + 1) * HASH_LENGTH));
3785
3755
  }
3786
3756
  return chunks;
3787
3757
  }
@@ -3816,7 +3786,7 @@ function xaeadDecrypt(key, nonce, associatedData, ciphertext) {
3816
3786
  const cipher = xchacha20poly1305(key, nonce, associatedData);
3817
3787
  return cipher.decrypt(ciphertext);
3818
3788
  }
3819
- function concatBytes4(...arrays) {
3789
+ function concatBytes3(...arrays) {
3820
3790
  const total = arrays.reduce((sum, arr) => sum + arr.length, 0);
3821
3791
  const result = new Uint8Array(total);
3822
3792
  let offset = 0;
@@ -3863,7 +3833,7 @@ var SymmetricState = class {
3863
3833
  hash;
3864
3834
  constructor(protocolName) {
3865
3835
  if (protocolName.length <= HASH_LENGTH) {
3866
- this.hash = concatBytes4(protocolName, new Uint8Array(HASH_LENGTH - protocolName.length));
3836
+ this.hash = concatBytes3(protocolName, new Uint8Array(HASH_LENGTH - protocolName.length));
3867
3837
  } else {
3868
3838
  this.hash = hashBlake2s(protocolName);
3869
3839
  }
@@ -3876,7 +3846,7 @@ var SymmetricState = class {
3876
3846
  this.cipherState.initializeKey(tempKey);
3877
3847
  }
3878
3848
  mixHash(data) {
3879
- this.hash = hashBlake2s(concatBytes4(this.hash, data));
3849
+ this.hash = hashBlake2s(concatBytes3(this.hash, data));
3880
3850
  }
3881
3851
  /** Processes a "psk" token: MixKeyAndHash(psk) per Noise section 9. */
3882
3852
  mixKeyAndHash(inputKeyMaterial) {
@@ -4036,7 +4006,7 @@ var HandshakeState = class {
4036
4006
  }
4037
4007
  }
4038
4008
  buffers.push(this.symmetricState.encryptAndHash(payload));
4039
- return { message: concatBytes4(...buffers), split: this.maybeSplit() };
4009
+ return { message: concatBytes3(...buffers), split: this.maybeSplit() };
4040
4010
  }
4041
4011
  readMessage(message) {
4042
4012
  const tokens = this.nextTokens();
@@ -4166,7 +4136,7 @@ var SecretstreamState = class {
4166
4136
  const associatedData = Uint8Array.of(tag);
4167
4137
  const ciphertext = xaeadEncrypt(this.key, this.nonceForCounter(this.counter), associatedData, plaintext);
4168
4138
  this.counter += 1n;
4169
- return concatBytes4(associatedData, ciphertext);
4139
+ return concatBytes3(associatedData, ciphertext);
4170
4140
  }
4171
4141
  /**
4172
4142
  * Decrypts one frame and advances this direction's counter. Throws if
@@ -4276,8 +4246,8 @@ function deriveShortAuthenticationString(handshakeHash) {
4276
4246
  const digitsValue = digitsRaw % 1e6;
4277
4247
  const digits = digitsValue.toString(10).padStart(6, "0");
4278
4248
  const emoji = [];
4279
- for (let i = 0; i < 5; i++) {
4280
- emoji.push(SAS_EMOJI_TABLE[bytes[4 + i] % SAS_EMOJI_TABLE.length]);
4249
+ for (let i2 = 0; i2 < 5; i2++) {
4250
+ emoji.push(SAS_EMOJI_TABLE[bytes[4 + i2] % SAS_EMOJI_TABLE.length]);
4281
4251
  }
4282
4252
  return { digits, emoji };
4283
4253
  }
@@ -4286,7 +4256,7 @@ function deriveShortAuthenticationString(handshakeHash) {
4286
4256
  var SESSION_SLOT_LABEL = "kangentic-session-slot-v1";
4287
4257
  var SESSION_SLOT_LENGTH = 16;
4288
4258
  function deriveSessionSlotId(desktopStaticPublicKey, phoneStaticPublicKey) {
4289
- const material = concatBytes4(desktopStaticPublicKey, phoneStaticPublicKey);
4259
+ const material = concatBytes3(desktopStaticPublicKey, phoneStaticPublicKey);
4290
4260
  return bytesToHex(deriveLabeledKey(material, SESSION_SLOT_LABEL, SESSION_SLOT_LENGTH));
4291
4261
  }
4292
4262
  var PAIRING_SLOT_LABEL = "kangentic-pairing-slot-v1";
@@ -4382,13 +4352,13 @@ var fdeb = new u8([
4382
4352
  var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
4383
4353
  var freb = function(eb, start) {
4384
4354
  var b = new u16(31);
4385
- for (var i = 0; i < 31; ++i) {
4386
- b[i] = start += 1 << eb[i - 1];
4355
+ for (var i2 = 0; i2 < 31; ++i2) {
4356
+ b[i2] = start += 1 << eb[i2 - 1];
4387
4357
  }
4388
4358
  var r = new i32(b[30]);
4389
- for (var i = 1; i < 30; ++i) {
4390
- for (var j = b[i]; j < b[i + 1]; ++j) {
4391
- r[j] = j - b[i] << 5 | i;
4359
+ for (var i2 = 1; i2 < 30; ++i2) {
4360
+ for (var j = b[i2]; j < b[i2 + 1]; ++j) {
4361
+ r[j] = j - b[i2] << 5 | i2;
4392
4362
  }
4393
4363
  }
4394
4364
  return { b, r };
@@ -4411,25 +4381,25 @@ var x;
4411
4381
  var i;
4412
4382
  var hMap = (function(cd, mb, r) {
4413
4383
  var s = cd.length;
4414
- var i = 0;
4384
+ var i2 = 0;
4415
4385
  var l = new u16(mb);
4416
- for (; i < s; ++i) {
4417
- if (cd[i])
4418
- ++l[cd[i] - 1];
4386
+ for (; i2 < s; ++i2) {
4387
+ if (cd[i2])
4388
+ ++l[cd[i2] - 1];
4419
4389
  }
4420
4390
  var le = new u16(mb);
4421
- for (i = 1; i < mb; ++i) {
4422
- le[i] = le[i - 1] + l[i - 1] << 1;
4391
+ for (i2 = 1; i2 < mb; ++i2) {
4392
+ le[i2] = le[i2 - 1] + l[i2 - 1] << 1;
4423
4393
  }
4424
4394
  var co;
4425
4395
  if (r) {
4426
4396
  co = new u16(1 << mb);
4427
4397
  var rvb = 15 - mb;
4428
- for (i = 0; i < s; ++i) {
4429
- if (cd[i]) {
4430
- var sv = i << 4 | cd[i];
4431
- var r_1 = mb - cd[i];
4432
- var v = le[cd[i] - 1]++ << r_1;
4398
+ for (i2 = 0; i2 < s; ++i2) {
4399
+ if (cd[i2]) {
4400
+ var sv = i2 << 4 | cd[i2];
4401
+ var r_1 = mb - cd[i2];
4402
+ var v = le[cd[i2] - 1]++ << r_1;
4433
4403
  for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
4434
4404
  co[rev[v] >> rvb] = sv;
4435
4405
  }
@@ -4437,9 +4407,9 @@ var hMap = (function(cd, mb, r) {
4437
4407
  }
4438
4408
  } else {
4439
4409
  co = new u16(s);
4440
- for (i = 0; i < s; ++i) {
4441
- if (cd[i]) {
4442
- co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
4410
+ for (i2 = 0; i2 < s; ++i2) {
4411
+ if (cd[i2]) {
4412
+ co[i2] = rev[le[cd[i2] - 1]++] >> 15 - cd[i2];
4443
4413
  }
4444
4414
  }
4445
4415
  }
@@ -4468,9 +4438,9 @@ var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
4468
4438
  var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
4469
4439
  var max = function(a) {
4470
4440
  var m = a[0];
4471
- for (var i = 1; i < a.length; ++i) {
4472
- if (a[i] > m)
4473
- m = a[i];
4441
+ for (var i2 = 1; i2 < a.length; ++i2) {
4442
+ if (a[i2] > m)
4443
+ m = a[i2];
4474
4444
  }
4475
4445
  return m;
4476
4446
  };
@@ -4563,28 +4533,28 @@ var inflt = function(dat, st, buf, dict) {
4563
4533
  pos += 14;
4564
4534
  var ldt = new u8(tl);
4565
4535
  var clt = new u8(19);
4566
- for (var i = 0; i < hcLen; ++i) {
4567
- clt[clim[i]] = bits(dat, pos + i * 3, 7);
4536
+ for (var i2 = 0; i2 < hcLen; ++i2) {
4537
+ clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
4568
4538
  }
4569
4539
  pos += hcLen * 3;
4570
4540
  var clb = max(clt), clbmsk = (1 << clb) - 1;
4571
4541
  var clm = hMap(clt, clb, 1);
4572
- for (var i = 0; i < tl; ) {
4542
+ for (var i2 = 0; i2 < tl; ) {
4573
4543
  var r = clm[bits(dat, pos, clbmsk)];
4574
4544
  pos += r & 15;
4575
4545
  var s = r >> 4;
4576
4546
  if (s < 16) {
4577
- ldt[i++] = s;
4547
+ ldt[i2++] = s;
4578
4548
  } else {
4579
4549
  var c = 0, n = 0;
4580
4550
  if (s == 16)
4581
- n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
4551
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i2 - 1];
4582
4552
  else if (s == 17)
4583
4553
  n = 3 + bits(dat, pos, 7), pos += 3;
4584
4554
  else if (s == 18)
4585
4555
  n = 11 + bits(dat, pos, 127), pos += 7;
4586
4556
  while (n--)
4587
- ldt[i++] = c;
4557
+ ldt[i2++] = c;
4588
4558
  }
4589
4559
  }
4590
4560
  var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
@@ -4622,8 +4592,8 @@ var inflt = function(dat, st, buf, dict) {
4622
4592
  } else {
4623
4593
  var add2 = sym - 254;
4624
4594
  if (sym > 264) {
4625
- var i = sym - 257, b = fleb[i];
4626
- add2 = bits(dat, pos, (1 << b) - 1) + fl[i];
4595
+ var i2 = sym - 257, b = fleb[i2];
4596
+ add2 = bits(dat, pos, (1 << b) - 1) + fl[i2];
4627
4597
  pos += b;
4628
4598
  }
4629
4599
  var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
@@ -4675,9 +4645,9 @@ var wbits16 = function(d, p, v) {
4675
4645
  };
4676
4646
  var hTree = function(d, mb) {
4677
4647
  var t = [];
4678
- for (var i = 0; i < d.length; ++i) {
4679
- if (d[i])
4680
- t.push({ s: i, f: d[i] });
4648
+ for (var i2 = 0; i2 < d.length; ++i2) {
4649
+ if (d[i2])
4650
+ t.push({ s: i2, f: d[i2] });
4681
4651
  }
4682
4652
  var s = t.length;
4683
4653
  var t2 = t.slice();
@@ -4692,28 +4662,28 @@ var hTree = function(d, mb) {
4692
4662
  return a.f - b.f;
4693
4663
  });
4694
4664
  t.push({ s: -1, f: 25001 });
4695
- var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
4665
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i22 = 2;
4696
4666
  t[0] = { s: -1, f: l.f + r.f, l, r };
4697
4667
  while (i1 != s - 1) {
4698
- l = t[t[i0].f < t[i2].f ? i0++ : i2++];
4699
- r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
4668
+ l = t[t[i0].f < t[i22].f ? i0++ : i22++];
4669
+ r = t[i0 != i1 && t[i0].f < t[i22].f ? i0++ : i22++];
4700
4670
  t[i1++] = { s: -1, f: l.f + r.f, l, r };
4701
4671
  }
4702
4672
  var maxSym = t2[0].s;
4703
- for (var i = 1; i < s; ++i) {
4704
- if (t2[i].s > maxSym)
4705
- maxSym = t2[i].s;
4673
+ for (var i2 = 1; i2 < s; ++i2) {
4674
+ if (t2[i2].s > maxSym)
4675
+ maxSym = t2[i2].s;
4706
4676
  }
4707
4677
  var tr = new u16(maxSym + 1);
4708
4678
  var mbt = ln(t[i1 - 1], tr, 0);
4709
4679
  if (mbt > mb) {
4710
- var i = 0, dt = 0;
4680
+ var i2 = 0, dt = 0;
4711
4681
  var lft = mbt - mb, cst = 1 << lft;
4712
4682
  t2.sort(function(a, b) {
4713
4683
  return tr[b.s] - tr[a.s] || a.f - b.f;
4714
4684
  });
4715
- for (; i < s; ++i) {
4716
- var i2_1 = t2[i].s;
4685
+ for (; i2 < s; ++i2) {
4686
+ var i2_1 = t2[i2].s;
4717
4687
  if (tr[i2_1] > mb) {
4718
4688
  dt += cst - (1 << mbt - tr[i2_1]);
4719
4689
  tr[i2_1] = mb;
@@ -4722,14 +4692,14 @@ var hTree = function(d, mb) {
4722
4692
  }
4723
4693
  dt >>= lft;
4724
4694
  while (dt > 0) {
4725
- var i2_2 = t2[i].s;
4695
+ var i2_2 = t2[i2].s;
4726
4696
  if (tr[i2_2] < mb)
4727
4697
  dt -= 1 << mb - tr[i2_2]++ - 1;
4728
4698
  else
4729
- ++i;
4699
+ ++i2;
4730
4700
  }
4731
- for (; i >= 0 && dt; --i) {
4732
- var i2_3 = t2[i].s;
4701
+ for (; i2 >= 0 && dt; --i2) {
4702
+ var i2_3 = t2[i2].s;
4733
4703
  if (tr[i2_3] == mb) {
4734
4704
  --tr[i2_3];
4735
4705
  ++dt;
@@ -4751,8 +4721,8 @@ var lc = function(c) {
4751
4721
  var w = function(v) {
4752
4722
  cl[cli++] = v;
4753
4723
  };
4754
- for (var i = 1; i <= s; ++i) {
4755
- if (c[i] == cln && i != s)
4724
+ for (var i2 = 1; i2 <= s; ++i2) {
4725
+ if (c[i2] == cln && i2 != s)
4756
4726
  ++cls;
4757
4727
  else {
4758
4728
  if (!cln && cls > 2) {
@@ -4772,15 +4742,15 @@ var lc = function(c) {
4772
4742
  while (cls--)
4773
4743
  w(cln);
4774
4744
  cls = 1;
4775
- cln = c[i];
4745
+ cln = c[i2];
4776
4746
  }
4777
4747
  }
4778
4748
  return { c: cl.subarray(0, cli), n: s };
4779
4749
  };
4780
4750
  var clen = function(cf, cl) {
4781
4751
  var l = 0;
4782
- for (var i = 0; i < cl.length; ++i)
4783
- l += cf[i] * cl[i];
4752
+ for (var i2 = 0; i2 < cl.length; ++i2)
4753
+ l += cf[i2] * cl[i2];
4784
4754
  return l;
4785
4755
  };
4786
4756
  var wfblk = function(out, pos, dat) {
@@ -4790,8 +4760,8 @@ var wfblk = function(out, pos, dat) {
4790
4760
  out[o + 1] = s >> 8;
4791
4761
  out[o + 2] = out[o] ^ 255;
4792
4762
  out[o + 3] = out[o + 1] ^ 255;
4793
- for (var i = 0; i < s; ++i)
4794
- out[o + i + 4] = dat[i];
4763
+ for (var i2 = 0; i2 < s; ++i2)
4764
+ out[o + i2 + 4] = dat[i2];
4795
4765
  return (o + 4 + s) * 8;
4796
4766
  };
4797
4767
  var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
@@ -4802,10 +4772,10 @@ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
4802
4772
  var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
4803
4773
  var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
4804
4774
  var lcfreq = new u16(19);
4805
- for (var i = 0; i < lclt.length; ++i)
4806
- ++lcfreq[lclt[i] & 31];
4807
- for (var i = 0; i < lcdt.length; ++i)
4808
- ++lcfreq[lcdt[i] & 31];
4775
+ for (var i2 = 0; i2 < lclt.length; ++i2)
4776
+ ++lcfreq[lclt[i2] & 31];
4777
+ for (var i2 = 0; i2 < lcdt.length; ++i2)
4778
+ ++lcfreq[lcdt[i2] & 31];
4809
4779
  var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
4810
4780
  var nlcc = 19;
4811
4781
  for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
@@ -4824,24 +4794,24 @@ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
4824
4794
  wbits(out, p + 5, ndc - 1);
4825
4795
  wbits(out, p + 10, nlcc - 4);
4826
4796
  p += 14;
4827
- for (var i = 0; i < nlcc; ++i)
4828
- wbits(out, p + 3 * i, lct[clim[i]]);
4797
+ for (var i2 = 0; i2 < nlcc; ++i2)
4798
+ wbits(out, p + 3 * i2, lct[clim[i2]]);
4829
4799
  p += 3 * nlcc;
4830
4800
  var lcts = [lclt, lcdt];
4831
4801
  for (var it = 0; it < 2; ++it) {
4832
4802
  var clct = lcts[it];
4833
- for (var i = 0; i < clct.length; ++i) {
4834
- var len = clct[i] & 31;
4803
+ for (var i2 = 0; i2 < clct.length; ++i2) {
4804
+ var len = clct[i2] & 31;
4835
4805
  wbits(out, p, llm[len]), p += lct[len];
4836
4806
  if (len > 15)
4837
- wbits(out, p, clct[i] >> 5 & 127), p += clct[i] >> 12;
4807
+ wbits(out, p, clct[i2] >> 5 & 127), p += clct[i2] >> 12;
4838
4808
  }
4839
4809
  }
4840
4810
  } else {
4841
4811
  lm = flm, ll = flt, dm = fdm, dl = fdt;
4842
4812
  }
4843
- for (var i = 0; i < li; ++i) {
4844
- var sym = syms[i];
4813
+ for (var i2 = 0; i2 < li; ++i2) {
4814
+ var sym = syms[i2];
4845
4815
  if (sym > 255) {
4846
4816
  var len = sym >> 18 & 31;
4847
4817
  wbits16(out, p, lm[len + 257]), p += ll[len + 257];
@@ -4874,36 +4844,36 @@ var dflt = function(dat, lvl, plvl, pre, post, st) {
4874
4844
  var msk_1 = (1 << plvl) - 1;
4875
4845
  var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
4876
4846
  var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
4877
- var hsh = function(i2) {
4878
- return (dat[i2] ^ dat[i2 + 1] << bs1_1 ^ dat[i2 + 2] << bs2_1) & msk_1;
4847
+ var hsh = function(i3) {
4848
+ return (dat[i3] ^ dat[i3 + 1] << bs1_1 ^ dat[i3 + 2] << bs2_1) & msk_1;
4879
4849
  };
4880
4850
  var syms = new i32(25e3);
4881
4851
  var lf = new u16(288), df = new u16(32);
4882
- var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
4883
- for (; i + 2 < s; ++i) {
4884
- var hv = hsh(i);
4885
- var imod = i & 32767, pimod = head[hv];
4852
+ var lc_1 = 0, eb = 0, i2 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
4853
+ for (; i2 + 2 < s; ++i2) {
4854
+ var hv = hsh(i2);
4855
+ var imod = i2 & 32767, pimod = head[hv];
4886
4856
  prev[imod] = pimod;
4887
4857
  head[hv] = imod;
4888
- if (wi <= i) {
4889
- var rem = s - i;
4858
+ if (wi <= i2) {
4859
+ var rem = s - i2;
4890
4860
  if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
4891
- pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
4892
- li = lc_1 = eb = 0, bs = i;
4861
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i2 - bs, pos);
4862
+ li = lc_1 = eb = 0, bs = i2;
4893
4863
  for (var j = 0; j < 286; ++j)
4894
4864
  lf[j] = 0;
4895
4865
  for (var j = 0; j < 30; ++j)
4896
4866
  df[j] = 0;
4897
4867
  }
4898
4868
  var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
4899
- if (rem > 2 && hv == hsh(i - dif)) {
4869
+ if (rem > 2 && hv == hsh(i2 - dif)) {
4900
4870
  var maxn = Math.min(n, rem) - 1;
4901
- var maxd = Math.min(32767, i);
4871
+ var maxd = Math.min(32767, i2);
4902
4872
  var ml = Math.min(258, rem);
4903
4873
  while (dif <= maxd && --ch_1 && imod != pimod) {
4904
- if (dat[i + l] == dat[i + l - dif]) {
4874
+ if (dat[i2 + l] == dat[i2 + l - dif]) {
4905
4875
  var nl = 0;
4906
- for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
4876
+ for (; nl < ml && dat[i2 + nl] == dat[i2 + nl - dif]; ++nl)
4907
4877
  ;
4908
4878
  if (nl > l) {
4909
4879
  l = nl, d = dif;
@@ -4912,7 +4882,7 @@ var dflt = function(dat, lvl, plvl, pre, post, st) {
4912
4882
  var mmd = Math.min(dif, nl - 2);
4913
4883
  var md = 0;
4914
4884
  for (var j = 0; j < mmd; ++j) {
4915
- var ti = i - dif + j & 32767;
4885
+ var ti = i2 - dif + j & 32767;
4916
4886
  var pti = prev[ti];
4917
4887
  var cd = ti - pti & 32767;
4918
4888
  if (cd > md)
@@ -4930,32 +4900,32 @@ var dflt = function(dat, lvl, plvl, pre, post, st) {
4930
4900
  eb += fleb[lin] + fdeb[din];
4931
4901
  ++lf[257 + lin];
4932
4902
  ++df[din];
4933
- wi = i + l;
4903
+ wi = i2 + l;
4934
4904
  ++lc_1;
4935
4905
  } else {
4936
- syms[li++] = dat[i];
4937
- ++lf[dat[i]];
4906
+ syms[li++] = dat[i2];
4907
+ ++lf[dat[i2]];
4938
4908
  }
4939
4909
  }
4940
4910
  }
4941
- for (i = Math.max(i, wi); i < s; ++i) {
4942
- syms[li++] = dat[i];
4943
- ++lf[dat[i]];
4911
+ for (i2 = Math.max(i2, wi); i2 < s; ++i2) {
4912
+ syms[li++] = dat[i2];
4913
+ ++lf[dat[i2]];
4944
4914
  }
4945
- pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
4915
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i2 - bs, pos);
4946
4916
  if (!lst) {
4947
4917
  st.r = pos & 7 | w[pos / 8 | 0] << 3;
4948
4918
  pos -= 7;
4949
- st.h = head, st.p = prev, st.i = i, st.w = wi;
4919
+ st.h = head, st.p = prev, st.i = i2, st.w = wi;
4950
4920
  }
4951
4921
  } else {
4952
- for (var i = st.w || 0; i < s + lst; i += 65535) {
4953
- var e = i + 65535;
4922
+ for (var i2 = st.w || 0; i2 < s + lst; i2 += 65535) {
4923
+ var e = i2 + 65535;
4954
4924
  if (e >= s) {
4955
4925
  w[pos / 8 | 0] = lst;
4956
4926
  e = s;
4957
4927
  }
4958
- pos = wfblk(w, pos + 1, dat.subarray(i, e));
4928
+ pos = wfblk(w, pos + 1, dat.subarray(i2, e));
4959
4929
  }
4960
4930
  st.i = s;
4961
4931
  }
@@ -5000,7 +4970,8 @@ var CAPABILITY_VERBS = [
5000
4970
  "interactive-terminal",
5001
4971
  "board-tool-read",
5002
4972
  "board-tool-write",
5003
- "register-push"
4973
+ "register-push",
4974
+ "start-session"
5004
4975
  ];
5005
4976
  function isCapabilityVerb(value) {
5006
4977
  return CAPABILITY_VERBS.includes(value);
@@ -5036,6 +5007,23 @@ var COMPRESSION_THRESHOLD = 4 * 1024;
5036
5007
  var FRAME_FORMAT_DEFLATE = 1;
5037
5008
  var JSON_OPEN_BRACE = 123;
5038
5009
  var DEFLATE_HEADER_LENGTH = 5;
5010
+ var UNSUPPORTED_VERB_ERROR_CODE = "unsupported-verb";
5011
+ var UNSUPPORTED_VERB_ERROR_NAME = "UnsupportedVerbError";
5012
+ var UnsupportedVerbError = class extends Error {
5013
+ requestId;
5014
+ verb;
5015
+ constructor(requestId, verb) {
5016
+ super(`capability-request has an unsupported "verb": ${verb}`);
5017
+ this.name = UNSUPPORTED_VERB_ERROR_NAME;
5018
+ this.requestId = requestId;
5019
+ this.verb = verb;
5020
+ }
5021
+ };
5022
+ function isUnsupportedVerbError(error) {
5023
+ if (!(error instanceof Error) || error.name !== UNSUPPORTED_VERB_ERROR_NAME) return false;
5024
+ const candidate = error;
5025
+ return typeof candidate.requestId === "string" && typeof candidate.verb === "string";
5026
+ }
5039
5027
  function encodeMessage(message) {
5040
5028
  const json = new TextEncoder().encode(JSON.stringify(message));
5041
5029
  if (json.length > MAX_DECODED_LENGTH) {
@@ -5114,8 +5102,9 @@ function validateBridgeMessage(value) {
5114
5102
  return { type: "heartbeat" };
5115
5103
  case "capability-request": {
5116
5104
  if (typeof value.requestId !== "string") throw new Error('capability-request missing "requestId"');
5117
- if (typeof value.verb !== "string" || !isCapabilityVerb(value.verb)) throw new Error('capability-request has an invalid "verb"');
5105
+ if (typeof value.verb !== "string") throw new Error('capability-request has an invalid "verb"');
5118
5106
  if (!isJsonValue(value.payload)) throw new Error('capability-request has a non-JSON "payload"');
5107
+ if (!isCapabilityVerb(value.verb)) throw new UnsupportedVerbError(value.requestId, value.verb);
5119
5108
  return { type: "capability-request", requestId: value.requestId, verb: value.verb, payload: value.payload };
5120
5109
  }
5121
5110
  case "capability-response": {
@@ -5123,12 +5112,14 @@ function validateBridgeMessage(value) {
5123
5112
  if (typeof value.ok !== "boolean") throw new Error('capability-response missing "ok"');
5124
5113
  if (value.payload !== void 0 && !isJsonValue(value.payload)) throw new Error('capability-response has a non-JSON "payload"');
5125
5114
  if (value.error !== void 0 && typeof value.error !== "string") throw new Error('capability-response has a non-string "error"');
5115
+ if (value.code !== void 0 && typeof value.code !== "string") throw new Error('capability-response has a non-string "code"');
5126
5116
  return {
5127
5117
  type: "capability-response",
5128
5118
  requestId: value.requestId,
5129
5119
  ok: value.ok,
5130
5120
  payload: value.payload,
5131
- error: value.error
5121
+ error: value.error,
5122
+ code: value.code
5132
5123
  };
5133
5124
  }
5134
5125
  case "event": {
@@ -5163,20 +5154,20 @@ function unwrapSessionFrame(frame) {
5163
5154
  // src/wire/base64url.ts
5164
5155
  var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
5165
5156
  var DECODE_MAP = {};
5166
- for (let i = 0; i < ALPHABET.length; i++) DECODE_MAP[ALPHABET[i]] = i;
5157
+ for (let i2 = 0; i2 < ALPHABET.length; i2++) DECODE_MAP[ALPHABET[i2]] = i2;
5167
5158
  function base64UrlEncode(bytes) {
5168
5159
  let result = "";
5169
- let i = 0;
5170
- for (; i + 2 < bytes.length; i += 3) {
5171
- const chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
5160
+ let i2 = 0;
5161
+ for (; i2 + 2 < bytes.length; i2 += 3) {
5162
+ const chunk = bytes[i2] << 16 | bytes[i2 + 1] << 8 | bytes[i2 + 2];
5172
5163
  result += ALPHABET[chunk >> 18 & 63] + ALPHABET[chunk >> 12 & 63] + ALPHABET[chunk >> 6 & 63] + ALPHABET[chunk & 63];
5173
5164
  }
5174
- const remaining = bytes.length - i;
5165
+ const remaining = bytes.length - i2;
5175
5166
  if (remaining === 1) {
5176
- const chunk = bytes[i] << 16;
5167
+ const chunk = bytes[i2] << 16;
5177
5168
  result += ALPHABET[chunk >> 18 & 63] + ALPHABET[chunk >> 12 & 63];
5178
5169
  } else if (remaining === 2) {
5179
- const chunk = bytes[i] << 16 | bytes[i + 1] << 8;
5170
+ const chunk = bytes[i2] << 16 | bytes[i2 + 1] << 8;
5180
5171
  result += ALPHABET[chunk >> 18 & 63] + ALPHABET[chunk >> 12 & 63] + ALPHABET[chunk >> 6 & 63];
5181
5172
  }
5182
5173
  return result;
@@ -5233,7 +5224,7 @@ function sealPushEnvelope(pushKey, recipientStaticPublicKey, plaintext) {
5233
5224
  const nonce = randomBytes4(XCHACHA_NONCE_LENGTH);
5234
5225
  const encodedPlaintext = new TextEncoder().encode(JSON.stringify(plaintext));
5235
5226
  const ciphertext = xaeadEncrypt(pushKey, nonce, recipientStaticPublicKey, encodedPlaintext);
5236
- return base64UrlEncode(concatBytes4(nonce, ciphertext));
5227
+ return base64UrlEncode(concatBytes3(nonce, ciphertext));
5237
5228
  }
5238
5229
  function openPushEnvelope(pushKey, recipientStaticPublicKey, blob) {
5239
5230
  const bytes = base64UrlDecode(blob);
@@ -5472,7 +5463,9 @@ function parseBoardTaskWire(value) {
5472
5463
  attachment_count: typeof value.attachment_count === "number" ? value.attachment_count : 0,
5473
5464
  archived_at: nullableString(value, "archived_at"),
5474
5465
  created_at: requireString(value, "created_at", "board task"),
5475
- updated_at: requireString(value, "updated_at", "board task")
5466
+ updated_at: requireString(value, "updated_at", "board task"),
5467
+ spawn_progress: nullableString(value, "spawn_progress"),
5468
+ resumable: nullableBoolean(value, "resumable")
5476
5469
  };
5477
5470
  }
5478
5471
  function parseBacklogItemWire(value) {
@@ -5524,6 +5517,9 @@ function parseDiffFileContentWire(payload) {
5524
5517
 
5525
5518
  // src/wire/payloads.ts
5526
5519
  var READ_STREAM_SESSION_STATUSES = ["running", "queued", "suspended", "exited"];
5520
+ function isReadStreamSessionStatusWire(value) {
5521
+ return typeof value === "string" && READ_STREAM_SESSION_STATUSES.includes(value);
5522
+ }
5527
5523
  function parseReadStreamResponsePayload(payload) {
5528
5524
  if (!isRecord(payload)) throw new Error("read-stream response must be an object");
5529
5525
  if (typeof payload.scrollback !== "string") throw new Error('read-stream response is missing "scrollback"');
@@ -5554,11 +5550,19 @@ function parseReadStreamResponsePayload(payload) {
5554
5550
  response.ptyDimensions = parseTerminalDimensionsWire(payload.ptyDimensions);
5555
5551
  }
5556
5552
  if (payload.sessionStatus !== void 0) {
5557
- if (typeof payload.sessionStatus !== "string" || !READ_STREAM_SESSION_STATUSES.includes(payload.sessionStatus)) {
5553
+ if (!isReadStreamSessionStatusWire(payload.sessionStatus)) {
5558
5554
  throw new Error('read-stream response has an invalid "sessionStatus"');
5559
5555
  }
5560
5556
  response.sessionStatus = payload.sessionStatus;
5561
5557
  }
5558
+ if (payload.resuming !== void 0) {
5559
+ if (typeof payload.resuming !== "boolean") throw new Error('read-stream response has an invalid "resuming"');
5560
+ response.resuming = payload.resuming;
5561
+ }
5562
+ if (payload.resumable !== void 0) {
5563
+ if (typeof payload.resumable !== "boolean") throw new Error('read-stream response has an invalid "resumable"');
5564
+ response.resumable = payload.resumable;
5565
+ }
5562
5566
  return response;
5563
5567
  }
5564
5568
  function parseTranscriptWindowResponsePayload(payload) {
@@ -5756,6 +5760,23 @@ function parseMoveTaskRequestPayload(payload) {
5756
5760
  projectId: payload.projectId
5757
5761
  };
5758
5762
  }
5763
+ function parseStartSessionRequestPayload(payload) {
5764
+ if (!isRecord(payload)) throw new Error("start-session payload must be an object");
5765
+ if (typeof payload.taskId !== "string") throw new Error('start-session payload missing "taskId"');
5766
+ if (typeof payload.projectId !== "string") throw new Error('start-session payload missing "projectId"');
5767
+ return {
5768
+ taskId: payload.taskId,
5769
+ projectId: payload.projectId
5770
+ };
5771
+ }
5772
+ function parseStartSessionResponsePayload(payload) {
5773
+ if (!isRecord(payload)) throw new Error("start-session response must be an object");
5774
+ if (typeof payload.ok !== "boolean") throw new Error('start-session response missing "ok"');
5775
+ if (payload.outcome !== "starting" && payload.outcome !== "live") {
5776
+ throw new Error('start-session response has an invalid "outcome"');
5777
+ }
5778
+ return { ok: payload.ok, outcome: payload.outcome };
5779
+ }
5759
5780
  function parseAnswerPermissionPromptRequestPayload(payload) {
5760
5781
  if (!isRecord(payload)) throw new Error("answer-permission-prompt payload must be an object");
5761
5782
  if (typeof payload.sessionId !== "string") throw new Error('answer-permission-prompt payload missing "sessionId"');
@@ -5851,6 +5872,8 @@ function parseCapabilityRequestPayload(verb, payload) {
5851
5872
  return parseBoardToolRequestPayload(payload);
5852
5873
  case "register-push":
5853
5874
  return parseRegisterPushRequestPayload(payload);
5875
+ case "start-session":
5876
+ return parseStartSessionRequestPayload(payload);
5854
5877
  default: {
5855
5878
  const exhaustiveCheck = verb;
5856
5879
  throw new Error(`Unknown capability verb: ${String(exhaustiveCheck)}`);
@@ -5916,7 +5939,7 @@ function encodePairingQrPayload(payload) {
5916
5939
  }
5917
5940
  const expiresAtBytes = new TextEncoder().encode(payload.expiresAt);
5918
5941
  const protocolVersionBytes = new TextEncoder().encode(payload.protocolVersion);
5919
- const body = concatBytes4(
5942
+ const body = concatBytes3(
5920
5943
  Uint8Array.of(PAYLOAD_VERSION),
5921
5944
  payload.desktopStaticPublicKey,
5922
5945
  payload.pairingToken,
@@ -5996,12 +6019,12 @@ function openPairingConfirm(initiatorToResponder, frame) {
5996
6019
  function uint32LengthPrefixed(bytes) {
5997
6020
  const prefix = new Uint8Array(4);
5998
6021
  new DataView(prefix.buffer).setUint32(0, bytes.length, false);
5999
- return concatBytes4(prefix, bytes);
6022
+ return concatBytes3(prefix, bytes);
6000
6023
  }
6001
6024
  function encodeRosterEntryForSigning(entry) {
6002
6025
  const encoder = new TextEncoder();
6003
6026
  const sortedCapabilities = entry.capabilities.slice().sort().join(",");
6004
- return concatBytes4(
6027
+ return concatBytes3(
6005
6028
  uint32LengthPrefixed(encoder.encode(entry.deviceId)),
6006
6029
  uint32LengthPrefixed(entry.staticPublicKey),
6007
6030
  uint32LengthPrefixed(encoder.encode(entry.displayName)),
@@ -6107,11 +6130,24 @@ function parseActivityEventPayload(payload) {
6107
6130
  }
6108
6131
  case "session-ended": {
6109
6132
  if (typeof payload.intentional !== "boolean") throw new Error('session-ended payload is missing "intentional"');
6110
- if (payload.spawnProgressLabel === void 0) {
6111
- return { type: "session-ended", intentional: payload.intentional };
6133
+ if (payload.spawnProgressLabel !== void 0 && typeof payload.spawnProgressLabel !== "string") {
6134
+ throw new Error('session-ended payload has an invalid "spawnProgressLabel"');
6135
+ }
6136
+ if (payload.successorSessionId !== void 0 && typeof payload.successorSessionId !== "string") {
6137
+ throw new Error('session-ended payload has an invalid "successorSessionId"');
6112
6138
  }
6113
- if (typeof payload.spawnProgressLabel !== "string") throw new Error('session-ended payload has an invalid "spawnProgressLabel"');
6114
- return { type: "session-ended", intentional: payload.intentional, spawnProgressLabel: payload.spawnProgressLabel };
6139
+ return {
6140
+ type: "session-ended",
6141
+ intentional: payload.intentional,
6142
+ ...payload.spawnProgressLabel !== void 0 ? { spawnProgressLabel: payload.spawnProgressLabel } : {},
6143
+ ...payload.successorSessionId !== void 0 ? { successorSessionId: payload.successorSessionId } : {}
6144
+ };
6145
+ }
6146
+ case "status": {
6147
+ if (!isReadStreamSessionStatusWire(payload.status)) throw new Error('status payload has an invalid "status"');
6148
+ if (typeof payload.resuming !== "boolean") throw new Error('status payload is missing "resuming"');
6149
+ if (typeof payload.resumable !== "boolean") throw new Error('status payload is missing "resumable"');
6150
+ return { type: "status", status: payload.status, resuming: payload.resuming, resumable: payload.resumable };
6115
6151
  }
6116
6152
  case "message-preview": {
6117
6153
  if (typeof payload.text !== "string") throw new Error('message-preview payload is missing "text"');
@@ -6192,6 +6228,8 @@ function isBridgeEvent(value) {
6192
6228
  PUSH_ENVELOPE_MAX_FUTURE_SKEW_MS,
6193
6229
  SecretstreamState,
6194
6230
  SessionFrameKind,
6231
+ UNSUPPORTED_VERB_ERROR_CODE,
6232
+ UnsupportedVerbError,
6195
6233
  X25519_KEY_LENGTH,
6196
6234
  bytesToHex,
6197
6235
  capabilitySetFromArray,
@@ -6224,10 +6262,12 @@ function isBridgeEvent(value) {
6224
6262
  isDoneRole,
6225
6263
  isJsonValue,
6226
6264
  isPushCategory,
6265
+ isReadStreamSessionStatusWire,
6227
6266
  isRecord,
6228
6267
  isRosterEntryExpired,
6229
6268
  isSecureRelayAddress,
6230
6269
  isTodoRole,
6270
+ isUnsupportedVerbError,
6231
6271
  openPairingConfirm,
6232
6272
  openPushEnvelope,
6233
6273
  parseActivityEventPayload,
@@ -6245,6 +6285,7 @@ function isBridgeEvent(value) {
6245
6285
  parseSessionEventWire,
6246
6286
  parseSessionSummaryWire,
6247
6287
  parseSessionUsageWire,
6288
+ parseStartSessionResponsePayload,
6248
6289
  parseTerminalDimensionsWire,
6249
6290
  parseTranscriptEntriesWire,
6250
6291
  parseTranscriptEventPayload,