@oneaddress/partner-sdk 2.4.1 → 2.6.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.
@@ -6,42 +6,55 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
6
6
  function isBytes(a) {
7
7
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
8
8
  }
9
+ var atitle = (title) => title ? `"${title}" ` : "";
9
10
  function anumber(n, title = "") {
10
- if (typeof n !== "number") {
11
- const prefix = title && `"${title}" `;
12
- throw new TypeError(`${prefix}expected number, got ${typeof n}`);
13
- }
14
- if (!Number.isSafeInteger(n) || n < 0) {
15
- const prefix = title && `"${title}" `;
16
- throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
17
- }
11
+ if (typeof n !== "number")
12
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
13
+ if (!Number.isSafeInteger(n) || n < 0)
14
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
15
+ return n;
18
16
  }
19
- function abytes(value, length, title = "") {
20
- const bytes = isBytes(value);
21
- const len = value?.length;
22
- const needsLen = length !== void 0;
23
- if (!bytes || needsLen && len !== length) {
24
- const prefix = title && `"${title}" `;
25
- const ofLen = needsLen ? ` of length ${length}` : "";
26
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
27
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
28
- if (!bytes)
29
- throw new TypeError(message);
30
- throw new RangeError(message);
31
- }
17
+ function abool(value, title = "") {
18
+ if (typeof value !== "boolean")
19
+ throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
32
20
  return value;
33
21
  }
22
+ function abytes(value, length, title = "") {
23
+ if (isBytes(value) && (length === void 0 || value.length === length))
24
+ return value;
25
+ if (length !== void 0)
26
+ anumber(length, "length");
27
+ const bytes = isBytes(value);
28
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
29
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
30
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
31
+ if (!bytes)
32
+ throw new TypeError(message);
33
+ throw new RangeError(message);
34
+ }
35
+ var aobject = (value, label) => {
36
+ if (value === null || typeof value !== "object" || Array.isArray(value))
37
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
38
+ };
39
+ var aopts = (value, label) => {
40
+ aobject(value, label);
41
+ const proto = Object.getPrototypeOf(value);
42
+ if (proto !== Object.prototype && proto !== null)
43
+ throw new TypeError(`"${label}" expected plain object`);
44
+ if (Object.hasOwn(value, "__proto__"))
45
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
46
+ };
34
47
  function aexists(instance, checkFinished = true) {
35
48
  if (instance.destroyed)
36
- throw new Error("Hash instance has been destroyed");
49
+ throw new Error("hash was destroyed");
37
50
  if (checkFinished && instance.finished)
38
- throw new Error("Hash#digest() has already been called");
51
+ throw new Error("digest() was already called");
39
52
  }
40
53
  function aoutput(out, instance) {
41
- abytes(out, void 0, "digestInto() output");
54
+ abytes(out, void 0, "output");
42
55
  const min = instance.outputLen;
43
- if (out.length < min) {
44
- throw new RangeError('"digestInto() output" expected to be of length >=' + min);
56
+ if (!(out.length >= min)) {
57
+ throw new RangeError('"output" expected length >= ' + min);
45
58
  }
46
59
  }
47
60
  function u32(arr) {
@@ -52,9 +65,6 @@ function clean(...arrays) {
52
65
  arrays[i].fill(0);
53
66
  }
54
67
  }
55
- function createView(arr) {
56
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
57
- }
58
68
  var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
59
69
  function byteSwap(word) {
60
70
  return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
@@ -81,15 +91,8 @@ function bytesToHex(bytes) {
81
91
  }
82
92
  return hex;
83
93
  }
84
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
85
94
  function asciiToBase16(ch) {
86
- if (ch >= asciis._0 && ch <= asciis._9)
87
- return ch - asciis._0;
88
- if (ch >= asciis.A && ch <= asciis.F)
89
- return ch - (asciis.A - 10);
90
- if (ch >= asciis.a && ch <= asciis.f)
91
- return ch - (asciis.a - 10);
92
- return;
95
+ return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
93
96
  }
94
97
  function hexToBytes(hex) {
95
98
  if (typeof hex !== "string")
@@ -134,7 +137,17 @@ function concatBytes(...arrays) {
134
137
  }
135
138
  return res;
136
139
  }
140
+ function checkOpts(defaults, opts2, title = "opts") {
141
+ aopts(defaults, "defaults");
142
+ if (opts2 !== void 0)
143
+ aopts(opts2, title);
144
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts2);
145
+ return merged;
146
+ }
137
147
  function createHasher(hashCons, info = {}) {
148
+ if (typeof hashCons !== "function")
149
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
150
+ info = checkOpts({}, info, "info");
138
151
  const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest();
139
152
  const tmp = hashCons(void 0);
140
153
  hashC.outputLen = tmp.outputLen;
@@ -160,8 +173,26 @@ var oidNist = (suffix) => ({
160
173
  });
161
174
 
162
175
  // ../../node_modules/@noble/curves/utils.js
176
+ function aarray(item, title, inner = () => {
177
+ }) {
178
+ if (!Array.isArray(item))
179
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
180
+ for (let i = 0; i < item.length; i++)
181
+ inner(item[i], `${title}[${i}]`);
182
+ return item;
183
+ }
163
184
  var abytes2 = (value, length, title) => abytes(value, length, title);
164
185
  var anumber2 = anumber;
186
+ function aobject2(value, title = "object") {
187
+ if (value === null || typeof value !== "object" || Array.isArray(value))
188
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
189
+ return value;
190
+ }
191
+ function afunction(value, title) {
192
+ if (typeof value !== "function")
193
+ throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
194
+ return value;
195
+ }
165
196
  var bytesToHex2 = bytesToHex;
166
197
  var concatBytes2 = (...arrays) => concatBytes(...arrays);
167
198
  var hexToBytes2 = (hex) => hexToBytes(hex);
@@ -169,11 +200,10 @@ var isBytes2 = isBytes;
169
200
  var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
170
201
  var _0n = /* @__PURE__ */ BigInt(0);
171
202
  var _1n = /* @__PURE__ */ BigInt(1);
172
- function abool(value, title = "") {
173
- if (typeof value !== "boolean") {
174
- const prefix = title && `"${title}" `;
175
- throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
176
- }
203
+ var atitle2 = (title) => title ? `"${title}" ` : "";
204
+ function abool2(value, title = "") {
205
+ if (typeof value !== "boolean")
206
+ throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
177
207
  return value;
178
208
  }
179
209
  function abignumber(n) {
@@ -208,26 +238,17 @@ function bytesToNumberLE(bytes) {
208
238
  function numberToBytesBE(n, len) {
209
239
  anumber(len);
210
240
  if (len === 0)
211
- throw new RangeError("zero length");
241
+ throw new Error("zero output length is invalid");
212
242
  n = abignumber(n);
243
+ const expectedLen = len * 2;
213
244
  const hex = n.toString(16);
214
- if (hex.length > len * 2)
215
- throw new RangeError("number too large");
216
- return hexToBytes(hex.padStart(len * 2, "0"));
245
+ if (hex.length > expectedLen)
246
+ throw new RangeError("number is too large");
247
+ return hexToBytes(hex.padStart(expectedLen, "0"));
217
248
  }
218
249
  function numberToBytesLE(n, len) {
219
250
  return numberToBytesBE(n, len).reverse();
220
251
  }
221
- function equalBytes(a, b) {
222
- a = abytes2(a);
223
- b = abytes2(b);
224
- if (a.length !== b.length)
225
- return false;
226
- let diff = 0;
227
- for (let i = 0; i < a.length; i++)
228
- diff |= a[i] ^ b[i];
229
- return diff === 0;
230
- }
231
252
  function copyBytes(bytes) {
232
253
  return Uint8Array.from(abytes2(bytes));
233
254
  }
@@ -242,7 +263,9 @@ function asciiToBytes(ascii) {
242
263
  return charCode;
243
264
  });
244
265
  }
245
- var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
266
+ function isPosBig(n) {
267
+ return typeof n === "bigint" && _0n <= n;
268
+ }
246
269
  function inRange(n, min, max) {
247
270
  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
248
271
  }
@@ -253,32 +276,32 @@ function aInRange(title, n, min, max) {
253
276
  function bitLen(n) {
254
277
  if (n < _0n)
255
278
  throw new Error("expected non-negative bigint, got " + n);
256
- let len;
257
- for (len = 0; n > _0n; n >>= _1n, len += 1)
258
- ;
259
- return len;
260
- }
261
- var bitMask = (n) => (_1n << BigInt(n)) - _1n;
262
- function validateObject(object, fields = {}, optFields = {}) {
263
- if (Object.prototype.toString.call(object) !== "[object Object]")
264
- throw new TypeError("expected valid options object");
279
+ return n === _0n ? 0 : n.toString(2).length;
280
+ }
281
+ var bitMask = (n) => {
282
+ asafenumber(n, "n");
283
+ return (_1n << BigInt(n)) - _1n;
284
+ };
285
+ function validateObject(object, fields = {}, optFields = {}, title = "object") {
286
+ aobject2(object, title);
287
+ aobject2(fields, "fields");
288
+ aobject2(optFields, "optFields");
265
289
  function checkField(fieldName, expectedType, isOpt) {
266
- if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
267
- throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
290
+ const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
268
291
  const val = object[fieldName];
292
+ if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
293
+ throw new TypeError(`${label} is invalid: expected own property`);
294
+ }
269
295
  if (isOpt && val === void 0)
270
296
  return;
271
297
  const current = typeof val;
272
298
  if (current !== expectedType || val === null)
273
- throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
299
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
274
300
  }
275
301
  const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
276
302
  iter(fields, false);
277
303
  iter(optFields, true);
278
304
  }
279
- var notImplemented = () => {
280
- throw new Error("not implemented");
281
- };
282
305
 
283
306
  // ../../node_modules/@noble/curves/abstract/modular.js
284
307
  var _0n2 = /* @__PURE__ */ BigInt(0);
@@ -290,14 +313,64 @@ var _5n = /* @__PURE__ */ BigInt(5);
290
313
  var _7n = /* @__PURE__ */ BigInt(7);
291
314
  var _8n = /* @__PURE__ */ BigInt(8);
292
315
  var _9n = /* @__PURE__ */ BigInt(9);
316
+ var _15n = /* @__PURE__ */ BigInt(15);
293
317
  var _16n = /* @__PURE__ */ BigInt(16);
318
+ var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
294
319
  function mod(a, b) {
295
320
  if (b <= _0n2)
296
321
  throw new Error("mod: expected positive modulus, got " + b);
297
322
  const result = a % b;
298
323
  return result >= _0n2 ? result : b + result;
299
324
  }
325
+ function pow(num, power, modulo) {
326
+ if (modulo <= _1n2)
327
+ throw new Error("pow: expected modulus > 1, got " + modulo);
328
+ if (typeof power !== "bigint")
329
+ throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
330
+ if (power < _0n2)
331
+ throw new Error("invalid exponent, negatives unsupported");
332
+ if (power === _0n2)
333
+ return _1n2;
334
+ if (power === _1n2)
335
+ return num;
336
+ let d = num % modulo;
337
+ if (d < _0n2)
338
+ d += modulo;
339
+ if (power < POW_WINDOWED_MIN) {
340
+ let p2 = _1n2;
341
+ while (power > _0n2) {
342
+ if (power & _1n2)
343
+ p2 = p2 * d % modulo;
344
+ d = d * d % modulo;
345
+ power >>= _1n2;
346
+ }
347
+ return p2;
348
+ }
349
+ const digits = [];
350
+ while (power > _0n2) {
351
+ digits.push(Number(power & _15n));
352
+ power >>= _4n;
353
+ }
354
+ const table = new Array(16);
355
+ table[0] = _1n2;
356
+ table[1] = d;
357
+ for (let i = 2; i < 16; i++)
358
+ table[i] = table[i - 1] * d % modulo;
359
+ let p = table[digits[digits.length - 1]];
360
+ for (let w = digits.length - 2; w >= 0; w--) {
361
+ p = p * p % modulo;
362
+ p = p * p % modulo;
363
+ p = p * p % modulo;
364
+ p = p * p % modulo;
365
+ const digit = digits[w];
366
+ if (digit !== 0)
367
+ p = p * table[digit] % modulo;
368
+ }
369
+ return p;
370
+ }
300
371
  function pow2(x, power, modulo) {
372
+ if (modulo <= _1n2)
373
+ throw new Error("pow2: expected modulus > 1, got " + modulo);
301
374
  if (power < _0n2)
302
375
  throw new Error("pow2: expected non-negative exponent, got " + power);
303
376
  let res = x;
@@ -310,37 +383,40 @@ function pow2(x, power, modulo) {
310
383
  function invert(number, modulo) {
311
384
  if (number === _0n2)
312
385
  throw new Error("invert: expected non-zero number");
313
- if (modulo <= _0n2)
314
- throw new Error("invert: expected positive modulus, got " + modulo);
386
+ if (modulo <= _1n2)
387
+ throw new Error("invert: expected modulus > 1, got " + modulo);
315
388
  let a = mod(number, modulo);
316
389
  let b = modulo;
317
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
390
+ let x = _0n2, u = _1n2;
318
391
  while (a !== _0n2) {
319
392
  const q = b / a;
320
393
  const r = b - a * q;
321
394
  const m = x - u * q;
322
- const n = y - v * q;
323
- b = a, a = r, x = u, y = v, u = m, v = n;
395
+ b = a, a = r, x = u, u = m;
324
396
  }
325
397
  const gcd = b;
326
398
  if (gcd !== _1n2)
327
399
  throw new Error("invert: does not exist");
328
400
  return mod(x, modulo);
329
401
  }
330
- function assertIsSquare(Fp2, root, n) {
331
- const F2 = Fp2;
402
+ function assertIsSquare(Fp, root, n) {
403
+ const F2 = Fp;
332
404
  if (!F2.eql(F2.sqr(root), n))
333
405
  throw new Error("Cannot find square root");
334
406
  }
335
- function sqrt3mod4(Fp2, n) {
336
- const F2 = Fp2;
407
+ function aoddModulus(order, fnName) {
408
+ if ((order & _1n2) === _0n2)
409
+ throw new Error(fnName + ": expected odd modulus, got " + order);
410
+ }
411
+ function sqrt3mod4(Fp, n) {
412
+ const F2 = Fp;
337
413
  const p1div4 = (F2.ORDER + _1n2) / _4n;
338
414
  const root = F2.pow(n, p1div4);
339
415
  assertIsSquare(F2, root, n);
340
416
  return root;
341
417
  }
342
- function sqrt5mod8(Fp2, n) {
343
- const F2 = Fp2;
418
+ function sqrt5mod8(Fp, n) {
419
+ const F2 = Fp;
344
420
  const p5div8 = (F2.ORDER - _5n) / _8n;
345
421
  const n2 = F2.mul(n, _2n);
346
422
  const v = F2.pow(n2, p5div8);
@@ -357,8 +433,8 @@ function sqrt9mod16(P) {
357
433
  const c2 = tn(Fp_, c1);
358
434
  const c3 = tn(Fp_, Fp_.neg(c1));
359
435
  const c4 = (P + _7n) / _16n;
360
- return ((Fp2, n) => {
361
- const F2 = Fp2;
436
+ return ((Fp, n) => {
437
+ const F2 = Fp;
362
438
  let tv1 = F2.pow(n, c4);
363
439
  let tv2 = F2.mul(tv1, c1);
364
440
  const tv3 = F2.mul(tv1, c2);
@@ -376,6 +452,7 @@ function sqrt9mod16(P) {
376
452
  function tonelliShanks(P) {
377
453
  if (P < _3n)
378
454
  throw new Error("sqrt is not defined for small field");
455
+ aoddModulus(P, "tonelliShanks");
379
456
  let Q2 = P - _1n2;
380
457
  let S = 0;
381
458
  while (Q2 % _2n === _0n2) {
@@ -392,8 +469,8 @@ function tonelliShanks(P) {
392
469
  return sqrt3mod4;
393
470
  let cc = _Fp.pow(Z, Q2);
394
471
  const Q1div2 = (Q2 + _1n2) / _2n;
395
- return function tonelliSlow(Fp2, n) {
396
- const F2 = Fp2;
472
+ return function tonelliSlow(Fp, n) {
473
+ const F2 = Fp;
397
474
  if (F2.is0(n))
398
475
  return n;
399
476
  if (FpLegendre(F2, n) !== 1)
@@ -404,7 +481,7 @@ function tonelliShanks(P) {
404
481
  let R = F2.pow(n, Q1div2);
405
482
  while (!F2.eql(t, F2.ONE)) {
406
483
  if (F2.is0(t))
407
- return F2.ZERO;
484
+ throw new Error("Cannot find square root: probably non-prime P");
408
485
  let i = 1;
409
486
  let t_tmp = F2.sqr(t);
410
487
  while (!F2.eql(t_tmp, F2.ONE)) {
@@ -424,6 +501,7 @@ function tonelliShanks(P) {
424
501
  };
425
502
  }
426
503
  function FpSqrt(P) {
504
+ aoddModulus(P, "Fp.sqrt");
427
505
  if (P % _4n === _3n)
428
506
  return sqrt3mod4;
429
507
  if (P % _8n === _5n)
@@ -453,44 +531,24 @@ var FIELD_FIELDS = [
453
531
  "sqrN"
454
532
  ];
455
533
  function validateField(field) {
456
- const initial = {
457
- ORDER: "bigint",
458
- BYTES: "number",
459
- BITS: "number"
460
- };
461
- const opts2 = FIELD_FIELDS.reduce((map, val) => {
462
- map[val] = "function";
463
- return map;
464
- }, initial);
465
- validateObject(field, opts2);
534
+ aobject2(field, "field");
535
+ if (typeof field.ORDER !== "bigint")
536
+ throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
466
537
  asafenumber(field.BYTES, "BYTES");
467
538
  asafenumber(field.BITS, "BITS");
539
+ for (const name of FIELD_FIELDS)
540
+ afunction(field[name], "field." + name);
468
541
  if (field.BYTES < 1 || field.BITS < 1)
469
542
  throw new Error("invalid field: expected BYTES/BITS > 0");
470
543
  if (field.ORDER <= _1n2)
471
544
  throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
472
545
  return field;
473
546
  }
474
- function FpPow(Fp2, num, power) {
475
- const F2 = Fp2;
476
- if (power < _0n2)
477
- throw new Error("invalid exponent, negatives unsupported");
478
- if (power === _0n2)
479
- return F2.ONE;
480
- if (power === _1n2)
481
- return num;
482
- let p = F2.ONE;
483
- let d = num;
484
- while (power > _0n2) {
485
- if (power & _1n2)
486
- p = F2.mul(p, d);
487
- d = F2.sqr(d);
488
- power >>= _1n2;
489
- }
490
- return p;
491
- }
492
- function FpInvertBatch(Fp2, nums, passZero = false) {
493
- const F2 = Fp2;
547
+ function FpInvertBatch(Fp, nums, passZero = false) {
548
+ validateField(Fp);
549
+ aarray(nums, "nums");
550
+ abool2(passZero, "passZero");
551
+ const F2 = Fp;
494
552
  const inverted = new Array(nums.length).fill(passZero ? F2.ZERO : void 0);
495
553
  const multipliedAcc = nums.reduce((acc, num, i) => {
496
554
  if (F2.is0(num))
@@ -507,8 +565,10 @@ function FpInvertBatch(Fp2, nums, passZero = false) {
507
565
  }, invertedAcc);
508
566
  return inverted;
509
567
  }
510
- function FpLegendre(Fp2, n) {
511
- const F2 = Fp2;
568
+ function FpLegendre(Fp, n) {
569
+ validateField(Fp);
570
+ const F2 = Fp;
571
+ aoddModulus(F2.ORDER, "FpLegendre");
512
572
  const p1mod2 = (F2.ORDER - _1n2) / _2n;
513
573
  const powered = F2.pow(n, p1mod2);
514
574
  const yes = F2.eql(powered, F2.ONE);
@@ -527,7 +587,7 @@ function nLength(n, nBitLength) {
527
587
  throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
528
588
  const bits = bitLen(n);
529
589
  if (nBitLength !== void 0 && nBitLength < bits)
530
- throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
590
+ throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
531
591
  const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
532
592
  const nByteLength = Math.ceil(_nBitLength / 8);
533
593
  return { nBitLength: _nBitLength, nByteLength };
@@ -604,7 +664,7 @@ var _Field = class {
604
664
  return mod(lhs * rhs, this.ORDER);
605
665
  }
606
666
  pow(num, power) {
607
- return FpPow(this, num, power);
667
+ return pow(num, power, this.ORDER);
608
668
  }
609
669
  div(lhs, rhs) {
610
670
  return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
@@ -658,201 +718,366 @@ var _Field = class {
658
718
  }
659
719
  // TODO: we don't need it here, move out to separate fn
660
720
  invertBatch(lst) {
661
- return FpInvertBatch(this, lst);
721
+ return FpInvertBatch(this, lst, true);
662
722
  }
663
723
  // We can't move this out because Fp6, Fp12 implement it
664
724
  // and it's unclear what to return in there.
665
725
  cmov(a, b, condition) {
666
- abool(condition, "condition");
726
+ abool2(condition, "condition");
667
727
  return condition ? b : a;
668
728
  }
669
729
  };
670
- Object.freeze(_Field.prototype);
671
730
  function Field(ORDER, opts2 = {}) {
731
+ Object.freeze(_Field.prototype);
672
732
  return new _Field(ORDER, opts2);
673
733
  }
674
734
 
675
735
  // ../../node_modules/@noble/curves/abstract/curve.js
676
736
  var _0n3 = /* @__PURE__ */ BigInt(0);
677
737
  var _1n3 = /* @__PURE__ */ BigInt(1);
678
- function negateCt(condition, item) {
679
- const neg = item.negate();
680
- return condition ? neg : item;
738
+ var _4n2 = /* @__PURE__ */ BigInt(4);
739
+ var BLIND_BYTES = 16;
740
+ var BLIND_BITS = 128;
741
+ var FW_WINDOW = 5;
742
+ var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
743
+ function validatePointCons(Point) {
744
+ const pc = Point;
745
+ if (typeof pc !== "function")
746
+ throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
747
+ afunction(pc.fromAffine, "Point.fromAffine");
748
+ afunction(pc.fromBytes, "Point.fromBytes");
749
+ afunction(pc.fromHex, "Point.fromHex");
750
+ aobject2(pc.BASE, "Point.BASE");
751
+ aobject2(pc.ZERO, "Point.ZERO");
752
+ validateField(pc.Fp);
753
+ validateField(pc.Fn);
681
754
  }
682
755
  function normalizeZ(c, points) {
756
+ validatePointCons(c);
757
+ validateMSMPoints(points, c);
683
758
  const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
684
759
  return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
685
760
  }
686
- function validateW(W, bits) {
687
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
688
- throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
761
+ function validateW(W, bits, min = 1) {
762
+ if (!Number.isSafeInteger(W) || W < min || W > bits)
763
+ throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
764
+ }
765
+ function validateTableBytes(numPoints, fpBytes) {
766
+ const bytes = numPoints * (4 * fpBytes + 128);
767
+ if (bytes > TABLE_BYTES_MAX)
768
+ throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
769
+ }
770
+ function probeRandomBytes(randomBytes4, length) {
771
+ if (randomBytes4 === void 0)
772
+ return void 0;
773
+ afunction(randomBytes4, "randomBytes");
774
+ try {
775
+ const probe = randomBytes4(length);
776
+ if (!isBytes2(probe) || probe.length !== length)
777
+ return void 0;
778
+ } catch {
779
+ return void 0;
780
+ }
781
+ return randomBytes4;
782
+ }
783
+ function validateMSMPoints(points, c) {
784
+ aarray(points, "points");
785
+ points.forEach((p, i) => {
786
+ if (!(p instanceof c))
787
+ throw new Error("invalid point at index " + i);
788
+ });
789
+ }
790
+ function validateMSMScalars(scalars, field, maxScalar) {
791
+ if (!Array.isArray(scalars))
792
+ throw new Error("array of scalars expected");
793
+ scalars.forEach((s, i) => {
794
+ const ok = maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar;
795
+ if (!ok)
796
+ throw new Error("invalid scalar at index " + i);
797
+ });
689
798
  }
690
- function calcWOpts(W, scalarBits) {
691
- validateW(W, scalarBits);
692
- const windows = Math.ceil(scalarBits / W) + 1;
693
- const windowSize = 2 ** (W - 1);
694
- const maxNumber = 2 ** W;
695
- const mask = bitMask(W);
696
- const shiftBy = BigInt(W);
697
- return { windows, windowSize, mask, maxNumber, shiftBy };
698
- }
699
- function calcOffsets(n, window, wOpts) {
700
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
701
- let wbits = Number(n & mask);
702
- let nextN = n >> shiftBy;
703
- if (wbits > windowSize) {
704
- wbits -= maxNumber;
705
- nextN += _1n3;
706
- }
707
- const offsetStart = window * windowSize;
708
- const offset = offsetStart + Math.abs(wbits) - 1;
709
- const isZero = wbits === 0;
710
- const isNeg = wbits < 0;
711
- const isNegF = window % 2 !== 0;
712
- const offsetF = offsetStart;
713
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
714
- }
715
- var pointPrecomputes = /* @__PURE__ */ new WeakMap();
716
799
  var pointWindowSizes = /* @__PURE__ */ new WeakMap();
717
- function getW(P) {
800
+ function getWindowSize(P) {
718
801
  return pointWindowSizes.get(P) || 1;
719
802
  }
720
- function assert0(n) {
803
+ function oddMultiples(p, size) {
804
+ const dbl = p.double();
805
+ const t = [p];
806
+ for (let j = 1; j < size; j++)
807
+ t.push(t[j - 1].add(dbl));
808
+ return t;
809
+ }
810
+ function wnafDigits(n, W) {
811
+ const size = 2 ** W;
812
+ const half = size / 2;
813
+ const mask = BigInt(size - 1);
814
+ const d = [];
815
+ while (n > _0n3) {
816
+ let w = 0;
817
+ if (n & _1n3) {
818
+ w = Number(n & mask);
819
+ if (w >= half)
820
+ w -= size;
821
+ n -= BigInt(w);
822
+ }
823
+ d.push(w);
824
+ n >>= _1n3;
825
+ }
826
+ return d;
827
+ }
828
+ function signedWindowDigits(n, W, windows) {
829
+ const size = 2 ** W;
830
+ const half = size / 2;
831
+ const mask = BigInt(size - 1);
832
+ const shiftBy = BigInt(W);
833
+ const d = [];
834
+ for (let w = 0; w < windows; w++) {
835
+ let v = Number(n & mask);
836
+ n >>= shiftBy;
837
+ if (v > half) {
838
+ v -= size;
839
+ n += _1n3;
840
+ }
841
+ d.push(v);
842
+ }
721
843
  if (n !== _0n3)
722
- throw new Error("invalid wNAF");
844
+ throw new Error("invalid wnaf");
845
+ return d;
846
+ }
847
+ function wnafWalk(zero, tables, digits) {
848
+ let max = 0;
849
+ for (const d of digits)
850
+ max = Math.max(max, d.length);
851
+ let acc = zero;
852
+ for (let bit = max - 1; bit >= 0; bit--) {
853
+ if (bit !== max - 1)
854
+ acc = acc.double();
855
+ for (let i = 0; i < digits.length; i++) {
856
+ const w = digits[i][bit];
857
+ if (w) {
858
+ const item = tables[i][Math.abs(w) - 1 >> 1];
859
+ acc = acc.add(w < 0 ? item.negate() : item);
860
+ }
861
+ }
862
+ }
863
+ return acc;
723
864
  }
724
- var wNAF = class {
865
+ var ScalarMultiplier = class {
725
866
  // Parametrized with a given Point class (not individual point)
726
- constructor(Point, bits) {
867
+ constructor(Point, randomBytes4) {
868
+ __publicField(this, "Point");
727
869
  __publicField(this, "BASE");
728
870
  __publicField(this, "ZERO");
729
- __publicField(this, "Fn");
871
+ __publicField(this, "randomBytes");
872
+ __publicField(this, "wnafPrecomputes", /* @__PURE__ */ new WeakMap());
873
+ __publicField(this, "baseCanBeBlinded");
730
874
  __publicField(this, "bits");
875
+ validatePointCons(Point);
876
+ this.randomBytes = probeRandomBytes(randomBytes4, BLIND_BYTES);
877
+ this.Point = Point;
731
878
  this.BASE = Point.BASE;
732
879
  this.ZERO = Point.ZERO;
733
- this.Fn = Point.Fn;
734
- this.bits = bits;
735
- }
736
- // non-const time multiplication ladder
737
- _unsafeLadder(elm, n, p = this.ZERO) {
738
- let d = elm;
739
- while (n > _0n3) {
740
- if (n & _1n3)
741
- p = p.add(d);
742
- d = d.double();
743
- n >>= _1n3;
744
- }
745
- return p;
880
+ this.bits = Point.Fn.BITS;
746
881
  }
747
882
  /**
748
- * Creates a wNAF precomputation window. Used for caching.
749
- * Default window size is set by `utils.precompute()` and is equal to 8.
750
- * Number of precomputed points depends on the curve size:
751
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
752
- * - 𝑊 is the window size
753
- * - 𝑛 is the bitlength of the curve order.
754
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
883
+ * Creates a signed fixed-window wNAF precomputation table: for every window w, the
884
+ * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
885
+ * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
886
+ * window absorbs the final carry of signed-digit recoding.
887
+ * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
755
888
  * @param point - Point instance
756
889
  * @param W - window size
757
- * @returns precomputed point tables flattened to a single array
890
+ * @param bits - scalar bitlength the table must cover
758
891
  */
759
- precomputeWindow(point, W) {
760
- const { windows, windowSize } = calcWOpts(W, this.bits);
761
- const points = [];
762
- let p = point;
763
- let base = p;
764
- for (let window = 0; window < windows; window++) {
765
- base = p;
766
- points.push(base);
767
- for (let i = 1; i < windowSize; i++) {
768
- base = base.add(p);
769
- points.push(base);
892
+ buildWnafTable(point, W, bits) {
893
+ const windows = Math.ceil(bits / W) + 1;
894
+ const half = 2 ** (W - 1);
895
+ const comp = [];
896
+ let base = point;
897
+ for (let w = 0; w < windows; w++) {
898
+ let acc = base;
899
+ for (let i = 0; i < half; i++) {
900
+ comp.push(acc);
901
+ acc = acc.add(base);
770
902
  }
771
- p = base.double();
903
+ base = comp[comp.length - 1].double();
772
904
  }
773
- return points;
905
+ return { W, bits, windows, comp };
774
906
  }
775
907
  /**
776
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
777
- * More compact implementation:
778
- * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
908
+ * Implements ec multiplication using precomputed signed fixed-window wNAF tables.
909
+ * Constant-time: fixed window count with one table addition per window — zero digits feed
910
+ * the fake accumulator — and no doublings; the lookup scans the whole window slice.
911
+ * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
912
+ * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
913
+ * signedWindowDigits throws if `n` exceeds the table.
779
914
  * @returns real and fake (for const-time) points
780
915
  */
781
- wNAF(W, precomputes, n) {
782
- if (!this.Fn.isValid(n))
783
- throw new Error("invalid scalar");
916
+ wnafCachedCT(precomputes, n) {
917
+ const { W, windows, comp } = precomputes;
918
+ const half = 2 ** (W - 1);
919
+ const digits = signedWindowDigits(n, W, windows);
784
920
  let p = this.ZERO;
785
921
  let f = this.BASE;
786
- const wo = calcWOpts(W, this.bits);
787
- for (let window = 0; window < wo.windows; window++) {
788
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
789
- n = nextN;
790
- if (isZero) {
791
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
792
- } else {
793
- p = p.add(negateCt(isNeg, precomputes[offset]));
794
- }
922
+ for (let w = 0; w < windows; w++) {
923
+ const digit = digits[w];
924
+ const start = w * half;
925
+ const idx = Math.abs(digit) - 1;
926
+ let sel = comp[start];
927
+ for (let i = 1; i < half; i++)
928
+ sel = i === idx ? comp[start + i] : sel;
929
+ const neg = sel.negate();
930
+ if (digit === 0)
931
+ f = f.add(comp[start]);
932
+ else
933
+ p = p.add(digit < 0 ? neg : sel);
795
934
  }
796
- assert0(n);
797
935
  return { p, f };
798
936
  }
799
- /**
800
- * Implements unsafe EC multiplication using precomputed tables
801
- * and w-ary non-adjacent form.
802
- * @param acc - accumulator point to add result of multiplication
803
- * @returns point
804
- */
805
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
806
- const wo = calcWOpts(W, this.bits);
807
- for (let window = 0; window < wo.windows; window++) {
808
- if (n === _0n3)
809
- break;
810
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
811
- n = nextN;
812
- if (isZero) {
813
- continue;
814
- } else {
815
- const item = precomputes[offset];
816
- acc = acc.add(isNeg ? item.negate() : item);
817
- }
818
- }
819
- assert0(n);
820
- return acc;
821
- }
822
- getPrecomputes(W, point, transform) {
823
- let comp = pointPrecomputes.get(point);
937
+ // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
938
+ // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
939
+ // incompatible `transform(...)` layouts and expect a separate cache entry.
940
+ getWnafPrecomputes(W, point, bits, transform) {
941
+ let entries = this.wnafPrecomputes.get(point);
942
+ let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
824
943
  if (!comp) {
825
- comp = this.precomputeWindow(point, W);
826
- if (W !== 1) {
827
- if (typeof transform === "function")
828
- comp = transform(comp);
829
- pointPrecomputes.set(point, comp);
944
+ comp = this.buildWnafTable(point, W, bits);
945
+ if (typeof transform === "function")
946
+ comp = { ...comp, comp: transform(comp.comp) };
947
+ if (!entries) {
948
+ entries = [];
949
+ this.wnafPrecomputes.set(point, entries);
830
950
  }
951
+ entries.push(comp);
831
952
  }
832
953
  return comp;
833
954
  }
834
- cached(point, scalar, transform) {
835
- const W = getW(point);
836
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
955
+ assertPoint(point) {
956
+ if (!(point instanceof this.Point))
957
+ throw new TypeError('"point" expected Point instance, got type=' + typeof point);
837
958
  }
838
- unsafe(point, scalar, transform, prev) {
839
- const W = getW(point);
959
+ // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
960
+ // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
961
+ // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
962
+ validateMulInput(point, scalar) {
963
+ this.assertPoint(point);
964
+ if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
965
+ throw new Error("invalid scalar");
966
+ }
967
+ // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
968
+ // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
969
+ // multiply. `n` must be < 2^bits.
970
+ runCT(point, n, bits, transform) {
971
+ const W = getWindowSize(point);
840
972
  if (W === 1)
841
- return this._unsafeLadder(point, scalar, prev);
842
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
973
+ return this.fixedWindowCT(point, n, bits);
974
+ return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
975
+ }
976
+ mulCT(point, scalar, transform) {
977
+ this.validateMulInput(point, scalar);
978
+ return this.runCT(point, scalar, this.bits, transform);
979
+ }
980
+ mulCTBlinded(point, scalar, transform) {
981
+ this.validateMulInput(point, scalar);
982
+ if (this.randomBytes === void 0)
983
+ throw new Error("randomBytes is required for scalar blinding");
984
+ const bits = this.Point.Fn.BITS + BLIND_BITS;
985
+ const blind = this.randomBytes(BLIND_BYTES);
986
+ if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
987
+ throw new Error("randomBytes returned invalid byte array");
988
+ blind[0] = blind[0] & 63 | 128;
989
+ const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
990
+ return this.runCT(point, n, bits, transform);
843
991
  }
844
- // We calculate precomputes for elliptic curve point multiplication
845
- // using windowed method. This specifies window size and
846
- // stores precomputed values. Usually only base point would be precomputed.
847
- createCache(P, W) {
992
+ /**
993
+ * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
994
+ * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
995
+ * far cheaper to build for a single use. The point-operation sequence is independent of `n`:
996
+ * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
997
+ * every table entry, and one addition (adds the identity when the window digit is 0 — never
998
+ * skipped).
999
+ *
1000
+ * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
1001
+ * add), which holds for the Weierstrass/Edwards point types used here. The table is left in
1002
+ * projective form (no normalizeZ): normalizing this small a table costs more than the
1003
+ * mixed-add savings it would buy for a single multiply.
1004
+ * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
1005
+ * (this path needs no fake accumulator — its op-count is already scalar-independent).
1006
+ */
1007
+ fixedWindowCT(point, n, bits) {
1008
+ const W = FW_WINDOW;
1009
+ const size = 1 << W;
1010
+ const mask = bitMask(W);
1011
+ const table = new Array(size);
1012
+ table[0] = this.ZERO;
1013
+ for (let i = 1; i < size; i++)
1014
+ table[i] = table[i - 1].add(point);
1015
+ const windows = Math.ceil(bits / W);
1016
+ let acc = this.ZERO;
1017
+ for (let window = windows - 1; window >= 0; window--) {
1018
+ if (window !== windows - 1)
1019
+ for (let d = 0; d < W; d++)
1020
+ acc = acc.double();
1021
+ const digit = Number(n >> BigInt(window * W) & mask);
1022
+ let sel = table[0];
1023
+ for (let i = 1; i < size; i++)
1024
+ sel = i === digit ? table[i] : sel;
1025
+ acc = acc.add(sel);
1026
+ }
1027
+ return { p: acc, f: acc };
1028
+ }
1029
+ shouldBlind(point, cofactor) {
1030
+ if (this.randomBytes === void 0)
1031
+ return false;
1032
+ if (cofactor === _1n3)
1033
+ return true;
1034
+ if (point !== this.BASE)
1035
+ return false;
1036
+ if (this.baseCanBeBlinded === void 0)
1037
+ this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
1038
+ return this.baseCanBeBlinded;
1039
+ }
1040
+ mulSecret(point, scalar, cofactor, transform) {
1041
+ return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
1042
+ }
1043
+ mulUnsafe(point, scalar, transform) {
1044
+ this.assertPoint(point);
1045
+ if (!isPosBig(scalar))
1046
+ throw new Error("invalid scalar");
1047
+ const W = getWindowSize(point);
1048
+ if (W === 1 || scalar >= this.Point.Fn.ORDER)
1049
+ return mulAddUnsafe(this.Point, [point], [scalar], true);
1050
+ const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
1051
+ return this.wnafCachedCT(precomputes, scalar).p;
1052
+ }
1053
+ // Remembers the window size used for precomputed wNAF multiplication of the given point
1054
+ // and drops any previously built tables. Usually only the base point is precomputed.
1055
+ // W=1 resets the point to the un-precomputed (table-less) paths.
1056
+ // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
1057
+ setWindowSize(point, W) {
1058
+ this.assertPoint(point);
848
1059
  validateW(W, this.bits);
849
- pointWindowSizes.set(P, W);
850
- pointPrecomputes.delete(P);
1060
+ const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
1061
+ validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
1062
+ pointWindowSizes.set(point, W);
1063
+ this.wnafPrecomputes.delete(point);
851
1064
  }
852
- hasCache(elm) {
853
- return getW(elm) !== 1;
1065
+ // True when a window size is set: tables themselves are built lazily on first multiply.
1066
+ hasWindowSize(point) {
1067
+ return getWindowSize(point) !== 1;
854
1068
  }
855
1069
  };
1070
+ function mulAddUnsafe(c, points, scalars, allowOversized = false) {
1071
+ validatePointCons(c);
1072
+ validateMSMPoints(points, c);
1073
+ abool2(allowOversized, "allowOversized");
1074
+ validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
1075
+ if (points.length !== scalars.length)
1076
+ throw new Error("arrays of points and scalars must have equal length");
1077
+ const tables = points.map((p) => oddMultiples(p, 4));
1078
+ const digits = scalars.map((n) => wnafDigits(n, 4));
1079
+ return wnafWalk(c.ZERO, tables, digits);
1080
+ }
856
1081
  function createField(order, field, isLE2) {
857
1082
  if (field) {
858
1083
  if (field.ORDER !== order)
@@ -864,25 +1089,28 @@ function createField(order, field, isLE2) {
864
1089
  }
865
1090
  }
866
1091
  function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1092
+ if (type !== "weierstrass" && type !== "edwards")
1093
+ throw new Error('expected curve type "weierstrass" or "edwards"');
867
1094
  if (FpFnLE === void 0)
868
1095
  FpFnLE = type === "edwards";
869
1096
  if (!CURVE || typeof CURVE !== "object")
870
1097
  throw new Error(`expected valid ${type} CURVE object`);
1098
+ validateObject(curveOpts);
871
1099
  for (const p of ["p", "n", "h"]) {
872
1100
  const val = CURVE[p];
873
- if (!(typeof val === "bigint" && val > _0n3))
1101
+ if (!(isPosBig(val) && val !== _0n3))
874
1102
  throw new Error(`CURVE.${p} must be positive bigint`);
875
1103
  }
876
- const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
877
- const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1104
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1105
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
878
1106
  const _b = type === "weierstrass" ? "b" : "d";
879
1107
  const params = ["Gx", "Gy", "a", _b];
880
1108
  for (const p of params) {
881
- if (!Fp2.isValid(CURVE[p]))
1109
+ if (!Fp.isValid(CURVE[p]))
882
1110
  throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
883
1111
  }
884
1112
  CURVE = Object.freeze(Object.assign({}, CURVE));
885
- return { CURVE, Fp: Fp2, Fn: Fn2 };
1113
+ return { CURVE, Fp, Fn };
886
1114
  }
887
1115
  function createKeygen(randomSecretKey, getPublicKey) {
888
1116
  return function keygen(seed) {
@@ -895,32 +1123,44 @@ function createKeygen(randomSecretKey, getPublicKey) {
895
1123
  var _0n4 = /* @__PURE__ */ BigInt(0);
896
1124
  var _1n4 = /* @__PURE__ */ BigInt(1);
897
1125
  var _2n2 = /* @__PURE__ */ BigInt(2);
1126
+ var _4n3 = /* @__PURE__ */ BigInt(4);
898
1127
  var _8n2 = /* @__PURE__ */ BigInt(8);
899
- function isEdValidXY(Fp2, CURVE, x, y) {
900
- const x2 = Fp2.sqr(x);
901
- const y2 = Fp2.sqr(y);
902
- const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
903
- const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
904
- return Fp2.eql(left, right);
1128
+ function isEdValidXY(Fp, CURVE, x, y) {
1129
+ const x2 = Fp.sqr(x);
1130
+ const y2 = Fp.sqr(y);
1131
+ const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
1132
+ const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
1133
+ return Fp.eql(left, right);
905
1134
  }
906
1135
  function edwards(params, extraOpts = {}) {
1136
+ validateObject(extraOpts, {}, {}, "extraOpts");
907
1137
  const opts2 = extraOpts;
908
1138
  const validated = createCurveFields("edwards", params, opts2, opts2.FpFnLE);
909
- const { Fp: Fp2, Fn: Fn2 } = validated;
1139
+ const { Fp, Fn } = validated;
910
1140
  let CURVE = validated.CURVE;
911
1141
  const { h: cofactor } = CURVE;
912
- validateObject(opts2, {}, { uvRatio: "function" });
913
- const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
914
- const modP = (n) => Fp2.create(n);
1142
+ if (FpLegendre(Fp, CURVE.a) !== 1)
1143
+ throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
1144
+ if (FpLegendre(Fp, CURVE.d) !== -1)
1145
+ throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
1146
+ validateObject(opts2, {}, { uvRatio: "function", randomBytes: "function" });
1147
+ const randomBytes4 = opts2.randomBytes === void 0 ? randomBytes2 : opts2.randomBytes;
1148
+ const MASK = _2n2 << BigInt(Fp.BYTES * 8) - _1n4;
1149
+ function isOdd(n) {
1150
+ if (!Fp.isOdd)
1151
+ throw new Error("Field does not have .isOdd()");
1152
+ return Fp.isOdd(n);
1153
+ }
915
1154
  const uvRatio2 = opts2.uvRatio === void 0 ? (u, v) => {
916
1155
  try {
917
- return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
1156
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
918
1157
  } catch (e) {
919
1158
  return { isValid: false, value: _0n4 };
920
1159
  }
921
1160
  } : opts2.uvRatio;
922
- if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1161
+ if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
923
1162
  throw new Error("bad curve params: generator point");
1163
+ const mulA = Fp.eql(CURVE.a, Fp.neg(Fp.ONE)) ? (x) => Fp.neg(x) : Fp.eql(CURVE.a, Fp.ONE) ? (x) => x : (x) => Fp.mul(CURVE.a, x);
924
1164
  function acoord(title, n, banZero = false) {
925
1165
  const min = banZero ? _1n4 : _0n4;
926
1166
  aInRange("coordinate " + title, n, min, MASK);
@@ -956,32 +1196,32 @@ function edwards(params, extraOpts = {}) {
956
1196
  const { x, y } = p || {};
957
1197
  acoord("x", x);
958
1198
  acoord("y", y);
959
- return new _Point(x, y, _1n4, modP(x * y));
1199
+ return new _Point(x, y, Fp.ONE, Fp.mul(x, y));
960
1200
  }
961
1201
  // Uses algo from RFC8032 5.1.3.
962
1202
  static fromBytes(bytes, zip215 = false) {
963
- const len = Fp2.BYTES;
1203
+ const len = Fp.BYTES;
964
1204
  const { a, d } = CURVE;
965
1205
  bytes = copyBytes(abytes2(bytes, len, "point"));
966
- abool(zip215, "zip215");
1206
+ abool2(zip215, "zip215");
967
1207
  const normed = copyBytes(bytes);
968
1208
  const lastByte = bytes[len - 1];
969
1209
  normed[len - 1] = lastByte & ~128;
970
1210
  const y = bytesToNumberLE(normed);
971
- const max = zip215 ? MASK : Fp2.ORDER;
1211
+ const max = zip215 ? MASK : Fp.ORDER;
972
1212
  aInRange("point.y", y, _0n4, max);
973
- const y2 = modP(y * y);
974
- const u = modP(y2 - _1n4);
975
- const v = modP(d * y2 - a);
1213
+ const y2 = Fp.sqr(y);
1214
+ const u = Fp.sub(y2, Fp.ONE);
1215
+ const v = Fp.sub(Fp.mulN(d, y2), a);
976
1216
  let { isValid, value: x } = uvRatio2(u, v);
977
1217
  if (!isValid)
978
1218
  throw new Error("bad point: invalid y coordinate");
979
- const isXOdd = (x & _1n4) === _1n4;
1219
+ const isXOdd = isOdd(x);
980
1220
  const isLastByteOdd = (lastByte & 128) !== 0;
981
- if (!zip215 && x === _0n4 && isLastByteOdd)
1221
+ if (!zip215 && Fp.is0(x) && isLastByteOdd)
982
1222
  throw new Error("bad point: x=0 and x_0=1");
983
1223
  if (isLastByteOdd !== isXOdd)
984
- x = modP(-x);
1224
+ x = Fp.neg(x);
985
1225
  return _Point.fromAffine({ x, y });
986
1226
  }
987
1227
  static fromHex(hex, zip215 = false) {
@@ -993,8 +1233,8 @@ function edwards(params, extraOpts = {}) {
993
1233
  get y() {
994
1234
  return this.toAffine().y;
995
1235
  }
996
- precompute(windowSize = 8, isLazy = true) {
997
- wnaf.createCache(this, windowSize);
1236
+ precompute(windowSize = 6, isLazy = true) {
1237
+ wnaf.setWindowSize(this, windowSize);
998
1238
  if (!isLazy)
999
1239
  this.multiply(_2n2);
1000
1240
  return this;
@@ -1006,18 +1246,18 @@ function edwards(params, extraOpts = {}) {
1006
1246
  if (p.is0())
1007
1247
  throw new Error("bad point: ZERO");
1008
1248
  const { X, Y, Z, T } = p;
1009
- const X2 = modP(X * X);
1010
- const Y2 = modP(Y * Y);
1011
- const Z2 = modP(Z * Z);
1012
- const Z4 = modP(Z2 * Z2);
1013
- const aX2 = modP(X2 * a);
1014
- const left = modP(Z2 * modP(aX2 + Y2));
1015
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1016
- if (left !== right)
1249
+ const X2 = Fp.sqr(X);
1250
+ const Y2 = Fp.sqr(Y);
1251
+ const Z2 = Fp.sqr(Z);
1252
+ const Z4 = Fp.sqr(Z2);
1253
+ const aX2 = Fp.mul(X2, a);
1254
+ const left = Fp.mul(Fp.add(aX2, Y2), Z2);
1255
+ const right = Fp.add(Z4, Fp.mul(d, Fp.mul(X2, Y2)));
1256
+ if (!Fp.eql(left, right))
1017
1257
  throw new Error("bad point: equation left != right (1)");
1018
- const XY = modP(X * Y);
1019
- const ZT = modP(Z * T);
1020
- if (XY !== ZT)
1258
+ const XY = Fp.mul(X, Y);
1259
+ const ZT = Fp.mul(Z, T);
1260
+ if (!Fp.eql(XY, ZT))
1021
1261
  throw new Error("bad point: equation left != right (2)");
1022
1262
  }
1023
1263
  // Compare one point to another.
@@ -1025,37 +1265,36 @@ function edwards(params, extraOpts = {}) {
1025
1265
  aedpoint(other);
1026
1266
  const { X: X1, Y: Y1, Z: Z1 } = this;
1027
1267
  const { X: X2, Y: Y2, Z: Z2 } = other;
1028
- const X1Z2 = modP(X1 * Z2);
1029
- const X2Z1 = modP(X2 * Z1);
1030
- const Y1Z2 = modP(Y1 * Z2);
1031
- const Y2Z1 = modP(Y2 * Z1);
1032
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1268
+ const X1Z2 = Fp.mul(X1, Z2);
1269
+ const X2Z1 = Fp.mul(X2, Z1);
1270
+ const Y1Z2 = Fp.mul(Y1, Z2);
1271
+ const Y2Z1 = Fp.mul(Y2, Z1);
1272
+ return Fp.eql(X1Z2, X2Z1) && Fp.eql(Y1Z2, Y2Z1);
1033
1273
  }
1034
1274
  is0() {
1035
1275
  return this.equals(_Point.ZERO);
1036
1276
  }
1037
1277
  negate() {
1038
- return new _Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1278
+ return new _Point(Fp.neg(this.X), this.Y, this.Z, Fp.neg(this.T));
1039
1279
  }
1040
1280
  // Fast algo for doubling Extended Point.
1041
1281
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1042
1282
  // Cost: 4M + 4S + 1*a + 6add + 1*2.
1043
1283
  double() {
1044
- const { a } = CURVE;
1045
1284
  const { X: X1, Y: Y1, Z: Z1 } = this;
1046
- const A = modP(X1 * X1);
1047
- const B = modP(Y1 * Y1);
1048
- const C = modP(_2n2 * modP(Z1 * Z1));
1049
- const D = modP(a * A);
1050
- const x1y1 = X1 + Y1;
1051
- const E = modP(modP(x1y1 * x1y1) - A - B);
1052
- const G = D + B;
1053
- const F2 = G - C;
1054
- const H = D - B;
1055
- const X3 = modP(E * F2);
1056
- const Y3 = modP(G * H);
1057
- const T3 = modP(E * H);
1058
- const Z3 = modP(F2 * G);
1285
+ const A = Fp.sqr(X1);
1286
+ const B2 = Fp.sqr(Y1);
1287
+ const C = Fp.mul(Fp.sqr(Z1), _2n2);
1288
+ const D = mulA(A);
1289
+ const x1y1 = Fp.addN(X1, Y1);
1290
+ const E = Fp.sub(Fp.subN(Fp.sqr(x1y1), A), B2);
1291
+ const G = Fp.addN(D, B2);
1292
+ const F2 = Fp.subN(G, C);
1293
+ const H = Fp.subN(D, B2);
1294
+ const X3 = Fp.mul(E, F2);
1295
+ const Y3 = Fp.mul(G, H);
1296
+ const T3 = Fp.mul(E, H);
1297
+ const Z3 = Fp.mul(F2, G);
1059
1298
  return new _Point(X3, Y3, Z3, T3);
1060
1299
  }
1061
1300
  // Fast algo for adding 2 Extended Points.
@@ -1063,21 +1302,21 @@ function edwards(params, extraOpts = {}) {
1063
1302
  // Cost: 9M + 1*a + 1*d + 7add.
1064
1303
  add(other) {
1065
1304
  aedpoint(other);
1066
- const { a, d } = CURVE;
1305
+ const { d } = CURVE;
1067
1306
  const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1068
1307
  const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1069
- const A = modP(X1 * X2);
1070
- const B = modP(Y1 * Y2);
1071
- const C = modP(T1 * d * T2);
1072
- const D = modP(Z1 * Z2);
1073
- const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1074
- const F2 = D - C;
1075
- const G = D + C;
1076
- const H = modP(B - a * A);
1077
- const X3 = modP(E * F2);
1078
- const Y3 = modP(G * H);
1079
- const T3 = modP(E * H);
1080
- const Z3 = modP(F2 * G);
1308
+ const A = Fp.mul(X1, X2);
1309
+ const B2 = Fp.mul(Y1, Y2);
1310
+ const C = Fp.mul(Fp.mulN(T1, d), T2);
1311
+ const D = Fp.mul(Z1, Z2);
1312
+ const E = Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1, Y1), Fp.addN(X2, Y2)), A), B2);
1313
+ const F2 = Fp.subN(D, C);
1314
+ const G = Fp.addN(D, C);
1315
+ const H = Fp.sub(B2, mulA(A));
1316
+ const X3 = Fp.mul(E, F2);
1317
+ const Y3 = Fp.mul(G, H);
1318
+ const T3 = Fp.mul(E, H);
1319
+ const Z3 = Fp.mul(F2, G);
1081
1320
  return new _Point(X3, Y3, Z3, T3);
1082
1321
  }
1083
1322
  subtract(other) {
@@ -1086,10 +1325,10 @@ function edwards(params, extraOpts = {}) {
1086
1325
  }
1087
1326
  // Constant-time multiplication.
1088
1327
  multiply(scalar) {
1089
- if (!Fn2.isValidNot0(scalar))
1328
+ if (!Fn.isValidNot0(scalar))
1090
1329
  throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1091
- const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(_Point, p2));
1092
- return normalizeZ(_Point, [p, f])[0];
1330
+ const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
1331
+ return normalize([p, f])[0];
1093
1332
  }
1094
1333
  // Non-constant-time multiplication. Uses double-and-add algorithm.
1095
1334
  // It's faster, but should only be used when you don't care about
@@ -1097,13 +1336,13 @@ function edwards(params, extraOpts = {}) {
1097
1336
  // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
1098
1337
  // n and larger values are rejected instead of being reduced mod n to the identity point.
1099
1338
  multiplyUnsafe(scalar) {
1100
- if (!Fn2.isValid(scalar))
1339
+ if (!Fn.isValid(scalar))
1101
1340
  throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1102
1341
  if (scalar === _0n4)
1103
1342
  return _Point.ZERO;
1104
1343
  if (this.is0() || scalar === _1n4)
1105
1344
  return this;
1106
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(_Point, p));
1345
+ return wnaf.mulUnsafe(this, scalar, normalize);
1107
1346
  }
1108
1347
  // Checks if point is of small order.
1109
1348
  // If you add something to small order point, you will have "dirty"
@@ -1115,35 +1354,43 @@ function edwards(params, extraOpts = {}) {
1115
1354
  // Multiplies point by curve order and checks if the result is 0.
1116
1355
  // Returns `false` is the point is dirty.
1117
1356
  isTorsionFree() {
1118
- return wnaf.unsafe(this, CURVE.n).is0();
1357
+ return wnaf.mulUnsafe(this, CURVE.n).is0();
1119
1358
  }
1120
1359
  // Converts Extended point to default (x, y) coordinates.
1121
1360
  // Can accept precomputed Z^-1 - for example, from invertBatch.
1122
1361
  toAffine(invertedZ) {
1123
1362
  const p = this;
1124
1363
  let iz = invertedZ;
1364
+ if (iz != null && typeof iz !== "bigint")
1365
+ throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
1125
1366
  const { X, Y, Z } = p;
1126
1367
  const is0 = p.is0();
1127
1368
  if (iz == null)
1128
- iz = is0 ? _8n2 : Fp2.inv(Z);
1129
- const x = modP(X * iz);
1130
- const y = modP(Y * iz);
1131
- const zz = Fp2.mul(Z, iz);
1369
+ iz = is0 ? Fp.create(_8n2) : Fp.inv(Z);
1370
+ const x = Fp.mul(X, iz);
1371
+ const y = Fp.mul(Y, iz);
1372
+ const zz = Fp.mul(Z, iz);
1132
1373
  if (is0)
1133
- return { x: _0n4, y: _1n4 };
1134
- if (zz !== _1n4)
1374
+ return { x: Fp.ZERO, y: Fp.ONE };
1375
+ if (!Fp.eql(zz, Fp.ONE))
1135
1376
  throw new Error("invZ was invalid");
1136
1377
  return { x, y };
1137
1378
  }
1138
1379
  clearCofactor() {
1139
1380
  if (cofactor === _1n4)
1140
1381
  return this;
1382
+ if (cofactor === _2n2)
1383
+ return this.double();
1384
+ if (cofactor === _4n3)
1385
+ return this.double().double();
1386
+ if (cofactor === _8n2)
1387
+ return this.double().double().double();
1141
1388
  return this.multiplyUnsafe(cofactor);
1142
1389
  }
1143
1390
  toBytes() {
1144
1391
  const { x, y } = this.toAffine();
1145
- const bytes = Fp2.toBytes(y);
1146
- bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1392
+ const bytes = Fp.toBytes(y);
1393
+ bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
1147
1394
  return bytes;
1148
1395
  }
1149
1396
  toHex() {
@@ -1153,108 +1400,36 @@ function edwards(params, extraOpts = {}) {
1153
1400
  return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1154
1401
  }
1155
1402
  };
1156
- // base / generator point
1157
- __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy)));
1158
- // zero / infinity / identity point
1159
- __publicField(_Point, "ZERO", new _Point(_0n4, _1n4, _1n4, _0n4));
1160
- // 0, 1, 1, 0
1161
- // math field
1162
- __publicField(_Point, "Fp", Fp2);
1163
- // scalar field
1164
- __publicField(_Point, "Fn", Fn2);
1403
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp.ONE, Fp.mul(CURVE.Gx, CURVE.Gy)));
1404
+ __publicField(_Point, "ZERO", new _Point(Fp.ZERO, Fp.ONE, Fp.ONE, Fp.ZERO));
1405
+ __publicField(_Point, "Fp", Fp);
1406
+ __publicField(_Point, "Fn", Fn);
1165
1407
  let Point = _Point;
1166
- const wnaf = new wNAF(Point, Fn2.BITS);
1167
- if (Fn2.BITS >= 8)
1168
- Point.BASE.precompute(8);
1408
+ const normalize = (points) => normalizeZ(Point, points);
1409
+ const wnaf = new ScalarMultiplier(Point, randomBytes4);
1410
+ if (wnaf.bits >= 6)
1411
+ Point.BASE.precompute(6);
1169
1412
  Object.freeze(Point.prototype);
1170
1413
  Object.freeze(Point);
1171
1414
  return Point;
1172
1415
  }
1173
- var PrimeEdwardsPoint = class {
1174
- /**
1175
- * Wrap one internal Edwards representative directly.
1176
- * This is not a canonical encoding boundary: alternate Edwards
1177
- * representatives may still describe the same abstract wrapper element.
1178
- */
1179
- constructor(ep) {
1180
- __publicField(this, "ep");
1181
- this.ep = ep;
1182
- }
1183
- // Static methods that must be implemented by subclasses
1184
- static fromBytes(_bytes) {
1185
- notImplemented();
1186
- }
1187
- static fromHex(_hex) {
1188
- notImplemented();
1189
- }
1190
- get x() {
1191
- return this.toAffine().x;
1192
- }
1193
- get y() {
1194
- return this.toAffine().y;
1195
- }
1196
- // Common implementations
1197
- clearCofactor() {
1198
- return this;
1199
- }
1200
- assertValidity() {
1201
- this.ep.assertValidity();
1202
- }
1203
- /**
1204
- * Return affine coordinates of the current internal Edwards representative.
1205
- * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
1206
- * Equal abstract elements may expose different `x` / `y`; use
1207
- * `toBytes()` / `fromBytes()` for canonical roundtrips.
1208
- */
1209
- toAffine(invertedZ) {
1210
- return this.ep.toAffine(invertedZ);
1211
- }
1212
- toHex() {
1213
- return bytesToHex2(this.toBytes());
1214
- }
1215
- toString() {
1216
- return this.toHex();
1217
- }
1218
- isTorsionFree() {
1219
- return true;
1220
- }
1221
- isSmallOrder() {
1222
- return false;
1223
- }
1224
- add(other) {
1225
- this.assertSame(other);
1226
- return this.init(this.ep.add(other.ep));
1227
- }
1228
- subtract(other) {
1229
- this.assertSame(other);
1230
- return this.init(this.ep.subtract(other.ep));
1231
- }
1232
- multiply(scalar) {
1233
- return this.init(this.ep.multiply(scalar));
1234
- }
1235
- multiplyUnsafe(scalar) {
1236
- return this.init(this.ep.multiplyUnsafe(scalar));
1237
- }
1238
- double() {
1239
- return this.init(this.ep.double());
1240
- }
1241
- negate() {
1242
- return this.init(this.ep.negate());
1243
- }
1244
- precompute(windowSize, isLazy) {
1245
- this.ep.precompute(windowSize, isLazy);
1246
- return this;
1247
- }
1248
- };
1249
- __publicField(PrimeEdwardsPoint, "BASE");
1250
- __publicField(PrimeEdwardsPoint, "ZERO");
1251
- __publicField(PrimeEdwardsPoint, "Fp");
1252
- __publicField(PrimeEdwardsPoint, "Fn");
1253
1416
 
1254
1417
  // ../../node_modules/@noble/curves/abstract/montgomery.js
1255
- var _0n5 = BigInt(0);
1256
- var _1n5 = BigInt(1);
1257
- var _2n3 = BigInt(2);
1418
+ var _0n5 = /* @__PURE__ */ BigInt(0);
1419
+ var _1n5 = /* @__PURE__ */ BigInt(1);
1420
+ var _2n3 = /* @__PURE__ */ BigInt(2);
1421
+ function cmask(P, swap) {
1422
+ return P + swap - (swap >> _1n5 << _1n5);
1423
+ }
1424
+ function cswap(P) {
1425
+ const offset = BigInt(6) * P;
1426
+ return (mask, x_2, x_3) => {
1427
+ const sum = x_2 + x_3;
1428
+ const d = offset + x_3 - x_2;
1429
+ const a = (d * mask + x_2) % P;
1430
+ return { x_2: a, x_3: sum - a };
1431
+ };
1432
+ }
1258
1433
  function validateOpts(curve) {
1259
1434
  validateObject(curve, {
1260
1435
  P: "bigint",
@@ -1262,23 +1437,26 @@ function validateOpts(curve) {
1262
1437
  adjustScalarBytes: "function",
1263
1438
  powPminus2: "function"
1264
1439
  }, {
1265
- randomBytes: "function"
1440
+ randomBytes: "function",
1441
+ scalarMultBase: "function"
1266
1442
  });
1267
1443
  return Object.freeze({ ...curve });
1268
1444
  }
1269
1445
  function montgomery(curveDef) {
1270
1446
  const CURVE = validateOpts(curveDef);
1271
1447
  const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
1448
+ const mulBaseHook = CURVE.scalarMultBase;
1272
1449
  const is25519 = type === "x25519";
1273
1450
  if (!is25519 && type !== "x448")
1274
1451
  throw new Error("invalid type");
1275
1452
  const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
1276
1453
  const montgomeryBits = is25519 ? 255 : 448;
1454
+ const swap = cswap(P);
1277
1455
  const fieldLen = is25519 ? 32 : 56;
1278
1456
  const Gu = is25519 ? BigInt(9) : BigInt(5);
1279
1457
  const a24 = is25519 ? BigInt(121665) : BigInt(39081);
1280
1458
  const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
1281
- const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
1459
+ const maxAdded = is25519 ? BigInt(8) * (_2n3 ** BigInt(251) - _1n5) : BigInt(4) * (_2n3 ** BigInt(445) - _1n5);
1282
1460
  const maxScalar = minScalar + maxAdded + _1n5;
1283
1461
  const modP = (n) => mod(n, P);
1284
1462
  const GuBytes = encodeU(Gu);
@@ -1294,23 +1472,34 @@ function montgomery(curveDef) {
1294
1472
  function decodeScalar(scalar) {
1295
1473
  return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
1296
1474
  }
1475
+ const lowOrderU = new Set(is25519 ? [
1476
+ _0n5,
1477
+ _1n5,
1478
+ P - _1n5,
1479
+ BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),
1480
+ BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")
1481
+ ] : [_0n5, _1n5, P - _1n5]);
1297
1482
  function scalarMult(scalar, u) {
1298
- const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
1483
+ const pointU = decodeU(u);
1484
+ if (lowOrderU.has(pointU))
1485
+ throw new Error("invalid private or public key received");
1486
+ const pu = montgomeryLadder(pointU, decodeScalar(scalar));
1299
1487
  if (pu === _0n5)
1300
1488
  throw new Error("invalid private or public key received");
1301
1489
  return encodeU(pu);
1302
1490
  }
1303
1491
  function scalarMultBase(scalar) {
1304
- return scalarMult(scalar, GuBytes);
1492
+ if (mulBaseHook === void 0)
1493
+ return scalarMult(scalar, GuBytes);
1494
+ const k = decodeScalar(scalar);
1495
+ aInRange("scalar", k, minScalar, maxScalar);
1496
+ const pu = modP(mulBaseHook(k));
1497
+ if (pu === _0n5)
1498
+ throw new Error("invalid private or public key received");
1499
+ return encodeU(pu);
1305
1500
  }
1306
1501
  const getPublicKey = scalarMultBase;
1307
1502
  const getSharedSecret = scalarMult;
1308
- function cswap(swap, x_2, x_3) {
1309
- const dummy = modP(swap * (x_2 - x_3));
1310
- x_2 = modP(x_2 - dummy);
1311
- x_3 = modP(x_3 + dummy);
1312
- return { x_2, x_3 };
1313
- }
1314
1503
  function montgomeryLadder(u, scalar) {
1315
1504
  aInRange("u", u, _0n5, P);
1316
1505
  aInRange("scalar", scalar, minScalar, maxScalar);
@@ -1320,22 +1509,20 @@ function montgomery(curveDef) {
1320
1509
  let z_2 = _0n5;
1321
1510
  let x_3 = u;
1322
1511
  let z_3 = _1n5;
1323
- let swap = _0n5;
1512
+ const kx = k ^ k >> _1n5;
1324
1513
  for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
1325
- const k_t = k >> t & _1n5;
1326
- swap ^= k_t;
1327
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1328
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1329
- swap = k_t;
1514
+ const mask2 = cmask(P, kx >> t);
1515
+ ({ x_2, x_3 } = swap(mask2, x_2, x_3));
1516
+ ({ x_2: z_2, x_3: z_3 } = swap(mask2, z_2, z_3));
1330
1517
  const A = x_2 + z_2;
1331
1518
  const AA = modP(A * A);
1332
- const B = x_2 - z_2;
1333
- const BB = modP(B * B);
1519
+ const B2 = x_2 - z_2;
1520
+ const BB = modP(B2 * B2);
1334
1521
  const E = AA - BB;
1335
1522
  const C = x_3 + z_3;
1336
1523
  const D = x_3 - z_3;
1337
1524
  const DA = modP(D * A);
1338
- const CB = modP(C * B);
1525
+ const CB = modP(C * B2);
1339
1526
  const dacb = DA + CB;
1340
1527
  const da_cb = DA - CB;
1341
1528
  x_3 = modP(dacb * dacb);
@@ -1343,8 +1530,9 @@ function montgomery(curveDef) {
1343
1530
  x_2 = modP(AA * BB);
1344
1531
  z_2 = modP(E * (AA + modP(a24 * E)));
1345
1532
  }
1346
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1347
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1533
+ const mask = cmask(P, k);
1534
+ ({ x_2, x_3 } = swap(mask, x_2, x_3));
1535
+ ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));
1348
1536
  const z2 = powPminus2(z_2);
1349
1537
  return modP(x_2 * z2);
1350
1538
  }
@@ -1373,124 +1561,8 @@ function montgomery(curveDef) {
1373
1561
  });
1374
1562
  }
1375
1563
 
1376
- // ../../node_modules/@noble/hashes/_md.js
1377
- var HashMD = class {
1378
- constructor(blockLen, outputLen, padOffset, isLE2) {
1379
- __publicField(this, "blockLen");
1380
- __publicField(this, "outputLen");
1381
- __publicField(this, "canXOF", false);
1382
- __publicField(this, "padOffset");
1383
- __publicField(this, "isLE");
1384
- // For partial updates less than block size
1385
- __publicField(this, "buffer");
1386
- __publicField(this, "view");
1387
- __publicField(this, "finished", false);
1388
- __publicField(this, "length", 0);
1389
- __publicField(this, "pos", 0);
1390
- __publicField(this, "destroyed", false);
1391
- this.blockLen = blockLen;
1392
- this.outputLen = outputLen;
1393
- this.padOffset = padOffset;
1394
- this.isLE = isLE2;
1395
- this.buffer = new Uint8Array(blockLen);
1396
- this.view = createView(this.buffer);
1397
- }
1398
- update(data) {
1399
- aexists(this);
1400
- abytes(data);
1401
- const { view, buffer, blockLen } = this;
1402
- const len = data.length;
1403
- for (let pos = 0; pos < len; ) {
1404
- const take = Math.min(blockLen - this.pos, len - pos);
1405
- if (take === blockLen) {
1406
- const dataView = createView(data);
1407
- for (; blockLen <= len - pos; pos += blockLen)
1408
- this.process(dataView, pos);
1409
- continue;
1410
- }
1411
- buffer.set(data.subarray(pos, pos + take), this.pos);
1412
- this.pos += take;
1413
- pos += take;
1414
- if (this.pos === blockLen) {
1415
- this.process(view, 0);
1416
- this.pos = 0;
1417
- }
1418
- }
1419
- this.length += data.length;
1420
- this.roundClean();
1421
- return this;
1422
- }
1423
- digestInto(out) {
1424
- aexists(this);
1425
- aoutput(out, this);
1426
- this.finished = true;
1427
- const { buffer, view, blockLen, isLE: isLE2 } = this;
1428
- let { pos } = this;
1429
- buffer[pos++] = 128;
1430
- clean(this.buffer.subarray(pos));
1431
- if (this.padOffset > blockLen - pos) {
1432
- this.process(view, 0);
1433
- pos = 0;
1434
- }
1435
- for (let i = pos; i < blockLen; i++)
1436
- buffer[i] = 0;
1437
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
1438
- this.process(view, 0);
1439
- const oview = createView(out);
1440
- const len = this.outputLen;
1441
- if (len % 4)
1442
- throw new Error("_sha2: outputLen must be aligned to 32bit");
1443
- const outLen = len / 4;
1444
- const state = this.get();
1445
- if (outLen > state.length)
1446
- throw new Error("_sha2: outputLen bigger than state");
1447
- for (let i = 0; i < outLen; i++)
1448
- oview.setUint32(4 * i, state[i], isLE2);
1449
- }
1450
- digest() {
1451
- const { buffer, outputLen } = this;
1452
- this.digestInto(buffer);
1453
- const res = buffer.slice(0, outputLen);
1454
- this.destroy();
1455
- return res;
1456
- }
1457
- _cloneInto(to) {
1458
- to ||= new this.constructor();
1459
- to.set(...this.get());
1460
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
1461
- to.destroyed = destroyed;
1462
- to.finished = finished;
1463
- to.length = length;
1464
- to.pos = pos;
1465
- if (length % blockLen)
1466
- to.buffer.set(buffer);
1467
- return to;
1468
- }
1469
- clone() {
1470
- return this._cloneInto();
1471
- }
1472
- };
1473
- var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1474
- 1779033703,
1475
- 4089235720,
1476
- 3144134277,
1477
- 2227873595,
1478
- 1013904242,
1479
- 4271175723,
1480
- 2773480762,
1481
- 1595750129,
1482
- 1359893119,
1483
- 2917565137,
1484
- 2600822924,
1485
- 725511199,
1486
- 528734635,
1487
- 4215389547,
1488
- 1541459225,
1489
- 327033209
1490
- ]);
1491
-
1492
1564
  // ../../node_modules/@noble/hashes/_u64.js
1493
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1565
+ var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
1494
1566
  var _32n = /* @__PURE__ */ BigInt(32);
1495
1567
  function fromBig(n, le = false) {
1496
1568
  if (le)
@@ -1507,248 +1579,23 @@ function split(lst, le = false) {
1507
1579
  }
1508
1580
  return [Ah, Al];
1509
1581
  }
1510
- var shrSH = (h, _l, s) => h >>> s;
1511
- var shrSL = (h, l, s) => h << 32 - s | l >>> s;
1512
- var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
1513
- var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
1514
- var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
1515
- var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
1516
- var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
1517
- var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
1518
- var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
1519
- var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
1520
- function add(Ah, Al, Bh, Bl) {
1521
- const l = (Al >>> 0) + (Bl >>> 0);
1522
- return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
1523
- }
1524
- var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1525
- var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1526
- var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1527
- var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1528
- var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1529
- var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1530
-
1531
- // ../../node_modules/@noble/hashes/sha2.js
1532
- var K512 = /* @__PURE__ */ (() => split([
1533
- "0x428a2f98d728ae22",
1534
- "0x7137449123ef65cd",
1535
- "0xb5c0fbcfec4d3b2f",
1536
- "0xe9b5dba58189dbbc",
1537
- "0x3956c25bf348b538",
1538
- "0x59f111f1b605d019",
1539
- "0x923f82a4af194f9b",
1540
- "0xab1c5ed5da6d8118",
1541
- "0xd807aa98a3030242",
1542
- "0x12835b0145706fbe",
1543
- "0x243185be4ee4b28c",
1544
- "0x550c7dc3d5ffb4e2",
1545
- "0x72be5d74f27b896f",
1546
- "0x80deb1fe3b1696b1",
1547
- "0x9bdc06a725c71235",
1548
- "0xc19bf174cf692694",
1549
- "0xe49b69c19ef14ad2",
1550
- "0xefbe4786384f25e3",
1551
- "0x0fc19dc68b8cd5b5",
1552
- "0x240ca1cc77ac9c65",
1553
- "0x2de92c6f592b0275",
1554
- "0x4a7484aa6ea6e483",
1555
- "0x5cb0a9dcbd41fbd4",
1556
- "0x76f988da831153b5",
1557
- "0x983e5152ee66dfab",
1558
- "0xa831c66d2db43210",
1559
- "0xb00327c898fb213f",
1560
- "0xbf597fc7beef0ee4",
1561
- "0xc6e00bf33da88fc2",
1562
- "0xd5a79147930aa725",
1563
- "0x06ca6351e003826f",
1564
- "0x142929670a0e6e70",
1565
- "0x27b70a8546d22ffc",
1566
- "0x2e1b21385c26c926",
1567
- "0x4d2c6dfc5ac42aed",
1568
- "0x53380d139d95b3df",
1569
- "0x650a73548baf63de",
1570
- "0x766a0abb3c77b2a8",
1571
- "0x81c2c92e47edaee6",
1572
- "0x92722c851482353b",
1573
- "0xa2bfe8a14cf10364",
1574
- "0xa81a664bbc423001",
1575
- "0xc24b8b70d0f89791",
1576
- "0xc76c51a30654be30",
1577
- "0xd192e819d6ef5218",
1578
- "0xd69906245565a910",
1579
- "0xf40e35855771202a",
1580
- "0x106aa07032bbd1b8",
1581
- "0x19a4c116b8d2d0c8",
1582
- "0x1e376c085141ab53",
1583
- "0x2748774cdf8eeb99",
1584
- "0x34b0bcb5e19b48a8",
1585
- "0x391c0cb3c5c95a63",
1586
- "0x4ed8aa4ae3418acb",
1587
- "0x5b9cca4f7763e373",
1588
- "0x682e6ff3d6b2b8a3",
1589
- "0x748f82ee5defb2fc",
1590
- "0x78a5636f43172f60",
1591
- "0x84c87814a1f0ab72",
1592
- "0x8cc702081a6439ec",
1593
- "0x90befffa23631e28",
1594
- "0xa4506cebde82bde9",
1595
- "0xbef9a3f7b2c67915",
1596
- "0xc67178f2e372532b",
1597
- "0xca273eceea26619c",
1598
- "0xd186b8c721c0c207",
1599
- "0xeada7dd6cde0eb1e",
1600
- "0xf57d4f7fee6ed178",
1601
- "0x06f067aa72176fba",
1602
- "0x0a637dc5a2c898a6",
1603
- "0x113f9804bef90dae",
1604
- "0x1b710b35131c471b",
1605
- "0x28db77f523047d84",
1606
- "0x32caab7b40c72493",
1607
- "0x3c9ebe0a15c9bebc",
1608
- "0x431d67c49c100d4c",
1609
- "0x4cc5d4becb3e42b6",
1610
- "0x597f299cfc657e2a",
1611
- "0x5fcb6fab3ad6faec",
1612
- "0x6c44198c4a475817"
1613
- ].map((n) => BigInt(n))))();
1614
- var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1615
- var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1616
- var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1617
- var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1618
- var SHA2_64B = class extends HashMD {
1619
- constructor(outputLen) {
1620
- super(128, outputLen, 16, false);
1621
- }
1622
- // prettier-ignore
1623
- get() {
1624
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1625
- return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1626
- }
1627
- // prettier-ignore
1628
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1629
- this.Ah = Ah | 0;
1630
- this.Al = Al | 0;
1631
- this.Bh = Bh | 0;
1632
- this.Bl = Bl | 0;
1633
- this.Ch = Ch | 0;
1634
- this.Cl = Cl | 0;
1635
- this.Dh = Dh | 0;
1636
- this.Dl = Dl | 0;
1637
- this.Eh = Eh | 0;
1638
- this.El = El | 0;
1639
- this.Fh = Fh | 0;
1640
- this.Fl = Fl | 0;
1641
- this.Gh = Gh | 0;
1642
- this.Gl = Gl | 0;
1643
- this.Hh = Hh | 0;
1644
- this.Hl = Hl | 0;
1645
- }
1646
- process(view, offset) {
1647
- for (let i = 0; i < 16; i++, offset += 4) {
1648
- SHA512_W_H[i] = view.getUint32(offset);
1649
- SHA512_W_L[i] = view.getUint32(offset += 4);
1650
- }
1651
- for (let i = 16; i < 80; i++) {
1652
- const W15h = SHA512_W_H[i - 15] | 0;
1653
- const W15l = SHA512_W_L[i - 15] | 0;
1654
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1655
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1656
- const W2h = SHA512_W_H[i - 2] | 0;
1657
- const W2l = SHA512_W_L[i - 2] | 0;
1658
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1659
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1660
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1661
- const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1662
- SHA512_W_H[i] = SUMh | 0;
1663
- SHA512_W_L[i] = SUMl | 0;
1664
- }
1665
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1666
- for (let i = 0; i < 80; i++) {
1667
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1668
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1669
- const CHIh = Eh & Fh ^ ~Eh & Gh;
1670
- const CHIl = El & Fl ^ ~El & Gl;
1671
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1672
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1673
- const T1l = T1ll | 0;
1674
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1675
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1676
- const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1677
- const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1678
- Hh = Gh | 0;
1679
- Hl = Gl | 0;
1680
- Gh = Fh | 0;
1681
- Gl = Fl | 0;
1682
- Fh = Eh | 0;
1683
- Fl = El | 0;
1684
- ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1685
- Dh = Ch | 0;
1686
- Dl = Cl | 0;
1687
- Ch = Bh | 0;
1688
- Cl = Bl | 0;
1689
- Bh = Ah | 0;
1690
- Bl = Al | 0;
1691
- const All = add3L(T1l, sigma0l, MAJl);
1692
- Ah = add3H(All, T1h, sigma0h, MAJh);
1693
- Al = All | 0;
1694
- }
1695
- ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1696
- ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1697
- ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1698
- ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1699
- ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1700
- ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1701
- ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1702
- ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1703
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1704
- }
1705
- roundClean() {
1706
- clean(SHA512_W_H, SHA512_W_L);
1707
- }
1708
- destroy() {
1709
- this.destroyed = true;
1710
- clean(this.buffer);
1711
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1712
- }
1713
- };
1714
- var _SHA512 = class extends SHA2_64B {
1715
- constructor() {
1716
- super(64);
1717
- __publicField(this, "Ah", SHA512_IV[0] | 0);
1718
- __publicField(this, "Al", SHA512_IV[1] | 0);
1719
- __publicField(this, "Bh", SHA512_IV[2] | 0);
1720
- __publicField(this, "Bl", SHA512_IV[3] | 0);
1721
- __publicField(this, "Ch", SHA512_IV[4] | 0);
1722
- __publicField(this, "Cl", SHA512_IV[5] | 0);
1723
- __publicField(this, "Dh", SHA512_IV[6] | 0);
1724
- __publicField(this, "Dl", SHA512_IV[7] | 0);
1725
- __publicField(this, "Eh", SHA512_IV[8] | 0);
1726
- __publicField(this, "El", SHA512_IV[9] | 0);
1727
- __publicField(this, "Fh", SHA512_IV[10] | 0);
1728
- __publicField(this, "Fl", SHA512_IV[11] | 0);
1729
- __publicField(this, "Gh", SHA512_IV[12] | 0);
1730
- __publicField(this, "Gl", SHA512_IV[13] | 0);
1731
- __publicField(this, "Hh", SHA512_IV[14] | 0);
1732
- __publicField(this, "Hl", SHA512_IV[15] | 0);
1733
- }
1734
- };
1735
- var sha512 = /* @__PURE__ */ createHasher(
1736
- () => new _SHA512(),
1737
- /* @__PURE__ */ oidNist(3)
1738
- );
1739
1582
 
1740
1583
  // ../../node_modules/@noble/curves/abstract/fft.js
1741
- function checkU32(n) {
1584
+ function checkU32(n, title = "n") {
1585
+ if (typeof n !== "number")
1586
+ throw new TypeError(`wrong u32 integer "${title}": expected number, got type=${typeof n}`);
1742
1587
  if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
1743
- throw new Error("wrong u32 integer:" + n);
1588
+ throw new RangeError(`wrong u32 integer "${title}": expected 0..4294967295, got ${n}`);
1744
1589
  return n;
1745
1590
  }
1746
1591
  function isPowerOfTwo(x) {
1747
- checkU32(x);
1592
+ checkU32(x, "x");
1748
1593
  return (x & x - 1) === 0 && x !== 0;
1749
1594
  }
1750
1595
  function reverseBits(n, bits) {
1751
1596
  checkU32(n);
1597
+ if (typeof bits !== "number")
1598
+ throw new TypeError('"bits" expected number, got type=' + typeof bits);
1752
1599
  if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
1753
1600
  throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
1754
1601
  let reversed = 0;
@@ -1761,6 +1608,8 @@ function log2(n) {
1761
1608
  return 31 - Math.clz32(n);
1762
1609
  }
1763
1610
  function bitReversalInplace(values) {
1611
+ if (!values || typeof values !== "object" || typeof values.length !== "number")
1612
+ throw new TypeError('"values" expected array-like, got type=' + typeof values);
1764
1613
  const n = values.length;
1765
1614
  if (!isPowerOfTwo(n))
1766
1615
  throw new Error("expected positive power-of-two length, got " + n);
@@ -1776,14 +1625,19 @@ function bitReversalInplace(values) {
1776
1625
  return values;
1777
1626
  }
1778
1627
  var FFTCore = (F2, coreOpts) => {
1628
+ validateObject(coreOpts, { N: "number", roots: "object", dit: "boolean" }, { invertButterflies: "boolean", skipStages: "number", brp: "boolean" }, "coreOpts");
1779
1629
  const { N: N2, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
1630
+ checkU32(N2, "coreOpts.N");
1780
1631
  const bits = log2(N2);
1781
1632
  if (!isPowerOfTwo(N2))
1782
1633
  throw new Error("FFT: Polynomial size should be power of two");
1634
+ checkU32(skipStages, "coreOpts.skipStages");
1635
+ const maxSkipStages = bits === 0 ? 0 : bits - 1;
1636
+ if (skipStages > maxSkipStages)
1637
+ throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${maxSkipStages}`);
1783
1638
  if (roots.length !== N2)
1784
1639
  throw new Error(`FFT: wrong roots length: expected ${N2}, got ${roots.length}`);
1785
1640
  const isDit = dit !== invertButterflies;
1786
- isDit;
1787
1641
  return (values) => {
1788
1642
  if (values.length !== N2)
1789
1643
  throw new Error("FFT: wrong Polynomial length");
@@ -1822,61 +1676,6 @@ var FFTCore = (F2, coreOpts) => {
1822
1676
  };
1823
1677
  };
1824
1678
 
1825
- // ../../node_modules/@noble/curves/abstract/hash-to-curve.js
1826
- function i2osp(value, length) {
1827
- asafenumber(value);
1828
- asafenumber(length);
1829
- if (length < 0 || length > 4)
1830
- throw new Error("invalid I2OSP length: " + length);
1831
- if (value < 0 || value > 2 ** (8 * length) - 1)
1832
- throw new Error("invalid I2OSP input: " + value);
1833
- const res = Array.from({ length }).fill(0);
1834
- for (let i = length - 1; i >= 0; i--) {
1835
- res[i] = value & 255;
1836
- value >>>= 8;
1837
- }
1838
- return new Uint8Array(res);
1839
- }
1840
- function strxor(a, b) {
1841
- const arr = new Uint8Array(a.length);
1842
- for (let i = 0; i < a.length; i++) {
1843
- arr[i] = a[i] ^ b[i];
1844
- }
1845
- return arr;
1846
- }
1847
- function normDST(DST) {
1848
- if (!isBytes2(DST) && typeof DST !== "string")
1849
- throw new Error("DST must be Uint8Array or ascii string");
1850
- const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
1851
- if (dst.length === 0)
1852
- throw new Error("DST must be non-empty");
1853
- return dst;
1854
- }
1855
- function expand_message_xmd(msg, DST, lenInBytes, H) {
1856
- abytes2(msg);
1857
- asafenumber(lenInBytes);
1858
- DST = normDST(DST);
1859
- if (DST.length > 255)
1860
- DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
1861
- const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1862
- const ell = Math.ceil(lenInBytes / b_in_bytes);
1863
- if (lenInBytes > 65535 || ell > 255)
1864
- throw new Error("expand_message_xmd: invalid lenInBytes");
1865
- const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
1866
- const Z_pad = new Uint8Array(r_in_bytes);
1867
- const l_i_b_str = i2osp(lenInBytes, 2);
1868
- const b = new Array(ell);
1869
- const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1870
- b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
1871
- for (let i = 1; i < ell; i++) {
1872
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1873
- b[i] = H(concatBytes2(...args));
1874
- }
1875
- const pseudo_random_bytes = concatBytes2(...b);
1876
- return pseudo_random_bytes.slice(0, lenInBytes);
1877
- }
1878
- var _DST_scalar = "HashToScalar-";
1879
-
1880
1679
  // ../../node_modules/@noble/curves/ed25519.js
1881
1680
  var _0n6 = /* @__PURE__ */ BigInt(0);
1882
1681
  var _1n6 = /* @__PURE__ */ BigInt(1);
@@ -1922,8 +1721,8 @@ function uvRatio(u, v) {
1922
1721
  const P = ed25519_CURVE_p;
1923
1722
  const v3 = mod(v * v * v, P);
1924
1723
  const v7 = mod(v3 * v3 * v, P);
1925
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1926
- let x = mod(u * v3 * pow, P);
1724
+ const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1725
+ let x = mod(u * v3 * pow3, P);
1927
1726
  const vx2 = mod(v * x * x, P);
1928
1727
  const root1 = x;
1929
1728
  const root2 = mod(x * ED25519_SQRT_M1, P);
@@ -1939,213 +1738,29 @@ function uvRatio(u, v) {
1939
1738
  return { isValid: useRoot1 || useRoot2, value: x };
1940
1739
  }
1941
1740
  var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
1942
- var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
1943
- var Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
1944
1741
  var x25519 = /* @__PURE__ */ (() => {
1945
1742
  const P = ed25519_CURVE_p;
1743
+ const powPminus2 = (x) => {
1744
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
1745
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
1746
+ };
1946
1747
  return montgomery({
1947
1748
  P,
1948
1749
  type: "x25519",
1949
- powPminus2: (x) => {
1950
- const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
1951
- return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
1952
- },
1953
- adjustScalarBytes
1750
+ powPminus2,
1751
+ adjustScalarBytes,
1752
+ // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached
1753
+ // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.
1754
+ // Same construction as libsodium's crypto_scalarmult_curve25519_base.
1755
+ scalarMultBase: (k) => {
1756
+ const kn = mod(k, ed25519_Point.Fn.ORDER);
1757
+ if (kn === _0n6)
1758
+ return _0n6;
1759
+ const p = ed25519_Point.BASE.multiply(kn);
1760
+ return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);
1761
+ }
1954
1762
  });
1955
1763
  })();
1956
- var SQRT_M1 = ED25519_SQRT_M1;
1957
- var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
1958
- var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
1959
- var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
1960
- var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
1961
- var invertSqrt = (number) => uvRatio(_1n6, number);
1962
- var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
1963
- var bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
1964
- function calcElligatorRistrettoMap(r0) {
1965
- const { d } = ed25519_CURVE;
1966
- const P = ed25519_CURVE_p;
1967
- const mod2 = (n) => Fp.create(n);
1968
- const r = mod2(SQRT_M1 * r0 * r0);
1969
- const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
1970
- let c = BigInt(-1);
1971
- const D = mod2((c - d * r) * mod2(r + d));
1972
- let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
1973
- let s_ = mod2(s * r0);
1974
- if (!isNegativeLE(s_, P))
1975
- s_ = mod2(-s_);
1976
- if (!Ns_D_is_sq)
1977
- s = s_;
1978
- if (!Ns_D_is_sq)
1979
- c = r;
1980
- const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
1981
- const s2 = s * s;
1982
- const W0 = mod2((s + s) * D);
1983
- const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
1984
- const W2 = mod2(_1n6 - s2);
1985
- const W3 = mod2(_1n6 + s2);
1986
- return new ed25519_Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
1987
- }
1988
- var __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
1989
- constructor(ep) {
1990
- super(ep);
1991
- }
1992
- /**
1993
- * Create one Ristretto255 point from affine Edwards coordinates.
1994
- * This wraps the internal Edwards representative directly and is not a
1995
- * canonical ristretto255 decoding path.
1996
- * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
1997
- */
1998
- static fromAffine(ap) {
1999
- return new __RistrettoPoint(ed25519_Point.fromAffine(ap));
2000
- }
2001
- assertSame(other) {
2002
- if (!(other instanceof __RistrettoPoint))
2003
- throw new Error("RistrettoPoint expected");
2004
- }
2005
- init(ep) {
2006
- return new __RistrettoPoint(ep);
2007
- }
2008
- static fromBytes(bytes) {
2009
- abytes(bytes, 32);
2010
- const { a, d } = ed25519_CURVE;
2011
- const P = ed25519_CURVE_p;
2012
- const mod2 = (n) => Fp.create(n);
2013
- const s = bytes255ToNumberLE(bytes);
2014
- if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2015
- throw new Error("invalid ristretto255 encoding 1");
2016
- const s2 = mod2(s * s);
2017
- const u1 = mod2(_1n6 + a * s2);
2018
- const u2 = mod2(_1n6 - a * s2);
2019
- const u1_2 = mod2(u1 * u1);
2020
- const u2_2 = mod2(u2 * u2);
2021
- const v = mod2(a * d * u1_2 - u2_2);
2022
- const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2023
- const Dx = mod2(I * u2);
2024
- const Dy = mod2(I * Dx * v);
2025
- let x = mod2((s + s) * Dx);
2026
- if (isNegativeLE(x, P))
2027
- x = mod2(-x);
2028
- const y = mod2(u1 * Dy);
2029
- const t = mod2(x * y);
2030
- if (!isValid || isNegativeLE(t, P) || y === _0n6)
2031
- throw new Error("invalid ristretto255 encoding 2");
2032
- return new __RistrettoPoint(new ed25519_Point(x, y, _1n6, t));
2033
- }
2034
- /**
2035
- * Converts ristretto-encoded string to ristretto point.
2036
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2037
- * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2038
- */
2039
- static fromHex(hex) {
2040
- return __RistrettoPoint.fromBytes(hexToBytes(hex));
2041
- }
2042
- /**
2043
- * Encodes ristretto point to Uint8Array.
2044
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2045
- */
2046
- toBytes() {
2047
- let { X, Y, Z, T } = this.ep;
2048
- const P = ed25519_CURVE_p;
2049
- const mod2 = (n) => Fp.create(n);
2050
- const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2051
- const u2 = mod2(X * Y);
2052
- const u2sq = mod2(u2 * u2);
2053
- const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2054
- const D1 = mod2(invsqrt * u1);
2055
- const D2 = mod2(invsqrt * u2);
2056
- const zInv = mod2(D1 * D2 * T);
2057
- let D;
2058
- if (isNegativeLE(T * zInv, P)) {
2059
- let _x = mod2(Y * SQRT_M1);
2060
- let _y = mod2(X * SQRT_M1);
2061
- X = _x;
2062
- Y = _y;
2063
- D = mod2(D1 * INVSQRT_A_MINUS_D);
2064
- } else {
2065
- D = D2;
2066
- }
2067
- if (isNegativeLE(X * zInv, P))
2068
- Y = mod2(-Y);
2069
- let s = mod2((Z - Y) * D);
2070
- if (isNegativeLE(s, P))
2071
- s = mod2(-s);
2072
- return Fp.toBytes(s);
2073
- }
2074
- /**
2075
- * Compares two Ristretto points.
2076
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2077
- */
2078
- equals(other) {
2079
- this.assertSame(other);
2080
- const { X: X1, Y: Y1 } = this.ep;
2081
- const { X: X2, Y: Y2 } = other.ep;
2082
- const mod2 = (n) => Fp.create(n);
2083
- const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2084
- const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2085
- return one || two;
2086
- }
2087
- is0() {
2088
- return this.equals(__RistrettoPoint.ZERO);
2089
- }
2090
- };
2091
- // Do NOT change syntax: the following gymnastics is done,
2092
- // because typescript strips comments, which makes bundlers disable tree-shaking.
2093
- // prettier-ignore
2094
- __publicField(__RistrettoPoint, "BASE", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.BASE))());
2095
- // prettier-ignore
2096
- __publicField(__RistrettoPoint, "ZERO", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.ZERO))());
2097
- // prettier-ignore
2098
- __publicField(__RistrettoPoint, "Fp", /* @__PURE__ */ (() => Fp)());
2099
- // prettier-ignore
2100
- __publicField(__RistrettoPoint, "Fn", /* @__PURE__ */ (() => Fn)());
2101
- var _RistrettoPoint = __RistrettoPoint;
2102
- Object.freeze(_RistrettoPoint.BASE);
2103
- Object.freeze(_RistrettoPoint.ZERO);
2104
- Object.freeze(_RistrettoPoint.prototype);
2105
- Object.freeze(_RistrettoPoint);
2106
- var ristretto255_hasher = Object.freeze({
2107
- Point: _RistrettoPoint,
2108
- /**
2109
- * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
2110
- * * There are no test vectors
2111
- * * encodeToCurve / mapToCurve is undefined
2112
- * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!
2113
- * * hashToScalar is undefined too, so we just use OPRF implementation
2114
- * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
2115
- (os2ip -> bytes255ToNumberLE)
2116
- * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
2117
- * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
2118
- version here. Using `bytes255ToNumblerLE` will create a different result
2119
- if we use `bytes255ToNumberLE` as os2ip
2120
- * * current version is closest to spec.
2121
- */
2122
- hashToCurve(msg, options) {
2123
- const DST = options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2124
- const xmd = expand_message_xmd(msg, DST, 64, sha512);
2125
- return ristretto255_hasher.deriveToCurve(xmd);
2126
- },
2127
- hashToScalar(msg, options = { DST: _DST_scalar }) {
2128
- const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2129
- return Fn.create(bytesToNumberLE(xmd));
2130
- },
2131
- /**
2132
- * HashToCurve-like construction based on RFC 9496 (Element Derivation).
2133
- * Converts 64 uniform random bytes into a curve point.
2134
- *
2135
- * WARNING: This represents an older hash-to-curve construction from before
2136
- * RFC 9380 was finalized.
2137
- * It was later reused as a component in the newer
2138
- * `hash_to_ristretto255` function defined in RFC 9380.
2139
- */
2140
- deriveToCurve(bytes) {
2141
- abytes(bytes, 64);
2142
- const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2143
- const R1 = calcElligatorRistrettoMap(r1);
2144
- const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2145
- const R2 = calcElligatorRistrettoMap(r2);
2146
- return new _RistrettoPoint(R1.add(R2));
2147
- }
2148
- });
2149
1764
 
2150
1765
  // ../../node_modules/@noble/hashes/sha3.js
2151
1766
  var _0n7 = BigInt(0);
@@ -2172,13 +1787,21 @@ for (let round = 0, R = _1n7, x = 1, y = 0; round < 24; round++) {
2172
1787
  var IOTAS = split(_SHA3_IOTA, true);
2173
1788
  var SHA3_IOTA_H = IOTAS[0];
2174
1789
  var SHA3_IOTA_L = IOTAS[1];
1790
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
1791
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
1792
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
1793
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
2175
1794
  var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
2176
1795
  var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
1796
+ var B = new Uint32Array(5 * 2);
2177
1797
  function keccakP(s, rounds = 24) {
1798
+ if (!(s instanceof Uint32Array))
1799
+ throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
1800
+ if (s.length !== 50)
1801
+ throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
2178
1802
  anumber(rounds, "rounds");
2179
1803
  if (rounds < 1 || rounds > 24)
2180
1804
  throw new Error('"rounds" expected integer 1..24');
2181
- const B = new Uint32Array(5 * 2);
2182
1805
  for (let round = 24 - rounds; round < 24; round++) {
2183
1806
  for (let x = 0; x < 10; x++)
2184
1807
  B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
@@ -2239,6 +1862,10 @@ var Keccak = class _Keccak {
2239
1862
  __publicField(this, "canXOF");
2240
1863
  __publicField(this, "enableXOF", false);
2241
1864
  __publicField(this, "rounds");
1865
+ anumber(blockLen, "blockLen");
1866
+ anumber(suffix, "suffix");
1867
+ anumber(rounds, "rounds");
1868
+ abool(enableXOF, "enableXOF");
2242
1869
  this.blockLen = blockLen;
2243
1870
  this.suffix = suffix;
2244
1871
  this.outputLen = outputLen;
@@ -2247,7 +1874,7 @@ var Keccak = class _Keccak {
2247
1874
  this.rounds = rounds;
2248
1875
  anumber(outputLen, "outputLen");
2249
1876
  if (!(0 < blockLen && blockLen < 200))
2250
- throw new Error("only keccak-f1600 function is supported");
1877
+ throw new Error('"blockLen" must be 1..199');
2251
1878
  this.state = new Uint8Array(200);
2252
1879
  this.state32 = u32(this.state);
2253
1880
  }
@@ -2264,9 +1891,20 @@ var Keccak = class _Keccak {
2264
1891
  update(data) {
2265
1892
  aexists(this);
2266
1893
  abytes(data);
2267
- const { blockLen, state } = this;
1894
+ const { blockLen, state, state32 } = this;
2268
1895
  const len = data.length;
1896
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
1897
+ const blockLen32 = blockLen / 4;
1898
+ const data32 = canUseU32 && len >= blockLen ? u32(data) : void 0;
2269
1899
  for (let pos = 0; pos < len; ) {
1900
+ if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
1901
+ for (let i = 0, o = pos / 4; i < blockLen32; i++)
1902
+ state32[i] ^= data32[o + i];
1903
+ pos += blockLen;
1904
+ this.pos = blockLen;
1905
+ this.keccak();
1906
+ continue;
1907
+ }
2270
1908
  const take = Math.min(blockLen - this.pos, len - pos);
2271
1909
  for (let i = 0; i < take; i++)
2272
1910
  state[this.pos++] ^= data[pos++];
@@ -2304,7 +1942,7 @@ var Keccak = class _Keccak {
2304
1942
  }
2305
1943
  xofInto(out) {
2306
1944
  if (!this.enableXOF)
2307
- throw new Error("XOF is not possible for this instance");
1945
+ throw new Error("XOF is not enabled");
2308
1946
  return this.writeInto(out);
2309
1947
  }
2310
1948
  xof(bytes) {
@@ -2315,7 +1953,7 @@ var Keccak = class _Keccak {
2315
1953
  aoutput(out, this);
2316
1954
  if (this.finished)
2317
1955
  throw new Error("digest() was already called");
2318
- this.writeInto(out.subarray(0, this.outputLen));
1956
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
2319
1957
  this.destroy();
2320
1958
  }
2321
1959
  digest() {
@@ -2357,14 +1995,32 @@ var sha3_512 = /* @__PURE__ */ genKeccak(
2357
1995
  64,
2358
1996
  /* @__PURE__ */ oidNist(10)
2359
1997
  );
2360
- var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info);
1998
+ var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => {
1999
+ opts2 = checkOpts({}, opts2);
2000
+ return new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true);
2001
+ }, info);
2361
2002
  var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
2362
2003
  var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
2363
2004
 
2364
2005
  // ../../node_modules/@noble/post-quantum/utils.js
2365
2006
  var abytesDoc = abytes;
2366
2007
  var randomBytes3 = randomBytes;
2367
- function equalBytes2(a, b) {
2008
+ function aarray2(item, title, inner = () => {
2009
+ }) {
2010
+ if (!Array.isArray(item))
2011
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
2012
+ for (let i = 0; i < item.length; i++)
2013
+ inner(item[i], `${title}[${i}]`);
2014
+ return item;
2015
+ }
2016
+ function aobject3(value, title = "object") {
2017
+ if (value === null || typeof value !== "object" || Array.isArray(value))
2018
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
2019
+ return value;
2020
+ }
2021
+ function equalBytes(a, b) {
2022
+ a = abytes(a);
2023
+ b = abytes(b);
2368
2024
  if (a.length !== b.length)
2369
2025
  return false;
2370
2026
  let diff = 0;
@@ -2373,7 +2029,7 @@ function equalBytes2(a, b) {
2373
2029
  return diff === 0;
2374
2030
  }
2375
2031
  function copyBytes2(bytes) {
2376
- return Uint8Array.from(abytes(bytes));
2032
+ return new Uint8Array(abytes(bytes));
2377
2033
  }
2378
2034
  function splitCoder(label, ...lengths) {
2379
2035
  const getLength = (c) => typeof c === "number" ? c : c.bytesLen;
@@ -2413,11 +2069,12 @@ function vecCoder(c, vecLen) {
2413
2069
  return {
2414
2070
  bytesLen,
2415
2071
  encode: (u) => {
2416
- if (u.length !== vecLen)
2417
- throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
2072
+ const uArr = aarray2(u, "u");
2073
+ if (uArr.length !== vecLen)
2074
+ throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);
2418
2075
  const res = new Uint8Array(bytesLen);
2419
- for (let i = 0, pos = 0; i < u.length; i++) {
2420
- const b = coder.encode(u[i]);
2076
+ for (let i = 0, pos = 0; i < uArr.length; i++) {
2077
+ const b = coder.encode(uArr[i]);
2421
2078
  res.set(b, pos);
2422
2079
  b.fill(0);
2423
2080
  pos += b.length;
@@ -2443,8 +2100,9 @@ function cleanBytes(...list) {
2443
2100
  }
2444
2101
  }
2445
2102
  function getMask(bits) {
2446
- if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
2447
- throw new RangeError(`expected bits in [0..32], got ${bits}`);
2103
+ anumber(bits, "bits");
2104
+ if (bits > 32)
2105
+ throw new RangeError('"bits" expected <= 32, got ' + bits);
2448
2106
  return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0;
2449
2107
  }
2450
2108
 
@@ -2469,13 +2127,25 @@ var genCrystals = (opts2) => {
2469
2127
  return out;
2470
2128
  }
2471
2129
  const nttZetas = getZettas();
2472
- const field = {
2130
+ const inv = (_a) => {
2131
+ throw new Error("not implemented");
2132
+ };
2133
+ const field = isKyber ? {
2134
+ add: (a, b) => {
2135
+ const r = a + b | 0;
2136
+ return r >= Q2 ? r - Q2 | 0 : r;
2137
+ },
2138
+ sub: (a, b) => {
2139
+ const r = a - b | 0;
2140
+ return r < 0 ? r + Q2 | 0 : r;
2141
+ },
2142
+ mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
2143
+ inv
2144
+ } : {
2473
2145
  add: (a, b) => mod2((a | 0) + (b | 0)) | 0,
2474
2146
  sub: (a, b) => mod2((a | 0) - (b | 0)) | 0,
2475
2147
  mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
2476
- inv: (_a) => {
2477
- throw new Error("not implemented");
2478
- }
2148
+ inv
2479
2149
  };
2480
2150
  const nttOpts = {
2481
2151
  N: N2,
@@ -2498,6 +2168,12 @@ var genCrystals = (opts2) => {
2498
2168
  }
2499
2169
  };
2500
2170
  const bitsCoder = (d, c) => {
2171
+ for (let i = 0, bufLen = 0; i < N2; i++) {
2172
+ bufLen += d;
2173
+ if (bufLen > 32)
2174
+ getMask(bufLen);
2175
+ bufLen %= 8;
2176
+ }
2501
2177
  const mask = getMask(d);
2502
2178
  const bytesLen = d * (N2 / 8);
2503
2179
  return {
@@ -2509,7 +2185,7 @@ var genCrystals = (opts2) => {
2509
2185
  buf |= (c.encode(poly[i]) & mask) << bufLen;
2510
2186
  bufLen += d;
2511
2187
  for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
2512
- r[pos++] = buf & getMask(bufLen);
2188
+ r[pos++] = buf & 255;
2513
2189
  }
2514
2190
  return r;
2515
2191
  },
@@ -2602,17 +2278,21 @@ var polyCoder = (d) => d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress
2602
2278
  function polyAdd(a_, b_) {
2603
2279
  const a = a_;
2604
2280
  const b = b_;
2605
- for (let i = 0; i < N; i++)
2606
- a[i] = crystals.mod(a[i] + b[i]);
2281
+ for (let i = 0; i < N; i++) {
2282
+ const r = a[i] + b[i];
2283
+ a[i] = r >= Q ? r - Q : r;
2284
+ }
2607
2285
  }
2608
2286
  function polySub(a_, b_) {
2609
2287
  const a = a_;
2610
2288
  const b = b_;
2611
- for (let i = 0; i < N; i++)
2612
- a[i] = crystals.mod(a[i] - b[i]);
2289
+ for (let i = 0; i < N; i++) {
2290
+ const r = a[i] - b[i];
2291
+ a[i] = r < 0 ? r + Q : r;
2292
+ }
2613
2293
  }
2614
2294
  function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
2615
- const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);
2295
+ const c0 = crystals.mod(crystals.mod(a1 * b1) * zeta + a0 * b0);
2616
2296
  const c1 = crystals.mod(a0 * b1 + a1 * b0);
2617
2297
  return { c0, c1 };
2618
2298
  }
@@ -2687,6 +2367,31 @@ var genKPKE = (opts_) => {
2687
2367
  const secretCoder = vecCoder(polyCoder(12), K);
2688
2368
  const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
2689
2369
  const seedCoder = splitCoder("seed", 32, 32);
2370
+ const encryptCore = (tHat, getA, msg, seed) => {
2371
+ const rHat = [];
2372
+ for (let i = 0; i < K; i++)
2373
+ rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2374
+ const tmp2 = new Uint16Array(N);
2375
+ const u = [];
2376
+ for (let i = 0; i < K; i++) {
2377
+ const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2378
+ const tmp = new Uint16Array(N);
2379
+ for (let j = 0; j < K; j++) {
2380
+ const aij = getA(i, j);
2381
+ polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2382
+ }
2383
+ polyAdd(e1, crystals.NTT.decode(tmp));
2384
+ u.push(e1);
2385
+ polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2386
+ cleanBytes(tmp);
2387
+ }
2388
+ const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2389
+ polyAdd(e2, crystals.NTT.decode(tmp2));
2390
+ const v = poly1.decode(msg);
2391
+ polyAdd(v, e2);
2392
+ cleanBytes(tHat, rHat, tmp2, e2);
2393
+ return cipherCoder.encode([u, v]);
2394
+ };
2690
2395
  return {
2691
2396
  secretCoder,
2692
2397
  lengths: {
@@ -2724,31 +2429,26 @@ var genKPKE = (opts_) => {
2724
2429
  },
2725
2430
  encrypt: (publicKey, msg, seed) => {
2726
2431
  const [tHat, rho] = publicCoder.decode(publicKey);
2727
- const rHat = [];
2728
- for (let i = 0; i < K; i++)
2729
- rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2730
2432
  const x = XOF(rho);
2731
- const tmp2 = new Uint16Array(N);
2732
- const u = [];
2733
- for (let i = 0; i < K; i++) {
2734
- const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2735
- const tmp = new Uint16Array(N);
2736
- for (let j = 0; j < K; j++) {
2737
- const aij = SampleNTT(x.get(i, j));
2738
- polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2739
- }
2740
- polyAdd(e1, crystals.NTT.decode(tmp));
2741
- u.push(e1);
2742
- polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2743
- cleanBytes(tmp);
2744
- }
2433
+ const res = encryptCore(tHat, (i, j) => SampleNTT(x.get(i, j)), msg, seed);
2745
2434
  x.clean();
2746
- const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2747
- polyAdd(e2, crystals.NTT.decode(tmp2));
2748
- const v = poly1.decode(msg);
2749
- polyAdd(v, e2);
2750
- cleanBytes(tHat, rHat, tmp2, e2);
2751
- return cipherCoder.encode([u, v]);
2435
+ return res;
2436
+ },
2437
+ // Expands the full  matrix (public data derived from rho) once, so repeated encryptions
2438
+ // against the same ek skip the K² SampleNTT XOF expansions. Cached polys are copied per
2439
+ // call because encryptCore mutates its inputs in place.
2440
+ prepare: (publicKey) => {
2441
+ const [tHat, rho] = publicCoder.decode(publicKey);
2442
+ const x = XOF(rho);
2443
+ const A = [];
2444
+ for (let i = 0; i < K; i++)
2445
+ for (let j = 0; j < K; j++)
2446
+ A.push(SampleNTT(x.get(i, j)));
2447
+ x.clean();
2448
+ return {
2449
+ encrypt: (msg, seed) => encryptCore(tHat.map((p) => p.slice()), (i, j) => A[i * K + j].slice(), msg, seed),
2450
+ clean: () => cleanBytes(tHat, A)
2451
+ };
2752
2452
  },
2753
2453
  decrypt: (cipherText, privateKey) => {
2754
2454
  const [u, v] = cipherCoder.decode(cipherText);
@@ -2757,8 +2457,9 @@ var genKPKE = (opts_) => {
2757
2457
  for (let i = 0; i < K; i++)
2758
2458
  polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));
2759
2459
  polySub(v, crystals.NTT.decode(tmp));
2760
- cleanBytes(tmp, sk, u);
2761
- return poly1.encode(v);
2460
+ const res = poly1.encode(v);
2461
+ cleanBytes(tmp, sk, u, v);
2462
+ return res;
2762
2463
  }
2763
2464
  };
2764
2465
  };
@@ -2770,6 +2471,14 @@ function createKyber(opts2) {
2770
2471
  const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
2771
2472
  const msgLen = 32;
2772
2473
  const seedLen = 64;
2474
+ const validateModulus = (publicKey, fn) => {
2475
+ const eke = publicKey.subarray(0, 384 * rawOpts.K);
2476
+ const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
2477
+ const ok = equalBytes(ek, eke);
2478
+ cleanBytes(ek);
2479
+ if (!ok)
2480
+ throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);
2481
+ };
2773
2482
  const kemLengths = Object.freeze({
2774
2483
  ...lengths,
2775
2484
  seed: 64,
@@ -2780,38 +2489,55 @@ function createKyber(opts2) {
2780
2489
  return Object.freeze({
2781
2490
  info: Object.freeze({ type: "ml-kem" }),
2782
2491
  lengths: kemLengths,
2783
- keygen: (seed = randomBytes3(seedLen)) => {
2784
- abytesDoc(seed, seedLen, "seed");
2785
- const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));
2786
- const publicKeyHash = HASH256(publicKey);
2787
- const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);
2788
- cleanBytes(sk, publicKeyHash);
2789
- return {
2790
- publicKey,
2791
- secretKey
2792
- };
2492
+ keygen: (seed) => {
2493
+ const ownSeed = seed === void 0;
2494
+ const s = ownSeed ? randomBytes3(seedLen) : seed;
2495
+ let sk;
2496
+ let publicKeyHash;
2497
+ try {
2498
+ abytesDoc(s, seedLen, "seed");
2499
+ const keys = KPKE.keygen(s.subarray(0, 32));
2500
+ const publicKey = keys.publicKey;
2501
+ sk = keys.secretKey;
2502
+ publicKeyHash = HASH256(publicKey);
2503
+ const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, s.subarray(32)]);
2504
+ return {
2505
+ publicKey,
2506
+ secretKey
2507
+ };
2508
+ } finally {
2509
+ if (sk !== void 0)
2510
+ cleanBytes(sk);
2511
+ if (publicKeyHash !== void 0)
2512
+ cleanBytes(publicKeyHash);
2513
+ if (ownSeed)
2514
+ cleanBytes(s);
2515
+ }
2793
2516
  },
2794
2517
  getPublicKey: (secretKey) => {
2795
2518
  const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
2796
2519
  return Uint8Array.from(publicKey);
2797
2520
  },
2798
- encapsulate: (publicKey, msg = randomBytes3(msgLen)) => {
2799
- abytesDoc(publicKey, lengths.publicKey, "publicKey");
2800
- abytesDoc(msg, msgLen, "message");
2801
- const eke = publicKey.subarray(0, 384 * opts2.K);
2802
- const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
2803
- if (!equalBytes2(ek, eke)) {
2804
- cleanBytes(ek);
2805
- throw new Error("ML-KEM.encapsulate: wrong publicKey modulus");
2521
+ encapsulate: (publicKey, msg) => {
2522
+ const ownMsg = msg === void 0;
2523
+ const m = ownMsg ? randomBytes3(msgLen) : msg;
2524
+ let kr;
2525
+ try {
2526
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2527
+ abytesDoc(m, msgLen, "message");
2528
+ validateModulus(publicKey, "encapsulate");
2529
+ kr = HASH512.create().update(m).update(HASH256(publicKey)).digest();
2530
+ const cipherText = KPKE.encrypt(publicKey, m, kr.subarray(32, 64));
2531
+ return {
2532
+ cipherText,
2533
+ sharedSecret: kr.subarray(0, 32)
2534
+ };
2535
+ } finally {
2536
+ if (kr !== void 0)
2537
+ cleanBytes(kr.subarray(32));
2538
+ if (ownMsg)
2539
+ cleanBytes(m);
2806
2540
  }
2807
- cleanBytes(ek);
2808
- const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();
2809
- const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2810
- cleanBytes(kr.subarray(32));
2811
- return {
2812
- cipherText,
2813
- sharedSecret: kr.subarray(0, 32)
2814
- };
2815
2541
  },
2816
2542
  decapsulate: (cipherText, secretKey) => {
2817
2543
  abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
@@ -2819,17 +2545,67 @@ function createKyber(opts2) {
2819
2545
  const k768 = secretCoder.bytesLen - 96;
2820
2546
  const start = k768 + 32;
2821
2547
  const test = HASH256(secretKey.subarray(k768 / 2, start));
2822
- if (!equalBytes2(test, secretKey.subarray(start, start + 32)))
2548
+ if (!equalBytes(test, secretKey.subarray(start, start + 32)))
2823
2549
  throw new Error("invalid secretKey: hash check failed");
2824
2550
  const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
2825
2551
  const msg = KPKE.decrypt(cipherText, sk);
2826
2552
  const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2827
2553
  const Khat = kr.subarray(0, 32);
2828
2554
  const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2829
- const isValid = equalBytes2(cipherText, cipherText2);
2555
+ const isValid = equalBytes(cipherText, cipherText2);
2830
2556
  const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2831
- cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);
2557
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2832
2558
  return isValid ? Khat : Kbar;
2559
+ },
2560
+ /**
2561
+ * Experimental prototype: pre-expand a public key so repeated encapsulate/decapsulate
2562
+ * against the same key skip re-validation, H(ek), t̂ decoding and the K² SampleNTT
2563
+ * XOF expansions of Â. Only public data is cached; see {@link KEMPrepared}.
2564
+ */
2565
+ prepare: (publicKey) => {
2566
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2567
+ validateModulus(publicKey, "prepare");
2568
+ const ek = copyBytes2(publicKey);
2569
+ const publicKeyHash = HASH256(ek);
2570
+ const cached = KPKE.prepare(ek);
2571
+ return Object.freeze({
2572
+ publicKey: ek,
2573
+ encapsulate: (msg) => {
2574
+ const ownMsg = msg === void 0;
2575
+ const m = ownMsg ? randomBytes3(msgLen) : msg;
2576
+ let kr;
2577
+ try {
2578
+ abytesDoc(m, msgLen, "message");
2579
+ kr = HASH512.create().update(m).update(publicKeyHash).digest();
2580
+ const cipherText = cached.encrypt(m, kr.subarray(32, 64));
2581
+ return {
2582
+ cipherText,
2583
+ sharedSecret: kr.subarray(0, 32)
2584
+ };
2585
+ } finally {
2586
+ if (kr !== void 0)
2587
+ cleanBytes(kr.subarray(32));
2588
+ if (ownMsg)
2589
+ cleanBytes(m);
2590
+ }
2591
+ },
2592
+ decapsulate: (cipherText, secretKey) => {
2593
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2594
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
2595
+ const [sk, ekEmbedded, storedHash, z] = secretCoder.decode(secretKey);
2596
+ if (!equalBytes(ekEmbedded, ek) || !equalBytes(storedHash, publicKeyHash))
2597
+ throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");
2598
+ const msg = KPKE.decrypt(cipherText, sk);
2599
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2600
+ const Khat = kr.subarray(0, 32);
2601
+ const cipherText2 = cached.encrypt(msg, kr.subarray(32, 64));
2602
+ const isValid = equalBytes(cipherText, cipherText2);
2603
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2604
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2605
+ return isValid ? Khat : Kbar;
2606
+ },
2607
+ clean: cached.clean
2608
+ });
2833
2609
  }
2834
2610
  });
2835
2611
  }
@@ -2850,18 +2626,32 @@ var mk = (params) => createKyber({
2850
2626
  var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();
2851
2627
 
2852
2628
  // ../../node_modules/@noble/post-quantum/hybrid.js
2629
+ var validateKEM = (kem, title) => {
2630
+ const k = aobject3(kem, title);
2631
+ aobject3(k.lengths, `${title}.lengths`);
2632
+ afunction(k.keygen, `${title}.keygen`);
2633
+ afunction(k.getPublicKey, `${title}.getPublicKey`);
2634
+ afunction(k.encapsulate, `${title}.encapsulate`);
2635
+ afunction(k.decapsulate, `${title}.decapsulate`);
2636
+ return k;
2637
+ };
2853
2638
  function ecKeygen(curve, allowZeroKey = false) {
2639
+ const c = aobject3(curve, "curve");
2640
+ aobject3(c.lengths, "curve.lengths");
2641
+ afunction(c.keygen, "curve.keygen");
2642
+ afunction(c.getPublicKey, "curve.getPublicKey");
2643
+ abool2(allowZeroKey, "allowZeroKey");
2854
2644
  const lengths = curve.lengths;
2855
2645
  let keygen = curve.keygen;
2856
2646
  if (allowZeroKey) {
2857
2647
  if (!("getSharedSecret" in curve && "sign" in curve && "verify" in curve))
2858
2648
  throw new Error("allowZeroKey requires a Weierstrass curve");
2859
2649
  const wCurve = curve;
2860
- const Fn2 = wCurve.Point.Fn;
2650
+ const Fn = wCurve.Point.Fn;
2861
2651
  keygen = (seed = randomBytes3(lengths.seed)) => {
2862
2652
  abytes(seed, lengths.seed, "seed");
2863
- const seedScalar = Fn2.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
2864
- const secretKey = Fn2.toBytes(Fn2.create(seedScalar));
2653
+ const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
2654
+ const secretKey = Fn.toBytes(Fn.create(seedScalar));
2865
2655
  return {
2866
2656
  secretKey,
2867
2657
  publicKey: curve.getPublicKey(secretKey)
@@ -2874,10 +2664,14 @@ function ecKeygen(curve, allowZeroKey = false) {
2874
2664
  getPublicKey: (secretKey) => curve.getPublicKey(secretKey)
2875
2665
  };
2876
2666
  }
2877
- function ecdhKem(curve, allowZeroKey = false) {
2667
+ function _ecdhKem(curve, allowZeroKey = false) {
2878
2668
  const kg = ecKeygen(curve, allowZeroKey);
2879
2669
  if (!curve.getSharedSecret)
2880
2670
  throw new Error("wrong curve");
2671
+ const decapsulate = (cipherText, secretKey) => {
2672
+ const res = curve.getSharedSecret(secretKey, cipherText);
2673
+ return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
2674
+ };
2881
2675
  return {
2882
2676
  lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },
2883
2677
  keygen: kg.keygen,
@@ -2886,8 +2680,8 @@ function ecdhKem(curve, allowZeroKey = false) {
2886
2680
  const seed = copyBytes2(rand);
2887
2681
  let ek = void 0;
2888
2682
  try {
2889
- ek = this.keygen(seed).secretKey;
2890
- const sharedSecret = this.decapsulate(publicKey, ek);
2683
+ ek = kg.keygen(seed).secretKey;
2684
+ const sharedSecret = decapsulate(publicKey, ek);
2891
2685
  const cipherText = curve.getPublicKey(ek);
2892
2686
  return { sharedSecret, cipherText };
2893
2687
  } finally {
@@ -2896,18 +2690,23 @@ function ecdhKem(curve, allowZeroKey = false) {
2896
2690
  cleanBytes(ek);
2897
2691
  }
2898
2692
  },
2899
- decapsulate(cipherText, secretKey) {
2900
- const res = curve.getSharedSecret(secretKey, cipherText);
2901
- return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
2902
- }
2693
+ decapsulate
2903
2694
  };
2904
2695
  }
2696
+ function positiveLength(value, title) {
2697
+ const length = anumber(value, title);
2698
+ if (length === 0)
2699
+ throw new RangeError(`"${title}" expected integer greater than 0, got 0`);
2700
+ return length;
2701
+ }
2905
2702
  function splitLengths(lst, name) {
2906
- return splitCoder(name, ...lst.map((i) => {
2703
+ const coder = splitCoder(name, ...lst.map((i) => {
2907
2704
  if (typeof i.lengths[name] !== "number")
2908
2705
  throw new Error("wrong length: " + name);
2909
- return i.lengths[name];
2706
+ return positiveLength(i.lengths[name], name);
2910
2707
  }));
2708
+ positiveLength(coder.bytesLen, name);
2709
+ return coder;
2911
2710
  }
2912
2711
  function expandSeedXof(xof) {
2913
2712
  return ((seed, seedLen) => xof(seed, { dkLen: seedLen }));
@@ -2917,11 +2716,9 @@ function combineKeys(realSeedLen, expandSeed_, ...ck_) {
2917
2716
  const ck = ck_;
2918
2717
  const seedCoder = splitLengths(ck, "seed");
2919
2718
  const pkCoder = splitLengths(ck, "publicKey");
2920
- if (realSeedLen === void 0)
2921
- realSeedLen = seedCoder.bytesLen;
2922
- anumber(realSeedLen);
2719
+ const rootSeedLen = positiveLength(realSeedLen === void 0 ? seedCoder.bytesLen : realSeedLen, "realSeedLen");
2923
2720
  function expandDecapsulationKey(seed) {
2924
- abytes(seed, realSeedLen);
2721
+ abytes(seed, rootSeedLen);
2925
2722
  const expandedRaw = expandSeed(seed, seedCoder.bytesLen);
2926
2723
  const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes2(expandedRaw) : expandedRaw;
2927
2724
  const expanded = [];
@@ -2946,41 +2743,79 @@ function combineKeys(realSeedLen, expandSeed_, ...ck_) {
2946
2743
  cleanBytes(secretKey);
2947
2744
  }
2948
2745
  }
2949
- return {
2950
- info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },
2951
- getPublicKey(secretKey) {
2952
- return this.keygen(secretKey).publicKey;
2953
- },
2954
- keygen(seed = randomBytes3(realSeedLen)) {
2955
- const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);
2746
+ const keygen = (seed) => {
2747
+ const root = seed === void 0 ? randomBytes3(rootSeedLen) : copyBytes2(seed);
2748
+ let res;
2749
+ try {
2750
+ const { publicKey: pk, secretKey } = expandDecapsulationKey(root);
2956
2751
  try {
2957
- const publicKey = pkCoder.encode(pk);
2958
- return { secretKey: seed, publicKey };
2752
+ res = {
2753
+ secretKey: root,
2754
+ publicKey: pkCoder.encode(pk)
2755
+ };
2959
2756
  } finally {
2960
- cleanBytes(pk);
2961
- cleanBytes(secretKey);
2757
+ cleanBytes(pk, secretKey);
2962
2758
  }
2759
+ return res;
2760
+ } finally {
2761
+ if (!res)
2762
+ cleanBytes(root);
2763
+ }
2764
+ };
2765
+ return {
2766
+ info: { lengths: { seed: rootSeedLen, publicKey: pkCoder.bytesLen, secretKey: rootSeedLen } },
2767
+ // Composite secret keys are root seeds, so public-key derivation reruns key expansion from
2768
+ // that seed instead of decoding a packed child-secret-key structure.
2769
+ getPublicKey: (secretKey) => {
2770
+ const keys = keygen(secretKey);
2771
+ cleanBytes(keys.secretKey);
2772
+ return keys.publicKey;
2963
2773
  },
2774
+ keygen,
2964
2775
  expandDecapsulationKey,
2965
- realSeedLen
2776
+ realSeedLen: rootSeedLen
2966
2777
  };
2967
2778
  }
2968
2779
  function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
2780
+ if (realSeedLen !== void 0)
2781
+ positiveLength(realSeedLen, "realSeedLen");
2782
+ if (realMsgLen !== void 0)
2783
+ positiveLength(realMsgLen, "realMsgLen");
2784
+ if (typeof expandSeed !== "function")
2785
+ throw new TypeError('"expandSeed" expected function, got type=' + typeof expandSeed);
2786
+ if (typeof combiner !== "function")
2787
+ throw new TypeError('"combiner" expected function, got type=' + typeof combiner);
2969
2788
  const rawCombiner = combiner;
2970
2789
  const rawKems = kems;
2790
+ if (rawKems.length === 0)
2791
+ throw new RangeError("combineKEMS requires at least one KEM");
2792
+ for (let i = 0; i < rawKems.length; i++)
2793
+ validateKEM(rawKems[i], `kems[${i}]`);
2971
2794
  const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);
2972
2795
  const ctCoder = splitLengths(rawKems, "cipherText");
2973
2796
  const pkCoder = splitLengths(rawKems, "publicKey");
2974
2797
  const msgCoder = splitLengths(rawKems, "msg");
2975
- if (realMsgLen === void 0)
2976
- realMsgLen = msgCoder.bytesLen;
2977
- anumber(realMsgLen);
2798
+ const sharedSecretLen = positiveLength(realMsgLen === void 0 ? msgCoder.bytesLen : realMsgLen, "realMsgLen");
2978
2799
  const lengths = Object.freeze({
2979
2800
  ...keys.info.lengths,
2980
- msg: realMsgLen,
2801
+ msg: sharedSecretLen,
2981
2802
  msgRand: msgCoder.bytesLen,
2982
2803
  cipherText: ctCoder.bytesLen
2983
2804
  });
2805
+ const combine = (publicKeys, cipherTexts, sharedSecrets) => {
2806
+ const combined = rawCombiner(publicKeys, cipherTexts, sharedSecrets);
2807
+ try {
2808
+ return copyBytes2(abytes(combined, sharedSecretLen, "sharedSecret"));
2809
+ } catch (error) {
2810
+ if (isBytes(combined)) {
2811
+ const overlaps = (value) => combined.buffer === value.buffer && combined.byteOffset < value.byteOffset + value.byteLength && value.byteOffset < combined.byteOffset + combined.byteLength;
2812
+ const aliasesPublicInput = publicKeys.some(overlaps) || cipherTexts.some(overlaps);
2813
+ if (!aliasesPublicInput)
2814
+ cleanBytes(combined);
2815
+ }
2816
+ throw error;
2817
+ }
2818
+ };
2984
2819
  return Object.freeze({
2985
2820
  lengths,
2986
2821
  getPublicKey: keys.getPublicKey,
@@ -2996,11 +2831,12 @@ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
2996
2831
  sharedSecret.push(enc.sharedSecret);
2997
2832
  cipherText.push(enc.cipherText);
2998
2833
  }
2834
+ const encodedCipherText = ctCoder.encode(cipherText);
2999
2835
  return {
3000
2836
  // Detach the combiner result before cleanup: a caller-provided combiner may alias one of
3001
2837
  // the child sharedSecret buffers, and those child buffers are zeroized immediately below.
3002
- sharedSecret: copyBytes2(rawCombiner(pks, cipherText, sharedSecret)),
3003
- cipherText: ctCoder.encode(cipherText)
2838
+ sharedSecret: combine(pks, cipherText, sharedSecret),
2839
+ cipherText: encodedCipherText
3004
2840
  };
3005
2841
  } finally {
3006
2842
  cleanBytes(sharedSecret, cipherText);
@@ -3009,16 +2845,18 @@ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
3009
2845
  decapsulate(ct, seed) {
3010
2846
  const cts = ctCoder.decode(ct);
3011
2847
  const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);
3012
- const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));
2848
+ const sharedSecret = [];
3013
2849
  try {
3014
- return copyBytes2(rawCombiner(publicKey, cts, sharedSecret));
2850
+ for (let i = 0; i < rawKems.length; i++)
2851
+ sharedSecret.push(rawKems[i].decapsulate(cts[i], secretKey[i]));
2852
+ return combine(publicKey, cts, sharedSecret);
3015
2853
  } finally {
3016
2854
  cleanBytes(secretKey, sharedSecret);
3017
2855
  }
3018
2856
  }
3019
2857
  });
3020
2858
  }
3021
- var x25519kem = /* @__PURE__ */ ecdhKem(x25519);
2859
+ var x25519kem = /* @__PURE__ */ _ecdhKem(x25519);
3022
2860
  var ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(
3023
2861
  32,
3024
2862
  32,
@@ -3028,7 +2866,6 @@ var ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(
3028
2866
  ml_kem768,
3029
2867
  x25519kem
3030
2868
  ))();
3031
- var XWing = /* @__PURE__ */ (() => ml_kem768_x25519)();
3032
2869
 
3033
2870
  // ../crypto/src/replay-window.ts
3034
2871
  var DEFAULT_REPLAY_WINDOW_SECS = 300;
@@ -3248,6 +3085,9 @@ function classifyEndpointProbe(input) {
3248
3085
  function countsAsFailure(verdict) {
3249
3086
  return !verdict.dispatchable;
3250
3087
  }
3088
+ var ENDPOINT_PROBE_INTERVAL_MINUTES = 15;
3089
+ var ENDPOINT_STALE_AFTER_MINUTES = ENDPOINT_PROBE_INTERVAL_MINUTES * 4;
3090
+ var ENDPOINT_UNUSABLE_AFTER_MINUTES = ENDPOINT_PROBE_INTERVAL_MINUTES * 24;
3251
3091
 
3252
3092
  // ../crypto/src/partner-key-attestation.ts
3253
3093
  var PARTNER_KEY_ATTESTATION_V1 = "oneaddress-partner-key-attestation:v1";
@@ -3328,6 +3168,49 @@ async function verifyPartnerKeyAttestationWithRoots(input, signatureHex, rootKey
3328
3168
  return verifyPartnerKeyAttestation(input, signatureHex, root.public_key_b64);
3329
3169
  }
3330
3170
 
3171
+ // ../crypto/src/registry-root-pin.ts
3172
+ var PINNED_REGISTRY_ROOTS = Object.freeze([
3173
+ Object.freeze({
3174
+ root_key_id: "rk1_251368ec9b0a84ae",
3175
+ spki_sha256: "251368ec9b0a84ae9881533bd1687efb7d439edd927aef47c1bb3bb069b3dc1d"
3176
+ })
3177
+ ]);
3178
+ var overrideForTests = null;
3179
+ function __setPinnedRegistryRootsForTests(pins) {
3180
+ overrideForTests = pins;
3181
+ }
3182
+ function pinnedRegistryRoots() {
3183
+ return overrideForTests ?? PINNED_REGISTRY_ROOTS;
3184
+ }
3185
+ function b64ToBytes2(b64) {
3186
+ const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
3187
+ const binary = atob(normalised);
3188
+ const out = new Uint8Array(binary.length);
3189
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
3190
+ return out;
3191
+ }
3192
+ async function spkiSha256HexFromB64(spkiB64) {
3193
+ const digest = await crypto.subtle.digest("SHA-256", b64ToBytes2(spkiB64));
3194
+ return bytesToHex3(new Uint8Array(digest));
3195
+ }
3196
+ async function rootIsPinned(root) {
3197
+ try {
3198
+ const digest = await spkiSha256HexFromB64(root.public_key_b64);
3199
+ return pinnedRegistryRoots().some(
3200
+ (p) => p.root_key_id === root.root_key_id && p.spki_sha256 === digest
3201
+ );
3202
+ } catch {
3203
+ return false;
3204
+ }
3205
+ }
3206
+ async function unpinnedRootIds(roots) {
3207
+ const out = [];
3208
+ for (const root of roots) {
3209
+ if (!await rootIsPinned(root)) out.push(String(root?.root_key_id ?? "(no id)"));
3210
+ }
3211
+ return out;
3212
+ }
3213
+
3331
3214
  // ../crypto/src/registry-head.ts
3332
3215
  var REGISTRY_HEAD_V1 = "oneaddress-partner-key-registry-head:v1";
3333
3216
  var REGISTRY_HEAD_V2 = "oneaddress-partner-key-registry-head:v2";
@@ -3404,7 +3287,7 @@ function buildRegistryHeadStatement(payload) {
3404
3287
  }
3405
3288
  return lines.join("\n");
3406
3289
  }
3407
- function b64ToBytes2(b64) {
3290
+ function b64ToBytes3(b64) {
3408
3291
  const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
3409
3292
  const binary = atob(normalised);
3410
3293
  const out = new Uint8Array(binary.length);
@@ -3449,7 +3332,7 @@ async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date())
3449
3332
  });
3450
3333
  const rootKey = await crypto.subtle.importKey(
3451
3334
  "spki",
3452
- b64ToBytes2(root.public_key_b64),
3335
+ b64ToBytes3(root.public_key_b64),
3453
3336
  { name: "ECDSA", namedCurve: "P-256" },
3454
3337
  false,
3455
3338
  ["verify"]
@@ -3477,7 +3360,7 @@ function headNamesPartner(doc, partnerId) {
3477
3360
  async function partnerKeyFingerprint(publicKeyB64) {
3478
3361
  const digest = await crypto.subtle.digest(
3479
3362
  "SHA-256",
3480
- b64ToBytes2(publicKeyB64)
3363
+ b64ToBytes3(publicKeyB64)
3481
3364
  );
3482
3365
  return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
3483
3366
  }
@@ -3506,6 +3389,7 @@ async function saysRootNotConfigured(res) {
3506
3389
  }
3507
3390
  }
3508
3391
  async function outcomeFor(partnerId, key, reg, bound) {
3392
+ if (reg.unpinnedRoots.length > 0) return "root-unpinned";
3509
3393
  if (!reg.head) return "head-unusable";
3510
3394
  if (!key.key_signature || !key.root_key_id) {
3511
3395
  if (!key.countersignature_exempt) return "unsigned";
@@ -3564,6 +3448,10 @@ function createPartnerKeyVerifier(env = {}) {
3564
3448
  if (roots.length === 0) {
3565
3449
  return { ok: false, failure: { reason: "roots-empty", status: rootsRes.status } };
3566
3450
  }
3451
+ const unpinnedRoots = await unpinnedRootIds(roots);
3452
+ if (unpinnedRoots.length > 0) {
3453
+ return { ok: true, registry: { roots: [], head: null, headVerdict: "root-unpinned", unpinnedRoots } };
3454
+ }
3567
3455
  let head = null;
3568
3456
  let headVerdict = "absent";
3569
3457
  if (headRes.ok) {
@@ -3571,7 +3459,7 @@ function createPartnerKeyVerifier(env = {}) {
3571
3459
  headVerdict = await verifyRegistryHead(head, roots);
3572
3460
  if (headVerdict !== "ok" && headVerdict !== "expired") head = null;
3573
3461
  }
3574
- return { ok: true, registry: { roots, head, headVerdict } };
3462
+ return { ok: true, registry: { roots, head, headVerdict, unpinnedRoots: [] } };
3575
3463
  } catch {
3576
3464
  return { ok: false, failure: { reason: "fetch-failed" } };
3577
3465
  }
@@ -3603,6 +3491,7 @@ function createPartnerKeyVerifier(env = {}) {
3603
3491
  "bad-attestation": [],
3604
3492
  "not-in-head": [],
3605
3493
  "head-unusable": [],
3494
+ "root-unpinned": [],
3606
3495
  "error": []
3607
3496
  };
3608
3497
  const blocked = {};
@@ -3646,6 +3535,9 @@ function createPartnerKeyVerifier(env = {}) {
3646
3535
  // Counted, not listed: an operator reading a real finding needs to know
3647
3536
  // how many keys were skipped as exempt, without the ids adding noise.
3648
3537
  exempt: tally.exempt.length,
3538
+ // The served root ids the bundle refused, so a report of a rotation
3539
+ // that outran its client build names the root to add.
3540
+ ...reg.unpinnedRoots.length > 0 ? { unpinnedRoots: reg.unpinnedRoots } : {},
3649
3541
  ...Object.fromEntries(failed.map((o) => [o, tally[o]]))
3650
3542
  });
3651
3543
  }
@@ -3774,7 +3666,7 @@ async function openSealedWithSenderHeldKey(share, envelope, partnerId, store) {
3774
3666
  }
3775
3667
 
3776
3668
  // ../crypto/src/index.ts
3777
- function b64ToBytes3(b64) {
3669
+ function b64ToBytes4(b64) {
3778
3670
  const binary = atob(b64);
3779
3671
  const bytes = new Uint8Array(binary.length);
3780
3672
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.codePointAt(i) ?? 0;
@@ -3782,13 +3674,13 @@ function b64ToBytes3(b64) {
3782
3674
  }
3783
3675
  function keyB64ToBytes(key) {
3784
3676
  const begin = key.indexOf("-----BEGIN");
3785
- if (begin === -1) return b64ToBytes3(key.replace(/\s+/g, ""));
3677
+ if (begin === -1) return b64ToBytes4(key.replace(/\s+/g, ""));
3786
3678
  const armourEnd = key.indexOf("-----", begin + "-----BEGIN".length);
3787
- if (armourEnd === -1) return b64ToBytes3(key.replace(/\s+/g, ""));
3679
+ if (armourEnd === -1) return b64ToBytes4(key.replace(/\s+/g, ""));
3788
3680
  const bodyStart = armourEnd + "-----".length;
3789
3681
  const end = key.indexOf("-----END", bodyStart);
3790
3682
  const body = end === -1 ? key.slice(bodyStart) : key.slice(bodyStart, end);
3791
- return b64ToBytes3(body.replace(/\s+/g, ""));
3683
+ return b64ToBytes4(body.replace(/\s+/g, ""));
3792
3684
  }
3793
3685
  function bytesToB64(bytes) {
3794
3686
  return btoa(String.fromCodePoint(...bytes));
@@ -3892,7 +3784,7 @@ async function generatePartnerKeyPair() {
3892
3784
  };
3893
3785
  }
3894
3786
  function generateHybridPartnerKeyPair() {
3895
- const { secretKey, publicKey } = XWing.keygen();
3787
+ const { secretKey, publicKey } = ml_kem768_x25519.keygen();
3896
3788
  return {
3897
3789
  publicKeyB64: bytesToB64(publicKey),
3898
3790
  privateKeyB64: bytesToB64(secretKey)
@@ -3900,7 +3792,7 @@ function generateHybridPartnerKeyPair() {
3900
3792
  }
3901
3793
  async function encryptAddressForPartner(address, partner) {
3902
3794
  const address_ = normaliseAddress(address);
3903
- const partnerPubKey = await importP256PublicKey(b64ToBytes3(partner.publicKeyB64));
3795
+ const partnerPubKey = await importP256PublicKey(b64ToBytes4(partner.publicKeyB64));
3904
3796
  const ephemeral = await subtle().generateKey(
3905
3797
  { name: "ECDH", namedCurve: "P-256" },
3906
3798
  true,
@@ -3948,7 +3840,7 @@ async function encryptAddressForPartner(address, partner) {
3948
3840
  };
3949
3841
  }
3950
3842
  async function encryptPayloadForPartner(payload, partner) {
3951
- const partnerPubKey = await importP256PublicKey(b64ToBytes3(partner.publicKeyB64));
3843
+ const partnerPubKey = await importP256PublicKey(b64ToBytes4(partner.publicKeyB64));
3952
3844
  const ephemeral = await subtle().generateKey(
3953
3845
  { name: "ECDH", namedCurve: "P-256" },
3954
3846
  true,
@@ -4001,7 +3893,7 @@ async function decryptAddress(encrypted, privateKeyB64) {
4001
3893
  );
4002
3894
  const ephemeralPub = await subtle().importKey(
4003
3895
  "raw",
4004
- b64ToBytes3(encrypted.ephemeralPublicKey),
3896
+ b64ToBytes4(encrypted.ephemeralPublicKey),
4005
3897
  { name: "ECDH", namedCurve: "P-256" },
4006
3898
  false,
4007
3899
  []
@@ -4011,7 +3903,7 @@ async function decryptAddress(encrypted, privateKeyB64) {
4011
3903
  privateKey,
4012
3904
  256
4013
3905
  );
4014
- const hkdfSalt = encrypted.hkdfSalt ? b64ToBytes3(encrypted.hkdfSalt) : new Uint8Array(32);
3906
+ const hkdfSalt = encrypted.hkdfSalt ? b64ToBytes4(encrypted.hkdfSalt) : new Uint8Array(32);
4015
3907
  const aesKey = await subtle().importKey(
4016
3908
  "raw",
4017
3909
  await subtle().deriveBits(
@@ -4029,9 +3921,9 @@ async function decryptAddress(encrypted, privateKeyB64) {
4029
3921
  ["decrypt"]
4030
3922
  );
4031
3923
  const plainBuf = await subtle().decrypt(
4032
- { name: "AES-GCM", iv: b64ToBytes3(encrypted.iv) },
3924
+ { name: "AES-GCM", iv: b64ToBytes4(encrypted.iv) },
4033
3925
  aesKey,
4034
- b64ToBytes3(encrypted.ciphertext)
3926
+ b64ToBytes4(encrypted.ciphertext)
4035
3927
  );
4036
3928
  return JSON.parse(new TextDecoder().decode(plainBuf));
4037
3929
  }
@@ -4060,7 +3952,7 @@ function bytesToB64Url(bytes) {
4060
3952
  }
4061
3953
  function b64UrlToBytes(b64url) {
4062
3954
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
4063
- return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3955
+ return b64ToBytes4(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
4064
3956
  }
4065
3957
  function toArrayBuffer(bytes) {
4066
3958
  return bytes.slice().buffer;
@@ -4082,7 +3974,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
4082
3974
  const session_envelope = bytesToB64Url(concat(sessionIv, sessionCt));
4083
3975
  const skRawForWrap = new Uint8Array(await subtle().exportKey("raw", sk));
4084
3976
  if (isHybridScheme(partner.algorithm)) {
4085
- const { cipherText: kemCt, sharedSecret: sharedSecret2 } = XWing.encapsulate(b64ToBytes3(partner.public_key_b64));
3977
+ const { cipherText: kemCt, sharedSecret: sharedSecret2 } = ml_kem768_x25519.encapsulate(b64ToBytes4(partner.public_key_b64));
4086
3978
  const wrapSalt2 = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_SALT_LENGTH));
4087
3979
  const wrapKeyRaw2 = await subtle().deriveBits(
4088
3980
  { name: "HKDF", hash: "SHA-256", salt: wrapSalt2, info: sessionWrapInfoPq(partner.partner_id) },
@@ -4109,7 +4001,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
4109
4001
  };
4110
4002
  }
4111
4003
  if (isRsaScheme(partner.algorithm)) {
4112
- const partnerRsaPub = await importRsaOaepPublicKey(b64ToBytes3(partner.public_key_b64));
4004
+ const partnerRsaPub = await importRsaOaepPublicKey(b64ToBytes4(partner.public_key_b64));
4113
4005
  const rsaWrapped = new Uint8Array(
4114
4006
  await subtle().encrypt({ name: "RSA-OAEP" }, partnerRsaPub, skRawForWrap)
4115
4007
  );
@@ -4126,7 +4018,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
4126
4018
  }
4127
4019
  };
4128
4020
  }
4129
- const partnerPub = await importP256PublicKey(b64ToBytes3(partner.public_key_b64));
4021
+ const partnerPub = await importP256PublicKey(b64ToBytes4(partner.public_key_b64));
4130
4022
  const ephemeral = await subtle().generateKey(
4131
4023
  { name: "ECDH", namedCurve: "P-256" },
4132
4024
  true,
@@ -4208,7 +4100,7 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expe
4208
4100
  throw new Error("decryptSession: hybrid share missing epk (KEM ciphertext)");
4209
4101
  }
4210
4102
  const kemCiphertext = b64UrlToBytes(share.epk);
4211
- const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(XWing.decapsulate(kemCiphertext, b64ToBytes3(privateKeyB64)));
4103
+ const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(ml_kem768_x25519.decapsulate(kemCiphertext, b64ToBytes4(privateKeyB64)));
4212
4104
  if (ops && sharedSecret.byteLength !== 32) {
4213
4105
  throw new Error(
4214
4106
  `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; X-Wing decapsulation is 32 bytes with no KDF applied.`
@@ -4431,6 +4323,9 @@ export {
4431
4323
  ENDPOINT_FAILURE_THRESHOLD,
4432
4324
  classifyEndpointProbe,
4433
4325
  countsAsFailure,
4326
+ ENDPOINT_PROBE_INTERVAL_MINUTES,
4327
+ ENDPOINT_STALE_AFTER_MINUTES,
4328
+ ENDPOINT_UNUSABLE_AFTER_MINUTES,
4434
4329
  PARTNER_KEY_ATTESTATION_V1,
4435
4330
  PARTNER_KEY_ATTESTATION_ALG,
4436
4331
  buildPartnerKeyAttestation,
@@ -4438,6 +4333,12 @@ export {
4438
4333
  rootKeyIdFromSpkiB64,
4439
4334
  verifyPartnerKeyAttestation,
4440
4335
  verifyPartnerKeyAttestationWithRoots,
4336
+ PINNED_REGISTRY_ROOTS,
4337
+ __setPinnedRegistryRootsForTests,
4338
+ pinnedRegistryRoots,
4339
+ spkiSha256HexFromB64,
4340
+ rootIsPinned,
4341
+ unpinnedRootIds,
4441
4342
  REGISTRY_HEAD_V1,
4442
4343
  REGISTRY_HEAD_V2,
4443
4344
  REGISTRY_HEAD_ALG,