@oneaddress/conformance 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -32,42 +32,55 @@ var import_node_crypto = __toESM(require("crypto"));
32
32
  function isBytes(a) {
33
33
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
34
34
  }
35
+ var atitle = (title) => title ? `"${title}" ` : "";
35
36
  function anumber(n, title = "") {
36
- if (typeof n !== "number") {
37
- const prefix = title && `"${title}" `;
38
- throw new TypeError(`${prefix}expected number, got ${typeof n}`);
39
- }
40
- if (!Number.isSafeInteger(n) || n < 0) {
41
- const prefix = title && `"${title}" `;
42
- throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
43
- }
37
+ if (typeof n !== "number")
38
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
39
+ if (!Number.isSafeInteger(n) || n < 0)
40
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
41
+ return n;
44
42
  }
45
- function abytes(value, length, title = "") {
46
- const bytes = isBytes(value);
47
- const len = value?.length;
48
- const needsLen = length !== void 0;
49
- if (!bytes || needsLen && len !== length) {
50
- const prefix = title && `"${title}" `;
51
- const ofLen = needsLen ? ` of length ${length}` : "";
52
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
53
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
54
- if (!bytes)
55
- throw new TypeError(message);
56
- throw new RangeError(message);
57
- }
43
+ function abool(value, title = "") {
44
+ if (typeof value !== "boolean")
45
+ throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
58
46
  return value;
59
47
  }
48
+ function abytes(value, length, title = "") {
49
+ if (isBytes(value) && (length === void 0 || value.length === length))
50
+ return value;
51
+ if (length !== void 0)
52
+ anumber(length, "length");
53
+ const bytes = isBytes(value);
54
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
55
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
56
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
57
+ if (!bytes)
58
+ throw new TypeError(message);
59
+ throw new RangeError(message);
60
+ }
61
+ var aobject = (value, label) => {
62
+ if (value === null || typeof value !== "object" || Array.isArray(value))
63
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
64
+ };
65
+ var aopts = (value, label) => {
66
+ aobject(value, label);
67
+ const proto = Object.getPrototypeOf(value);
68
+ if (proto !== Object.prototype && proto !== null)
69
+ throw new TypeError(`"${label}" expected plain object`);
70
+ if (Object.hasOwn(value, "__proto__"))
71
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
72
+ };
60
73
  function aexists(instance, checkFinished = true) {
61
74
  if (instance.destroyed)
62
- throw new Error("Hash instance has been destroyed");
75
+ throw new Error("hash was destroyed");
63
76
  if (checkFinished && instance.finished)
64
- throw new Error("Hash#digest() has already been called");
77
+ throw new Error("digest() was already called");
65
78
  }
66
79
  function aoutput(out, instance) {
67
- abytes(out, void 0, "digestInto() output");
80
+ abytes(out, void 0, "output");
68
81
  const min = instance.outputLen;
69
- if (out.length < min) {
70
- throw new RangeError('"digestInto() output" expected to be of length >=' + min);
82
+ if (!(out.length >= min)) {
83
+ throw new RangeError('"output" expected length >= ' + min);
71
84
  }
72
85
  }
73
86
  function u32(arr) {
@@ -107,15 +120,8 @@ function bytesToHex(bytes) {
107
120
  }
108
121
  return hex;
109
122
  }
110
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
111
123
  function asciiToBase16(ch) {
112
- if (ch >= asciis._0 && ch <= asciis._9)
113
- return ch - asciis._0;
114
- if (ch >= asciis.A && ch <= asciis.F)
115
- return ch - (asciis.A - 10);
116
- if (ch >= asciis.a && ch <= asciis.f)
117
- return ch - (asciis.a - 10);
118
- return;
124
+ return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
119
125
  }
120
126
  function hexToBytes(hex) {
121
127
  if (typeof hex !== "string")
@@ -160,7 +166,17 @@ function concatBytes(...arrays) {
160
166
  }
161
167
  return res;
162
168
  }
169
+ function checkOpts(defaults, opts2, title = "opts") {
170
+ aopts(defaults, "defaults");
171
+ if (opts2 !== void 0)
172
+ aopts(opts2, title);
173
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts2);
174
+ return merged;
175
+ }
163
176
  function createHasher(hashCons, info = {}) {
177
+ if (typeof hashCons !== "function")
178
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
179
+ info = checkOpts({}, info, "info");
164
180
  const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest();
165
181
  const tmp = hashCons(void 0);
166
182
  hashC.outputLen = tmp.outputLen;
@@ -186,8 +202,26 @@ var oidNist = (suffix) => ({
186
202
  });
187
203
 
188
204
  // ../../node_modules/@noble/curves/utils.js
205
+ function aarray(item, title, inner = () => {
206
+ }) {
207
+ if (!Array.isArray(item))
208
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
209
+ for (let i = 0; i < item.length; i++)
210
+ inner(item[i], `${title}[${i}]`);
211
+ return item;
212
+ }
189
213
  var abytes2 = (value, length, title) => abytes(value, length, title);
190
214
  var anumber2 = anumber;
215
+ function aobject2(value, title = "object") {
216
+ if (value === null || typeof value !== "object" || Array.isArray(value))
217
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
218
+ return value;
219
+ }
220
+ function afunction(value, title) {
221
+ if (typeof value !== "function")
222
+ throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
223
+ return value;
224
+ }
191
225
  var bytesToHex2 = bytesToHex;
192
226
  var concatBytes2 = (...arrays) => concatBytes(...arrays);
193
227
  var hexToBytes2 = (hex) => hexToBytes(hex);
@@ -195,11 +229,10 @@ var isBytes2 = isBytes;
195
229
  var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
196
230
  var _0n = /* @__PURE__ */ BigInt(0);
197
231
  var _1n = /* @__PURE__ */ BigInt(1);
198
- function abool(value, title = "") {
199
- if (typeof value !== "boolean") {
200
- const prefix = title && `"${title}" `;
201
- throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
202
- }
232
+ var atitle2 = (title) => title ? `"${title}" ` : "";
233
+ function abool2(value, title = "") {
234
+ if (typeof value !== "boolean")
235
+ throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
203
236
  return value;
204
237
  }
205
238
  function abignumber(n) {
@@ -234,12 +267,13 @@ function bytesToNumberLE(bytes) {
234
267
  function numberToBytesBE(n, len) {
235
268
  anumber(len);
236
269
  if (len === 0)
237
- throw new RangeError("zero length");
270
+ throw new Error("zero output length is invalid");
238
271
  n = abignumber(n);
272
+ const expectedLen = len * 2;
239
273
  const hex = n.toString(16);
240
- if (hex.length > len * 2)
241
- throw new RangeError("number too large");
242
- return hexToBytes(hex.padStart(len * 2, "0"));
274
+ if (hex.length > expectedLen)
275
+ throw new RangeError("number is too large");
276
+ return hexToBytes(hex.padStart(expectedLen, "0"));
243
277
  }
244
278
  function numberToBytesLE(n, len) {
245
279
  return numberToBytesBE(n, len).reverse();
@@ -268,7 +302,9 @@ function asciiToBytes(ascii) {
268
302
  return charCode;
269
303
  });
270
304
  }
271
- var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
305
+ function isPosBig(n) {
306
+ return typeof n === "bigint" && _0n <= n;
307
+ }
272
308
  function inRange(n, min, max) {
273
309
  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
274
310
  }
@@ -279,24 +315,27 @@ function aInRange(title, n, min, max) {
279
315
  function bitLen(n) {
280
316
  if (n < _0n)
281
317
  throw new Error("expected non-negative bigint, got " + n);
282
- let len;
283
- for (len = 0; n > _0n; n >>= _1n, len += 1)
284
- ;
285
- return len;
286
- }
287
- var bitMask = (n) => (_1n << BigInt(n)) - _1n;
288
- function validateObject(object, fields = {}, optFields = {}) {
289
- if (Object.prototype.toString.call(object) !== "[object Object]")
290
- throw new TypeError("expected valid options object");
318
+ return n === _0n ? 0 : n.toString(2).length;
319
+ }
320
+ var bitMask = (n) => {
321
+ asafenumber(n, "n");
322
+ return (_1n << BigInt(n)) - _1n;
323
+ };
324
+ function validateObject(object, fields = {}, optFields = {}, title = "object") {
325
+ aobject2(object, title);
326
+ aobject2(fields, "fields");
327
+ aobject2(optFields, "optFields");
291
328
  function checkField(fieldName, expectedType, isOpt) {
292
- if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
293
- throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
329
+ const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
294
330
  const val = object[fieldName];
331
+ if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
332
+ throw new TypeError(`${label} is invalid: expected own property`);
333
+ }
295
334
  if (isOpt && val === void 0)
296
335
  return;
297
336
  const current = typeof val;
298
337
  if (current !== expectedType || val === null)
299
- throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
338
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
300
339
  }
301
340
  const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
302
341
  iter(fields, false);
@@ -316,14 +355,64 @@ var _5n = /* @__PURE__ */ BigInt(5);
316
355
  var _7n = /* @__PURE__ */ BigInt(7);
317
356
  var _8n = /* @__PURE__ */ BigInt(8);
318
357
  var _9n = /* @__PURE__ */ BigInt(9);
358
+ var _15n = /* @__PURE__ */ BigInt(15);
319
359
  var _16n = /* @__PURE__ */ BigInt(16);
360
+ var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
320
361
  function mod(a, b) {
321
362
  if (b <= _0n2)
322
363
  throw new Error("mod: expected positive modulus, got " + b);
323
364
  const result = a % b;
324
365
  return result >= _0n2 ? result : b + result;
325
366
  }
367
+ function pow(num, power, modulo) {
368
+ if (modulo <= _1n2)
369
+ throw new Error("pow: expected modulus > 1, got " + modulo);
370
+ if (typeof power !== "bigint")
371
+ throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
372
+ if (power < _0n2)
373
+ throw new Error("invalid exponent, negatives unsupported");
374
+ if (power === _0n2)
375
+ return _1n2;
376
+ if (power === _1n2)
377
+ return num;
378
+ let d = num % modulo;
379
+ if (d < _0n2)
380
+ d += modulo;
381
+ if (power < POW_WINDOWED_MIN) {
382
+ let p2 = _1n2;
383
+ while (power > _0n2) {
384
+ if (power & _1n2)
385
+ p2 = p2 * d % modulo;
386
+ d = d * d % modulo;
387
+ power >>= _1n2;
388
+ }
389
+ return p2;
390
+ }
391
+ const digits = [];
392
+ while (power > _0n2) {
393
+ digits.push(Number(power & _15n));
394
+ power >>= _4n;
395
+ }
396
+ const table = new Array(16);
397
+ table[0] = _1n2;
398
+ table[1] = d;
399
+ for (let i = 2; i < 16; i++)
400
+ table[i] = table[i - 1] * d % modulo;
401
+ let p = table[digits[digits.length - 1]];
402
+ for (let w = digits.length - 2; w >= 0; w--) {
403
+ p = p * p % modulo;
404
+ p = p * p % modulo;
405
+ p = p * p % modulo;
406
+ p = p * p % modulo;
407
+ const digit = digits[w];
408
+ if (digit !== 0)
409
+ p = p * table[digit] % modulo;
410
+ }
411
+ return p;
412
+ }
326
413
  function pow2(x, power, modulo) {
414
+ if (modulo <= _1n2)
415
+ throw new Error("pow2: expected modulus > 1, got " + modulo);
327
416
  if (power < _0n2)
328
417
  throw new Error("pow2: expected non-negative exponent, got " + power);
329
418
  let res = x;
@@ -336,28 +425,42 @@ function pow2(x, power, modulo) {
336
425
  function invert(number, modulo) {
337
426
  if (number === _0n2)
338
427
  throw new Error("invert: expected non-zero number");
339
- if (modulo <= _0n2)
340
- throw new Error("invert: expected positive modulus, got " + modulo);
428
+ if (modulo <= _1n2)
429
+ throw new Error("invert: expected modulus > 1, got " + modulo);
341
430
  let a = mod(number, modulo);
342
431
  let b = modulo;
343
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
432
+ let x = _0n2, u = _1n2;
344
433
  while (a !== _0n2) {
345
434
  const q = b / a;
346
435
  const r = b - a * q;
347
436
  const m = x - u * q;
348
- const n = y - v * q;
349
- b = a, a = r, x = u, y = v, u = m, v = n;
437
+ b = a, a = r, x = u, u = m;
350
438
  }
351
439
  const gcd = b;
352
440
  if (gcd !== _1n2)
353
441
  throw new Error("invert: does not exist");
354
442
  return mod(x, modulo);
355
443
  }
444
+ function invertCt(a, prime) {
445
+ if (prime <= _1n2)
446
+ throw new Error("invertCt: expected prime modulus > 1, got " + prime);
447
+ const an = mod(a, prime);
448
+ if (an === _0n2)
449
+ throw new Error("invertCt: expected non-zero number");
450
+ const inverse = pow(an, prime - _2n, prime);
451
+ if (mod(an * inverse, prime) !== _1n2)
452
+ throw new Error("invertCt: does not exist");
453
+ return inverse;
454
+ }
356
455
  function assertIsSquare(Fp2, root, n) {
357
456
  const F2 = Fp2;
358
457
  if (!F2.eql(F2.sqr(root), n))
359
458
  throw new Error("Cannot find square root");
360
459
  }
460
+ function aoddModulus(order, fnName) {
461
+ if ((order & _1n2) === _0n2)
462
+ throw new Error(fnName + ": expected odd modulus, got " + order);
463
+ }
361
464
  function sqrt3mod4(Fp2, n) {
362
465
  const F2 = Fp2;
363
466
  const p1div4 = (F2.ORDER + _1n2) / _4n;
@@ -402,6 +505,7 @@ function sqrt9mod16(P) {
402
505
  function tonelliShanks(P) {
403
506
  if (P < _3n)
404
507
  throw new Error("sqrt is not defined for small field");
508
+ aoddModulus(P, "tonelliShanks");
405
509
  let Q2 = P - _1n2;
406
510
  let S = 0;
407
511
  while (Q2 % _2n === _0n2) {
@@ -430,7 +534,7 @@ function tonelliShanks(P) {
430
534
  let R = F2.pow(n, Q1div2);
431
535
  while (!F2.eql(t, F2.ONE)) {
432
536
  if (F2.is0(t))
433
- return F2.ZERO;
537
+ throw new Error("Cannot find square root: probably non-prime P");
434
538
  let i = 1;
435
539
  let t_tmp = F2.sqr(t);
436
540
  while (!F2.eql(t_tmp, F2.ONE)) {
@@ -450,6 +554,7 @@ function tonelliShanks(P) {
450
554
  };
451
555
  }
452
556
  function FpSqrt(P) {
557
+ aoddModulus(P, "Fp.sqrt");
453
558
  if (P % _4n === _3n)
454
559
  return sqrt3mod4;
455
560
  if (P % _8n === _5n)
@@ -479,43 +584,23 @@ var FIELD_FIELDS = [
479
584
  "sqrN"
480
585
  ];
481
586
  function validateField(field) {
482
- const initial = {
483
- ORDER: "bigint",
484
- BYTES: "number",
485
- BITS: "number"
486
- };
487
- const opts2 = FIELD_FIELDS.reduce((map, val) => {
488
- map[val] = "function";
489
- return map;
490
- }, initial);
491
- validateObject(field, opts2);
587
+ aobject2(field, "field");
588
+ if (typeof field.ORDER !== "bigint")
589
+ throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
492
590
  asafenumber(field.BYTES, "BYTES");
493
591
  asafenumber(field.BITS, "BITS");
592
+ for (const name of FIELD_FIELDS)
593
+ afunction(field[name], "field." + name);
494
594
  if (field.BYTES < 1 || field.BITS < 1)
495
595
  throw new Error("invalid field: expected BYTES/BITS > 0");
496
596
  if (field.ORDER <= _1n2)
497
597
  throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
498
598
  return field;
499
599
  }
500
- function FpPow(Fp2, num, power) {
501
- const F2 = Fp2;
502
- if (power < _0n2)
503
- throw new Error("invalid exponent, negatives unsupported");
504
- if (power === _0n2)
505
- return F2.ONE;
506
- if (power === _1n2)
507
- return num;
508
- let p = F2.ONE;
509
- let d = num;
510
- while (power > _0n2) {
511
- if (power & _1n2)
512
- p = F2.mul(p, d);
513
- d = F2.sqr(d);
514
- power >>= _1n2;
515
- }
516
- return p;
517
- }
518
600
  function FpInvertBatch(Fp2, nums, passZero = false) {
601
+ validateField(Fp2);
602
+ aarray(nums, "nums");
603
+ abool2(passZero, "passZero");
519
604
  const F2 = Fp2;
520
605
  const inverted = new Array(nums.length).fill(passZero ? F2.ZERO : void 0);
521
606
  const multipliedAcc = nums.reduce((acc, num, i) => {
@@ -534,7 +619,9 @@ function FpInvertBatch(Fp2, nums, passZero = false) {
534
619
  return inverted;
535
620
  }
536
621
  function FpLegendre(Fp2, n) {
622
+ validateField(Fp2);
537
623
  const F2 = Fp2;
624
+ aoddModulus(F2.ORDER, "FpLegendre");
538
625
  const p1mod2 = (F2.ORDER - _1n2) / _2n;
539
626
  const powered = F2.pow(n, p1mod2);
540
627
  const yes = F2.eql(powered, F2.ONE);
@@ -553,7 +640,7 @@ function nLength(n, nBitLength) {
553
640
  throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
554
641
  const bits = bitLen(n);
555
642
  if (nBitLength !== void 0 && nBitLength < bits)
556
- throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
643
+ throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
557
644
  const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
558
645
  const nByteLength = Math.ceil(_nBitLength / 8);
559
646
  return { nBitLength: _nBitLength, nByteLength };
@@ -630,7 +717,7 @@ var _Field = class {
630
717
  return mod(lhs * rhs, this.ORDER);
631
718
  }
632
719
  pow(num, power) {
633
- return FpPow(this, num, power);
720
+ return pow(num, power, this.ORDER);
634
721
  }
635
722
  div(lhs, rhs) {
636
723
  return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
@@ -684,201 +771,389 @@ var _Field = class {
684
771
  }
685
772
  // TODO: we don't need it here, move out to separate fn
686
773
  invertBatch(lst) {
687
- return FpInvertBatch(this, lst);
774
+ return FpInvertBatch(this, lst, true);
688
775
  }
689
776
  // We can't move this out because Fp6, Fp12 implement it
690
777
  // and it's unclear what to return in there.
691
778
  cmov(a, b, condition) {
692
- abool(condition, "condition");
779
+ abool2(condition, "condition");
693
780
  return condition ? b : a;
694
781
  }
695
782
  };
696
- Object.freeze(_Field.prototype);
697
783
  function Field(ORDER, opts2 = {}) {
784
+ Object.freeze(_Field.prototype);
698
785
  return new _Field(ORDER, opts2);
699
786
  }
787
+ function getFieldBytesLength(fieldOrder) {
788
+ if (typeof fieldOrder !== "bigint")
789
+ throw new Error("field order must be bigint");
790
+ if (fieldOrder <= _1n2)
791
+ throw new Error("field order must be greater than 1");
792
+ const bitLength = bitLen(fieldOrder - _1n2);
793
+ return Math.ceil(bitLength / 8);
794
+ }
795
+ function getMinHashLength(fieldOrder) {
796
+ const length = getFieldBytesLength(fieldOrder);
797
+ return length + Math.ceil(length / 2);
798
+ }
799
+ function mapHashToField(key, fieldOrder, isLE2 = false) {
800
+ abytes2(key);
801
+ const len = key.length;
802
+ const fieldLen = getFieldBytesLength(fieldOrder);
803
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
804
+ if (len < minLen || len > 1024)
805
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
806
+ const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
807
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
808
+ return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
809
+ }
700
810
 
701
811
  // ../../node_modules/@noble/curves/abstract/curve.js
702
812
  var _0n3 = /* @__PURE__ */ BigInt(0);
703
813
  var _1n3 = /* @__PURE__ */ BigInt(1);
704
- function negateCt(condition, item) {
705
- const neg = item.negate();
706
- return condition ? neg : item;
814
+ var _4n2 = /* @__PURE__ */ BigInt(4);
815
+ var BLIND_BYTES = 16;
816
+ var BLIND_BITS = 128;
817
+ var FW_WINDOW = 5;
818
+ var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
819
+ function validatePointCons(Point) {
820
+ const pc = Point;
821
+ if (typeof pc !== "function")
822
+ throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
823
+ afunction(pc.fromAffine, "Point.fromAffine");
824
+ afunction(pc.fromBytes, "Point.fromBytes");
825
+ afunction(pc.fromHex, "Point.fromHex");
826
+ aobject2(pc.BASE, "Point.BASE");
827
+ aobject2(pc.ZERO, "Point.ZERO");
828
+ validateField(pc.Fp);
829
+ validateField(pc.Fn);
707
830
  }
708
831
  function normalizeZ(c, points) {
832
+ validatePointCons(c);
833
+ validateMSMPoints(points, c);
709
834
  const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
710
835
  return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
711
836
  }
712
- function validateW(W, bits) {
713
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
714
- throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
837
+ function validateW(W, bits, min = 1) {
838
+ if (!Number.isSafeInteger(W) || W < min || W > bits)
839
+ throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
840
+ }
841
+ function validateTableBytes(numPoints, fpBytes) {
842
+ const bytes = numPoints * (4 * fpBytes + 128);
843
+ if (bytes > TABLE_BYTES_MAX)
844
+ throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
845
+ }
846
+ function probeRandomBytes(randomBytes4, length) {
847
+ if (randomBytes4 === void 0)
848
+ return void 0;
849
+ afunction(randomBytes4, "randomBytes");
850
+ try {
851
+ const probe = randomBytes4(length);
852
+ if (!isBytes2(probe) || probe.length !== length)
853
+ return void 0;
854
+ } catch {
855
+ return void 0;
856
+ }
857
+ return randomBytes4;
858
+ }
859
+ function validateMSMPoints(points, c) {
860
+ aarray(points, "points");
861
+ points.forEach((p, i) => {
862
+ if (!(p instanceof c))
863
+ throw new Error("invalid point at index " + i);
864
+ });
865
+ }
866
+ function validateMSMScalars(scalars, field, maxScalar) {
867
+ if (!Array.isArray(scalars))
868
+ throw new Error("array of scalars expected");
869
+ scalars.forEach((s, i) => {
870
+ const ok = maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar;
871
+ if (!ok)
872
+ throw new Error("invalid scalar at index " + i);
873
+ });
715
874
  }
716
- function calcWOpts(W, scalarBits) {
717
- validateW(W, scalarBits);
718
- const windows = Math.ceil(scalarBits / W) + 1;
719
- const windowSize = 2 ** (W - 1);
720
- const maxNumber = 2 ** W;
721
- const mask = bitMask(W);
722
- const shiftBy = BigInt(W);
723
- return { windows, windowSize, mask, maxNumber, shiftBy };
724
- }
725
- function calcOffsets(n, window, wOpts) {
726
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
727
- let wbits = Number(n & mask);
728
- let nextN = n >> shiftBy;
729
- if (wbits > windowSize) {
730
- wbits -= maxNumber;
731
- nextN += _1n3;
732
- }
733
- const offsetStart = window * windowSize;
734
- const offset = offsetStart + Math.abs(wbits) - 1;
735
- const isZero = wbits === 0;
736
- const isNeg = wbits < 0;
737
- const isNegF = window % 2 !== 0;
738
- const offsetF = offsetStart;
739
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
740
- }
741
- var pointPrecomputes = /* @__PURE__ */ new WeakMap();
742
875
  var pointWindowSizes = /* @__PURE__ */ new WeakMap();
743
- function getW(P) {
876
+ function getWindowSize(P) {
744
877
  return pointWindowSizes.get(P) || 1;
745
878
  }
746
- function assert0(n) {
879
+ function oddMultiples(p, size) {
880
+ const dbl = p.double();
881
+ const t = [p];
882
+ for (let j = 1; j < size; j++)
883
+ t.push(t[j - 1].add(dbl));
884
+ return t;
885
+ }
886
+ function wnafDigits(n, W) {
887
+ const size = 2 ** W;
888
+ const half = size / 2;
889
+ const mask = BigInt(size - 1);
890
+ const d = [];
891
+ while (n > _0n3) {
892
+ let w = 0;
893
+ if (n & _1n3) {
894
+ w = Number(n & mask);
895
+ if (w >= half)
896
+ w -= size;
897
+ n -= BigInt(w);
898
+ }
899
+ d.push(w);
900
+ n >>= _1n3;
901
+ }
902
+ return d;
903
+ }
904
+ function signedWindowDigits(n, W, windows) {
905
+ const size = 2 ** W;
906
+ const half = size / 2;
907
+ const mask = BigInt(size - 1);
908
+ const shiftBy = BigInt(W);
909
+ const d = [];
910
+ for (let w = 0; w < windows; w++) {
911
+ let v = Number(n & mask);
912
+ n >>= shiftBy;
913
+ if (v > half) {
914
+ v -= size;
915
+ n += _1n3;
916
+ }
917
+ d.push(v);
918
+ }
747
919
  if (n !== _0n3)
748
- throw new Error("invalid wNAF");
920
+ throw new Error("invalid wnaf");
921
+ return d;
922
+ }
923
+ function wnafWalk(zero, tables, digits) {
924
+ let max = 0;
925
+ for (const d of digits)
926
+ max = Math.max(max, d.length);
927
+ let acc = zero;
928
+ for (let bit = max - 1; bit >= 0; bit--) {
929
+ if (bit !== max - 1)
930
+ acc = acc.double();
931
+ for (let i = 0; i < digits.length; i++) {
932
+ const w = digits[i][bit];
933
+ if (w) {
934
+ const item = tables[i][Math.abs(w) - 1 >> 1];
935
+ acc = acc.add(w < 0 ? item.negate() : item);
936
+ }
937
+ }
938
+ }
939
+ return acc;
749
940
  }
750
- var wNAF = class {
941
+ var ScalarMultiplier = class {
751
942
  // Parametrized with a given Point class (not individual point)
752
- constructor(Point, bits) {
943
+ constructor(Point, randomBytes4) {
944
+ __publicField(this, "Point");
753
945
  __publicField(this, "BASE");
754
946
  __publicField(this, "ZERO");
755
- __publicField(this, "Fn");
947
+ __publicField(this, "randomBytes");
948
+ __publicField(this, "wnafPrecomputes", /* @__PURE__ */ new WeakMap());
949
+ __publicField(this, "baseCanBeBlinded");
756
950
  __publicField(this, "bits");
951
+ validatePointCons(Point);
952
+ this.randomBytes = probeRandomBytes(randomBytes4, BLIND_BYTES);
953
+ this.Point = Point;
757
954
  this.BASE = Point.BASE;
758
955
  this.ZERO = Point.ZERO;
759
- this.Fn = Point.Fn;
760
- this.bits = bits;
761
- }
762
- // non-const time multiplication ladder
763
- _unsafeLadder(elm, n, p = this.ZERO) {
764
- let d = elm;
765
- while (n > _0n3) {
766
- if (n & _1n3)
767
- p = p.add(d);
768
- d = d.double();
769
- n >>= _1n3;
770
- }
771
- return p;
956
+ this.bits = Point.Fn.BITS;
772
957
  }
773
958
  /**
774
- * Creates a wNAF precomputation window. Used for caching.
775
- * Default window size is set by `utils.precompute()` and is equal to 8.
776
- * Number of precomputed points depends on the curve size:
777
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
778
- * - 𝑊 is the window size
779
- * - 𝑛 is the bitlength of the curve order.
780
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
959
+ * Creates a signed fixed-window wNAF precomputation table: for every window w, the
960
+ * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
961
+ * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
962
+ * window absorbs the final carry of signed-digit recoding.
963
+ * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
781
964
  * @param point - Point instance
782
965
  * @param W - window size
783
- * @returns precomputed point tables flattened to a single array
966
+ * @param bits - scalar bitlength the table must cover
784
967
  */
785
- precomputeWindow(point, W) {
786
- const { windows, windowSize } = calcWOpts(W, this.bits);
787
- const points = [];
788
- let p = point;
789
- let base = p;
790
- for (let window = 0; window < windows; window++) {
791
- base = p;
792
- points.push(base);
793
- for (let i = 1; i < windowSize; i++) {
794
- base = base.add(p);
795
- points.push(base);
968
+ buildWnafTable(point, W, bits) {
969
+ const windows = Math.ceil(bits / W) + 1;
970
+ const half = 2 ** (W - 1);
971
+ const comp = [];
972
+ let base = point;
973
+ for (let w = 0; w < windows; w++) {
974
+ let acc = base;
975
+ for (let i = 0; i < half; i++) {
976
+ comp.push(acc);
977
+ acc = acc.add(base);
796
978
  }
797
- p = base.double();
979
+ base = comp[comp.length - 1].double();
798
980
  }
799
- return points;
981
+ return { W, bits, windows, comp };
800
982
  }
801
983
  /**
802
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
803
- * More compact implementation:
804
- * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
984
+ * Implements ec multiplication using precomputed signed fixed-window wNAF tables.
985
+ * Constant-time: fixed window count with one table addition per window — zero digits feed
986
+ * the fake accumulator — and no doublings; the lookup scans the whole window slice.
987
+ * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
988
+ * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
989
+ * signedWindowDigits throws if `n` exceeds the table.
805
990
  * @returns real and fake (for const-time) points
806
991
  */
807
- wNAF(W, precomputes, n) {
808
- if (!this.Fn.isValid(n))
809
- throw new Error("invalid scalar");
992
+ wnafCachedCT(precomputes, n) {
993
+ const { W, windows, comp } = precomputes;
994
+ const half = 2 ** (W - 1);
995
+ const digits = signedWindowDigits(n, W, windows);
810
996
  let p = this.ZERO;
811
997
  let f = this.BASE;
812
- const wo = calcWOpts(W, this.bits);
813
- for (let window = 0; window < wo.windows; window++) {
814
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
815
- n = nextN;
816
- if (isZero) {
817
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
818
- } else {
819
- p = p.add(negateCt(isNeg, precomputes[offset]));
820
- }
998
+ for (let w = 0; w < windows; w++) {
999
+ const digit = digits[w];
1000
+ const start = w * half;
1001
+ const idx = Math.abs(digit) - 1;
1002
+ let sel = comp[start];
1003
+ for (let i = 1; i < half; i++)
1004
+ sel = i === idx ? comp[start + i] : sel;
1005
+ const neg = sel.negate();
1006
+ if (digit === 0)
1007
+ f = f.add(comp[start]);
1008
+ else
1009
+ p = p.add(digit < 0 ? neg : sel);
821
1010
  }
822
- assert0(n);
823
1011
  return { p, f };
824
1012
  }
825
- /**
826
- * Implements unsafe EC multiplication using precomputed tables
827
- * and w-ary non-adjacent form.
828
- * @param acc - accumulator point to add result of multiplication
829
- * @returns point
830
- */
831
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
832
- const wo = calcWOpts(W, this.bits);
833
- for (let window = 0; window < wo.windows; window++) {
834
- if (n === _0n3)
835
- break;
836
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
837
- n = nextN;
838
- if (isZero) {
839
- continue;
840
- } else {
841
- const item = precomputes[offset];
842
- acc = acc.add(isNeg ? item.negate() : item);
843
- }
844
- }
845
- assert0(n);
846
- return acc;
847
- }
848
- getPrecomputes(W, point, transform) {
849
- let comp = pointPrecomputes.get(point);
1013
+ // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
1014
+ // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
1015
+ // incompatible `transform(...)` layouts and expect a separate cache entry.
1016
+ getWnafPrecomputes(W, point, bits, transform) {
1017
+ let entries = this.wnafPrecomputes.get(point);
1018
+ let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
850
1019
  if (!comp) {
851
- comp = this.precomputeWindow(point, W);
852
- if (W !== 1) {
853
- if (typeof transform === "function")
854
- comp = transform(comp);
855
- pointPrecomputes.set(point, comp);
1020
+ comp = this.buildWnafTable(point, W, bits);
1021
+ if (typeof transform === "function")
1022
+ comp = { ...comp, comp: transform(comp.comp) };
1023
+ if (!entries) {
1024
+ entries = [];
1025
+ this.wnafPrecomputes.set(point, entries);
856
1026
  }
1027
+ entries.push(comp);
857
1028
  }
858
1029
  return comp;
859
1030
  }
860
- cached(point, scalar, transform) {
861
- const W = getW(point);
862
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1031
+ assertPoint(point) {
1032
+ if (!(point instanceof this.Point))
1033
+ throw new TypeError('"point" expected Point instance, got type=' + typeof point);
1034
+ }
1035
+ // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
1036
+ // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
1037
+ // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
1038
+ validateMulInput(point, scalar) {
1039
+ this.assertPoint(point);
1040
+ if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
1041
+ throw new Error("invalid scalar");
863
1042
  }
864
- unsafe(point, scalar, transform, prev) {
865
- const W = getW(point);
1043
+ // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
1044
+ // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
1045
+ // multiply. `n` must be < 2^bits.
1046
+ runCT(point, n, bits, transform) {
1047
+ const W = getWindowSize(point);
866
1048
  if (W === 1)
867
- return this._unsafeLadder(point, scalar, prev);
868
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1049
+ return this.fixedWindowCT(point, n, bits);
1050
+ return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
1051
+ }
1052
+ mulCT(point, scalar, transform) {
1053
+ this.validateMulInput(point, scalar);
1054
+ return this.runCT(point, scalar, this.bits, transform);
1055
+ }
1056
+ mulCTBlinded(point, scalar, transform) {
1057
+ this.validateMulInput(point, scalar);
1058
+ if (this.randomBytes === void 0)
1059
+ throw new Error("randomBytes is required for scalar blinding");
1060
+ const bits = this.Point.Fn.BITS + BLIND_BITS;
1061
+ const blind = this.randomBytes(BLIND_BYTES);
1062
+ if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
1063
+ throw new Error("randomBytes returned invalid byte array");
1064
+ blind[0] = blind[0] & 63 | 128;
1065
+ const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
1066
+ return this.runCT(point, n, bits, transform);
869
1067
  }
870
- // We calculate precomputes for elliptic curve point multiplication
871
- // using windowed method. This specifies window size and
872
- // stores precomputed values. Usually only base point would be precomputed.
873
- createCache(P, W) {
1068
+ /**
1069
+ * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
1070
+ * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
1071
+ * far cheaper to build for a single use. The point-operation sequence is independent of `n`:
1072
+ * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
1073
+ * every table entry, and one addition (adds the identity when the window digit is 0 — never
1074
+ * skipped).
1075
+ *
1076
+ * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
1077
+ * add), which holds for the Weierstrass/Edwards point types used here. The table is left in
1078
+ * projective form (no normalizeZ): normalizing this small a table costs more than the
1079
+ * mixed-add savings it would buy for a single multiply.
1080
+ * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
1081
+ * (this path needs no fake accumulator — its op-count is already scalar-independent).
1082
+ */
1083
+ fixedWindowCT(point, n, bits) {
1084
+ const W = FW_WINDOW;
1085
+ const size = 1 << W;
1086
+ const mask = bitMask(W);
1087
+ const table = new Array(size);
1088
+ table[0] = this.ZERO;
1089
+ for (let i = 1; i < size; i++)
1090
+ table[i] = table[i - 1].add(point);
1091
+ const windows = Math.ceil(bits / W);
1092
+ let acc = this.ZERO;
1093
+ for (let window = windows - 1; window >= 0; window--) {
1094
+ if (window !== windows - 1)
1095
+ for (let d = 0; d < W; d++)
1096
+ acc = acc.double();
1097
+ const digit = Number(n >> BigInt(window * W) & mask);
1098
+ let sel = table[0];
1099
+ for (let i = 1; i < size; i++)
1100
+ sel = i === digit ? table[i] : sel;
1101
+ acc = acc.add(sel);
1102
+ }
1103
+ return { p: acc, f: acc };
1104
+ }
1105
+ shouldBlind(point, cofactor) {
1106
+ if (this.randomBytes === void 0)
1107
+ return false;
1108
+ if (cofactor === _1n3)
1109
+ return true;
1110
+ if (point !== this.BASE)
1111
+ return false;
1112
+ if (this.baseCanBeBlinded === void 0)
1113
+ this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
1114
+ return this.baseCanBeBlinded;
1115
+ }
1116
+ mulSecret(point, scalar, cofactor, transform) {
1117
+ return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
1118
+ }
1119
+ mulUnsafe(point, scalar, transform) {
1120
+ this.assertPoint(point);
1121
+ if (!isPosBig(scalar))
1122
+ throw new Error("invalid scalar");
1123
+ const W = getWindowSize(point);
1124
+ if (W === 1 || scalar >= this.Point.Fn.ORDER)
1125
+ return mulAddUnsafe(this.Point, [point], [scalar], true);
1126
+ const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
1127
+ return this.wnafCachedCT(precomputes, scalar).p;
1128
+ }
1129
+ // Remembers the window size used for precomputed wNAF multiplication of the given point
1130
+ // and drops any previously built tables. Usually only the base point is precomputed.
1131
+ // W=1 resets the point to the un-precomputed (table-less) paths.
1132
+ // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
1133
+ setWindowSize(point, W) {
1134
+ this.assertPoint(point);
874
1135
  validateW(W, this.bits);
875
- pointWindowSizes.set(P, W);
876
- pointPrecomputes.delete(P);
1136
+ const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
1137
+ validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
1138
+ pointWindowSizes.set(point, W);
1139
+ this.wnafPrecomputes.delete(point);
877
1140
  }
878
- hasCache(elm) {
879
- return getW(elm) !== 1;
1141
+ // True when a window size is set: tables themselves are built lazily on first multiply.
1142
+ hasWindowSize(point) {
1143
+ return getWindowSize(point) !== 1;
880
1144
  }
881
1145
  };
1146
+ function mulAddUnsafe(c, points, scalars, allowOversized = false) {
1147
+ validatePointCons(c);
1148
+ validateMSMPoints(points, c);
1149
+ abool2(allowOversized, "allowOversized");
1150
+ validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
1151
+ if (points.length !== scalars.length)
1152
+ throw new Error("arrays of points and scalars must have equal length");
1153
+ const tables = points.map((p) => oddMultiples(p, 4));
1154
+ const digits = scalars.map((n) => wnafDigits(n, 4));
1155
+ return wnafWalk(c.ZERO, tables, digits);
1156
+ }
882
1157
  function createField(order, field, isLE2) {
883
1158
  if (field) {
884
1159
  if (field.ORDER !== order)
@@ -890,13 +1165,16 @@ function createField(order, field, isLE2) {
890
1165
  }
891
1166
  }
892
1167
  function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1168
+ if (type !== "weierstrass" && type !== "edwards")
1169
+ throw new Error('expected curve type "weierstrass" or "edwards"');
893
1170
  if (FpFnLE === void 0)
894
1171
  FpFnLE = type === "edwards";
895
1172
  if (!CURVE || typeof CURVE !== "object")
896
1173
  throw new Error(`expected valid ${type} CURVE object`);
1174
+ validateObject(curveOpts);
897
1175
  for (const p of ["p", "n", "h"]) {
898
1176
  const val = CURVE[p];
899
- if (!(typeof val === "bigint" && val > _0n3))
1177
+ if (!(isPosBig(val) && val !== _0n3))
900
1178
  throw new Error(`CURVE.${p} must be positive bigint`);
901
1179
  }
902
1180
  const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
@@ -921,6 +1199,7 @@ function createKeygen(randomSecretKey, getPublicKey) {
921
1199
  var _0n4 = /* @__PURE__ */ BigInt(0);
922
1200
  var _1n4 = /* @__PURE__ */ BigInt(1);
923
1201
  var _2n2 = /* @__PURE__ */ BigInt(2);
1202
+ var _4n3 = /* @__PURE__ */ BigInt(4);
924
1203
  var _8n2 = /* @__PURE__ */ BigInt(8);
925
1204
  function isEdValidXY(Fp2, CURVE, x, y) {
926
1205
  const x2 = Fp2.sqr(x);
@@ -930,14 +1209,24 @@ function isEdValidXY(Fp2, CURVE, x, y) {
930
1209
  return Fp2.eql(left, right);
931
1210
  }
932
1211
  function edwards(params, extraOpts = {}) {
1212
+ validateObject(extraOpts, {}, {}, "extraOpts");
933
1213
  const opts2 = extraOpts;
934
1214
  const validated = createCurveFields("edwards", params, opts2, opts2.FpFnLE);
935
1215
  const { Fp: Fp2, Fn: Fn2 } = validated;
936
1216
  let CURVE = validated.CURVE;
937
1217
  const { h: cofactor } = CURVE;
938
- validateObject(opts2, {}, { uvRatio: "function" });
939
- const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
940
- const modP = (n) => Fp2.create(n);
1218
+ if (FpLegendre(Fp2, CURVE.a) !== 1)
1219
+ throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
1220
+ if (FpLegendre(Fp2, CURVE.d) !== -1)
1221
+ throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
1222
+ validateObject(opts2, {}, { uvRatio: "function", randomBytes: "function" });
1223
+ const randomBytes4 = opts2.randomBytes === void 0 ? randomBytes2 : opts2.randomBytes;
1224
+ const MASK = _2n2 << BigInt(Fp2.BYTES * 8) - _1n4;
1225
+ function isOdd(n) {
1226
+ if (!Fp2.isOdd)
1227
+ throw new Error("Field does not have .isOdd()");
1228
+ return Fp2.isOdd(n);
1229
+ }
941
1230
  const uvRatio2 = opts2.uvRatio === void 0 ? (u, v) => {
942
1231
  try {
943
1232
  return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
@@ -947,6 +1236,7 @@ function edwards(params, extraOpts = {}) {
947
1236
  } : opts2.uvRatio;
948
1237
  if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
949
1238
  throw new Error("bad curve params: generator point");
1239
+ const mulA = Fp2.eql(CURVE.a, Fp2.neg(Fp2.ONE)) ? (x) => Fp2.neg(x) : Fp2.eql(CURVE.a, Fp2.ONE) ? (x) => x : (x) => Fp2.mul(CURVE.a, x);
950
1240
  function acoord(title, n, banZero = false) {
951
1241
  const min = banZero ? _1n4 : _0n4;
952
1242
  aInRange("coordinate " + title, n, min, MASK);
@@ -982,32 +1272,32 @@ function edwards(params, extraOpts = {}) {
982
1272
  const { x, y } = p || {};
983
1273
  acoord("x", x);
984
1274
  acoord("y", y);
985
- return new _Point(x, y, _1n4, modP(x * y));
1275
+ return new _Point(x, y, Fp2.ONE, Fp2.mul(x, y));
986
1276
  }
987
1277
  // Uses algo from RFC8032 5.1.3.
988
1278
  static fromBytes(bytes, zip215 = false) {
989
1279
  const len = Fp2.BYTES;
990
1280
  const { a, d } = CURVE;
991
1281
  bytes = copyBytes(abytes2(bytes, len, "point"));
992
- abool(zip215, "zip215");
1282
+ abool2(zip215, "zip215");
993
1283
  const normed = copyBytes(bytes);
994
1284
  const lastByte = bytes[len - 1];
995
1285
  normed[len - 1] = lastByte & ~128;
996
1286
  const y = bytesToNumberLE(normed);
997
1287
  const max = zip215 ? MASK : Fp2.ORDER;
998
1288
  aInRange("point.y", y, _0n4, max);
999
- const y2 = modP(y * y);
1000
- const u = modP(y2 - _1n4);
1001
- const v = modP(d * y2 - a);
1289
+ const y2 = Fp2.sqr(y);
1290
+ const u = Fp2.sub(y2, Fp2.ONE);
1291
+ const v = Fp2.sub(Fp2.mulN(d, y2), a);
1002
1292
  let { isValid, value: x } = uvRatio2(u, v);
1003
1293
  if (!isValid)
1004
1294
  throw new Error("bad point: invalid y coordinate");
1005
- const isXOdd = (x & _1n4) === _1n4;
1295
+ const isXOdd = isOdd(x);
1006
1296
  const isLastByteOdd = (lastByte & 128) !== 0;
1007
- if (!zip215 && x === _0n4 && isLastByteOdd)
1297
+ if (!zip215 && Fp2.is0(x) && isLastByteOdd)
1008
1298
  throw new Error("bad point: x=0 and x_0=1");
1009
1299
  if (isLastByteOdd !== isXOdd)
1010
- x = modP(-x);
1300
+ x = Fp2.neg(x);
1011
1301
  return _Point.fromAffine({ x, y });
1012
1302
  }
1013
1303
  static fromHex(hex, zip215 = false) {
@@ -1019,8 +1309,8 @@ function edwards(params, extraOpts = {}) {
1019
1309
  get y() {
1020
1310
  return this.toAffine().y;
1021
1311
  }
1022
- precompute(windowSize = 8, isLazy = true) {
1023
- wnaf.createCache(this, windowSize);
1312
+ precompute(windowSize = 6, isLazy = true) {
1313
+ wnaf.setWindowSize(this, windowSize);
1024
1314
  if (!isLazy)
1025
1315
  this.multiply(_2n2);
1026
1316
  return this;
@@ -1032,18 +1322,18 @@ function edwards(params, extraOpts = {}) {
1032
1322
  if (p.is0())
1033
1323
  throw new Error("bad point: ZERO");
1034
1324
  const { X, Y, Z, T } = p;
1035
- const X2 = modP(X * X);
1036
- const Y2 = modP(Y * Y);
1037
- const Z2 = modP(Z * Z);
1038
- const Z4 = modP(Z2 * Z2);
1039
- const aX2 = modP(X2 * a);
1040
- const left = modP(Z2 * modP(aX2 + Y2));
1041
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1042
- if (left !== right)
1325
+ const X2 = Fp2.sqr(X);
1326
+ const Y2 = Fp2.sqr(Y);
1327
+ const Z2 = Fp2.sqr(Z);
1328
+ const Z4 = Fp2.sqr(Z2);
1329
+ const aX2 = Fp2.mul(X2, a);
1330
+ const left = Fp2.mul(Fp2.add(aX2, Y2), Z2);
1331
+ const right = Fp2.add(Z4, Fp2.mul(d, Fp2.mul(X2, Y2)));
1332
+ if (!Fp2.eql(left, right))
1043
1333
  throw new Error("bad point: equation left != right (1)");
1044
- const XY = modP(X * Y);
1045
- const ZT = modP(Z * T);
1046
- if (XY !== ZT)
1334
+ const XY = Fp2.mul(X, Y);
1335
+ const ZT = Fp2.mul(Z, T);
1336
+ if (!Fp2.eql(XY, ZT))
1047
1337
  throw new Error("bad point: equation left != right (2)");
1048
1338
  }
1049
1339
  // Compare one point to another.
@@ -1051,37 +1341,36 @@ function edwards(params, extraOpts = {}) {
1051
1341
  aedpoint(other);
1052
1342
  const { X: X1, Y: Y1, Z: Z1 } = this;
1053
1343
  const { X: X2, Y: Y2, Z: Z2 } = other;
1054
- const X1Z2 = modP(X1 * Z2);
1055
- const X2Z1 = modP(X2 * Z1);
1056
- const Y1Z2 = modP(Y1 * Z2);
1057
- const Y2Z1 = modP(Y2 * Z1);
1058
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1344
+ const X1Z2 = Fp2.mul(X1, Z2);
1345
+ const X2Z1 = Fp2.mul(X2, Z1);
1346
+ const Y1Z2 = Fp2.mul(Y1, Z2);
1347
+ const Y2Z1 = Fp2.mul(Y2, Z1);
1348
+ return Fp2.eql(X1Z2, X2Z1) && Fp2.eql(Y1Z2, Y2Z1);
1059
1349
  }
1060
1350
  is0() {
1061
1351
  return this.equals(_Point.ZERO);
1062
1352
  }
1063
1353
  negate() {
1064
- return new _Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1354
+ return new _Point(Fp2.neg(this.X), this.Y, this.Z, Fp2.neg(this.T));
1065
1355
  }
1066
1356
  // Fast algo for doubling Extended Point.
1067
1357
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1068
1358
  // Cost: 4M + 4S + 1*a + 6add + 1*2.
1069
1359
  double() {
1070
- const { a } = CURVE;
1071
1360
  const { X: X1, Y: Y1, Z: Z1 } = this;
1072
- const A = modP(X1 * X1);
1073
- const B = modP(Y1 * Y1);
1074
- const C = modP(_2n2 * modP(Z1 * Z1));
1075
- const D = modP(a * A);
1076
- const x1y1 = X1 + Y1;
1077
- const E = modP(modP(x1y1 * x1y1) - A - B);
1078
- const G = D + B;
1079
- const F2 = G - C;
1080
- const H = D - B;
1081
- const X3 = modP(E * F2);
1082
- const Y3 = modP(G * H);
1083
- const T3 = modP(E * H);
1084
- const Z3 = modP(F2 * G);
1361
+ const A = Fp2.sqr(X1);
1362
+ const B2 = Fp2.sqr(Y1);
1363
+ const C = Fp2.mul(Fp2.sqr(Z1), _2n2);
1364
+ const D = mulA(A);
1365
+ const x1y1 = Fp2.addN(X1, Y1);
1366
+ const E = Fp2.sub(Fp2.subN(Fp2.sqr(x1y1), A), B2);
1367
+ const G = Fp2.addN(D, B2);
1368
+ const F2 = Fp2.subN(G, C);
1369
+ const H = Fp2.subN(D, B2);
1370
+ const X3 = Fp2.mul(E, F2);
1371
+ const Y3 = Fp2.mul(G, H);
1372
+ const T3 = Fp2.mul(E, H);
1373
+ const Z3 = Fp2.mul(F2, G);
1085
1374
  return new _Point(X3, Y3, Z3, T3);
1086
1375
  }
1087
1376
  // Fast algo for adding 2 Extended Points.
@@ -1089,21 +1378,21 @@ function edwards(params, extraOpts = {}) {
1089
1378
  // Cost: 9M + 1*a + 1*d + 7add.
1090
1379
  add(other) {
1091
1380
  aedpoint(other);
1092
- const { a, d } = CURVE;
1381
+ const { d } = CURVE;
1093
1382
  const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1094
1383
  const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1095
- const A = modP(X1 * X2);
1096
- const B = modP(Y1 * Y2);
1097
- const C = modP(T1 * d * T2);
1098
- const D = modP(Z1 * Z2);
1099
- const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1100
- const F2 = D - C;
1101
- const G = D + C;
1102
- const H = modP(B - a * A);
1103
- const X3 = modP(E * F2);
1104
- const Y3 = modP(G * H);
1105
- const T3 = modP(E * H);
1106
- const Z3 = modP(F2 * G);
1384
+ const A = Fp2.mul(X1, X2);
1385
+ const B2 = Fp2.mul(Y1, Y2);
1386
+ const C = Fp2.mul(Fp2.mulN(T1, d), T2);
1387
+ const D = Fp2.mul(Z1, Z2);
1388
+ const E = Fp2.sub(Fp2.subN(Fp2.mulN(Fp2.addN(X1, Y1), Fp2.addN(X2, Y2)), A), B2);
1389
+ const F2 = Fp2.subN(D, C);
1390
+ const G = Fp2.addN(D, C);
1391
+ const H = Fp2.sub(B2, mulA(A));
1392
+ const X3 = Fp2.mul(E, F2);
1393
+ const Y3 = Fp2.mul(G, H);
1394
+ const T3 = Fp2.mul(E, H);
1395
+ const Z3 = Fp2.mul(F2, G);
1107
1396
  return new _Point(X3, Y3, Z3, T3);
1108
1397
  }
1109
1398
  subtract(other) {
@@ -1114,8 +1403,8 @@ function edwards(params, extraOpts = {}) {
1114
1403
  multiply(scalar) {
1115
1404
  if (!Fn2.isValidNot0(scalar))
1116
1405
  throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1117
- const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(_Point, p2));
1118
- return normalizeZ(_Point, [p, f])[0];
1406
+ const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
1407
+ return normalize([p, f])[0];
1119
1408
  }
1120
1409
  // Non-constant-time multiplication. Uses double-and-add algorithm.
1121
1410
  // It's faster, but should only be used when you don't care about
@@ -1129,7 +1418,7 @@ function edwards(params, extraOpts = {}) {
1129
1418
  return _Point.ZERO;
1130
1419
  if (this.is0() || scalar === _1n4)
1131
1420
  return this;
1132
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(_Point, p));
1421
+ return wnaf.mulUnsafe(this, scalar, normalize);
1133
1422
  }
1134
1423
  // Checks if point is of small order.
1135
1424
  // If you add something to small order point, you will have "dirty"
@@ -1141,35 +1430,43 @@ function edwards(params, extraOpts = {}) {
1141
1430
  // Multiplies point by curve order and checks if the result is 0.
1142
1431
  // Returns `false` is the point is dirty.
1143
1432
  isTorsionFree() {
1144
- return wnaf.unsafe(this, CURVE.n).is0();
1433
+ return wnaf.mulUnsafe(this, CURVE.n).is0();
1145
1434
  }
1146
1435
  // Converts Extended point to default (x, y) coordinates.
1147
1436
  // Can accept precomputed Z^-1 - for example, from invertBatch.
1148
1437
  toAffine(invertedZ) {
1149
1438
  const p = this;
1150
1439
  let iz = invertedZ;
1440
+ if (iz != null && typeof iz !== "bigint")
1441
+ throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
1151
1442
  const { X, Y, Z } = p;
1152
1443
  const is0 = p.is0();
1153
1444
  if (iz == null)
1154
- iz = is0 ? _8n2 : Fp2.inv(Z);
1155
- const x = modP(X * iz);
1156
- const y = modP(Y * iz);
1445
+ iz = is0 ? Fp2.create(_8n2) : Fp2.inv(Z);
1446
+ const x = Fp2.mul(X, iz);
1447
+ const y = Fp2.mul(Y, iz);
1157
1448
  const zz = Fp2.mul(Z, iz);
1158
1449
  if (is0)
1159
- return { x: _0n4, y: _1n4 };
1160
- if (zz !== _1n4)
1450
+ return { x: Fp2.ZERO, y: Fp2.ONE };
1451
+ if (!Fp2.eql(zz, Fp2.ONE))
1161
1452
  throw new Error("invZ was invalid");
1162
1453
  return { x, y };
1163
1454
  }
1164
1455
  clearCofactor() {
1165
1456
  if (cofactor === _1n4)
1166
1457
  return this;
1458
+ if (cofactor === _2n2)
1459
+ return this.double();
1460
+ if (cofactor === _4n3)
1461
+ return this.double().double();
1462
+ if (cofactor === _8n2)
1463
+ return this.double().double().double();
1167
1464
  return this.multiplyUnsafe(cofactor);
1168
1465
  }
1169
1466
  toBytes() {
1170
1467
  const { x, y } = this.toAffine();
1171
1468
  const bytes = Fp2.toBytes(y);
1172
- bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1469
+ bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
1173
1470
  return bytes;
1174
1471
  }
1175
1472
  toHex() {
@@ -1179,19 +1476,15 @@ function edwards(params, extraOpts = {}) {
1179
1476
  return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1180
1477
  }
1181
1478
  };
1182
- // base / generator point
1183
- __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy)));
1184
- // zero / infinity / identity point
1185
- __publicField(_Point, "ZERO", new _Point(_0n4, _1n4, _1n4, _0n4));
1186
- // 0, 1, 1, 0
1187
- // math field
1479
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp2.ONE, Fp2.mul(CURVE.Gx, CURVE.Gy)));
1480
+ __publicField(_Point, "ZERO", new _Point(Fp2.ZERO, Fp2.ONE, Fp2.ONE, Fp2.ZERO));
1188
1481
  __publicField(_Point, "Fp", Fp2);
1189
- // scalar field
1190
1482
  __publicField(_Point, "Fn", Fn2);
1191
1483
  let Point = _Point;
1192
- const wnaf = new wNAF(Point, Fn2.BITS);
1193
- if (Fn2.BITS >= 8)
1194
- Point.BASE.precompute(8);
1484
+ const normalize = (points) => normalizeZ(Point, points);
1485
+ const wnaf = new ScalarMultiplier(Point, randomBytes4);
1486
+ if (wnaf.bits >= 6)
1487
+ Point.BASE.precompute(6);
1195
1488
  Object.freeze(Point.prototype);
1196
1489
  Object.freeze(Point);
1197
1490
  return Point;
@@ -1278,9 +1571,21 @@ __publicField(PrimeEdwardsPoint, "Fp");
1278
1571
  __publicField(PrimeEdwardsPoint, "Fn");
1279
1572
 
1280
1573
  // ../../node_modules/@noble/curves/abstract/montgomery.js
1281
- var _0n5 = BigInt(0);
1282
- var _1n5 = BigInt(1);
1283
- var _2n3 = BigInt(2);
1574
+ var _0n5 = /* @__PURE__ */ BigInt(0);
1575
+ var _1n5 = /* @__PURE__ */ BigInt(1);
1576
+ var _2n3 = /* @__PURE__ */ BigInt(2);
1577
+ function cmask(P, swap) {
1578
+ return P + swap - (swap >> _1n5 << _1n5);
1579
+ }
1580
+ function cswap(P) {
1581
+ const offset = BigInt(6) * P;
1582
+ return (mask, x_2, x_3) => {
1583
+ const sum = x_2 + x_3;
1584
+ const d = offset + x_3 - x_2;
1585
+ const a = (d * mask + x_2) % P;
1586
+ return { x_2: a, x_3: sum - a };
1587
+ };
1588
+ }
1284
1589
  function validateOpts(curve) {
1285
1590
  validateObject(curve, {
1286
1591
  P: "bigint",
@@ -1288,23 +1593,26 @@ function validateOpts(curve) {
1288
1593
  adjustScalarBytes: "function",
1289
1594
  powPminus2: "function"
1290
1595
  }, {
1291
- randomBytes: "function"
1596
+ randomBytes: "function",
1597
+ scalarMultBase: "function"
1292
1598
  });
1293
1599
  return Object.freeze({ ...curve });
1294
1600
  }
1295
1601
  function montgomery(curveDef) {
1296
1602
  const CURVE = validateOpts(curveDef);
1297
1603
  const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
1604
+ const mulBaseHook = CURVE.scalarMultBase;
1298
1605
  const is25519 = type === "x25519";
1299
1606
  if (!is25519 && type !== "x448")
1300
1607
  throw new Error("invalid type");
1301
1608
  const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
1302
1609
  const montgomeryBits = is25519 ? 255 : 448;
1610
+ const swap = cswap(P);
1303
1611
  const fieldLen = is25519 ? 32 : 56;
1304
1612
  const Gu = is25519 ? BigInt(9) : BigInt(5);
1305
1613
  const a24 = is25519 ? BigInt(121665) : BigInt(39081);
1306
1614
  const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
1307
- const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
1615
+ const maxAdded = is25519 ? BigInt(8) * (_2n3 ** BigInt(251) - _1n5) : BigInt(4) * (_2n3 ** BigInt(445) - _1n5);
1308
1616
  const maxScalar = minScalar + maxAdded + _1n5;
1309
1617
  const modP = (n) => mod(n, P);
1310
1618
  const GuBytes = encodeU(Gu);
@@ -1320,23 +1628,34 @@ function montgomery(curveDef) {
1320
1628
  function decodeScalar(scalar) {
1321
1629
  return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
1322
1630
  }
1631
+ const lowOrderU = new Set(is25519 ? [
1632
+ _0n5,
1633
+ _1n5,
1634
+ P - _1n5,
1635
+ BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),
1636
+ BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")
1637
+ ] : [_0n5, _1n5, P - _1n5]);
1323
1638
  function scalarMult(scalar, u) {
1324
- const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
1639
+ const pointU = decodeU(u);
1640
+ if (lowOrderU.has(pointU))
1641
+ throw new Error("invalid private or public key received");
1642
+ const pu = montgomeryLadder(pointU, decodeScalar(scalar));
1325
1643
  if (pu === _0n5)
1326
1644
  throw new Error("invalid private or public key received");
1327
1645
  return encodeU(pu);
1328
1646
  }
1329
1647
  function scalarMultBase(scalar) {
1330
- return scalarMult(scalar, GuBytes);
1648
+ if (mulBaseHook === void 0)
1649
+ return scalarMult(scalar, GuBytes);
1650
+ const k = decodeScalar(scalar);
1651
+ aInRange("scalar", k, minScalar, maxScalar);
1652
+ const pu = modP(mulBaseHook(k));
1653
+ if (pu === _0n5)
1654
+ throw new Error("invalid private or public key received");
1655
+ return encodeU(pu);
1331
1656
  }
1332
1657
  const getPublicKey = scalarMultBase;
1333
1658
  const getSharedSecret = scalarMult;
1334
- function cswap(swap, x_2, x_3) {
1335
- const dummy = modP(swap * (x_2 - x_3));
1336
- x_2 = modP(x_2 - dummy);
1337
- x_3 = modP(x_3 + dummy);
1338
- return { x_2, x_3 };
1339
- }
1340
1659
  function montgomeryLadder(u, scalar) {
1341
1660
  aInRange("u", u, _0n5, P);
1342
1661
  aInRange("scalar", scalar, minScalar, maxScalar);
@@ -1346,22 +1665,20 @@ function montgomery(curveDef) {
1346
1665
  let z_2 = _0n5;
1347
1666
  let x_3 = u;
1348
1667
  let z_3 = _1n5;
1349
- let swap = _0n5;
1668
+ const kx = k ^ k >> _1n5;
1350
1669
  for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
1351
- const k_t = k >> t & _1n5;
1352
- swap ^= k_t;
1353
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1354
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1355
- swap = k_t;
1670
+ const mask2 = cmask(P, kx >> t);
1671
+ ({ x_2, x_3 } = swap(mask2, x_2, x_3));
1672
+ ({ x_2: z_2, x_3: z_3 } = swap(mask2, z_2, z_3));
1356
1673
  const A = x_2 + z_2;
1357
1674
  const AA = modP(A * A);
1358
- const B = x_2 - z_2;
1359
- const BB = modP(B * B);
1675
+ const B2 = x_2 - z_2;
1676
+ const BB = modP(B2 * B2);
1360
1677
  const E = AA - BB;
1361
1678
  const C = x_3 + z_3;
1362
1679
  const D = x_3 - z_3;
1363
1680
  const DA = modP(D * A);
1364
- const CB = modP(C * B);
1681
+ const CB = modP(C * B2);
1365
1682
  const dacb = DA + CB;
1366
1683
  const da_cb = DA - CB;
1367
1684
  x_3 = modP(dacb * dacb);
@@ -1369,8 +1686,9 @@ function montgomery(curveDef) {
1369
1686
  x_2 = modP(AA * BB);
1370
1687
  z_2 = modP(E * (AA + modP(a24 * E)));
1371
1688
  }
1372
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1373
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1689
+ const mask = cmask(P, k);
1690
+ ({ x_2, x_3 } = swap(mask, x_2, x_3));
1691
+ ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));
1374
1692
  const z2 = powPminus2(z_2);
1375
1693
  return modP(x_2 * z2);
1376
1694
  }
@@ -1399,6 +1717,49 @@ function montgomery(curveDef) {
1399
1717
  });
1400
1718
  }
1401
1719
 
1720
+ // ../../node_modules/@noble/hashes/_u64.js
1721
+ var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
1722
+ var _32n = /* @__PURE__ */ BigInt(32);
1723
+ function fromBig(n, le = false) {
1724
+ if (le)
1725
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
1726
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1727
+ }
1728
+ function split(lst, le = false) {
1729
+ const len = lst.length;
1730
+ let Ah = new Uint32Array(len);
1731
+ let Al = new Uint32Array(len);
1732
+ for (let i = 0; i < len; i++) {
1733
+ const { h, l } = fromBig(lst[i], le);
1734
+ [Ah[i], Al[i]] = [h, l];
1735
+ }
1736
+ return [Ah, Al];
1737
+ }
1738
+ var fromNumH = (n) => n / 2 ** 32 | 0;
1739
+ var fromNumL = (n) => n >>> 0;
1740
+ function setU64FromNum(view, byteOffset, n, isLE2) {
1741
+ const h = fromNumH(n);
1742
+ const l = fromNumL(n);
1743
+ view.setUint32(byteOffset, isLE2 ? l : h, isLE2);
1744
+ view.setUint32(byteOffset + 4, isLE2 ? h : l, isLE2);
1745
+ }
1746
+ var shrSH = (h, _l, s) => h >>> s;
1747
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
1748
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
1749
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
1750
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
1751
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
1752
+ function add(Ah, Al, Bh, Bl) {
1753
+ const l = (Al >>> 0) + (Bl >>> 0);
1754
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
1755
+ }
1756
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1757
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1758
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1759
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1760
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1761
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1762
+
1402
1763
  // ../../node_modules/@noble/hashes/_md.js
1403
1764
  var HashMD = class {
1404
1765
  constructor(blockLen, outputLen, padOffset, isLE2) {
@@ -1426,24 +1787,28 @@ var HashMD = class {
1426
1787
  abytes(data);
1427
1788
  const { view, buffer, blockLen } = this;
1428
1789
  const len = data.length;
1790
+ let processed = false;
1429
1791
  for (let pos = 0; pos < len; ) {
1430
1792
  const take = Math.min(blockLen - this.pos, len - pos);
1431
1793
  if (take === blockLen) {
1432
1794
  const dataView = createView(data);
1433
1795
  for (; blockLen <= len - pos; pos += blockLen)
1434
1796
  this.process(dataView, pos);
1797
+ processed = true;
1435
1798
  continue;
1436
1799
  }
1437
- buffer.set(data.subarray(pos, pos + take), this.pos);
1800
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
1438
1801
  this.pos += take;
1439
1802
  pos += take;
1440
1803
  if (this.pos === blockLen) {
1441
1804
  this.process(view, 0);
1442
1805
  this.pos = 0;
1806
+ processed = true;
1443
1807
  }
1444
1808
  }
1445
1809
  this.length += data.length;
1446
- this.roundClean();
1810
+ if (processed)
1811
+ this.roundClean();
1447
1812
  return this;
1448
1813
  }
1449
1814
  digestInto(out) {
@@ -1453,23 +1818,20 @@ var HashMD = class {
1453
1818
  const { buffer, view, blockLen, isLE: isLE2 } = this;
1454
1819
  let { pos } = this;
1455
1820
  buffer[pos++] = 128;
1456
- clean(this.buffer.subarray(pos));
1821
+ buffer.fill(0, pos);
1457
1822
  if (this.padOffset > blockLen - pos) {
1458
1823
  this.process(view, 0);
1459
- pos = 0;
1824
+ buffer.fill(0);
1460
1825
  }
1461
- for (let i = pos; i < blockLen; i++)
1462
- buffer[i] = 0;
1463
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
1826
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE2);
1464
1827
  this.process(view, 0);
1465
- const oview = createView(out);
1828
+ this.roundClean();
1829
+ const oview = out === buffer ? view : createView(out);
1466
1830
  const len = this.outputLen;
1467
- if (len % 4)
1468
- throw new Error("_sha2: outputLen must be aligned to 32bit");
1469
1831
  const outLen = len / 4;
1470
1832
  const state = this.get();
1471
- if (outLen > state.length)
1472
- throw new Error("_sha2: outputLen bigger than state");
1833
+ if (len % 4 || outLen > state.length)
1834
+ throw new Error("invalid outputLen");
1473
1835
  for (let i = 0; i < outLen; i++)
1474
1836
  oview.setUint32(4 * i, state[i], isLE2);
1475
1837
  }
@@ -1480,15 +1842,13 @@ var HashMD = class {
1480
1842
  this.destroy();
1481
1843
  return res;
1482
1844
  }
1483
- _cloneInto(to) {
1484
- to || (to = new this.constructor());
1485
- to.set(...this.get());
1486
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
1845
+ _cloneIntoMeta(to) {
1846
+ const { buffer, length, finished, destroyed, pos } = this;
1487
1847
  to.destroyed = destroyed;
1488
1848
  to.finished = finished;
1489
1849
  to.length = length;
1490
1850
  to.pos = pos;
1491
- if (length % blockLen)
1851
+ if (pos)
1492
1852
  to.buffer.set(buffer);
1493
1853
  return to;
1494
1854
  }
@@ -1515,45 +1875,6 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1515
1875
  327033209
1516
1876
  ]);
1517
1877
 
1518
- // ../../node_modules/@noble/hashes/_u64.js
1519
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1520
- var _32n = /* @__PURE__ */ BigInt(32);
1521
- function fromBig(n, le = false) {
1522
- if (le)
1523
- return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
1524
- return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1525
- }
1526
- function split(lst, le = false) {
1527
- const len = lst.length;
1528
- let Ah = new Uint32Array(len);
1529
- let Al = new Uint32Array(len);
1530
- for (let i = 0; i < len; i++) {
1531
- const { h, l } = fromBig(lst[i], le);
1532
- [Ah[i], Al[i]] = [h, l];
1533
- }
1534
- return [Ah, Al];
1535
- }
1536
- var shrSH = (h, _l, s) => h >>> s;
1537
- var shrSL = (h, l, s) => h << 32 - s | l >>> s;
1538
- var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
1539
- var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
1540
- var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
1541
- var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
1542
- var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
1543
- var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
1544
- var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
1545
- var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
1546
- function add(Ah, Al, Bh, Bl) {
1547
- const l = (Al >>> 0) + (Bl >>> 0);
1548
- return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
1549
- }
1550
- var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1551
- var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1552
- var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1553
- var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1554
- var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1555
- var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1556
-
1557
1878
  // ../../node_modules/@noble/hashes/sha2.js
1558
1879
  var K512 = /* @__PURE__ */ (() => split([
1559
1880
  "0x428a2f98d728ae22",
@@ -1642,8 +1963,45 @@ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1642
1963
  var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1643
1964
  var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1644
1965
  var SHA2_64B = class extends HashMD {
1645
- constructor(outputLen) {
1966
+ constructor(outputLen, IV) {
1646
1967
  super(128, outputLen, 16, false);
1968
+ // We cannot use array here since array allows indexing by variable
1969
+ // which means optimizer/compiler cannot use registers.
1970
+ // h -- high 32 bits, l -- low 32 bits
1971
+ // Numeric initializers matter: starting the fields as `undefined` changes
1972
+ // V8's field representation and slows hashing down (measured on sha256).
1973
+ __publicField(this, "Ah", 0);
1974
+ __publicField(this, "Al", 0);
1975
+ __publicField(this, "Bh", 0);
1976
+ __publicField(this, "Bl", 0);
1977
+ __publicField(this, "Ch", 0);
1978
+ __publicField(this, "Cl", 0);
1979
+ __publicField(this, "Dh", 0);
1980
+ __publicField(this, "Dl", 0);
1981
+ __publicField(this, "Eh", 0);
1982
+ __publicField(this, "El", 0);
1983
+ __publicField(this, "Fh", 0);
1984
+ __publicField(this, "Fl", 0);
1985
+ __publicField(this, "Gh", 0);
1986
+ __publicField(this, "Gl", 0);
1987
+ __publicField(this, "Hh", 0);
1988
+ __publicField(this, "Hl", 0);
1989
+ this.Ah = IV[0] | 0;
1990
+ this.Al = IV[1] | 0;
1991
+ this.Bh = IV[2] | 0;
1992
+ this.Bl = IV[3] | 0;
1993
+ this.Ch = IV[4] | 0;
1994
+ this.Cl = IV[5] | 0;
1995
+ this.Dh = IV[6] | 0;
1996
+ this.Dl = IV[7] | 0;
1997
+ this.Eh = IV[8] | 0;
1998
+ this.El = IV[9] | 0;
1999
+ this.Fh = IV[10] | 0;
2000
+ this.Fl = IV[11] | 0;
2001
+ this.Gh = IV[12] | 0;
2002
+ this.Gl = IV[13] | 0;
2003
+ this.Hh = IV[14] | 0;
2004
+ this.Hl = IV[15] | 0;
1647
2005
  }
1648
2006
  // prettier-ignore
1649
2007
  get() {
@@ -1669,6 +2027,10 @@ var SHA2_64B = class extends HashMD {
1669
2027
  this.Hh = Hh | 0;
1670
2028
  this.Hl = Hl | 0;
1671
2029
  }
2030
+ _cloneInto(to) {
2031
+ (to || (to = new this.constructor())).set(...this.get());
2032
+ return this._cloneIntoMeta(to);
2033
+ }
1672
2034
  process(view, offset) {
1673
2035
  for (let i = 0; i < 16; i++, offset += 4) {
1674
2036
  SHA512_W_H[i] = view.getUint32(offset);
@@ -1739,23 +2101,7 @@ var SHA2_64B = class extends HashMD {
1739
2101
  };
1740
2102
  var _SHA512 = class extends SHA2_64B {
1741
2103
  constructor() {
1742
- super(64);
1743
- __publicField(this, "Ah", SHA512_IV[0] | 0);
1744
- __publicField(this, "Al", SHA512_IV[1] | 0);
1745
- __publicField(this, "Bh", SHA512_IV[2] | 0);
1746
- __publicField(this, "Bl", SHA512_IV[3] | 0);
1747
- __publicField(this, "Ch", SHA512_IV[4] | 0);
1748
- __publicField(this, "Cl", SHA512_IV[5] | 0);
1749
- __publicField(this, "Dh", SHA512_IV[6] | 0);
1750
- __publicField(this, "Dl", SHA512_IV[7] | 0);
1751
- __publicField(this, "Eh", SHA512_IV[8] | 0);
1752
- __publicField(this, "El", SHA512_IV[9] | 0);
1753
- __publicField(this, "Fh", SHA512_IV[10] | 0);
1754
- __publicField(this, "Fl", SHA512_IV[11] | 0);
1755
- __publicField(this, "Gh", SHA512_IV[12] | 0);
1756
- __publicField(this, "Gl", SHA512_IV[13] | 0);
1757
- __publicField(this, "Hh", SHA512_IV[14] | 0);
1758
- __publicField(this, "Hl", SHA512_IV[15] | 0);
2104
+ super(64, SHA512_IV);
1759
2105
  }
1760
2106
  };
1761
2107
  var sha512 = /* @__PURE__ */ createHasher(
@@ -1764,17 +2110,21 @@ var sha512 = /* @__PURE__ */ createHasher(
1764
2110
  );
1765
2111
 
1766
2112
  // ../../node_modules/@noble/curves/abstract/fft.js
1767
- function checkU32(n) {
2113
+ function checkU32(n, title = "n") {
2114
+ if (typeof n !== "number")
2115
+ throw new TypeError(`wrong u32 integer "${title}": expected number, got type=${typeof n}`);
1768
2116
  if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
1769
- throw new Error("wrong u32 integer:" + n);
2117
+ throw new RangeError(`wrong u32 integer "${title}": expected 0..4294967295, got ${n}`);
1770
2118
  return n;
1771
2119
  }
1772
2120
  function isPowerOfTwo(x) {
1773
- checkU32(x);
2121
+ checkU32(x, "x");
1774
2122
  return (x & x - 1) === 0 && x !== 0;
1775
2123
  }
1776
2124
  function reverseBits(n, bits) {
1777
2125
  checkU32(n);
2126
+ if (typeof bits !== "number")
2127
+ throw new TypeError('"bits" expected number, got type=' + typeof bits);
1778
2128
  if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
1779
2129
  throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
1780
2130
  let reversed = 0;
@@ -1787,6 +2137,8 @@ function log2(n) {
1787
2137
  return 31 - Math.clz32(n);
1788
2138
  }
1789
2139
  function bitReversalInplace(values) {
2140
+ if (!values || typeof values !== "object" || typeof values.length !== "number")
2141
+ throw new TypeError('"values" expected array-like, got type=' + typeof values);
1790
2142
  const n = values.length;
1791
2143
  if (!isPowerOfTwo(n))
1792
2144
  throw new Error("expected positive power-of-two length, got " + n);
@@ -1802,14 +2154,19 @@ function bitReversalInplace(values) {
1802
2154
  return values;
1803
2155
  }
1804
2156
  var FFTCore = (F2, coreOpts) => {
2157
+ validateObject(coreOpts, { N: "number", roots: "object", dit: "boolean" }, { invertButterflies: "boolean", skipStages: "number", brp: "boolean" }, "coreOpts");
1805
2158
  const { N: N2, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
2159
+ checkU32(N2, "coreOpts.N");
1806
2160
  const bits = log2(N2);
1807
2161
  if (!isPowerOfTwo(N2))
1808
2162
  throw new Error("FFT: Polynomial size should be power of two");
2163
+ checkU32(skipStages, "coreOpts.skipStages");
2164
+ const maxSkipStages = bits === 0 ? 0 : bits - 1;
2165
+ if (skipStages > maxSkipStages)
2166
+ throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${maxSkipStages}`);
1809
2167
  if (roots.length !== N2)
1810
2168
  throw new Error(`FFT: wrong roots length: expected ${N2}, got ${roots.length}`);
1811
2169
  const isDit = dit !== invertButterflies;
1812
- isDit;
1813
2170
  return (values) => {
1814
2171
  if (values.length !== N2)
1815
2172
  throw new Error("FFT: wrong Polynomial length");
@@ -1881,6 +2238,10 @@ function normDST(DST) {
1881
2238
  function expand_message_xmd(msg, DST, lenInBytes, H) {
1882
2239
  abytes2(msg);
1883
2240
  asafenumber(lenInBytes);
2241
+ if (typeof H !== "function")
2242
+ throw new Error("expand_message_xmd: expected hash function");
2243
+ asafenumber(H.outputLen, "hash.outputLen");
2244
+ asafenumber(H.blockLen, "hash.blockLen");
1884
2245
  DST = normDST(DST);
1885
2246
  if (DST.length > 255)
1886
2247
  DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
@@ -1903,6 +2264,275 @@ function expand_message_xmd(msg, DST, lenInBytes, H) {
1903
2264
  }
1904
2265
  var _DST_scalar = "HashToScalar-";
1905
2266
 
2267
+ // ../../node_modules/@noble/curves/abstract/oprf.js
2268
+ var _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar);
2269
+ function createOPRF(opts2) {
2270
+ validateObject(opts2, {
2271
+ name: "string",
2272
+ hash: "function",
2273
+ hashToScalar: "function",
2274
+ hashToGroup: "function"
2275
+ });
2276
+ validatePointCons(opts2.Point);
2277
+ const { name, Point, hash, hashToGroup: hashToGroupHook, hashToScalar } = opts2;
2278
+ const { Fn: Fn2 } = Point;
2279
+ const invertSecret = (value) => invertCt(value, Fn2.ORDER);
2280
+ const hashToGroup = (msg, ctx) => hashToGroupHook(msg, {
2281
+ DST: concatBytes2(asciiToBytes("HashToGroup-"), ctx)
2282
+ });
2283
+ const hashToScalarPrefixed = (msg, ctx) => hashToScalar(msg, { DST: concatBytes2(_DST_scalarBytes, ctx) });
2284
+ const randomScalar = (rng = randomBytes2) => {
2285
+ if (typeof rng !== "function")
2286
+ throw new TypeError('"rng" expected function, got type=' + typeof rng);
2287
+ const t = mapHashToField(rng(getMinHashLength(Fn2.ORDER)), Fn2.ORDER, Fn2.isLE);
2288
+ return Fn2.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
2289
+ };
2290
+ const msm = (points, scalars) => mulAddUnsafe(Point, points, scalars);
2291
+ const getCtx = (mode) => concatBytes2(asciiToBytes("OPRFV1-"), new Uint8Array([mode]), asciiToBytes("-" + name));
2292
+ const ctxOPRF = getCtx(0);
2293
+ const ctxVOPRF = getCtx(1);
2294
+ const ctxPOPRF = getCtx(2);
2295
+ function encode(...args) {
2296
+ const res2 = [];
2297
+ for (const a of args) {
2298
+ if (typeof a === "number")
2299
+ res2.push(numberToBytesBE(a, 2));
2300
+ else if (typeof a === "string")
2301
+ res2.push(asciiToBytes(a));
2302
+ else {
2303
+ abytes2(a);
2304
+ res2.push(numberToBytesBE(a.length, 2), a);
2305
+ }
2306
+ }
2307
+ return concatBytes2(...res2);
2308
+ }
2309
+ const inputBytes = (title, bytes) => {
2310
+ abytes2(bytes, void 0, title);
2311
+ if (bytes.length > 65535)
2312
+ throw new Error(`"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}`);
2313
+ return bytes;
2314
+ };
2315
+ const hashInput = (...bytes) => hash(encode(...bytes, "Finalize"));
2316
+ function getTranscripts(B2, C, D, ctx) {
2317
+ const Bm = B2.toBytes();
2318
+ const seed = hash(encode(Bm, concatBytes2(asciiToBytes("Seed-"), ctx)));
2319
+ const res2 = [];
2320
+ for (let i = 0; i < C.length; i++) {
2321
+ const Ci = C[i].toBytes();
2322
+ const Di = D[i].toBytes();
2323
+ const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, "Composite"), ctx);
2324
+ res2.push(di);
2325
+ }
2326
+ return res2;
2327
+ }
2328
+ function computeComposites(B2, C, D, ctx) {
2329
+ const T = getTranscripts(B2, C, D, ctx);
2330
+ const M = msm(C, T);
2331
+ const Z = msm(D, T);
2332
+ return { M, Z };
2333
+ }
2334
+ function computeCompositesFast(k, B2, C, D, ctx) {
2335
+ const T = getTranscripts(B2, C, D, ctx);
2336
+ const M = msm(C, T);
2337
+ const Z = M.multiply(k);
2338
+ return { M, Z };
2339
+ }
2340
+ function challengeTranscript(B2, M, Z, t2, t3, ctx) {
2341
+ const [Bm, a0, a1, a2, a3] = [B2, M, Z, t2, t3].map((i) => i.toBytes());
2342
+ return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, "Challenge"), ctx);
2343
+ }
2344
+ function generateProof(ctx, k, B2, C, D, rng) {
2345
+ const { M, Z } = computeCompositesFast(k, B2, C, D, ctx);
2346
+ const r = randomScalar(rng);
2347
+ const t2 = Point.BASE.multiply(r);
2348
+ const t3 = M.multiply(r);
2349
+ const c = challengeTranscript(B2, M, Z, t2, t3, ctx);
2350
+ const s = Fn2.sub(r, Fn2.mul(c, k));
2351
+ return concatBytes2(...[c, s].map((i) => Fn2.toBytes(i)));
2352
+ }
2353
+ function verifyProof(ctx, B2, C, D, proof) {
2354
+ abytes2(proof, 2 * Fn2.BYTES);
2355
+ const { M, Z } = computeComposites(B2, C, D, ctx);
2356
+ const [c, s] = [proof.subarray(0, Fn2.BYTES), proof.subarray(Fn2.BYTES)].map((f) => Fn2.fromBytes(f));
2357
+ const t2 = msm([Point.BASE, B2], [s, c]);
2358
+ const t3 = msm([M, Z], [s, c]);
2359
+ const expectedC = challengeTranscript(B2, M, Z, t2, t3, ctx);
2360
+ if (!Fn2.eql(c, expectedC))
2361
+ throw new Error("proof verification failed");
2362
+ }
2363
+ function generateKeyPair() {
2364
+ const skS = randomScalar();
2365
+ const pkS = Point.BASE.multiply(skS);
2366
+ return { secretKey: Fn2.toBytes(skS), publicKey: pkS.toBytes() };
2367
+ }
2368
+ function deriveKeyPair(ctx, seed, info) {
2369
+ abytes2(seed, 32, "seed");
2370
+ info = inputBytes("keyInfo", info);
2371
+ const dst = concatBytes2(asciiToBytes("DeriveKeyPair"), ctx);
2372
+ const msg = concatBytes2(seed, encode(info), Uint8Array.of(0));
2373
+ for (let counter = 0; counter <= 255; counter++) {
2374
+ msg[msg.length - 1] = counter;
2375
+ const skS = hashToScalar(msg, { DST: dst });
2376
+ if (Fn2.is0(skS))
2377
+ continue;
2378
+ return {
2379
+ secretKey: Fn2.toBytes(skS),
2380
+ publicKey: Point.BASE.multiply(skS).toBytes()
2381
+ };
2382
+ }
2383
+ throw new Error("Cannot derive key");
2384
+ }
2385
+ const wirePoint = (label, bytes) => {
2386
+ const point = Point.fromBytes(bytes);
2387
+ if (point.equals(Point.ZERO))
2388
+ throw new Error(label + " point at infinity");
2389
+ return point;
2390
+ };
2391
+ function blind(ctx, input, rng = randomBytes2) {
2392
+ input = inputBytes("input", input);
2393
+ const blind2 = randomScalar(rng);
2394
+ const inputPoint = hashToGroup(input, ctx);
2395
+ if (inputPoint.equals(Point.ZERO))
2396
+ throw new Error("Input point at infinity");
2397
+ const blinded = inputPoint.multiply(blind2);
2398
+ return { blind: Fn2.toBytes(blind2), blinded: blinded.toBytes() };
2399
+ }
2400
+ function evaluate(ctx, secretKey, input) {
2401
+ input = inputBytes("input", input);
2402
+ const skS = Fn2.fromBytes(secretKey);
2403
+ const inputPoint = hashToGroup(input, ctx);
2404
+ if (inputPoint.equals(Point.ZERO))
2405
+ throw new Error("Input point at infinity");
2406
+ const unblinded = inputPoint.multiply(skS).toBytes();
2407
+ return hashInput(input, unblinded);
2408
+ }
2409
+ const oprf2 = Object.freeze({
2410
+ generateKeyPair,
2411
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),
2412
+ blind: (input, rng = randomBytes2) => blind(ctxOPRF, input, rng),
2413
+ blindEvaluate(secretKey, blindedPoint) {
2414
+ const skS = Fn2.fromBytes(secretKey);
2415
+ const elm = wirePoint("blinded", blindedPoint);
2416
+ return elm.multiply(skS).toBytes();
2417
+ },
2418
+ finalize(input, blindBytes, evaluatedBytes) {
2419
+ input = inputBytes("input", input);
2420
+ const blind2 = Fn2.fromBytes(blindBytes);
2421
+ const evalPoint = wirePoint("evaluated", evaluatedBytes);
2422
+ const unblinded = evalPoint.multiply(Fn2.inv(blind2)).toBytes();
2423
+ return hashInput(input, unblinded);
2424
+ },
2425
+ evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input)
2426
+ });
2427
+ const voprf = Object.freeze({
2428
+ generateKeyPair,
2429
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),
2430
+ blind: (input, rng = randomBytes2) => blind(ctxVOPRF, input, rng),
2431
+ blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes2) {
2432
+ if (!Array.isArray(blinded))
2433
+ throw new Error("expected array");
2434
+ const skS = Fn2.fromBytes(secretKey);
2435
+ const pkS = wirePoint("public key", publicKey);
2436
+ const blindedPoints = blinded.map((i) => wirePoint("blinded", i));
2437
+ const evaluated = blindedPoints.map((i) => i.multiply(skS));
2438
+ const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);
2439
+ return { evaluated: evaluated.map((i) => i.toBytes()), proof };
2440
+ },
2441
+ blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes2) {
2442
+ const res2 = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);
2443
+ return { evaluated: res2.evaluated[0], proof: res2.proof };
2444
+ },
2445
+ finalizeBatch(items, publicKey, proof) {
2446
+ if (!Array.isArray(items))
2447
+ throw new Error("expected array");
2448
+ const pkS = wirePoint("public key", publicKey);
2449
+ const blindedPoints = items.map((i) => wirePoint("blinded", i.blinded));
2450
+ const evalPoints = items.map((i) => wirePoint("evaluated", i.evaluated));
2451
+ verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);
2452
+ return items.map((i, j) => {
2453
+ const input = inputBytes("input", i.input);
2454
+ const blind2 = Fn2.fromBytes(i.blind);
2455
+ const unblinded = evalPoints[j].multiply(Fn2.inv(blind2)).toBytes();
2456
+ return hashInput(input, unblinded);
2457
+ });
2458
+ },
2459
+ finalize(input, blind2, evaluated, blinded, publicKey, proof) {
2460
+ return this.finalizeBatch([{ input, blind: blind2, evaluated, blinded }], publicKey, proof)[0];
2461
+ },
2462
+ evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input)
2463
+ });
2464
+ const poprf = (info) => {
2465
+ info = copyBytes(inputBytes("info", info));
2466
+ const m = hashToScalarPrefixed(encode("Info", info), ctxPOPRF);
2467
+ const T = Point.BASE.multiply(m);
2468
+ return Object.freeze({
2469
+ generateKeyPair,
2470
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),
2471
+ blind(input, publicKey, rng = randomBytes2) {
2472
+ input = inputBytes("input", input);
2473
+ const pkS = wirePoint("public key", publicKey);
2474
+ const tweakedKey = T.add(pkS);
2475
+ if (tweakedKey.equals(Point.ZERO))
2476
+ throw new Error("tweakedKey point at infinity");
2477
+ const blind2 = randomScalar(rng);
2478
+ const inputPoint = hashToGroup(input, ctxPOPRF);
2479
+ if (inputPoint.equals(Point.ZERO))
2480
+ throw new Error("Input point at infinity");
2481
+ const blindedPoint = inputPoint.multiply(blind2);
2482
+ return {
2483
+ blind: Fn2.toBytes(blind2),
2484
+ blinded: blindedPoint.toBytes(),
2485
+ tweakedKey: tweakedKey.toBytes()
2486
+ };
2487
+ },
2488
+ blindEvaluateBatch(secretKey, blinded, rng = randomBytes2) {
2489
+ if (!Array.isArray(blinded))
2490
+ throw new Error("expected array");
2491
+ const skS = Fn2.fromBytes(secretKey);
2492
+ const t = Fn2.add(skS, m);
2493
+ const invT = invertSecret(t);
2494
+ const blindedPoints = blinded.map((i) => wirePoint("blinded", i));
2495
+ const evalPoints = blindedPoints.map((i) => i.multiply(invT));
2496
+ const tweakedKey = Point.BASE.multiply(t);
2497
+ const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);
2498
+ return { evaluated: evalPoints.map((i) => i.toBytes()), proof };
2499
+ },
2500
+ blindEvaluate(secretKey, blinded, rng = randomBytes2) {
2501
+ const res2 = this.blindEvaluateBatch(secretKey, [blinded], rng);
2502
+ return { evaluated: res2.evaluated[0], proof: res2.proof };
2503
+ },
2504
+ finalizeBatch(items, proof, tweakedKey) {
2505
+ if (!Array.isArray(items))
2506
+ throw new Error("expected array");
2507
+ const inputs = items.map((i) => inputBytes("input", i.input));
2508
+ const evalPoints = items.map((i) => wirePoint("evaluated", i.evaluated));
2509
+ verifyProof(ctxPOPRF, wirePoint("tweakedKey", tweakedKey), evalPoints, items.map((i) => wirePoint("blinded", i.blinded)), proof);
2510
+ return items.map((i, j) => {
2511
+ const blind2 = Fn2.fromBytes(i.blind);
2512
+ const point = evalPoints[j].multiply(Fn2.inv(blind2)).toBytes();
2513
+ return hashInput(inputs[j], info, point);
2514
+ });
2515
+ },
2516
+ finalize(input, blind2, evaluated, blinded, proof, tweakedKey) {
2517
+ return this.finalizeBatch([{ input, blind: blind2, evaluated, blinded }], proof, tweakedKey)[0];
2518
+ },
2519
+ evaluate(secretKey, input) {
2520
+ input = inputBytes("input", input);
2521
+ const skS = Fn2.fromBytes(secretKey);
2522
+ const inputPoint = hashToGroup(input, ctxPOPRF);
2523
+ if (inputPoint.equals(Point.ZERO))
2524
+ throw new Error("Input point at infinity");
2525
+ const t = Fn2.add(skS, m);
2526
+ const invT = invertSecret(t);
2527
+ const unblinded = inputPoint.multiply(invT).toBytes();
2528
+ return hashInput(input, info, unblinded);
2529
+ }
2530
+ });
2531
+ };
2532
+ const res = { name, oprf: oprf2, voprf, poprf, __tests: Object.freeze({ Fn: Fn2, invertSecret }) };
2533
+ return Object.freeze(res);
2534
+ }
2535
+
1906
2536
  // ../../node_modules/@noble/curves/ed25519.js
1907
2537
  var _0n6 = /* @__PURE__ */ BigInt(0);
1908
2538
  var _1n6 = /* @__PURE__ */ BigInt(1);
@@ -1948,8 +2578,8 @@ function uvRatio(u, v) {
1948
2578
  const P = ed25519_CURVE_p;
1949
2579
  const v3 = mod(v * v * v, P);
1950
2580
  const v7 = mod(v3 * v3 * v, P);
1951
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1952
- let x = mod(u * v3 * pow, P);
2581
+ const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2582
+ let x = mod(u * v3 * pow3, P);
1953
2583
  const vx2 = mod(v * x * x, P);
1954
2584
  const root1 = x;
1955
2585
  const root2 = mod(x * ED25519_SQRT_M1, P);
@@ -1969,14 +2599,25 @@ var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
1969
2599
  var Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
1970
2600
  var x25519 = /* @__PURE__ */ (() => {
1971
2601
  const P = ed25519_CURVE_p;
2602
+ const powPminus2 = (x) => {
2603
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
2604
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2605
+ };
1972
2606
  return montgomery({
1973
2607
  P,
1974
2608
  type: "x25519",
1975
- powPminus2: (x) => {
1976
- const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
1977
- return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
1978
- },
1979
- adjustScalarBytes
2609
+ powPminus2,
2610
+ adjustScalarBytes,
2611
+ // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached
2612
+ // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.
2613
+ // Same construction as libsodium's crypto_scalarmult_curve25519_base.
2614
+ scalarMultBase: (k) => {
2615
+ const kn = mod(k, ed25519_Point.Fn.ORDER);
2616
+ if (kn === _0n6)
2617
+ return _0n6;
2618
+ const p = ed25519_Point.BASE.multiply(kn);
2619
+ return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);
2620
+ }
1980
2621
  });
1981
2622
  })();
1982
2623
  var SQRT_M1 = ED25519_SQRT_M1;
@@ -1989,27 +2630,25 @@ var MAX_255B = /* @__PURE__ */ BigInt("0x7ffffffffffffffffffffffffffffffffffffff
1989
2630
  var bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
1990
2631
  function calcElligatorRistrettoMap(r0) {
1991
2632
  const { d } = ed25519_CURVE;
1992
- const P = ed25519_CURVE_p;
1993
- const mod2 = (n) => Fp.create(n);
1994
- const r = mod2(SQRT_M1 * r0 * r0);
1995
- const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
2633
+ const r = Fp.mul(Fp.mulN(SQRT_M1, r0), r0);
2634
+ const Ns = Fp.mul(Fp.addN(r, _1n6), ONE_MINUS_D_SQ);
1996
2635
  let c = BigInt(-1);
1997
- const D = mod2((c - d * r) * mod2(r + d));
2636
+ const D = Fp.mul(Fp.subN(c, Fp.mulN(d, r)), Fp.add(r, d));
1998
2637
  let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
1999
- let s_ = mod2(s * r0);
2000
- if (!isNegativeLE(s_, P))
2001
- s_ = mod2(-s_);
2638
+ let s_ = Fp.mul(s, r0);
2639
+ if (!Fp.isOdd(s_))
2640
+ s_ = Fp.neg(s_);
2002
2641
  if (!Ns_D_is_sq)
2003
2642
  s = s_;
2004
2643
  if (!Ns_D_is_sq)
2005
2644
  c = r;
2006
- const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2007
- const s2 = s * s;
2008
- const W0 = mod2((s + s) * D);
2009
- const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2010
- const W2 = mod2(_1n6 - s2);
2011
- const W3 = mod2(_1n6 + s2);
2012
- return new ed25519_Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2645
+ const Nt = Fp.sub(Fp.mulN(Fp.mulN(c, Fp.subN(r, _1n6)), D_MINUS_ONE_SQ), D);
2646
+ const s2 = Fp.sqrN(s);
2647
+ const W0 = Fp.mul(Fp.addN(s, s), D);
2648
+ const W1 = Fp.mul(Nt, SQRT_AD_MINUS_ONE);
2649
+ const W2 = Fp.sub(_1n6, s2);
2650
+ const W3 = Fp.add(_1n6, s2);
2651
+ return new ed25519_Point(Fp.mul(W0, W3), Fp.mul(W2, W1), Fp.mul(W1, W3), Fp.mul(W0, W2));
2013
2652
  }
2014
2653
  var __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2015
2654
  constructor(ep) {
@@ -2034,28 +2673,26 @@ var __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2034
2673
  static fromBytes(bytes) {
2035
2674
  abytes(bytes, 32);
2036
2675
  const { a, d } = ed25519_CURVE;
2037
- const P = ed25519_CURVE_p;
2038
- const mod2 = (n) => Fp.create(n);
2039
2676
  const s = bytes255ToNumberLE(bytes);
2040
- if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2677
+ if (!equalBytes(Fp.toBytes(s), bytes) || Fp.isOdd(s))
2041
2678
  throw new Error("invalid ristretto255 encoding 1");
2042
- const s2 = mod2(s * s);
2043
- const u1 = mod2(_1n6 + a * s2);
2044
- const u2 = mod2(_1n6 - a * s2);
2045
- const u1_2 = mod2(u1 * u1);
2046
- const u2_2 = mod2(u2 * u2);
2047
- const v = mod2(a * d * u1_2 - u2_2);
2048
- const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2049
- const Dx = mod2(I * u2);
2050
- const Dy = mod2(I * Dx * v);
2051
- let x = mod2((s + s) * Dx);
2052
- if (isNegativeLE(x, P))
2053
- x = mod2(-x);
2054
- const y = mod2(u1 * Dy);
2055
- const t = mod2(x * y);
2056
- if (!isValid || isNegativeLE(t, P) || y === _0n6)
2679
+ const s2 = Fp.sqr(s);
2680
+ const u1 = Fp.add(_1n6, Fp.mulN(a, s2));
2681
+ const u2 = Fp.sub(_1n6, Fp.mulN(a, s2));
2682
+ const u1_2 = Fp.sqr(u1);
2683
+ const u2_2 = Fp.sqr(u2);
2684
+ const v = Fp.sub(Fp.mulN(Fp.mulN(a, d), u1_2), u2_2);
2685
+ const { isValid, value: I } = invertSqrt(Fp.mul(v, u2_2));
2686
+ const Dx = Fp.mul(I, u2);
2687
+ const Dy = Fp.mul(Fp.mulN(I, Dx), v);
2688
+ let x = Fp.mul(Fp.addN(s, s), Dx);
2689
+ if (Fp.isOdd(x))
2690
+ x = Fp.neg(x);
2691
+ const y = Fp.mul(u1, Dy);
2692
+ const t = Fp.mul(x, y);
2693
+ if (!isValid || Fp.isOdd(t) || Fp.is0(y))
2057
2694
  throw new Error("invalid ristretto255 encoding 2");
2058
- return new __RistrettoPoint(new ed25519_Point(x, y, _1n6, t));
2695
+ return new __RistrettoPoint(new ed25519_Point(x, y, Fp.ONE, t));
2059
2696
  }
2060
2697
  /**
2061
2698
  * Converts ristretto-encoded string to ristretto point.
@@ -2071,30 +2708,28 @@ var __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2071
2708
  */
2072
2709
  toBytes() {
2073
2710
  let { X, Y, Z, T } = this.ep;
2074
- const P = ed25519_CURVE_p;
2075
- const mod2 = (n) => Fp.create(n);
2076
- const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2077
- const u2 = mod2(X * Y);
2078
- const u2sq = mod2(u2 * u2);
2079
- const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2080
- const D1 = mod2(invsqrt * u1);
2081
- const D2 = mod2(invsqrt * u2);
2082
- const zInv = mod2(D1 * D2 * T);
2711
+ const u1 = Fp.mul(Fp.add(Z, Y), Fp.sub(Z, Y));
2712
+ const u2 = Fp.mul(X, Y);
2713
+ const u2sq = Fp.sqr(u2);
2714
+ const { value: invsqrt } = invertSqrt(Fp.mul(u1, u2sq));
2715
+ const D1 = Fp.mul(invsqrt, u1);
2716
+ const D2 = Fp.mul(invsqrt, u2);
2717
+ const zInv = Fp.mul(Fp.mulN(D1, D2), T);
2083
2718
  let D;
2084
- if (isNegativeLE(T * zInv, P)) {
2085
- let _x = mod2(Y * SQRT_M1);
2086
- let _y = mod2(X * SQRT_M1);
2719
+ if (Fp.isOdd(Fp.mul(T, zInv))) {
2720
+ let _x = Fp.mul(Y, SQRT_M1);
2721
+ let _y = Fp.mul(X, SQRT_M1);
2087
2722
  X = _x;
2088
2723
  Y = _y;
2089
- D = mod2(D1 * INVSQRT_A_MINUS_D);
2724
+ D = Fp.mul(D1, INVSQRT_A_MINUS_D);
2090
2725
  } else {
2091
2726
  D = D2;
2092
2727
  }
2093
- if (isNegativeLE(X * zInv, P))
2094
- Y = mod2(-Y);
2095
- let s = mod2((Z - Y) * D);
2096
- if (isNegativeLE(s, P))
2097
- s = mod2(-s);
2728
+ if (Fp.isOdd(Fp.mul(X, zInv)))
2729
+ Y = Fp.neg(Y);
2730
+ let s = Fp.mul(Fp.subN(Z, Y), D);
2731
+ if (Fp.isOdd(s))
2732
+ s = Fp.neg(s);
2098
2733
  return Fp.toBytes(s);
2099
2734
  }
2100
2735
  /**
@@ -2105,9 +2740,8 @@ var __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2105
2740
  this.assertSame(other);
2106
2741
  const { X: X1, Y: Y1 } = this.ep;
2107
2742
  const { X: X2, Y: Y2 } = other.ep;
2108
- const mod2 = (n) => Fp.create(n);
2109
- const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2110
- const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2743
+ const one = Fp.eql(Fp.mul(X1, Y2), Fp.mul(Y1, X2));
2744
+ const two = Fp.eql(Fp.mul(Y1, Y2), Fp.mul(X1, X2));
2111
2745
  return one || two;
2112
2746
  }
2113
2747
  is0() {
@@ -2125,11 +2759,7 @@ __publicField(__RistrettoPoint, "Fp", /* @__PURE__ */ (() => Fp)());
2125
2759
  // prettier-ignore
2126
2760
  __publicField(__RistrettoPoint, "Fn", /* @__PURE__ */ (() => Fn)());
2127
2761
  var _RistrettoPoint = __RistrettoPoint;
2128
- Object.freeze(_RistrettoPoint.BASE);
2129
- Object.freeze(_RistrettoPoint.ZERO);
2130
- Object.freeze(_RistrettoPoint.prototype);
2131
- Object.freeze(_RistrettoPoint);
2132
- var ristretto255_hasher = Object.freeze({
2762
+ var ristretto255_hasher = /* @__PURE__ */ Object.freeze({
2133
2763
  Point: _RistrettoPoint,
2134
2764
  /**
2135
2765
  * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
@@ -2150,8 +2780,9 @@ var ristretto255_hasher = Object.freeze({
2150
2780
  const xmd = expand_message_xmd(msg, DST, 64, sha512);
2151
2781
  return ristretto255_hasher.deriveToCurve(xmd);
2152
2782
  },
2153
- hashToScalar(msg, options = { DST: _DST_scalar }) {
2154
- const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2783
+ hashToScalar(msg, options) {
2784
+ const DST = options?.DST === void 0 ? _DST_scalar : options.DST;
2785
+ const xmd = expand_message_xmd(msg, DST, 64, sha512);
2155
2786
  return Fn.create(bytesToNumberLE(xmd));
2156
2787
  },
2157
2788
  /**
@@ -2172,6 +2803,13 @@ var ristretto255_hasher = Object.freeze({
2172
2803
  return new _RistrettoPoint(R1.add(R2));
2173
2804
  }
2174
2805
  });
2806
+ var ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({
2807
+ name: "ristretto255-SHA512",
2808
+ Point: _RistrettoPoint,
2809
+ hash: sha512,
2810
+ hashToGroup: ristretto255_hasher.hashToCurve,
2811
+ hashToScalar: ristretto255_hasher.hashToScalar
2812
+ }))();
2175
2813
 
2176
2814
  // ../../node_modules/@noble/hashes/sha3.js
2177
2815
  var _0n7 = BigInt(0);
@@ -2198,13 +2836,21 @@ for (let round = 0, R = _1n7, x = 1, y = 0; round < 24; round++) {
2198
2836
  var IOTAS = split(_SHA3_IOTA, true);
2199
2837
  var SHA3_IOTA_H = IOTAS[0];
2200
2838
  var SHA3_IOTA_L = IOTAS[1];
2839
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
2840
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
2841
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
2842
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
2201
2843
  var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
2202
2844
  var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
2845
+ var B = new Uint32Array(5 * 2);
2203
2846
  function keccakP(s, rounds = 24) {
2847
+ if (!(s instanceof Uint32Array))
2848
+ throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
2849
+ if (s.length !== 50)
2850
+ throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
2204
2851
  anumber(rounds, "rounds");
2205
2852
  if (rounds < 1 || rounds > 24)
2206
2853
  throw new Error('"rounds" expected integer 1..24');
2207
- const B = new Uint32Array(5 * 2);
2208
2854
  for (let round = 24 - rounds; round < 24; round++) {
2209
2855
  for (let x = 0; x < 10; x++)
2210
2856
  B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
@@ -2265,6 +2911,10 @@ var Keccak = class _Keccak {
2265
2911
  __publicField(this, "canXOF");
2266
2912
  __publicField(this, "enableXOF", false);
2267
2913
  __publicField(this, "rounds");
2914
+ anumber(blockLen, "blockLen");
2915
+ anumber(suffix, "suffix");
2916
+ anumber(rounds, "rounds");
2917
+ abool(enableXOF, "enableXOF");
2268
2918
  this.blockLen = blockLen;
2269
2919
  this.suffix = suffix;
2270
2920
  this.outputLen = outputLen;
@@ -2273,7 +2923,7 @@ var Keccak = class _Keccak {
2273
2923
  this.rounds = rounds;
2274
2924
  anumber(outputLen, "outputLen");
2275
2925
  if (!(0 < blockLen && blockLen < 200))
2276
- throw new Error("only keccak-f1600 function is supported");
2926
+ throw new Error('"blockLen" must be 1..199');
2277
2927
  this.state = new Uint8Array(200);
2278
2928
  this.state32 = u32(this.state);
2279
2929
  }
@@ -2290,9 +2940,20 @@ var Keccak = class _Keccak {
2290
2940
  update(data) {
2291
2941
  aexists(this);
2292
2942
  abytes(data);
2293
- const { blockLen, state } = this;
2943
+ const { blockLen, state, state32 } = this;
2294
2944
  const len = data.length;
2945
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
2946
+ const blockLen32 = blockLen / 4;
2947
+ const data32 = canUseU32 && len >= blockLen ? u32(data) : void 0;
2295
2948
  for (let pos = 0; pos < len; ) {
2949
+ if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
2950
+ for (let i = 0, o = pos / 4; i < blockLen32; i++)
2951
+ state32[i] ^= data32[o + i];
2952
+ pos += blockLen;
2953
+ this.pos = blockLen;
2954
+ this.keccak();
2955
+ continue;
2956
+ }
2296
2957
  const take = Math.min(blockLen - this.pos, len - pos);
2297
2958
  for (let i = 0; i < take; i++)
2298
2959
  state[this.pos++] ^= data[pos++];
@@ -2330,7 +2991,7 @@ var Keccak = class _Keccak {
2330
2991
  }
2331
2992
  xofInto(out) {
2332
2993
  if (!this.enableXOF)
2333
- throw new Error("XOF is not possible for this instance");
2994
+ throw new Error("XOF is not enabled");
2334
2995
  return this.writeInto(out);
2335
2996
  }
2336
2997
  xof(bytes) {
@@ -2341,7 +3002,7 @@ var Keccak = class _Keccak {
2341
3002
  aoutput(out, this);
2342
3003
  if (this.finished)
2343
3004
  throw new Error("digest() was already called");
2344
- this.writeInto(out.subarray(0, this.outputLen));
3005
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
2345
3006
  this.destroy();
2346
3007
  }
2347
3008
  digest() {
@@ -2383,14 +3044,32 @@ var sha3_512 = /* @__PURE__ */ genKeccak(
2383
3044
  64,
2384
3045
  /* @__PURE__ */ oidNist(10)
2385
3046
  );
2386
- var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info);
3047
+ var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => {
3048
+ opts2 = checkOpts({}, opts2);
3049
+ return new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true);
3050
+ }, info);
2387
3051
  var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
2388
3052
  var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
2389
3053
 
2390
3054
  // ../../node_modules/@noble/post-quantum/utils.js
2391
3055
  var abytesDoc = abytes;
2392
3056
  var randomBytes3 = randomBytes;
3057
+ function aarray2(item, title, inner = () => {
3058
+ }) {
3059
+ if (!Array.isArray(item))
3060
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
3061
+ for (let i = 0; i < item.length; i++)
3062
+ inner(item[i], `${title}[${i}]`);
3063
+ return item;
3064
+ }
3065
+ function aobject3(value, title = "object") {
3066
+ if (value === null || typeof value !== "object" || Array.isArray(value))
3067
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
3068
+ return value;
3069
+ }
2393
3070
  function equalBytes2(a, b) {
3071
+ a = abytes(a);
3072
+ b = abytes(b);
2394
3073
  if (a.length !== b.length)
2395
3074
  return false;
2396
3075
  let diff = 0;
@@ -2399,7 +3078,7 @@ function equalBytes2(a, b) {
2399
3078
  return diff === 0;
2400
3079
  }
2401
3080
  function copyBytes2(bytes) {
2402
- return Uint8Array.from(abytes(bytes));
3081
+ return new Uint8Array(abytes(bytes));
2403
3082
  }
2404
3083
  function splitCoder(label, ...lengths) {
2405
3084
  const getLength = (c) => typeof c === "number" ? c : c.bytesLen;
@@ -2439,11 +3118,12 @@ function vecCoder(c, vecLen) {
2439
3118
  return {
2440
3119
  bytesLen,
2441
3120
  encode: (u) => {
2442
- if (u.length !== vecLen)
2443
- throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
3121
+ const uArr = aarray2(u, "u");
3122
+ if (uArr.length !== vecLen)
3123
+ throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);
2444
3124
  const res = new Uint8Array(bytesLen);
2445
- for (let i = 0, pos = 0; i < u.length; i++) {
2446
- const b = coder.encode(u[i]);
3125
+ for (let i = 0, pos = 0; i < uArr.length; i++) {
3126
+ const b = coder.encode(uArr[i]);
2447
3127
  res.set(b, pos);
2448
3128
  b.fill(0);
2449
3129
  pos += b.length;
@@ -2469,8 +3149,9 @@ function cleanBytes(...list) {
2469
3149
  }
2470
3150
  }
2471
3151
  function getMask(bits) {
2472
- if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
2473
- throw new RangeError(`expected bits in [0..32], got ${bits}`);
3152
+ anumber(bits, "bits");
3153
+ if (bits > 32)
3154
+ throw new RangeError('"bits" expected <= 32, got ' + bits);
2474
3155
  return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0;
2475
3156
  }
2476
3157
 
@@ -2495,13 +3176,25 @@ var genCrystals = (opts2) => {
2495
3176
  return out;
2496
3177
  }
2497
3178
  const nttZetas = getZettas();
2498
- const field = {
3179
+ const inv = (_a) => {
3180
+ throw new Error("not implemented");
3181
+ };
3182
+ const field = isKyber ? {
3183
+ add: (a, b) => {
3184
+ const r = a + b | 0;
3185
+ return r >= Q2 ? r - Q2 | 0 : r;
3186
+ },
3187
+ sub: (a, b) => {
3188
+ const r = a - b | 0;
3189
+ return r < 0 ? r + Q2 | 0 : r;
3190
+ },
3191
+ mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
3192
+ inv
3193
+ } : {
2499
3194
  add: (a, b) => mod2((a | 0) + (b | 0)) | 0,
2500
3195
  sub: (a, b) => mod2((a | 0) - (b | 0)) | 0,
2501
3196
  mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
2502
- inv: (_a) => {
2503
- throw new Error("not implemented");
2504
- }
3197
+ inv
2505
3198
  };
2506
3199
  const nttOpts = {
2507
3200
  N: N2,
@@ -2524,6 +3217,12 @@ var genCrystals = (opts2) => {
2524
3217
  }
2525
3218
  };
2526
3219
  const bitsCoder = (d, c) => {
3220
+ for (let i = 0, bufLen = 0; i < N2; i++) {
3221
+ bufLen += d;
3222
+ if (bufLen > 32)
3223
+ getMask(bufLen);
3224
+ bufLen %= 8;
3225
+ }
2527
3226
  const mask = getMask(d);
2528
3227
  const bytesLen = d * (N2 / 8);
2529
3228
  return {
@@ -2535,7 +3234,7 @@ var genCrystals = (opts2) => {
2535
3234
  buf |= (c.encode(poly[i]) & mask) << bufLen;
2536
3235
  bufLen += d;
2537
3236
  for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
2538
- r[pos++] = buf & getMask(bufLen);
3237
+ r[pos++] = buf & 255;
2539
3238
  }
2540
3239
  return r;
2541
3240
  },
@@ -2628,17 +3327,21 @@ var polyCoder = (d) => d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress
2628
3327
  function polyAdd(a_, b_) {
2629
3328
  const a = a_;
2630
3329
  const b = b_;
2631
- for (let i = 0; i < N; i++)
2632
- a[i] = crystals.mod(a[i] + b[i]);
3330
+ for (let i = 0; i < N; i++) {
3331
+ const r = a[i] + b[i];
3332
+ a[i] = r >= Q ? r - Q : r;
3333
+ }
2633
3334
  }
2634
3335
  function polySub(a_, b_) {
2635
3336
  const a = a_;
2636
3337
  const b = b_;
2637
- for (let i = 0; i < N; i++)
2638
- a[i] = crystals.mod(a[i] - b[i]);
3338
+ for (let i = 0; i < N; i++) {
3339
+ const r = a[i] - b[i];
3340
+ a[i] = r < 0 ? r + Q : r;
3341
+ }
2639
3342
  }
2640
3343
  function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
2641
- const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);
3344
+ const c0 = crystals.mod(crystals.mod(a1 * b1) * zeta + a0 * b0);
2642
3345
  const c1 = crystals.mod(a0 * b1 + a1 * b0);
2643
3346
  return { c0, c1 };
2644
3347
  }
@@ -2713,6 +3416,31 @@ var genKPKE = (opts_) => {
2713
3416
  const secretCoder = vecCoder(polyCoder(12), K);
2714
3417
  const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
2715
3418
  const seedCoder = splitCoder("seed", 32, 32);
3419
+ const encryptCore = (tHat, getA, msg, seed) => {
3420
+ const rHat = [];
3421
+ for (let i = 0; i < K; i++)
3422
+ rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
3423
+ const tmp2 = new Uint16Array(N);
3424
+ const u = [];
3425
+ for (let i = 0; i < K; i++) {
3426
+ const e1 = sampleCBD(PRF, seed, K + i, ETA2);
3427
+ const tmp = new Uint16Array(N);
3428
+ for (let j = 0; j < K; j++) {
3429
+ const aij = getA(i, j);
3430
+ polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
3431
+ }
3432
+ polyAdd(e1, crystals.NTT.decode(tmp));
3433
+ u.push(e1);
3434
+ polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
3435
+ cleanBytes(tmp);
3436
+ }
3437
+ const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
3438
+ polyAdd(e2, crystals.NTT.decode(tmp2));
3439
+ const v = poly1.decode(msg);
3440
+ polyAdd(v, e2);
3441
+ cleanBytes(tHat, rHat, tmp2, e2);
3442
+ return cipherCoder.encode([u, v]);
3443
+ };
2716
3444
  return {
2717
3445
  secretCoder,
2718
3446
  lengths: {
@@ -2750,31 +3478,26 @@ var genKPKE = (opts_) => {
2750
3478
  },
2751
3479
  encrypt: (publicKey, msg, seed) => {
2752
3480
  const [tHat, rho] = publicCoder.decode(publicKey);
2753
- const rHat = [];
2754
- for (let i = 0; i < K; i++)
2755
- rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2756
3481
  const x = XOF(rho);
2757
- const tmp2 = new Uint16Array(N);
2758
- const u = [];
2759
- for (let i = 0; i < K; i++) {
2760
- const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2761
- const tmp = new Uint16Array(N);
2762
- for (let j = 0; j < K; j++) {
2763
- const aij = SampleNTT(x.get(i, j));
2764
- polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2765
- }
2766
- polyAdd(e1, crystals.NTT.decode(tmp));
2767
- u.push(e1);
2768
- polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2769
- cleanBytes(tmp);
2770
- }
3482
+ const res = encryptCore(tHat, (i, j) => SampleNTT(x.get(i, j)), msg, seed);
3483
+ x.clean();
3484
+ return res;
3485
+ },
3486
+ // Expands the full  matrix (public data derived from rho) once, so repeated encryptions
3487
+ // against the same ek skip the K² SampleNTT XOF expansions. Cached polys are copied per
3488
+ // call because encryptCore mutates its inputs in place.
3489
+ prepare: (publicKey) => {
3490
+ const [tHat, rho] = publicCoder.decode(publicKey);
3491
+ const x = XOF(rho);
3492
+ const A = [];
3493
+ for (let i = 0; i < K; i++)
3494
+ for (let j = 0; j < K; j++)
3495
+ A.push(SampleNTT(x.get(i, j)));
2771
3496
  x.clean();
2772
- const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2773
- polyAdd(e2, crystals.NTT.decode(tmp2));
2774
- const v = poly1.decode(msg);
2775
- polyAdd(v, e2);
2776
- cleanBytes(tHat, rHat, tmp2, e2);
2777
- return cipherCoder.encode([u, v]);
3497
+ return {
3498
+ encrypt: (msg, seed) => encryptCore(tHat.map((p) => p.slice()), (i, j) => A[i * K + j].slice(), msg, seed),
3499
+ clean: () => cleanBytes(tHat, A)
3500
+ };
2778
3501
  },
2779
3502
  decrypt: (cipherText, privateKey) => {
2780
3503
  const [u, v] = cipherCoder.decode(cipherText);
@@ -2783,8 +3506,9 @@ var genKPKE = (opts_) => {
2783
3506
  for (let i = 0; i < K; i++)
2784
3507
  polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));
2785
3508
  polySub(v, crystals.NTT.decode(tmp));
2786
- cleanBytes(tmp, sk, u);
2787
- return poly1.encode(v);
3509
+ const res = poly1.encode(v);
3510
+ cleanBytes(tmp, sk, u, v);
3511
+ return res;
2788
3512
  }
2789
3513
  };
2790
3514
  };
@@ -2796,6 +3520,14 @@ function createKyber(opts2) {
2796
3520
  const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
2797
3521
  const msgLen = 32;
2798
3522
  const seedLen = 64;
3523
+ const validateModulus = (publicKey, fn) => {
3524
+ const eke = publicKey.subarray(0, 384 * rawOpts.K);
3525
+ const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
3526
+ const ok = equalBytes2(ek, eke);
3527
+ cleanBytes(ek);
3528
+ if (!ok)
3529
+ throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);
3530
+ };
2799
3531
  const kemLengths = Object.freeze({
2800
3532
  ...lengths,
2801
3533
  seed: 64,
@@ -2806,38 +3538,55 @@ function createKyber(opts2) {
2806
3538
  return Object.freeze({
2807
3539
  info: Object.freeze({ type: "ml-kem" }),
2808
3540
  lengths: kemLengths,
2809
- keygen: (seed = randomBytes3(seedLen)) => {
2810
- abytesDoc(seed, seedLen, "seed");
2811
- const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));
2812
- const publicKeyHash = HASH256(publicKey);
2813
- const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);
2814
- cleanBytes(sk, publicKeyHash);
2815
- return {
2816
- publicKey,
2817
- secretKey
2818
- };
3541
+ keygen: (seed) => {
3542
+ const ownSeed = seed === void 0;
3543
+ const s = ownSeed ? randomBytes3(seedLen) : seed;
3544
+ let sk;
3545
+ let publicKeyHash;
3546
+ try {
3547
+ abytesDoc(s, seedLen, "seed");
3548
+ const keys = KPKE.keygen(s.subarray(0, 32));
3549
+ const publicKey = keys.publicKey;
3550
+ sk = keys.secretKey;
3551
+ publicKeyHash = HASH256(publicKey);
3552
+ const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, s.subarray(32)]);
3553
+ return {
3554
+ publicKey,
3555
+ secretKey
3556
+ };
3557
+ } finally {
3558
+ if (sk !== void 0)
3559
+ cleanBytes(sk);
3560
+ if (publicKeyHash !== void 0)
3561
+ cleanBytes(publicKeyHash);
3562
+ if (ownSeed)
3563
+ cleanBytes(s);
3564
+ }
2819
3565
  },
2820
3566
  getPublicKey: (secretKey) => {
2821
3567
  const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
2822
3568
  return Uint8Array.from(publicKey);
2823
3569
  },
2824
- encapsulate: (publicKey, msg = randomBytes3(msgLen)) => {
2825
- abytesDoc(publicKey, lengths.publicKey, "publicKey");
2826
- abytesDoc(msg, msgLen, "message");
2827
- const eke = publicKey.subarray(0, 384 * opts2.K);
2828
- const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
2829
- if (!equalBytes2(ek, eke)) {
2830
- cleanBytes(ek);
2831
- throw new Error("ML-KEM.encapsulate: wrong publicKey modulus");
3570
+ encapsulate: (publicKey, msg) => {
3571
+ const ownMsg = msg === void 0;
3572
+ const m = ownMsg ? randomBytes3(msgLen) : msg;
3573
+ let kr;
3574
+ try {
3575
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
3576
+ abytesDoc(m, msgLen, "message");
3577
+ validateModulus(publicKey, "encapsulate");
3578
+ kr = HASH512.create().update(m).update(HASH256(publicKey)).digest();
3579
+ const cipherText = KPKE.encrypt(publicKey, m, kr.subarray(32, 64));
3580
+ return {
3581
+ cipherText,
3582
+ sharedSecret: kr.subarray(0, 32)
3583
+ };
3584
+ } finally {
3585
+ if (kr !== void 0)
3586
+ cleanBytes(kr.subarray(32));
3587
+ if (ownMsg)
3588
+ cleanBytes(m);
2832
3589
  }
2833
- cleanBytes(ek);
2834
- const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();
2835
- const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2836
- cleanBytes(kr.subarray(32));
2837
- return {
2838
- cipherText,
2839
- sharedSecret: kr.subarray(0, 32)
2840
- };
2841
3590
  },
2842
3591
  decapsulate: (cipherText, secretKey) => {
2843
3592
  abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
@@ -2854,8 +3603,58 @@ function createKyber(opts2) {
2854
3603
  const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2855
3604
  const isValid = equalBytes2(cipherText, cipherText2);
2856
3605
  const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2857
- cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);
3606
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2858
3607
  return isValid ? Khat : Kbar;
3608
+ },
3609
+ /**
3610
+ * Experimental prototype: pre-expand a public key so repeated encapsulate/decapsulate
3611
+ * against the same key skip re-validation, H(ek), t̂ decoding and the K² SampleNTT
3612
+ * XOF expansions of Â. Only public data is cached; see {@link KEMPrepared}.
3613
+ */
3614
+ prepare: (publicKey) => {
3615
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
3616
+ validateModulus(publicKey, "prepare");
3617
+ const ek = copyBytes2(publicKey);
3618
+ const publicKeyHash = HASH256(ek);
3619
+ const cached = KPKE.prepare(ek);
3620
+ return Object.freeze({
3621
+ publicKey: ek,
3622
+ encapsulate: (msg) => {
3623
+ const ownMsg = msg === void 0;
3624
+ const m = ownMsg ? randomBytes3(msgLen) : msg;
3625
+ let kr;
3626
+ try {
3627
+ abytesDoc(m, msgLen, "message");
3628
+ kr = HASH512.create().update(m).update(publicKeyHash).digest();
3629
+ const cipherText = cached.encrypt(m, kr.subarray(32, 64));
3630
+ return {
3631
+ cipherText,
3632
+ sharedSecret: kr.subarray(0, 32)
3633
+ };
3634
+ } finally {
3635
+ if (kr !== void 0)
3636
+ cleanBytes(kr.subarray(32));
3637
+ if (ownMsg)
3638
+ cleanBytes(m);
3639
+ }
3640
+ },
3641
+ decapsulate: (cipherText, secretKey) => {
3642
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
3643
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
3644
+ const [sk, ekEmbedded, storedHash, z] = secretCoder.decode(secretKey);
3645
+ if (!equalBytes2(ekEmbedded, ek) || !equalBytes2(storedHash, publicKeyHash))
3646
+ throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");
3647
+ const msg = KPKE.decrypt(cipherText, sk);
3648
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
3649
+ const Khat = kr.subarray(0, 32);
3650
+ const cipherText2 = cached.encrypt(msg, kr.subarray(32, 64));
3651
+ const isValid = equalBytes2(cipherText, cipherText2);
3652
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
3653
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
3654
+ return isValid ? Khat : Kbar;
3655
+ },
3656
+ clean: cached.clean
3657
+ });
2859
3658
  }
2860
3659
  });
2861
3660
  }
@@ -2876,7 +3675,21 @@ var mk = (params) => createKyber({
2876
3675
  var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();
2877
3676
 
2878
3677
  // ../../node_modules/@noble/post-quantum/hybrid.js
3678
+ var validateKEM = (kem, title) => {
3679
+ const k = aobject3(kem, title);
3680
+ aobject3(k.lengths, `${title}.lengths`);
3681
+ afunction(k.keygen, `${title}.keygen`);
3682
+ afunction(k.getPublicKey, `${title}.getPublicKey`);
3683
+ afunction(k.encapsulate, `${title}.encapsulate`);
3684
+ afunction(k.decapsulate, `${title}.decapsulate`);
3685
+ return k;
3686
+ };
2879
3687
  function ecKeygen(curve, allowZeroKey = false) {
3688
+ const c = aobject3(curve, "curve");
3689
+ aobject3(c.lengths, "curve.lengths");
3690
+ afunction(c.keygen, "curve.keygen");
3691
+ afunction(c.getPublicKey, "curve.getPublicKey");
3692
+ abool2(allowZeroKey, "allowZeroKey");
2880
3693
  const lengths = curve.lengths;
2881
3694
  let keygen = curve.keygen;
2882
3695
  if (allowZeroKey) {
@@ -2900,10 +3713,14 @@ function ecKeygen(curve, allowZeroKey = false) {
2900
3713
  getPublicKey: (secretKey) => curve.getPublicKey(secretKey)
2901
3714
  };
2902
3715
  }
2903
- function ecdhKem(curve, allowZeroKey = false) {
3716
+ function _ecdhKem(curve, allowZeroKey = false) {
2904
3717
  const kg = ecKeygen(curve, allowZeroKey);
2905
3718
  if (!curve.getSharedSecret)
2906
3719
  throw new Error("wrong curve");
3720
+ const decapsulate = (cipherText, secretKey) => {
3721
+ const res = curve.getSharedSecret(secretKey, cipherText);
3722
+ return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
3723
+ };
2907
3724
  return {
2908
3725
  lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },
2909
3726
  keygen: kg.keygen,
@@ -2912,8 +3729,8 @@ function ecdhKem(curve, allowZeroKey = false) {
2912
3729
  const seed = copyBytes2(rand);
2913
3730
  let ek = void 0;
2914
3731
  try {
2915
- ek = this.keygen(seed).secretKey;
2916
- const sharedSecret = this.decapsulate(publicKey, ek);
3732
+ ek = kg.keygen(seed).secretKey;
3733
+ const sharedSecret = decapsulate(publicKey, ek);
2917
3734
  const cipherText = curve.getPublicKey(ek);
2918
3735
  return { sharedSecret, cipherText };
2919
3736
  } finally {
@@ -2922,18 +3739,23 @@ function ecdhKem(curve, allowZeroKey = false) {
2922
3739
  cleanBytes(ek);
2923
3740
  }
2924
3741
  },
2925
- decapsulate(cipherText, secretKey) {
2926
- const res = curve.getSharedSecret(secretKey, cipherText);
2927
- return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
2928
- }
3742
+ decapsulate
2929
3743
  };
2930
3744
  }
3745
+ function positiveLength(value, title) {
3746
+ const length = anumber(value, title);
3747
+ if (length === 0)
3748
+ throw new RangeError(`"${title}" expected integer greater than 0, got 0`);
3749
+ return length;
3750
+ }
2931
3751
  function splitLengths(lst, name) {
2932
- return splitCoder(name, ...lst.map((i) => {
3752
+ const coder = splitCoder(name, ...lst.map((i) => {
2933
3753
  if (typeof i.lengths[name] !== "number")
2934
3754
  throw new Error("wrong length: " + name);
2935
- return i.lengths[name];
3755
+ return positiveLength(i.lengths[name], name);
2936
3756
  }));
3757
+ positiveLength(coder.bytesLen, name);
3758
+ return coder;
2937
3759
  }
2938
3760
  function expandSeedXof(xof) {
2939
3761
  return ((seed, seedLen) => xof(seed, { dkLen: seedLen }));
@@ -2943,11 +3765,9 @@ function combineKeys(realSeedLen, expandSeed_, ...ck_) {
2943
3765
  const ck = ck_;
2944
3766
  const seedCoder = splitLengths(ck, "seed");
2945
3767
  const pkCoder = splitLengths(ck, "publicKey");
2946
- if (realSeedLen === void 0)
2947
- realSeedLen = seedCoder.bytesLen;
2948
- anumber(realSeedLen);
3768
+ const rootSeedLen = positiveLength(realSeedLen === void 0 ? seedCoder.bytesLen : realSeedLen, "realSeedLen");
2949
3769
  function expandDecapsulationKey(seed) {
2950
- abytes(seed, realSeedLen);
3770
+ abytes(seed, rootSeedLen);
2951
3771
  const expandedRaw = expandSeed(seed, seedCoder.bytesLen);
2952
3772
  const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes2(expandedRaw) : expandedRaw;
2953
3773
  const expanded = [];
@@ -2972,41 +3792,79 @@ function combineKeys(realSeedLen, expandSeed_, ...ck_) {
2972
3792
  cleanBytes(secretKey);
2973
3793
  }
2974
3794
  }
2975
- return {
2976
- info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },
2977
- getPublicKey(secretKey) {
2978
- return this.keygen(secretKey).publicKey;
2979
- },
2980
- keygen(seed = randomBytes3(realSeedLen)) {
2981
- const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);
3795
+ const keygen = (seed) => {
3796
+ const root = seed === void 0 ? randomBytes3(rootSeedLen) : copyBytes2(seed);
3797
+ let res;
3798
+ try {
3799
+ const { publicKey: pk, secretKey } = expandDecapsulationKey(root);
2982
3800
  try {
2983
- const publicKey = pkCoder.encode(pk);
2984
- return { secretKey: seed, publicKey };
3801
+ res = {
3802
+ secretKey: root,
3803
+ publicKey: pkCoder.encode(pk)
3804
+ };
2985
3805
  } finally {
2986
- cleanBytes(pk);
2987
- cleanBytes(secretKey);
3806
+ cleanBytes(pk, secretKey);
2988
3807
  }
3808
+ return res;
3809
+ } finally {
3810
+ if (!res)
3811
+ cleanBytes(root);
3812
+ }
3813
+ };
3814
+ return {
3815
+ info: { lengths: { seed: rootSeedLen, publicKey: pkCoder.bytesLen, secretKey: rootSeedLen } },
3816
+ // Composite secret keys are root seeds, so public-key derivation reruns key expansion from
3817
+ // that seed instead of decoding a packed child-secret-key structure.
3818
+ getPublicKey: (secretKey) => {
3819
+ const keys = keygen(secretKey);
3820
+ cleanBytes(keys.secretKey);
3821
+ return keys.publicKey;
2989
3822
  },
3823
+ keygen,
2990
3824
  expandDecapsulationKey,
2991
- realSeedLen
3825
+ realSeedLen: rootSeedLen
2992
3826
  };
2993
3827
  }
2994
3828
  function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
3829
+ if (realSeedLen !== void 0)
3830
+ positiveLength(realSeedLen, "realSeedLen");
3831
+ if (realMsgLen !== void 0)
3832
+ positiveLength(realMsgLen, "realMsgLen");
3833
+ if (typeof expandSeed !== "function")
3834
+ throw new TypeError('"expandSeed" expected function, got type=' + typeof expandSeed);
3835
+ if (typeof combiner !== "function")
3836
+ throw new TypeError('"combiner" expected function, got type=' + typeof combiner);
2995
3837
  const rawCombiner = combiner;
2996
3838
  const rawKems = kems;
3839
+ if (rawKems.length === 0)
3840
+ throw new RangeError("combineKEMS requires at least one KEM");
3841
+ for (let i = 0; i < rawKems.length; i++)
3842
+ validateKEM(rawKems[i], `kems[${i}]`);
2997
3843
  const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);
2998
3844
  const ctCoder = splitLengths(rawKems, "cipherText");
2999
3845
  const pkCoder = splitLengths(rawKems, "publicKey");
3000
3846
  const msgCoder = splitLengths(rawKems, "msg");
3001
- if (realMsgLen === void 0)
3002
- realMsgLen = msgCoder.bytesLen;
3003
- anumber(realMsgLen);
3847
+ const sharedSecretLen = positiveLength(realMsgLen === void 0 ? msgCoder.bytesLen : realMsgLen, "realMsgLen");
3004
3848
  const lengths = Object.freeze({
3005
3849
  ...keys.info.lengths,
3006
- msg: realMsgLen,
3850
+ msg: sharedSecretLen,
3007
3851
  msgRand: msgCoder.bytesLen,
3008
3852
  cipherText: ctCoder.bytesLen
3009
3853
  });
3854
+ const combine = (publicKeys, cipherTexts, sharedSecrets) => {
3855
+ const combined = rawCombiner(publicKeys, cipherTexts, sharedSecrets);
3856
+ try {
3857
+ return copyBytes2(abytes(combined, sharedSecretLen, "sharedSecret"));
3858
+ } catch (error) {
3859
+ if (isBytes(combined)) {
3860
+ const overlaps = (value) => combined.buffer === value.buffer && combined.byteOffset < value.byteOffset + value.byteLength && value.byteOffset < combined.byteOffset + combined.byteLength;
3861
+ const aliasesPublicInput = publicKeys.some(overlaps) || cipherTexts.some(overlaps);
3862
+ if (!aliasesPublicInput)
3863
+ cleanBytes(combined);
3864
+ }
3865
+ throw error;
3866
+ }
3867
+ };
3010
3868
  return Object.freeze({
3011
3869
  lengths,
3012
3870
  getPublicKey: keys.getPublicKey,
@@ -3018,15 +3876,16 @@ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
3018
3876
  const cipherText = [];
3019
3877
  try {
3020
3878
  for (let i = 0; i < rawKems.length; i++) {
3021
- const enc = rawKems[i].encapsulate(pks[i], rand[i]);
3022
- sharedSecret.push(enc.sharedSecret);
3023
- cipherText.push(enc.cipherText);
3879
+ const enc2 = rawKems[i].encapsulate(pks[i], rand[i]);
3880
+ sharedSecret.push(enc2.sharedSecret);
3881
+ cipherText.push(enc2.cipherText);
3024
3882
  }
3883
+ const encodedCipherText = ctCoder.encode(cipherText);
3025
3884
  return {
3026
3885
  // Detach the combiner result before cleanup: a caller-provided combiner may alias one of
3027
3886
  // the child sharedSecret buffers, and those child buffers are zeroized immediately below.
3028
- sharedSecret: copyBytes2(rawCombiner(pks, cipherText, sharedSecret)),
3029
- cipherText: ctCoder.encode(cipherText)
3887
+ sharedSecret: combine(pks, cipherText, sharedSecret),
3888
+ cipherText: encodedCipherText
3030
3889
  };
3031
3890
  } finally {
3032
3891
  cleanBytes(sharedSecret, cipherText);
@@ -3035,16 +3894,18 @@ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
3035
3894
  decapsulate(ct, seed) {
3036
3895
  const cts = ctCoder.decode(ct);
3037
3896
  const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);
3038
- const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));
3897
+ const sharedSecret = [];
3039
3898
  try {
3040
- return copyBytes2(rawCombiner(publicKey, cts, sharedSecret));
3899
+ for (let i = 0; i < rawKems.length; i++)
3900
+ sharedSecret.push(rawKems[i].decapsulate(cts[i], secretKey[i]));
3901
+ return combine(publicKey, cts, sharedSecret);
3041
3902
  } finally {
3042
3903
  cleanBytes(secretKey, sharedSecret);
3043
3904
  }
3044
3905
  }
3045
3906
  });
3046
3907
  }
3047
- var x25519kem = /* @__PURE__ */ ecdhKem(x25519);
3908
+ var x25519kem = /* @__PURE__ */ _ecdhKem(x25519);
3048
3909
  var ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(
3049
3910
  32,
3050
3911
  32,
@@ -3054,7 +3915,23 @@ var ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(
3054
3915
  ml_kem768,
3055
3916
  x25519kem
3056
3917
  ))();
3057
- var XWing = /* @__PURE__ */ (() => ml_kem768_x25519)();
3918
+
3919
+ // ../crypto/src/endpoint-health.ts
3920
+ var ENDPOINT_PROBE_INTERVAL_MINUTES = 15;
3921
+ var ENDPOINT_STALE_AFTER_MINUTES = ENDPOINT_PROBE_INTERVAL_MINUTES * 4;
3922
+ var ENDPOINT_UNUSABLE_AFTER_MINUTES = ENDPOINT_PROBE_INTERVAL_MINUTES * 24;
3923
+
3924
+ // ../crypto/src/registry-root-pin.ts
3925
+ var PINNED_REGISTRY_ROOTS = Object.freeze([
3926
+ Object.freeze({
3927
+ root_key_id: "rk1_251368ec9b0a84ae",
3928
+ spki_sha256: "251368ec9b0a84ae9881533bd1687efb7d439edd927aef47c1bb3bb069b3dc1d"
3929
+ })
3930
+ ]);
3931
+
3932
+ // ../crypto/src/vault-pin-hardening.ts
3933
+ var oprf = ristretto255_oprf.oprf;
3934
+ var enc = new TextEncoder();
3058
3935
 
3059
3936
  // ../crypto/src/index.ts
3060
3937
  function b64ToBytes(b64) {
@@ -3148,7 +4025,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
3148
4025
  const session_envelope = bytesToB64Url(concat(sessionIv, sessionCt));
3149
4026
  const skRawForWrap = new Uint8Array(await subtle().exportKey("raw", sk));
3150
4027
  if (isHybridScheme(partner.algorithm)) {
3151
- const { cipherText: kemCt, sharedSecret: sharedSecret2 } = XWing.encapsulate(b64ToBytes(partner.public_key_b64));
4028
+ const { cipherText: kemCt, sharedSecret: sharedSecret2 } = ml_kem768_x25519.encapsulate(b64ToBytes(partner.public_key_b64));
3152
4029
  const wrapSalt2 = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_SALT_LENGTH));
3153
4030
  const wrapKeyRaw2 = await subtle().deriveBits(
3154
4031
  { name: "HKDF", hash: "SHA-256", salt: wrapSalt2, info: sessionWrapInfoPq(partner.partner_id) },
@@ -3327,10 +4204,12 @@ var D5_BODY_CONDITIONAL = {
3327
4204
  crossover_key_ids: "key-crossover copy only"
3328
4205
  };
3329
4206
  var D5_BODY_DRILL_ONLY = ["conformance"];
4207
+ var D5_BODY_ADDED_AT_SEND = ["dispatch_id"];
3330
4208
  var D5_BODY_ALL_ALLOWED = [
3331
4209
  ...D5_BODY_ALWAYS,
3332
4210
  ...Object.keys(D5_BODY_CONDITIONAL),
3333
- ...D5_BODY_DRILL_ONLY
4211
+ ...D5_BODY_DRILL_ONLY,
4212
+ ...D5_BODY_ADDED_AT_SEND
3334
4213
  ];
3335
4214
 
3336
4215
  // ../protocol/src/retention.ts
@@ -3542,8 +4421,9 @@ async function post(url, body, headers, timeoutMs = 12e3) {
3542
4421
  clearTimeout(timer);
3543
4422
  }
3544
4423
  }
3545
- function signGet(timestamp, secret) {
3546
- return import_node_crypto.default.createHmac("sha256", secret).update(`${timestamp}.`).digest("hex");
4424
+ function signPullV2(timestamp, secret, url, method = "GET", body = "") {
4425
+ const u = new URL(url);
4426
+ return import_node_crypto.default.createHmac("sha256", secret).update(`v2.${timestamp}.${method.toUpperCase()}.${u.pathname}${u.search}.${body}`).digest("hex");
3547
4427
  }
3548
4428
  async function get(url, headers, timeoutMs = 12e3) {
3549
4429
  const controller = new AbortController();
@@ -3721,6 +4601,7 @@ async function runChecksDetailed(urlOrOptions, secret = TEST_WEBHOOK_SECRET, par
3721
4601
  const ts2 = String(Math.floor(Date.now() / 1e3));
3722
4602
  const sig2 = sign(sharedBody, ts2, secret);
3723
4603
  const res2 = await fetch(targetUrl, {
4604
+ redirect: "error",
3724
4605
  method: "POST",
3725
4606
  headers: buildHeaders(partnerId, ts2, sig2, `dedup-${dedupId}`),
3726
4607
  body: sharedBody
@@ -3793,6 +4674,7 @@ async function runChecksDetailed(urlOrOptions, secret = TEST_WEBHOOK_SECRET, par
3793
4674
  const ts = String(Math.floor(Date.now() / 1e3));
3794
4675
  const sig = sign(foreignBody, ts, secret);
3795
4676
  const res = await fetch(targetUrl, {
4677
+ redirect: "error",
3796
4678
  method: "POST",
3797
4679
  headers: buildHeaders(partnerId, ts, sig, `undecryptable-${import_node_crypto.default.randomUUID().slice(0, 8)}`),
3798
4680
  body: foreignBody,
@@ -3827,6 +4709,7 @@ async function runChecksDetailed(urlOrOptions, secret = TEST_WEBHOOK_SECRET, par
3827
4709
  const ts = String(Math.floor(Date.now() / 1e3));
3828
4710
  const sig = sign(body, ts, secret);
3829
4711
  const res = await fetch(targetUrl, {
4712
+ redirect: "error",
3830
4713
  method: "POST",
3831
4714
  headers: buildHeaders(partnerId, ts, sig, `nomatch-${nonce.slice(0, 8)}`),
3832
4715
  body,
@@ -3868,6 +4751,7 @@ async function runChecksDetailed(urlOrOptions, secret = TEST_WEBHOOK_SECRET, par
3868
4751
  const ts = String(Math.floor(Date.now() / 1e3));
3869
4752
  const sig = sign(body, ts, secret);
3870
4753
  const res = await fetch(targetUrl, {
4754
+ redirect: "error",
3871
4755
  method: "POST",
3872
4756
  // `contact.updated`, matching what the relay now sends for a dispatch
3873
4757
  // carrying no address (`dispatchEventName`). This line previously said
@@ -4044,11 +4928,12 @@ async function runChecksDetailed(urlOrOptions, secret = TEST_WEBHOOK_SECRET, par
4044
4928
  const pullBase = customerUrl.replace(/\/$/, "");
4045
4929
  {
4046
4930
  const ts = String(Math.floor(Date.now() / 1e3));
4047
- const sig = signGet(ts, secret);
4048
4931
  const url = `${pullBase}/api/partners/${partnerId}/updates`;
4932
+ const sig = signPullV2(ts, secret, url);
4049
4933
  const { status, error } = await get(url, {
4050
4934
  "X-OneAddress-Timestamp": ts,
4051
- "X-OneAddress-Signature": sig
4935
+ "X-OneAddress-Signature": sig,
4936
+ "X-OneAddress-Signature-Version": "2"
4052
4937
  });
4053
4938
  const passed = !error && status === 200;
4054
4939
  results.push({
@@ -4061,11 +4946,12 @@ async function runChecksDetailed(urlOrOptions, secret = TEST_WEBHOOK_SECRET, par
4061
4946
  }
4062
4947
  {
4063
4948
  const ts = String(Math.floor(Date.now() / 1e3));
4064
- const sig = signGet(ts, secret);
4065
4949
  const url = `${pullBase}/api/partners/${partnerId}/audit`;
4950
+ const sig = signPullV2(ts, secret, url);
4066
4951
  const { status, headers: resHdrs, body: resBody, error } = await get(url, {
4067
4952
  "X-OneAddress-Timestamp": ts,
4068
- "X-OneAddress-Signature": sig
4953
+ "X-OneAddress-Signature": sig,
4954
+ "X-OneAddress-Signature-Version": "2"
4069
4955
  });
4070
4956
  let passed = false;
4071
4957
  let detail;
@@ -4459,6 +5345,7 @@ main().catch((err) => {
4459
5345
  @noble/curves/abstract/curve.js:
4460
5346
  @noble/curves/abstract/edwards.js:
4461
5347
  @noble/curves/abstract/montgomery.js:
5348
+ @noble/curves/abstract/oprf.js:
4462
5349
  @noble/curves/ed25519.js:
4463
5350
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4464
5351