@toon-protocol/client-mcp 0.1.0 → 0.2.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.
@@ -1,13 +1,17 @@
1
1
  import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
2
2
 
3
- // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/utils.js
3
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js
4
4
  function isBytes(a) {
5
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
5
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
6
6
  }
7
7
  function anumber(n, title = "") {
8
+ if (typeof n !== "number") {
9
+ const prefix = title && `"${title}" `;
10
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
11
+ }
8
12
  if (!Number.isSafeInteger(n) || n < 0) {
9
13
  const prefix = title && `"${title}" `;
10
- throw new Error(`${prefix}expected integer >= 0, got ${n}`);
14
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
11
15
  }
12
16
  }
13
17
  function abytes(value, length, title = "") {
@@ -18,7 +22,10 @@ function abytes(value, length, title = "") {
18
22
  const prefix = title && `"${title}" `;
19
23
  const ofLen = needsLen ? ` of length ${length}` : "";
20
24
  const got = bytes ? `length=${len}` : `type=${typeof value}`;
21
- throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
25
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
26
+ if (!bytes)
27
+ throw new TypeError(message);
28
+ throw new RangeError(message);
22
29
  }
23
30
  return value;
24
31
  }
@@ -32,7 +39,7 @@ function aoutput(out, instance) {
32
39
  abytes(out, void 0, "digestInto() output");
33
40
  const min = instance.outputLen;
34
41
  if (out.length < min) {
35
- throw new Error('"digestInto() output" expected to be of length >=' + min);
42
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
36
43
  }
37
44
  }
38
45
  function clean(...arrays) {
@@ -43,6 +50,9 @@ function clean(...arrays) {
43
50
  function createView(arr) {
44
51
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
45
52
  }
53
+ function rotr(word, shift) {
54
+ return word << 32 - shift | word >>> shift;
55
+ }
46
56
  var hasHexBuiltin = /* @__PURE__ */ (() => (
47
57
  // @ts-ignore
48
58
  typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
@@ -70,25 +80,37 @@ function asciiToBase16(ch) {
70
80
  }
71
81
  function hexToBytes(hex) {
72
82
  if (typeof hex !== "string")
73
- throw new Error("hex string expected, got " + typeof hex);
74
- if (hasHexBuiltin)
75
- return Uint8Array.fromHex(hex);
83
+ throw new TypeError("hex string expected, got " + typeof hex);
84
+ if (hasHexBuiltin) {
85
+ try {
86
+ return Uint8Array.fromHex(hex);
87
+ } catch (error) {
88
+ if (error instanceof SyntaxError)
89
+ throw new RangeError(error.message);
90
+ throw error;
91
+ }
92
+ }
76
93
  const hl = hex.length;
77
94
  const al = hl / 2;
78
95
  if (hl % 2)
79
- throw new Error("hex string expected, got unpadded hex of length " + hl);
96
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
80
97
  const array = new Uint8Array(al);
81
98
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
82
99
  const n1 = asciiToBase16(hex.charCodeAt(hi));
83
100
  const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
84
101
  if (n1 === void 0 || n2 === void 0) {
85
102
  const char = hex[hi] + hex[hi + 1];
86
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
103
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
87
104
  }
88
105
  array[ai] = n1 * 16 + n2;
89
106
  }
90
107
  return array;
91
108
  }
109
+ function utf8ToBytes(str) {
110
+ if (typeof str !== "string")
111
+ throw new TypeError("string expected");
112
+ return new Uint8Array(new TextEncoder().encode(str));
113
+ }
92
114
  function concatBytes(...arrays) {
93
115
  let sum = 0;
94
116
  for (let i = 0; i < arrays.length; i++) {
@@ -109,24 +131,37 @@ function createHasher(hashCons, info = {}) {
109
131
  const tmp = hashCons(void 0);
110
132
  hashC.outputLen = tmp.outputLen;
111
133
  hashC.blockLen = tmp.blockLen;
134
+ hashC.canXOF = tmp.canXOF;
112
135
  hashC.create = (opts) => hashCons(opts);
113
136
  Object.assign(hashC, info);
114
137
  return Object.freeze(hashC);
115
138
  }
116
139
  function randomBytes(bytesLength = 32) {
140
+ anumber(bytesLength, "bytesLength");
117
141
  const cr = typeof globalThis === "object" ? globalThis.crypto : null;
118
142
  if (typeof cr?.getRandomValues !== "function")
119
143
  throw new Error("crypto.getRandomValues must be defined");
144
+ if (bytesLength > 65536)
145
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
120
146
  return cr.getRandomValues(new Uint8Array(bytesLength));
121
147
  }
122
148
  var oidNist = (suffix) => ({
149
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
150
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
123
151
  oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
124
152
  });
125
153
 
126
- // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_md.js
154
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js
155
+ function Chi(a, b, c) {
156
+ return a & b ^ ~a & c;
157
+ }
158
+ function Maj(a, b, c) {
159
+ return a & b ^ a & c ^ b & c;
160
+ }
127
161
  var HashMD = class {
128
162
  blockLen;
129
163
  outputLen;
164
+ canXOF = false;
130
165
  padOffset;
131
166
  isLE;
132
167
  // For partial updates less than block size
@@ -219,6 +254,16 @@ var HashMD = class {
219
254
  return this._cloneInto();
220
255
  }
221
256
  };
257
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
258
+ 1779033703,
259
+ 3144134277,
260
+ 1013904242,
261
+ 2773480762,
262
+ 1359893119,
263
+ 2600822924,
264
+ 528734635,
265
+ 1541459225
266
+ ]);
222
267
  var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
223
268
  1779033703,
224
269
  4089235720,
@@ -238,7 +283,7 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
238
283
  327033209
239
284
  ]);
240
285
 
241
- // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_u64.js
286
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js
242
287
  var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
243
288
  var _32n = /* @__PURE__ */ BigInt(32);
244
289
  function fromBig(n, le = false) {
@@ -273,7 +318,152 @@ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0
273
318
  var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
274
319
  var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
275
320
 
276
- // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/sha2.js
321
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js
322
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
323
+ 1116352408,
324
+ 1899447441,
325
+ 3049323471,
326
+ 3921009573,
327
+ 961987163,
328
+ 1508970993,
329
+ 2453635748,
330
+ 2870763221,
331
+ 3624381080,
332
+ 310598401,
333
+ 607225278,
334
+ 1426881987,
335
+ 1925078388,
336
+ 2162078206,
337
+ 2614888103,
338
+ 3248222580,
339
+ 3835390401,
340
+ 4022224774,
341
+ 264347078,
342
+ 604807628,
343
+ 770255983,
344
+ 1249150122,
345
+ 1555081692,
346
+ 1996064986,
347
+ 2554220882,
348
+ 2821834349,
349
+ 2952996808,
350
+ 3210313671,
351
+ 3336571891,
352
+ 3584528711,
353
+ 113926993,
354
+ 338241895,
355
+ 666307205,
356
+ 773529912,
357
+ 1294757372,
358
+ 1396182291,
359
+ 1695183700,
360
+ 1986661051,
361
+ 2177026350,
362
+ 2456956037,
363
+ 2730485921,
364
+ 2820302411,
365
+ 3259730800,
366
+ 3345764771,
367
+ 3516065817,
368
+ 3600352804,
369
+ 4094571909,
370
+ 275423344,
371
+ 430227734,
372
+ 506948616,
373
+ 659060556,
374
+ 883997877,
375
+ 958139571,
376
+ 1322822218,
377
+ 1537002063,
378
+ 1747873779,
379
+ 1955562222,
380
+ 2024104815,
381
+ 2227730452,
382
+ 2361852424,
383
+ 2428436474,
384
+ 2756734187,
385
+ 3204031479,
386
+ 3329325298
387
+ ]);
388
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
389
+ var SHA2_32B = class extends HashMD {
390
+ constructor(outputLen) {
391
+ super(64, outputLen, 8, false);
392
+ }
393
+ get() {
394
+ const { A, B, C, D, E, F, G, H } = this;
395
+ return [A, B, C, D, E, F, G, H];
396
+ }
397
+ // prettier-ignore
398
+ set(A, B, C, D, E, F, G, H) {
399
+ this.A = A | 0;
400
+ this.B = B | 0;
401
+ this.C = C | 0;
402
+ this.D = D | 0;
403
+ this.E = E | 0;
404
+ this.F = F | 0;
405
+ this.G = G | 0;
406
+ this.H = H | 0;
407
+ }
408
+ process(view, offset) {
409
+ for (let i = 0; i < 16; i++, offset += 4)
410
+ SHA256_W[i] = view.getUint32(offset, false);
411
+ for (let i = 16; i < 64; i++) {
412
+ const W15 = SHA256_W[i - 15];
413
+ const W2 = SHA256_W[i - 2];
414
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
415
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
416
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
417
+ }
418
+ let { A, B, C, D, E, F, G, H } = this;
419
+ for (let i = 0; i < 64; i++) {
420
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
421
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
422
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
423
+ const T2 = sigma0 + Maj(A, B, C) | 0;
424
+ H = G;
425
+ G = F;
426
+ F = E;
427
+ E = D + T1 | 0;
428
+ D = C;
429
+ C = B;
430
+ B = A;
431
+ A = T1 + T2 | 0;
432
+ }
433
+ A = A + this.A | 0;
434
+ B = B + this.B | 0;
435
+ C = C + this.C | 0;
436
+ D = D + this.D | 0;
437
+ E = E + this.E | 0;
438
+ F = F + this.F | 0;
439
+ G = G + this.G | 0;
440
+ H = H + this.H | 0;
441
+ this.set(A, B, C, D, E, F, G, H);
442
+ }
443
+ roundClean() {
444
+ clean(SHA256_W);
445
+ }
446
+ destroy() {
447
+ this.destroyed = true;
448
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
449
+ clean(this.buffer);
450
+ }
451
+ };
452
+ var _SHA256 = class extends SHA2_32B {
453
+ // We cannot use array here since array allows indexing by variable
454
+ // which means optimizer/compiler cannot use registers.
455
+ A = SHA256_IV[0] | 0;
456
+ B = SHA256_IV[1] | 0;
457
+ C = SHA256_IV[2] | 0;
458
+ D = SHA256_IV[3] | 0;
459
+ E = SHA256_IV[4] | 0;
460
+ F = SHA256_IV[5] | 0;
461
+ G = SHA256_IV[6] | 0;
462
+ H = SHA256_IV[7] | 0;
463
+ constructor() {
464
+ super(32);
465
+ }
466
+ };
277
467
  var K512 = /* @__PURE__ */ (() => split([
278
468
  "0x428a2f98d728ae22",
279
469
  "0x7137449123ef65cd",
@@ -451,6 +641,7 @@ var SHA2_64B = class extends HashMD {
451
641
  clean(SHA512_W_H, SHA512_W_L);
452
642
  }
453
643
  destroy() {
644
+ this.destroyed = true;
454
645
  clean(this.buffer);
455
646
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
456
647
  }
@@ -476,38 +667,53 @@ var _SHA512 = class extends SHA2_64B {
476
667
  super(64);
477
668
  }
478
669
  };
670
+ var sha256 = /* @__PURE__ */ createHasher(
671
+ () => new _SHA256(),
672
+ /* @__PURE__ */ oidNist(1)
673
+ );
479
674
  var sha512 = /* @__PURE__ */ createHasher(
480
675
  () => new _SHA512(),
481
676
  /* @__PURE__ */ oidNist(3)
482
677
  );
483
678
 
484
- // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/utils.js
679
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/utils.js
680
+ var abytes2 = (value, length, title) => abytes(value, length, title);
681
+ var anumber2 = anumber;
682
+ var bytesToHex2 = bytesToHex;
683
+ var concatBytes2 = (...arrays) => concatBytes(...arrays);
684
+ var hexToBytes2 = (hex) => hexToBytes(hex);
685
+ var isBytes2 = isBytes;
686
+ var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
485
687
  var _0n = /* @__PURE__ */ BigInt(0);
486
688
  var _1n = /* @__PURE__ */ BigInt(1);
487
689
  function abool(value, title = "") {
488
690
  if (typeof value !== "boolean") {
489
691
  const prefix = title && `"${title}" `;
490
- throw new Error(prefix + "expected boolean, got type=" + typeof value);
692
+ throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
491
693
  }
492
694
  return value;
493
695
  }
494
696
  function abignumber(n) {
495
697
  if (typeof n === "bigint") {
496
698
  if (!isPosBig(n))
497
- throw new Error("positive bigint expected, got " + n);
699
+ throw new RangeError("positive bigint expected, got " + n);
498
700
  } else
499
- anumber(n);
701
+ anumber2(n);
500
702
  return n;
501
703
  }
502
704
  function asafenumber(value, title = "") {
705
+ if (typeof value !== "number") {
706
+ const prefix = title && `"${title}" `;
707
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
708
+ }
503
709
  if (!Number.isSafeInteger(value)) {
504
710
  const prefix = title && `"${title}" `;
505
- throw new Error(prefix + "expected safe integer, got type=" + typeof value);
711
+ throw new RangeError(prefix + "expected safe integer, got " + value);
506
712
  }
507
713
  }
508
714
  function hexToNumber(hex) {
509
715
  if (typeof hex !== "string")
510
- throw new Error("hex string expected, got " + typeof hex);
716
+ throw new TypeError("hex string expected, got " + typeof hex);
511
717
  return hex === "" ? _0n : BigInt("0x" + hex);
512
718
  }
513
719
  function bytesToNumberBE(bytes) {
@@ -518,16 +724,20 @@ function bytesToNumberLE(bytes) {
518
724
  }
519
725
  function numberToBytesBE(n, len) {
520
726
  anumber(len);
727
+ if (len === 0)
728
+ throw new RangeError("zero length");
521
729
  n = abignumber(n);
522
- const res = hexToBytes(n.toString(16).padStart(len * 2, "0"));
523
- if (res.length !== len)
524
- throw new Error("number too large");
525
- return res;
730
+ const hex = n.toString(16);
731
+ if (hex.length > len * 2)
732
+ throw new RangeError("number too large");
733
+ return hexToBytes(hex.padStart(len * 2, "0"));
526
734
  }
527
735
  function numberToBytesLE(n, len) {
528
736
  return numberToBytesBE(n, len).reverse();
529
737
  }
530
738
  function equalBytes(a, b) {
739
+ a = abytes2(a);
740
+ b = abytes2(b);
531
741
  if (a.length !== b.length)
532
742
  return false;
533
743
  let diff = 0;
@@ -536,13 +746,15 @@ function equalBytes(a, b) {
536
746
  return diff === 0;
537
747
  }
538
748
  function copyBytes(bytes) {
539
- return Uint8Array.from(bytes);
749
+ return Uint8Array.from(abytes2(bytes));
540
750
  }
541
751
  function asciiToBytes(ascii) {
752
+ if (typeof ascii !== "string")
753
+ throw new TypeError("ascii string expected, got " + typeof ascii);
542
754
  return Uint8Array.from(ascii, (c, i) => {
543
755
  const charCode = c.charCodeAt(0);
544
756
  if (c.length !== 1 || charCode > 127) {
545
- throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
757
+ throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
546
758
  }
547
759
  return charCode;
548
760
  });
@@ -553,9 +765,11 @@ function inRange(n, min, max) {
553
765
  }
554
766
  function aInRange(title, n, min, max) {
555
767
  if (!inRange(n, min, max))
556
- throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
768
+ throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
557
769
  }
558
770
  function bitLen(n) {
771
+ if (n < _0n)
772
+ throw new Error("expected non-negative bigint, got " + n);
559
773
  let len;
560
774
  for (len = 0; n > _0n; n >>= _1n, len += 1)
561
775
  ;
@@ -563,15 +777,17 @@ function bitLen(n) {
563
777
  }
564
778
  var bitMask = (n) => (_1n << BigInt(n)) - _1n;
565
779
  function validateObject(object, fields = {}, optFields = {}) {
566
- if (!object || typeof object !== "object")
567
- throw new Error("expected valid options object");
780
+ if (Object.prototype.toString.call(object) !== "[object Object]")
781
+ throw new TypeError("expected valid options object");
568
782
  function checkField(fieldName, expectedType, isOpt) {
783
+ if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
784
+ throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
569
785
  const val = object[fieldName];
570
786
  if (isOpt && val === void 0)
571
787
  return;
572
788
  const current = typeof val;
573
789
  if (current !== expectedType || val === null)
574
- throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
790
+ throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
575
791
  }
576
792
  const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
577
793
  iter(fields, false);
@@ -580,19 +796,8 @@ function validateObject(object, fields = {}, optFields = {}) {
580
796
  var notImplemented = () => {
581
797
  throw new Error("not implemented");
582
798
  };
583
- function memoized(fn) {
584
- const map = /* @__PURE__ */ new WeakMap();
585
- return (arg, ...args) => {
586
- const val = map.get(arg);
587
- if (val !== void 0)
588
- return val;
589
- const computed = fn(arg, ...args);
590
- map.set(arg, computed);
591
- return computed;
592
- };
593
- }
594
799
 
595
- // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/modular.js
800
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/modular.js
596
801
  var _0n2 = /* @__PURE__ */ BigInt(0);
597
802
  var _1n2 = /* @__PURE__ */ BigInt(1);
598
803
  var _2n = /* @__PURE__ */ BigInt(2);
@@ -604,10 +809,14 @@ var _8n = /* @__PURE__ */ BigInt(8);
604
809
  var _9n = /* @__PURE__ */ BigInt(9);
605
810
  var _16n = /* @__PURE__ */ BigInt(16);
606
811
  function mod(a, b) {
812
+ if (b <= _0n2)
813
+ throw new Error("mod: expected positive modulus, got " + b);
607
814
  const result = a % b;
608
815
  return result >= _0n2 ? result : b + result;
609
816
  }
610
817
  function pow2(x, power, modulo) {
818
+ if (power < _0n2)
819
+ throw new Error("pow2: expected non-negative exponent, got " + power);
611
820
  let res = x;
612
821
  while (power-- > _0n2) {
613
822
  res *= res;
@@ -625,7 +834,7 @@ function invert(number, modulo) {
625
834
  let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
626
835
  while (a !== _0n2) {
627
836
  const q = b / a;
628
- const r = b % a;
837
+ const r = b - a * q;
629
838
  const m = x - u * q;
630
839
  const n = y - v * q;
631
840
  b = a, a = r, x = u, y = v, u = m, v = n;
@@ -636,23 +845,26 @@ function invert(number, modulo) {
636
845
  return mod(x, modulo);
637
846
  }
638
847
  function assertIsSquare(Fp2, root, n) {
639
- if (!Fp2.eql(Fp2.sqr(root), n))
848
+ const F = Fp2;
849
+ if (!F.eql(F.sqr(root), n))
640
850
  throw new Error("Cannot find square root");
641
851
  }
642
852
  function sqrt3mod4(Fp2, n) {
643
- const p1div4 = (Fp2.ORDER + _1n2) / _4n;
644
- const root = Fp2.pow(n, p1div4);
645
- assertIsSquare(Fp2, root, n);
853
+ const F = Fp2;
854
+ const p1div4 = (F.ORDER + _1n2) / _4n;
855
+ const root = F.pow(n, p1div4);
856
+ assertIsSquare(F, root, n);
646
857
  return root;
647
858
  }
648
859
  function sqrt5mod8(Fp2, n) {
649
- const p5div8 = (Fp2.ORDER - _5n) / _8n;
650
- const n2 = Fp2.mul(n, _2n);
651
- const v = Fp2.pow(n2, p5div8);
652
- const nv = Fp2.mul(n, v);
653
- const i = Fp2.mul(Fp2.mul(nv, _2n), v);
654
- const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
655
- assertIsSquare(Fp2, root, n);
860
+ const F = Fp2;
861
+ const p5div8 = (F.ORDER - _5n) / _8n;
862
+ const n2 = F.mul(n, _2n);
863
+ const v = F.pow(n2, p5div8);
864
+ const nv = F.mul(n, v);
865
+ const i = F.mul(F.mul(nv, _2n), v);
866
+ const root = F.mul(nv, F.sub(i, F.ONE));
867
+ assertIsSquare(F, root, n);
656
868
  return root;
657
869
  }
658
870
  function sqrt9mod16(P) {
@@ -662,20 +874,21 @@ function sqrt9mod16(P) {
662
874
  const c2 = tn(Fp_, c1);
663
875
  const c3 = tn(Fp_, Fp_.neg(c1));
664
876
  const c4 = (P + _7n) / _16n;
665
- return (Fp2, n) => {
666
- let tv1 = Fp2.pow(n, c4);
667
- let tv2 = Fp2.mul(tv1, c1);
668
- const tv3 = Fp2.mul(tv1, c2);
669
- const tv4 = Fp2.mul(tv1, c3);
670
- const e1 = Fp2.eql(Fp2.sqr(tv2), n);
671
- const e2 = Fp2.eql(Fp2.sqr(tv3), n);
672
- tv1 = Fp2.cmov(tv1, tv2, e1);
673
- tv2 = Fp2.cmov(tv4, tv3, e2);
674
- const e3 = Fp2.eql(Fp2.sqr(tv2), n);
675
- const root = Fp2.cmov(tv1, tv2, e3);
676
- assertIsSquare(Fp2, root, n);
877
+ return ((Fp2, n) => {
878
+ const F = Fp2;
879
+ let tv1 = F.pow(n, c4);
880
+ let tv2 = F.mul(tv1, c1);
881
+ const tv3 = F.mul(tv1, c2);
882
+ const tv4 = F.mul(tv1, c3);
883
+ const e1 = F.eql(F.sqr(tv2), n);
884
+ const e2 = F.eql(F.sqr(tv3), n);
885
+ tv1 = F.cmov(tv1, tv2, e1);
886
+ tv2 = F.cmov(tv4, tv3, e2);
887
+ const e3 = F.eql(F.sqr(tv2), n);
888
+ const root = F.cmov(tv1, tv2, e3);
889
+ assertIsSquare(F, root, n);
677
890
  return root;
678
- };
891
+ });
679
892
  }
680
893
  function tonelliShanks(P) {
681
894
  if (P < _3n)
@@ -697,31 +910,32 @@ function tonelliShanks(P) {
697
910
  let cc = _Fp.pow(Z, Q);
698
911
  const Q1div2 = (Q + _1n2) / _2n;
699
912
  return function tonelliSlow(Fp2, n) {
700
- if (Fp2.is0(n))
913
+ const F = Fp2;
914
+ if (F.is0(n))
701
915
  return n;
702
- if (FpLegendre(Fp2, n) !== 1)
916
+ if (FpLegendre(F, n) !== 1)
703
917
  throw new Error("Cannot find square root");
704
918
  let M = S;
705
- let c = Fp2.mul(Fp2.ONE, cc);
706
- let t = Fp2.pow(n, Q);
707
- let R = Fp2.pow(n, Q1div2);
708
- while (!Fp2.eql(t, Fp2.ONE)) {
709
- if (Fp2.is0(t))
710
- return Fp2.ZERO;
919
+ let c = F.mul(F.ONE, cc);
920
+ let t = F.pow(n, Q);
921
+ let R = F.pow(n, Q1div2);
922
+ while (!F.eql(t, F.ONE)) {
923
+ if (F.is0(t))
924
+ return F.ZERO;
711
925
  let i = 1;
712
- let t_tmp = Fp2.sqr(t);
713
- while (!Fp2.eql(t_tmp, Fp2.ONE)) {
926
+ let t_tmp = F.sqr(t);
927
+ while (!F.eql(t_tmp, F.ONE)) {
714
928
  i++;
715
- t_tmp = Fp2.sqr(t_tmp);
929
+ t_tmp = F.sqr(t_tmp);
716
930
  if (i === M)
717
931
  throw new Error("Cannot find square root");
718
932
  }
719
933
  const exponent = _1n2 << BigInt(M - i - 1);
720
- const b = Fp2.pow(c, exponent);
934
+ const b = F.pow(c, exponent);
721
935
  M = i;
722
- c = Fp2.sqr(b);
723
- t = Fp2.mul(t, c);
724
- R = Fp2.mul(R, b);
936
+ c = F.sqr(b);
937
+ t = F.mul(t, c);
938
+ R = F.mul(R, b);
725
939
  }
726
940
  return R;
727
941
  };
@@ -766,59 +980,76 @@ function validateField(field) {
766
980
  return map;
767
981
  }, initial);
768
982
  validateObject(field, opts);
983
+ asafenumber(field.BYTES, "BYTES");
984
+ asafenumber(field.BITS, "BITS");
985
+ if (field.BYTES < 1 || field.BITS < 1)
986
+ throw new Error("invalid field: expected BYTES/BITS > 0");
987
+ if (field.ORDER <= _1n2)
988
+ throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
769
989
  return field;
770
990
  }
771
991
  function FpPow(Fp2, num, power) {
992
+ const F = Fp2;
772
993
  if (power < _0n2)
773
994
  throw new Error("invalid exponent, negatives unsupported");
774
995
  if (power === _0n2)
775
- return Fp2.ONE;
996
+ return F.ONE;
776
997
  if (power === _1n2)
777
998
  return num;
778
- let p = Fp2.ONE;
999
+ let p = F.ONE;
779
1000
  let d = num;
780
1001
  while (power > _0n2) {
781
1002
  if (power & _1n2)
782
- p = Fp2.mul(p, d);
783
- d = Fp2.sqr(d);
1003
+ p = F.mul(p, d);
1004
+ d = F.sqr(d);
784
1005
  power >>= _1n2;
785
1006
  }
786
1007
  return p;
787
1008
  }
788
1009
  function FpInvertBatch(Fp2, nums, passZero = false) {
789
- const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0);
1010
+ const F = Fp2;
1011
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
790
1012
  const multipliedAcc = nums.reduce((acc, num, i) => {
791
- if (Fp2.is0(num))
1013
+ if (F.is0(num))
792
1014
  return acc;
793
1015
  inverted[i] = acc;
794
- return Fp2.mul(acc, num);
795
- }, Fp2.ONE);
796
- const invertedAcc = Fp2.inv(multipliedAcc);
1016
+ return F.mul(acc, num);
1017
+ }, F.ONE);
1018
+ const invertedAcc = F.inv(multipliedAcc);
797
1019
  nums.reduceRight((acc, num, i) => {
798
- if (Fp2.is0(num))
1020
+ if (F.is0(num))
799
1021
  return acc;
800
- inverted[i] = Fp2.mul(acc, inverted[i]);
801
- return Fp2.mul(acc, num);
1022
+ inverted[i] = F.mul(acc, inverted[i]);
1023
+ return F.mul(acc, num);
802
1024
  }, invertedAcc);
803
1025
  return inverted;
804
1026
  }
805
1027
  function FpLegendre(Fp2, n) {
806
- const p1mod2 = (Fp2.ORDER - _1n2) / _2n;
807
- const powered = Fp2.pow(n, p1mod2);
808
- const yes = Fp2.eql(powered, Fp2.ONE);
809
- const zero = Fp2.eql(powered, Fp2.ZERO);
810
- const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
1028
+ const F = Fp2;
1029
+ const p1mod2 = (F.ORDER - _1n2) / _2n;
1030
+ const powered = F.pow(n, p1mod2);
1031
+ const yes = F.eql(powered, F.ONE);
1032
+ const zero = F.eql(powered, F.ZERO);
1033
+ const no = F.eql(powered, F.neg(F.ONE));
811
1034
  if (!yes && !zero && !no)
812
1035
  throw new Error("invalid Legendre symbol result");
813
1036
  return yes ? 1 : zero ? 0 : -1;
814
1037
  }
815
1038
  function nLength(n, nBitLength) {
816
1039
  if (nBitLength !== void 0)
817
- anumber(nBitLength);
818
- const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
1040
+ anumber2(nBitLength);
1041
+ if (n <= _0n2)
1042
+ throw new Error("invalid n length: expected positive n, got " + n);
1043
+ if (nBitLength !== void 0 && nBitLength < 1)
1044
+ throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
1045
+ const bits = bitLen(n);
1046
+ if (nBitLength !== void 0 && nBitLength < bits)
1047
+ throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
1048
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
819
1049
  const nByteLength = Math.ceil(_nBitLength / 8);
820
1050
  return { nBitLength: _nBitLength, nByteLength };
821
1051
  }
1052
+ var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
822
1053
  var _Field = class {
823
1054
  ORDER;
824
1055
  BITS;
@@ -827,23 +1058,21 @@ var _Field = class {
827
1058
  ZERO = _0n2;
828
1059
  ONE = _1n2;
829
1060
  _lengths;
830
- _sqrt;
831
- // cached sqrt
832
1061
  _mod;
833
1062
  constructor(ORDER, opts = {}) {
834
- if (ORDER <= _0n2)
835
- throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
1063
+ if (ORDER <= _1n2)
1064
+ throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
836
1065
  let _nbitLength = void 0;
837
1066
  this.isLE = false;
838
1067
  if (opts != null && typeof opts === "object") {
839
1068
  if (typeof opts.BITS === "number")
840
1069
  _nbitLength = opts.BITS;
841
1070
  if (typeof opts.sqrt === "function")
842
- this.sqrt = opts.sqrt;
1071
+ Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
843
1072
  if (typeof opts.isLE === "boolean")
844
1073
  this.isLE = opts.isLE;
845
1074
  if (opts.allowedLengths)
846
- this._lengths = opts.allowedLengths?.slice();
1075
+ this._lengths = Object.freeze(opts.allowedLengths.slice());
847
1076
  if (typeof opts.modFromBytes === "boolean")
848
1077
  this._mod = opts.modFromBytes;
849
1078
  }
@@ -853,15 +1082,14 @@ var _Field = class {
853
1082
  this.ORDER = ORDER;
854
1083
  this.BITS = nBitLength;
855
1084
  this.BYTES = nByteLength;
856
- this._sqrt = void 0;
857
- Object.preventExtensions(this);
1085
+ Object.freeze(this);
858
1086
  }
859
1087
  create(num) {
860
1088
  return mod(num, this.ORDER);
861
1089
  }
862
1090
  isValid(num) {
863
1091
  if (typeof num !== "bigint")
864
- throw new Error("invalid field element: expected bigint, got " + typeof num);
1092
+ throw new TypeError("invalid field element: expected bigint, got " + typeof num);
865
1093
  return _0n2 <= num && num < this.ORDER;
866
1094
  }
867
1095
  is0(num) {
@@ -915,18 +1143,19 @@ var _Field = class {
915
1143
  return invert(num, this.ORDER);
916
1144
  }
917
1145
  sqrt(num) {
918
- if (!this._sqrt)
919
- this._sqrt = FpSqrt(this.ORDER);
920
- return this._sqrt(this, num);
1146
+ let sqrt = FIELD_SQRT.get(this);
1147
+ if (!sqrt)
1148
+ FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
1149
+ return sqrt(this, num);
921
1150
  }
922
1151
  toBytes(num) {
923
1152
  return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
924
1153
  }
925
1154
  fromBytes(bytes, skipValidation = false) {
926
- abytes(bytes);
1155
+ abytes2(bytes);
927
1156
  const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
928
1157
  if (allowedLengths) {
929
- if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1158
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
930
1159
  throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
931
1160
  }
932
1161
  const padded = new Uint8Array(BYTES);
@@ -951,22 +1180,27 @@ var _Field = class {
951
1180
  // We can't move this out because Fp6, Fp12 implement it
952
1181
  // and it's unclear what to return in there.
953
1182
  cmov(a, b, condition) {
1183
+ abool(condition, "condition");
954
1184
  return condition ? b : a;
955
1185
  }
956
1186
  };
1187
+ Object.freeze(_Field.prototype);
957
1188
  function Field(ORDER, opts = {}) {
958
1189
  return new _Field(ORDER, opts);
959
1190
  }
960
1191
  function FpSqrtEven(Fp2, elm) {
961
- if (!Fp2.isOdd)
1192
+ const F = Fp2;
1193
+ if (!F.isOdd)
962
1194
  throw new Error("Field doesn't have isOdd");
963
- const root = Fp2.sqrt(elm);
964
- return Fp2.isOdd(root) ? Fp2.neg(root) : root;
1195
+ const root = F.sqrt(elm);
1196
+ return F.isOdd(root) ? F.neg(root) : root;
965
1197
  }
966
1198
  function getFieldBytesLength(fieldOrder) {
967
1199
  if (typeof fieldOrder !== "bigint")
968
1200
  throw new Error("field order must be bigint");
969
- const bitLength = fieldOrder.toString(2).length;
1201
+ if (fieldOrder <= _1n2)
1202
+ throw new Error("field order must be greater than 1");
1203
+ const bitLength = bitLen(fieldOrder - _1n2);
970
1204
  return Math.ceil(bitLength / 8);
971
1205
  }
972
1206
  function getMinHashLength(fieldOrder) {
@@ -974,20 +1208,40 @@ function getMinHashLength(fieldOrder) {
974
1208
  return length + Math.ceil(length / 2);
975
1209
  }
976
1210
  function mapHashToField(key, fieldOrder, isLE = false) {
977
- abytes(key);
1211
+ abytes2(key);
978
1212
  const len = key.length;
979
1213
  const fieldLen = getFieldBytesLength(fieldOrder);
980
- const minLen = getMinHashLength(fieldOrder);
981
- if (len < 16 || len < minLen || len > 1024)
1214
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
1215
+ if (len < minLen || len > 1024)
982
1216
  throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
983
1217
  const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
984
1218
  const reduced = mod(num, fieldOrder - _1n2) + _1n2;
985
1219
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
986
1220
  }
987
1221
 
988
- // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/curve.js
1222
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/curve.js
989
1223
  var _0n3 = /* @__PURE__ */ BigInt(0);
990
1224
  var _1n3 = /* @__PURE__ */ BigInt(1);
1225
+ function validatePointCons(Point) {
1226
+ const pc = Point;
1227
+ if (typeof pc !== "function")
1228
+ throw new TypeError("Point must be a constructor");
1229
+ validateObject({
1230
+ Fp: pc.Fp,
1231
+ Fn: pc.Fn,
1232
+ fromAffine: pc.fromAffine,
1233
+ fromBytes: pc.fromBytes,
1234
+ fromHex: pc.fromHex
1235
+ }, {
1236
+ Fp: "object",
1237
+ Fn: "object",
1238
+ fromAffine: "function",
1239
+ fromBytes: "function",
1240
+ fromHex: "function"
1241
+ });
1242
+ validateField(pc.Fp);
1243
+ validateField(pc.Fn);
1244
+ }
991
1245
  function negateCt(condition, item) {
992
1246
  const neg = item.negate();
993
1247
  return condition ? neg : item;
@@ -1081,8 +1335,8 @@ var wNAF = class {
1081
1335
  * - 𝑊 is the window size
1082
1336
  * - 𝑛 is the bitlength of the curve order.
1083
1337
  * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1084
- * @param point Point instance
1085
- * @param W window size
1338
+ * @param point - Point instance
1339
+ * @param W - window size
1086
1340
  * @returns precomputed point tables flattened to a single array
1087
1341
  */
1088
1342
  precomputeWindow(point, W) {
@@ -1126,8 +1380,9 @@ var wNAF = class {
1126
1380
  return { p, f };
1127
1381
  }
1128
1382
  /**
1129
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1130
- * @param acc accumulator point to add result of multiplication
1383
+ * Implements unsafe EC multiplication using precomputed tables
1384
+ * and w-ary non-adjacent form.
1385
+ * @param acc - accumulator point to add result of multiplication
1131
1386
  * @returns point
1132
1387
  */
1133
1388
  wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
@@ -1259,11 +1514,11 @@ function createKeygen(randomSecretKey, getPublicKey) {
1259
1514
  };
1260
1515
  }
1261
1516
 
1262
- // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/edwards.js
1263
- var _0n4 = BigInt(0);
1264
- var _1n4 = BigInt(1);
1265
- var _2n2 = BigInt(2);
1266
- var _8n2 = BigInt(8);
1517
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/edwards.js
1518
+ var _0n4 = /* @__PURE__ */ BigInt(0);
1519
+ var _1n4 = /* @__PURE__ */ BigInt(1);
1520
+ var _2n2 = /* @__PURE__ */ BigInt(2);
1521
+ var _8n2 = /* @__PURE__ */ BigInt(8);
1267
1522
  function isEdValidXY(Fp2, CURVE, x, y) {
1268
1523
  const x2 = Fp2.sqr(x);
1269
1524
  const y2 = Fp2.sqr(y);
@@ -1272,20 +1527,21 @@ function isEdValidXY(Fp2, CURVE, x, y) {
1272
1527
  return Fp2.eql(left, right);
1273
1528
  }
1274
1529
  function edwards(params, extraOpts = {}) {
1275
- const validated = createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
1530
+ const opts = extraOpts;
1531
+ const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
1276
1532
  const { Fp: Fp2, Fn: Fn2 } = validated;
1277
1533
  let CURVE = validated.CURVE;
1278
1534
  const { h: cofactor } = CURVE;
1279
- validateObject(extraOpts, {}, { uvRatio: "function" });
1535
+ validateObject(opts, {}, { uvRatio: "function" });
1280
1536
  const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
1281
1537
  const modP = (n) => Fp2.create(n);
1282
- const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
1538
+ const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
1283
1539
  try {
1284
1540
  return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
1285
1541
  } catch (e) {
1286
1542
  return { isValid: false, value: _0n4 };
1287
1543
  }
1288
- });
1544
+ } : opts.uvRatio;
1289
1545
  if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1290
1546
  throw new Error("bad curve params: generator point");
1291
1547
  function acoord(title, n, banZero = false) {
@@ -1297,40 +1553,6 @@ function edwards(params, extraOpts = {}) {
1297
1553
  if (!(other instanceof Point))
1298
1554
  throw new Error("EdwardsPoint expected");
1299
1555
  }
1300
- const toAffineMemo = memoized((p, iz) => {
1301
- const { X, Y, Z } = p;
1302
- const is0 = p.is0();
1303
- if (iz == null)
1304
- iz = is0 ? _8n2 : Fp2.inv(Z);
1305
- const x = modP(X * iz);
1306
- const y = modP(Y * iz);
1307
- const zz = Fp2.mul(Z, iz);
1308
- if (is0)
1309
- return { x: _0n4, y: _1n4 };
1310
- if (zz !== _1n4)
1311
- throw new Error("invZ was invalid");
1312
- return { x, y };
1313
- });
1314
- const assertValidMemo = memoized((p) => {
1315
- const { a, d } = CURVE;
1316
- if (p.is0())
1317
- throw new Error("bad point: ZERO");
1318
- const { X, Y, Z, T } = p;
1319
- const X2 = modP(X * X);
1320
- const Y2 = modP(Y * Y);
1321
- const Z2 = modP(Z * Z);
1322
- const Z4 = modP(Z2 * Z2);
1323
- const aX2 = modP(X2 * a);
1324
- const left = modP(Z2 * modP(aX2 + Y2));
1325
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1326
- if (left !== right)
1327
- throw new Error("bad point: equation left != right (1)");
1328
- const XY = modP(X * Y);
1329
- const ZT = modP(Z * T);
1330
- if (XY !== ZT)
1331
- throw new Error("bad point: equation left != right (2)");
1332
- return true;
1333
- });
1334
1556
  class Point {
1335
1557
  // base / generator point
1336
1558
  static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
@@ -1355,6 +1577,11 @@ function edwards(params, extraOpts = {}) {
1355
1577
  static CURVE() {
1356
1578
  return CURVE;
1357
1579
  }
1580
+ /**
1581
+ * Create one extended Edwards point from affine coordinates.
1582
+ * Does NOT validate that the point is on-curve or torsion-free.
1583
+ * Use `.assertValidity()` on adversarial inputs.
1584
+ */
1358
1585
  static fromAffine(p) {
1359
1586
  if (p instanceof Point)
1360
1587
  throw new Error("extended point not allowed");
@@ -1367,7 +1594,7 @@ function edwards(params, extraOpts = {}) {
1367
1594
  static fromBytes(bytes, zip215 = false) {
1368
1595
  const len = Fp2.BYTES;
1369
1596
  const { a, d } = CURVE;
1370
- bytes = copyBytes(abytes(bytes, len, "point"));
1597
+ bytes = copyBytes(abytes2(bytes, len, "point"));
1371
1598
  abool(zip215, "zip215");
1372
1599
  const normed = copyBytes(bytes);
1373
1600
  const lastByte = bytes[len - 1];
@@ -1390,7 +1617,7 @@ function edwards(params, extraOpts = {}) {
1390
1617
  return Point.fromAffine({ x, y });
1391
1618
  }
1392
1619
  static fromHex(hex, zip215 = false) {
1393
- return Point.fromBytes(hexToBytes(hex), zip215);
1620
+ return Point.fromBytes(hexToBytes2(hex), zip215);
1394
1621
  }
1395
1622
  get x() {
1396
1623
  return this.toAffine().x;
@@ -1406,7 +1633,24 @@ function edwards(params, extraOpts = {}) {
1406
1633
  }
1407
1634
  // Useful in fromAffine() - not for fromBytes(), which always created valid points.
1408
1635
  assertValidity() {
1409
- assertValidMemo(this);
1636
+ const p = this;
1637
+ const { a, d } = CURVE;
1638
+ if (p.is0())
1639
+ throw new Error("bad point: ZERO");
1640
+ const { X, Y, Z, T } = p;
1641
+ const X2 = modP(X * X);
1642
+ const Y2 = modP(Y * Y);
1643
+ const Z2 = modP(Z * Z);
1644
+ const Z4 = modP(Z2 * Z2);
1645
+ const aX2 = modP(X2 * a);
1646
+ const left = modP(Z2 * modP(aX2 + Y2));
1647
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1648
+ if (left !== right)
1649
+ throw new Error("bad point: equation left != right (1)");
1650
+ const XY = modP(X * Y);
1651
+ const ZT = modP(Z * T);
1652
+ if (XY !== ZT)
1653
+ throw new Error("bad point: equation left != right (2)");
1410
1654
  }
1411
1655
  // Compare one point to another.
1412
1656
  equals(other) {
@@ -1469,35 +1713,36 @@ function edwards(params, extraOpts = {}) {
1469
1713
  return new Point(X3, Y3, Z3, T3);
1470
1714
  }
1471
1715
  subtract(other) {
1716
+ aedpoint(other);
1472
1717
  return this.add(other.negate());
1473
1718
  }
1474
1719
  // Constant-time multiplication.
1475
1720
  multiply(scalar) {
1476
1721
  if (!Fn2.isValidNot0(scalar))
1477
- throw new Error("invalid scalar: expected 1 <= sc < curve.n");
1722
+ throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1478
1723
  const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1479
1724
  return normalizeZ(Point, [p, f])[0];
1480
1725
  }
1481
1726
  // Non-constant-time multiplication. Uses double-and-add algorithm.
1482
1727
  // It's faster, but should only be used when you don't care about
1483
1728
  // an exposed private key e.g. sig verification.
1484
- // Does NOT allow scalars higher than CURVE.n.
1485
- // Accepts optional accumulator to merge with multiply (important for sparse scalars)
1486
- multiplyUnsafe(scalar, acc = Point.ZERO) {
1729
+ // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
1730
+ // n and larger values are rejected instead of being reduced mod n to the identity point.
1731
+ multiplyUnsafe(scalar) {
1487
1732
  if (!Fn2.isValid(scalar))
1488
- throw new Error("invalid scalar: expected 0 <= sc < curve.n");
1733
+ throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1489
1734
  if (scalar === _0n4)
1490
1735
  return Point.ZERO;
1491
1736
  if (this.is0() || scalar === _1n4)
1492
1737
  return this;
1493
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
1738
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));
1494
1739
  }
1495
1740
  // Checks if point is of small order.
1496
1741
  // If you add something to small order point, you will have "dirty"
1497
1742
  // point with torsion component.
1498
- // Multiplies point by cofactor and checks if the result is 0.
1743
+ // Clears cofactor and checks if the result is 0.
1499
1744
  isSmallOrder() {
1500
- return this.multiplyUnsafe(cofactor).is0();
1745
+ return this.clearCofactor().is0();
1501
1746
  }
1502
1747
  // Multiplies point by curve order and checks if the result is 0.
1503
1748
  // Returns `false` is the point is dirty.
@@ -1507,7 +1752,20 @@ function edwards(params, extraOpts = {}) {
1507
1752
  // Converts Extended point to default (x, y) coordinates.
1508
1753
  // Can accept precomputed Z^-1 - for example, from invertBatch.
1509
1754
  toAffine(invertedZ) {
1510
- return toAffineMemo(this, invertedZ);
1755
+ const p = this;
1756
+ let iz = invertedZ;
1757
+ const { X, Y, Z } = p;
1758
+ const is0 = p.is0();
1759
+ if (iz == null)
1760
+ iz = is0 ? _8n2 : Fp2.inv(Z);
1761
+ const x = modP(X * iz);
1762
+ const y = modP(Y * iz);
1763
+ const zz = Fp2.mul(Z, iz);
1764
+ if (is0)
1765
+ return { x: _0n4, y: _1n4 };
1766
+ if (zz !== _1n4)
1767
+ throw new Error("invZ was invalid");
1768
+ return { x, y };
1511
1769
  }
1512
1770
  clearCofactor() {
1513
1771
  if (cofactor === _1n4)
@@ -1521,14 +1779,17 @@ function edwards(params, extraOpts = {}) {
1521
1779
  return bytes;
1522
1780
  }
1523
1781
  toHex() {
1524
- return bytesToHex(this.toBytes());
1782
+ return bytesToHex2(this.toBytes());
1525
1783
  }
1526
1784
  toString() {
1527
1785
  return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1528
1786
  }
1529
1787
  }
1530
1788
  const wnaf = new wNAF(Point, Fn2.BITS);
1531
- Point.BASE.precompute(8);
1789
+ if (Fn2.BITS >= 8)
1790
+ Point.BASE.precompute(8);
1791
+ Object.freeze(Point.prototype);
1792
+ Object.freeze(Point);
1532
1793
  return Point;
1533
1794
  }
1534
1795
  var PrimeEdwardsPoint = class {
@@ -1537,6 +1798,11 @@ var PrimeEdwardsPoint = class {
1537
1798
  static Fp;
1538
1799
  static Fn;
1539
1800
  ep;
1801
+ /**
1802
+ * Wrap one internal Edwards representative directly.
1803
+ * This is not a canonical encoding boundary: alternate Edwards
1804
+ * representatives may still describe the same abstract wrapper element.
1805
+ */
1540
1806
  constructor(ep) {
1541
1807
  this.ep = ep;
1542
1808
  }
@@ -1560,11 +1826,17 @@ var PrimeEdwardsPoint = class {
1560
1826
  assertValidity() {
1561
1827
  this.ep.assertValidity();
1562
1828
  }
1829
+ /**
1830
+ * Return affine coordinates of the current internal Edwards representative.
1831
+ * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
1832
+ * Equal abstract elements may expose different `x` / `y`; use
1833
+ * `toBytes()` / `fromBytes()` for canonical roundtrips.
1834
+ */
1563
1835
  toAffine(invertedZ) {
1564
1836
  return this.ep.toAffine(invertedZ);
1565
1837
  }
1566
1838
  toHex() {
1567
- return bytesToHex(this.toBytes());
1839
+ return bytesToHex2(this.toBytes());
1568
1840
  }
1569
1841
  toString() {
1570
1842
  return this.toHex();
@@ -1596,36 +1868,47 @@ var PrimeEdwardsPoint = class {
1596
1868
  return this.init(this.ep.negate());
1597
1869
  }
1598
1870
  precompute(windowSize, isLazy) {
1599
- return this.init(this.ep.precompute(windowSize, isLazy));
1871
+ this.ep.precompute(windowSize, isLazy);
1872
+ return this;
1600
1873
  }
1601
1874
  };
1602
1875
  function eddsa(Point, cHash, eddsaOpts = {}) {
1603
1876
  if (typeof cHash !== "function")
1604
1877
  throw new Error('"hash" function param is required');
1605
- validateObject(eddsaOpts, {}, {
1878
+ const hash = cHash;
1879
+ const opts = eddsaOpts;
1880
+ validateObject(opts, {}, {
1606
1881
  adjustScalarBytes: "function",
1607
1882
  randomBytes: "function",
1608
1883
  domain: "function",
1609
1884
  prehash: "function",
1885
+ zip215: "boolean",
1610
1886
  mapToCurve: "function"
1611
1887
  });
1612
- const { prehash } = eddsaOpts;
1888
+ const { prehash } = opts;
1613
1889
  const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
1614
- const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
1615
- const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
1616
- const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
1890
+ const outputLen = hash.outputLen;
1891
+ const expectedLen = 2 * Fp2.BYTES;
1892
+ if (outputLen !== void 0) {
1893
+ asafenumber(outputLen, "hash.outputLen");
1894
+ if (outputLen !== expectedLen)
1895
+ throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
1896
+ }
1897
+ const randomBytes3 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
1898
+ const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
1899
+ const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
1617
1900
  abool(phflag, "phflag");
1618
1901
  if (ctx.length || phflag)
1619
1902
  throw new Error("Contexts/pre-hash are not supported");
1620
1903
  return data;
1621
- });
1622
- function modN_LE(hash) {
1623
- return Fn2.create(bytesToNumberLE(hash));
1904
+ } : opts.domain;
1905
+ function modN_LE(hash2) {
1906
+ return Fn2.create(bytesToNumberLE(hash2));
1624
1907
  }
1625
1908
  function getPrivateScalar(key) {
1626
1909
  const len = lengths.secretKey;
1627
- abytes(key, lengths.secretKey, "secretKey");
1628
- const hashed = abytes(cHash(key), 2 * len, "hashedSecretKey");
1910
+ abytes2(key, lengths.secretKey, "secretKey");
1911
+ const hashed = abytes2(hash(key), 2 * len, "hashedSecretKey");
1629
1912
  const head = adjustScalarBytes2(hashed.slice(0, len));
1630
1913
  const prefix = hashed.slice(len, 2 * len);
1631
1914
  const scalar = modN_LE(head);
@@ -1641,11 +1924,11 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1641
1924
  return getExtendedPublicKey(secretKey).pointBytes;
1642
1925
  }
1643
1926
  function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
1644
- const msg = concatBytes(...msgs);
1645
- return modN_LE(cHash(domain(msg, abytes(context, void 0, "context"), !!prehash)));
1927
+ const msg = concatBytes2(...msgs);
1928
+ return modN_LE(hash(domain(msg, abytes2(context, void 0, "context"), !!prehash)));
1646
1929
  }
1647
1930
  function sign(msg, secretKey, options = {}) {
1648
- msg = abytes(msg, void 0, "message");
1931
+ msg = abytes2(msg, void 0, "message");
1649
1932
  if (prehash)
1650
1933
  msg = prehash(msg);
1651
1934
  const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
@@ -1655,16 +1938,19 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1655
1938
  const s = Fn2.create(r + k * scalar);
1656
1939
  if (!Fn2.isValid(s))
1657
1940
  throw new Error("sign failed: invalid s");
1658
- const rs = concatBytes(R, Fn2.toBytes(s));
1659
- return abytes(rs, lengths.signature, "result");
1941
+ const rs = concatBytes2(R, Fn2.toBytes(s));
1942
+ return abytes2(rs, lengths.signature, "result");
1660
1943
  }
1661
- const verifyOpts = { zip215: true };
1944
+ const verifyOpts = {
1945
+ zip215: opts.zip215
1946
+ };
1662
1947
  function verify(sig, msg, publicKey, options = verifyOpts) {
1663
- const { context, zip215 } = options;
1948
+ const { context } = options;
1949
+ const zip215 = options.zip215 === void 0 ? !!verifyOpts.zip215 : options.zip215;
1664
1950
  const len = lengths.signature;
1665
- sig = abytes(sig, len, "signature");
1666
- msg = abytes(msg, void 0, "message");
1667
- publicKey = abytes(publicKey, lengths.publicKey, "publicKey");
1951
+ sig = abytes2(sig, len, "signature");
1952
+ msg = abytes2(msg, void 0, "message");
1953
+ publicKey = abytes2(publicKey, lengths.publicKey, "publicKey");
1668
1954
  if (zip215 !== void 0)
1669
1955
  abool(zip215, "zip215");
1670
1956
  if (prehash)
@@ -1682,7 +1968,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1682
1968
  }
1683
1969
  if (!zip215 && A.isSmallOrder())
1684
1970
  return false;
1685
- const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
1971
+ const k = hashDomainToScalar(context, r, publicKey, msg);
1686
1972
  const RkA = R.add(A.multiplyUnsafe(k));
1687
1973
  return RkA.subtract(SB).clearCofactor().is0();
1688
1974
  }
@@ -1693,15 +1979,16 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1693
1979
  signature: 2 * _size,
1694
1980
  seed: _size
1695
1981
  };
1696
- function randomSecretKey(seed = randomBytes2(lengths.seed)) {
1697
- return abytes(seed, lengths.seed, "seed");
1982
+ function randomSecretKey(seed) {
1983
+ seed = seed === void 0 ? randomBytes3(lengths.seed) : seed;
1984
+ return abytes2(seed, lengths.seed, "seed");
1698
1985
  }
1699
1986
  function isValidSecretKey(key) {
1700
- return isBytes(key) && key.length === Fn2.BYTES;
1987
+ return isBytes2(key) && key.length === lengths.secretKey;
1701
1988
  }
1702
1989
  function isValidPublicKey(key, zip215) {
1703
1990
  try {
1704
- return !!Point.fromBytes(key, zip215);
1991
+ return !!Point.fromBytes(key, zip215 === void 0 ? verifyOpts.zip215 : zip215);
1705
1992
  } catch (error) {
1706
1993
  return false;
1707
1994
  }
@@ -1731,11 +2018,13 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1731
2018
  },
1732
2019
  toMontgomerySecret(secretKey) {
1733
2020
  const size = lengths.secretKey;
1734
- abytes(secretKey, size);
1735
- const hashed = cHash(secretKey.subarray(0, size));
2021
+ abytes2(secretKey, size);
2022
+ const hashed = hash(secretKey.subarray(0, size));
1736
2023
  return adjustScalarBytes2(hashed).subarray(0, size);
1737
2024
  }
1738
2025
  };
2026
+ Object.freeze(lengths);
2027
+ Object.freeze(utils);
1739
2028
  return Object.freeze({
1740
2029
  keygen: createKeygen(randomSecretKey, getPublicKey),
1741
2030
  getPublicKey,
@@ -1747,12 +2036,223 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
1747
2036
  });
1748
2037
  }
1749
2038
 
1750
- // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/hash-to-curve.js
2039
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/fft.js
2040
+ function checkU32(n) {
2041
+ if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
2042
+ throw new Error("wrong u32 integer:" + n);
2043
+ return n;
2044
+ }
2045
+ function nextPowerOfTwo(n) {
2046
+ checkU32(n);
2047
+ if (n <= 1)
2048
+ return 1;
2049
+ if (n > 2147483648)
2050
+ throw new Error("nextPowerOfTwo overflow: result does not fit u32");
2051
+ return 1 << log2(n - 1) + 1 >>> 0;
2052
+ }
2053
+ function log2(n) {
2054
+ checkU32(n);
2055
+ return 31 - Math.clz32(n);
2056
+ }
2057
+ function poly(field, roots, create, fft, length) {
2058
+ const F = field;
2059
+ const _create = create || ((len, elm) => new Array(len).fill(elm ?? F.ZERO));
2060
+ const isPoly = (x) => {
2061
+ if (Array.isArray(x))
2062
+ return true;
2063
+ if (!ArrayBuffer.isView(x))
2064
+ return false;
2065
+ const v = x;
2066
+ return typeof v.length === "number" && typeof v.slice === "function" && typeof v[Symbol.iterator] === "function";
2067
+ };
2068
+ const checkLength = (...lst) => {
2069
+ if (!lst.length)
2070
+ return 0;
2071
+ for (const i of lst)
2072
+ if (!isPoly(i))
2073
+ throw new Error("poly: not polynomial: " + i);
2074
+ const L = lst[0].length;
2075
+ for (let i = 1; i < lst.length; i++)
2076
+ if (lst[i].length !== L)
2077
+ throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
2078
+ if (length !== void 0 && L !== length)
2079
+ throw new Error(`poly: expected fixed length ${length}, got ${L}`);
2080
+ return L;
2081
+ };
2082
+ function findOmegaIndex(x, n, brp = false) {
2083
+ const bits = log2(n);
2084
+ const omega = brp ? roots.brp(bits) : roots.roots(bits);
2085
+ for (let i = 0; i < n; i++)
2086
+ if (F.eql(x, omega[i]))
2087
+ return i;
2088
+ return -1;
2089
+ }
2090
+ return {
2091
+ roots,
2092
+ create: _create,
2093
+ length,
2094
+ extend: (a, len) => {
2095
+ checkLength(a);
2096
+ const out = _create(len, F.ZERO);
2097
+ for (let i = 0; i < Math.min(a.length, len); i++)
2098
+ out[i] = a[i];
2099
+ return out;
2100
+ },
2101
+ degree: (a) => {
2102
+ checkLength(a);
2103
+ for (let i = a.length - 1; i >= 0; i--)
2104
+ if (!F.is0(a[i]))
2105
+ return i;
2106
+ return -1;
2107
+ },
2108
+ add: (a, b) => {
2109
+ const len = checkLength(a, b);
2110
+ const out = _create(len);
2111
+ for (let i = 0; i < len; i++)
2112
+ out[i] = F.add(a[i], b[i]);
2113
+ return out;
2114
+ },
2115
+ sub: (a, b) => {
2116
+ const len = checkLength(a, b);
2117
+ const out = _create(len);
2118
+ for (let i = 0; i < len; i++)
2119
+ out[i] = F.sub(a[i], b[i]);
2120
+ return out;
2121
+ },
2122
+ dot: (a, b) => {
2123
+ const len = checkLength(a, b);
2124
+ const out = _create(len);
2125
+ for (let i = 0; i < len; i++)
2126
+ out[i] = F.mul(a[i], b[i]);
2127
+ return out;
2128
+ },
2129
+ mul: (a, b) => {
2130
+ if (isPoly(b)) {
2131
+ const len = checkLength(a, b);
2132
+ if (fft) {
2133
+ const A = fft.direct(a, false, true);
2134
+ const B = fft.direct(b, false, true);
2135
+ for (let i = 0; i < A.length; i++)
2136
+ A[i] = F.mul(A[i], B[i]);
2137
+ return fft.inverse(A, true, false);
2138
+ } else {
2139
+ const res = _create(len);
2140
+ for (let i = 0; i < len; i++) {
2141
+ for (let j = 0; j < len; j++) {
2142
+ const k = (i + j) % len;
2143
+ res[k] = F.add(res[k], F.mul(a[i], b[j]));
2144
+ }
2145
+ }
2146
+ return res;
2147
+ }
2148
+ } else {
2149
+ const out = _create(checkLength(a));
2150
+ for (let i = 0; i < out.length; i++)
2151
+ out[i] = F.mul(a[i], b);
2152
+ return out;
2153
+ }
2154
+ },
2155
+ convolve(a, b) {
2156
+ const len = nextPowerOfTwo(a.length + b.length - 1);
2157
+ return this.mul(this.extend(a, len), this.extend(b, len));
2158
+ },
2159
+ shift(p, factor) {
2160
+ const out = _create(checkLength(p));
2161
+ out[0] = p[0];
2162
+ for (let i = 1, power = F.ONE; i < p.length; i++) {
2163
+ power = F.mul(power, factor);
2164
+ out[i] = F.mul(p[i], power);
2165
+ }
2166
+ return out;
2167
+ },
2168
+ clone: (a) => {
2169
+ checkLength(a);
2170
+ const out = _create(a.length);
2171
+ for (let i = 0; i < a.length; i++)
2172
+ out[i] = a[i];
2173
+ return out;
2174
+ },
2175
+ eval: (a, basis) => {
2176
+ checkLength(a, basis);
2177
+ let acc = F.ZERO;
2178
+ for (let i = 0; i < a.length; i++)
2179
+ acc = F.add(acc, F.mul(a[i], basis[i]));
2180
+ return acc;
2181
+ },
2182
+ monomial: {
2183
+ basis: (x, n) => {
2184
+ const out = _create(n);
2185
+ let pow = F.ONE;
2186
+ for (let i = 0; i < n; i++) {
2187
+ out[i] = pow;
2188
+ pow = F.mul(pow, x);
2189
+ }
2190
+ return out;
2191
+ },
2192
+ eval: (a, x) => {
2193
+ checkLength(a);
2194
+ let acc = F.ZERO;
2195
+ for (let i = a.length - 1; i >= 0; i--)
2196
+ acc = F.add(F.mul(acc, x), a[i]);
2197
+ return acc;
2198
+ }
2199
+ },
2200
+ lagrange: {
2201
+ basis: (x, n, brp = false, weights) => {
2202
+ const bits = log2(n);
2203
+ const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits));
2204
+ const out = _create(n);
2205
+ const idx = findOmegaIndex(x, n, brp);
2206
+ if (idx !== -1) {
2207
+ out[idx] = F.ONE;
2208
+ return out;
2209
+ }
2210
+ const tm = F.pow(x, BigInt(n));
2211
+ const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n)));
2212
+ const denom = _create(n);
2213
+ for (let i = 0; i < n; i++)
2214
+ denom[i] = F.sub(x, cache[i]);
2215
+ const inv = F.invertBatch(denom);
2216
+ for (let i = 0; i < n; i++)
2217
+ out[i] = F.mul(c, F.mul(cache[i], inv[i]));
2218
+ return out;
2219
+ },
2220
+ eval(a, x, brp = false) {
2221
+ checkLength(a);
2222
+ const idx = findOmegaIndex(x, a.length, brp);
2223
+ if (idx !== -1)
2224
+ return a[idx];
2225
+ const L = this.basis(x, a.length, brp);
2226
+ let acc = F.ZERO;
2227
+ for (let i = 0; i < a.length; i++)
2228
+ if (!F.is0(a[i]))
2229
+ acc = F.add(acc, F.mul(a[i], L[i]));
2230
+ return acc;
2231
+ }
2232
+ },
2233
+ vanishing(roots2) {
2234
+ checkLength(roots2);
2235
+ const out = _create(roots2.length + 1, F.ZERO);
2236
+ out[0] = F.ONE;
2237
+ for (const r of roots2) {
2238
+ const neg = F.neg(r);
2239
+ for (let j = out.length - 1; j > 0; j--)
2240
+ out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
2241
+ out[0] = F.mul(out[0], neg);
2242
+ }
2243
+ return out;
2244
+ }
2245
+ };
2246
+ }
2247
+
2248
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/hash-to-curve.js
1751
2249
  var os2ip = bytesToNumberBE;
1752
2250
  function i2osp(value, length) {
1753
2251
  asafenumber(value);
1754
2252
  asafenumber(length);
1755
- if (value < 0 || value >= 1 << 8 * length)
2253
+ if (length < 0 || length > 4)
2254
+ throw new Error("invalid I2OSP length: " + length);
2255
+ if (value < 0 || value > 2 ** (8 * length) - 1)
1756
2256
  throw new Error("invalid I2OSP input: " + value);
1757
2257
  const res = Array.from({ length }).fill(0);
1758
2258
  for (let i = length - 1; i >= 0; i--) {
@@ -1769,35 +2269,38 @@ function strxor(a, b) {
1769
2269
  return arr;
1770
2270
  }
1771
2271
  function normDST(DST) {
1772
- if (!isBytes(DST) && typeof DST !== "string")
2272
+ if (!isBytes2(DST) && typeof DST !== "string")
1773
2273
  throw new Error("DST must be Uint8Array or ascii string");
1774
- return typeof DST === "string" ? asciiToBytes(DST) : DST;
2274
+ const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
2275
+ if (dst.length === 0)
2276
+ throw new Error("DST must be non-empty");
2277
+ return dst;
1775
2278
  }
1776
2279
  function expand_message_xmd(msg, DST, lenInBytes, H) {
1777
- abytes(msg);
2280
+ abytes2(msg);
1778
2281
  asafenumber(lenInBytes);
1779
2282
  DST = normDST(DST);
1780
2283
  if (DST.length > 255)
1781
- DST = H(concatBytes(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
2284
+ DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
1782
2285
  const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1783
2286
  const ell = Math.ceil(lenInBytes / b_in_bytes);
1784
2287
  if (lenInBytes > 65535 || ell > 255)
1785
2288
  throw new Error("expand_message_xmd: invalid lenInBytes");
1786
- const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
1787
- const Z_pad = i2osp(0, r_in_bytes);
2289
+ const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
2290
+ const Z_pad = new Uint8Array(r_in_bytes);
1788
2291
  const l_i_b_str = i2osp(lenInBytes, 2);
1789
2292
  const b = new Array(ell);
1790
- const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1791
- b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
1792
- for (let i = 1; i <= ell; i++) {
2293
+ const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
2294
+ b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
2295
+ for (let i = 1; i < ell; i++) {
1793
2296
  const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1794
- b[i] = H(concatBytes(...args));
2297
+ b[i] = H(concatBytes2(...args));
1795
2298
  }
1796
- const pseudo_random_bytes = concatBytes(...b);
2299
+ const pseudo_random_bytes = concatBytes2(...b);
1797
2300
  return pseudo_random_bytes.slice(0, lenInBytes);
1798
2301
  }
1799
2302
  function expand_message_xof(msg, DST, lenInBytes, k, H) {
1800
- abytes(msg);
2303
+ abytes2(msg);
1801
2304
  asafenumber(lenInBytes);
1802
2305
  DST = normDST(DST);
1803
2306
  if (DST.length > 255) {
@@ -1817,8 +2320,12 @@ function hash_to_field(msg, count, options) {
1817
2320
  });
1818
2321
  const { p, k, m, hash, expand, DST } = options;
1819
2322
  asafenumber(hash.outputLen, "valid hash");
1820
- abytes(msg);
2323
+ abytes2(msg);
1821
2324
  asafenumber(count);
2325
+ if (count < 1)
2326
+ throw new Error("hash_to_field: expected count >= 1");
2327
+ if (m < 1)
2328
+ throw new Error("hash_to_field: expected m >= 1");
1822
2329
  const log2p = p.toString(2).length;
1823
2330
  const L = Math.ceil((log2p + k) / 8);
1824
2331
  const len_in_bytes = count * m * L;
@@ -1844,10 +2351,16 @@ function hash_to_field(msg, count, options) {
1844
2351
  }
1845
2352
  return u;
1846
2353
  }
1847
- var _DST_scalar = asciiToBytes("HashToScalar-");
2354
+ var _DST_scalar = "HashToScalar-";
1848
2355
  function createHasher2(Point, mapToCurve, defaults) {
1849
2356
  if (typeof mapToCurve !== "function")
1850
2357
  throw new Error("mapToCurve() must be defined");
2358
+ const snapshot = (src) => Object.freeze({
2359
+ ...src,
2360
+ DST: isBytes2(src.DST) ? copyBytes(src.DST) : src.DST,
2361
+ ...src.encodeDST === void 0 ? {} : { encodeDST: isBytes2(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }
2362
+ });
2363
+ const safeDefaults = snapshot(defaults);
1851
2364
  function map(num) {
1852
2365
  return Point.fromAffine(mapToCurve(num));
1853
2366
  }
@@ -1858,26 +2371,28 @@ function createHasher2(Point, mapToCurve, defaults) {
1858
2371
  P.assertValidity();
1859
2372
  return P;
1860
2373
  }
1861
- return {
1862
- defaults: Object.freeze(defaults),
2374
+ return Object.freeze({
2375
+ get defaults() {
2376
+ return snapshot(safeDefaults);
2377
+ },
1863
2378
  Point,
1864
2379
  hashToCurve(msg, options) {
1865
- const opts = Object.assign({}, defaults, options);
2380
+ const opts = Object.assign({}, safeDefaults, options);
1866
2381
  const u = hash_to_field(msg, 2, opts);
1867
2382
  const u0 = map(u[0]);
1868
2383
  const u1 = map(u[1]);
1869
2384
  return clear(u0.add(u1));
1870
2385
  },
1871
2386
  encodeToCurve(msg, options) {
1872
- const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
1873
- const opts = Object.assign({}, defaults, optsDst, options);
2387
+ const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};
2388
+ const opts = Object.assign({}, safeDefaults, optsDst, options);
1874
2389
  const u = hash_to_field(msg, 1, opts);
1875
2390
  const u0 = map(u[0]);
1876
2391
  return clear(u0);
1877
2392
  },
1878
2393
  /** See {@link H2CHasher} */
1879
2394
  mapToCurve(scalars) {
1880
- if (defaults.m === 1) {
2395
+ if (safeDefaults.m === 1) {
1881
2396
  if (typeof scalars !== "bigint")
1882
2397
  throw new Error("expected bigint (m=1)");
1883
2398
  return clear(map([scalars]));
@@ -1890,23 +2405,641 @@ function createHasher2(Point, mapToCurve, defaults) {
1890
2405
  return clear(map(scalars));
1891
2406
  },
1892
2407
  // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
1893
- // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
2408
+ // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic
2409
+ // `HashToScalar-` prefix above unless the caller overrides it per invocation.
1894
2410
  hashToScalar(msg, options) {
1895
2411
  const N = Point.Fn.ORDER;
1896
- const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
2412
+ const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);
1897
2413
  return hash_to_field(msg, 1, opts)[0][0];
1898
2414
  }
2415
+ });
2416
+ }
2417
+
2418
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/frost.js
2419
+ var validateSigners = (signers) => {
2420
+ if (!Number.isSafeInteger(signers.min) || !Number.isSafeInteger(signers.max))
2421
+ throw new Error("Wrong signers info: min=" + signers.min + " max=" + signers.max);
2422
+ if (signers.min < 2 || signers.max < 2 || signers.min > signers.max)
2423
+ throw new Error("Wrong signers info: min=" + signers.min + " max=" + signers.max);
2424
+ };
2425
+ var validateCommitmentsNum = (signers, len) => {
2426
+ if (len < signers.min || len > signers.max)
2427
+ throw new Error("Wrong number of commitments=" + len);
2428
+ };
2429
+ var AggErr = class extends Error {
2430
+ // Empty means aggregation failed before per-share verification could attribute a signer.
2431
+ cheaters;
2432
+ constructor(msg, cheaters) {
2433
+ super(msg);
2434
+ this.cheaters = cheaters;
2435
+ }
2436
+ };
2437
+ function createFROST(opts) {
2438
+ validateObject(opts, {
2439
+ name: "string",
2440
+ hash: "function"
2441
+ }, {
2442
+ hashToScalar: "function",
2443
+ validatePoint: "function",
2444
+ parsePublicKey: "function",
2445
+ adjustScalar: "function",
2446
+ adjustPoint: "function",
2447
+ challenge: "function",
2448
+ adjustNonces: "function",
2449
+ adjustSecret: "function",
2450
+ adjustPublic: "function",
2451
+ adjustGroupCommitmentShare: "function",
2452
+ adjustDKG: "function"
2453
+ });
2454
+ validatePointCons(opts.Point);
2455
+ const { Point } = opts;
2456
+ const Fn2 = opts.Fn === void 0 ? Point.Fn : opts.Fn;
2457
+ const hashBytes = opts.hash;
2458
+ const hashToScalar = opts.hashToScalar === void 0 ? (msg, opts2 = { DST: new Uint8Array() }) => {
2459
+ const t = hashBytes(concatBytes2(opts2.DST, msg));
2460
+ return Fn2.create(Fn2.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t));
2461
+ } : opts.hashToScalar;
2462
+ const H1Prefix = utf8ToBytes(opts.H1 !== void 0 ? opts.H1 : opts.name + "rho");
2463
+ const H2Prefix = utf8ToBytes(opts.H2 !== void 0 ? opts.H2 : opts.name + "chal");
2464
+ const H3Prefix = utf8ToBytes(opts.H3 !== void 0 ? opts.H3 : opts.name + "nonce");
2465
+ const H4Prefix = utf8ToBytes(opts.H4 !== void 0 ? opts.H4 : opts.name + "msg");
2466
+ const H5Prefix = utf8ToBytes(opts.H5 !== void 0 ? opts.H5 : opts.name + "com");
2467
+ const HDKGPrefix = utf8ToBytes(opts.HDKG !== void 0 ? opts.HDKG : opts.name + "dkg");
2468
+ const HIDPrefix = utf8ToBytes(opts.HID !== void 0 ? opts.HID : opts.name + "id");
2469
+ const H1 = (msg) => hashToScalar(msg, { DST: H1Prefix });
2470
+ const H2 = (msg) => hashToScalar(msg, { DST: H2Prefix });
2471
+ const H3 = (msg) => hashToScalar(msg, { DST: H3Prefix });
2472
+ const H4 = (msg) => hashBytes(concatBytes2(H4Prefix, msg));
2473
+ const H5 = (msg) => hashBytes(concatBytes2(H5Prefix, msg));
2474
+ const HDKG = (msg) => hashToScalar(msg, { DST: HDKGPrefix });
2475
+ const HID = (msg) => hashToScalar(msg, { DST: HIDPrefix });
2476
+ const randomScalar = (rng = randomBytes2) => {
2477
+ const t = mapHashToField(rng(getMinHashLength(Fn2.ORDER)), Fn2.ORDER, Fn2.isLE);
2478
+ return Fn2.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
2479
+ };
2480
+ const serializePoint = (p) => p.toBytes();
2481
+ const parsePoint = (bytes) => {
2482
+ const p = Point.fromBytes(bytes);
2483
+ if (opts.validatePoint)
2484
+ opts.validatePoint(p);
2485
+ return p;
2486
+ };
2487
+ const nonceCommitments = (identifier, nonces) => ({
2488
+ identifier,
2489
+ hiding: serializePoint(Point.BASE.multiply(Fn2.fromBytes(nonces.hiding))),
2490
+ binding: serializePoint(Point.BASE.multiply(Fn2.fromBytes(nonces.binding)))
2491
+ });
2492
+ const adjustPoint = opts.adjustPoint === void 0 ? (n) => n : opts.adjustPoint;
2493
+ const validateIdentifier = (n) => {
2494
+ if (!Fn2.isValid(n) || Fn2.is0(n))
2495
+ throw new Error("Invalid identifier " + n);
2496
+ return n;
2497
+ };
2498
+ const serializeIdentifier = (id) => bytesToHex2(Fn2.toBytes(validateIdentifier(id)));
2499
+ const parseIdentifier = (id) => {
2500
+ const n = validateIdentifier(Fn2.fromBytes(hexToBytes2(id)));
2501
+ if (serializeIdentifier(n) !== id)
2502
+ throw new Error("expected canonical identifier hex");
2503
+ return n;
2504
+ };
2505
+ const Signature = {
2506
+ // RFC 9591 Appendix A encodes signatures canonically as
2507
+ // SerializeElement(R) || SerializeScalar(z).
2508
+ encode: (R, z) => {
2509
+ let res = concatBytes2(serializePoint(R), Fn2.toBytes(z));
2510
+ if (opts.adjustTx)
2511
+ res = opts.adjustTx.encode(res);
2512
+ return res;
2513
+ },
2514
+ decode: (sig) => {
2515
+ if (opts.adjustTx)
2516
+ sig = opts.adjustTx.decode(sig);
2517
+ const R = parsePoint(sig.subarray(0, -Fn2.BYTES));
2518
+ const z = Fn2.fromBytes(sig.subarray(-Fn2.BYTES));
2519
+ return { R, z };
2520
+ }
2521
+ };
2522
+ const genPointScalarPair = (rng = randomBytes2) => {
2523
+ let n = randomScalar(rng);
2524
+ if (opts.adjustScalar)
2525
+ n = opts.adjustScalar(n);
2526
+ let p = Point.BASE.multiply(n);
2527
+ return { scalar: n, point: p };
2528
+ };
2529
+ const nrErr = "roots are unavailable in FROST polynomial mode";
2530
+ const noRoots = {
2531
+ info: { G: Fn2.ZERO, oddFactor: Fn2.ZERO, powerOfTwo: 0 },
2532
+ roots() {
2533
+ throw new Error(nrErr);
2534
+ },
2535
+ brp() {
2536
+ throw new Error(nrErr);
2537
+ },
2538
+ inverse() {
2539
+ throw new Error(nrErr);
2540
+ },
2541
+ omega() {
2542
+ throw new Error(nrErr);
2543
+ },
2544
+ clear() {
2545
+ }
2546
+ };
2547
+ const Poly = poly(Fn2, noRoots);
2548
+ const msm = (points, scalars) => pippenger(Point, points, scalars);
2549
+ const polynomialEvaluate = (x, coeffs) => {
2550
+ if (!coeffs.length)
2551
+ throw new Error("empty coefficients");
2552
+ return Poly.monomial.eval(coeffs, x);
2553
+ };
2554
+ const deriveInterpolatingValue = (L, xi) => {
2555
+ const err = "invalid parameters";
2556
+ if (!L.some((x) => Fn2.eql(x, xi)))
2557
+ throw new Error(err);
2558
+ const Lset = new Set(L);
2559
+ if (Lset.size !== L.length)
2560
+ throw new Error(err);
2561
+ if (!Lset.has(xi))
2562
+ throw new Error(err);
2563
+ let num = Fn2.ONE;
2564
+ let den = Fn2.ONE;
2565
+ for (const x of L) {
2566
+ if (Fn2.eql(x, xi))
2567
+ continue;
2568
+ num = Fn2.mul(num, x);
2569
+ den = Fn2.mul(den, Fn2.sub(x, xi));
2570
+ }
2571
+ return Fn2.div(num, den);
2572
+ };
2573
+ const evalutateVSS = (identifier, commitment) => {
2574
+ const monomial = Poly.monomial.basis(identifier, commitment.length);
2575
+ return msm(commitment, monomial);
2576
+ };
2577
+ const generateSecretPolynomial = (signers, secret, coeffs, rng = randomBytes2) => {
2578
+ validateSigners(signers);
2579
+ const secretScalar = secret === void 0 ? randomScalar(rng) : Fn2.fromBytes(secret);
2580
+ if (!coeffs) {
2581
+ coeffs = [];
2582
+ for (let i = 0; i < signers.min - 1; i++)
2583
+ coeffs.push(randomScalar(rng));
2584
+ }
2585
+ if (coeffs.length !== signers.min - 1)
2586
+ throw new Error("wrong coefficients length");
2587
+ const coefficients = [secretScalar, ...coeffs];
2588
+ const commitment = coefficients.map((i) => Point.BASE.multiply(i));
2589
+ return { coefficients, commitment, secret: secretScalar };
2590
+ };
2591
+ const ProofOfKnowledge = {
2592
+ challenge: (id, verKey, R) => HDKG(concatBytes2(Fn2.toBytes(id), serializePoint(verKey), serializePoint(R))),
2593
+ compute(id, coefficents, commitments, rng = randomBytes2) {
2594
+ if (coefficents.length < 1)
2595
+ throw new Error("coefficients should have at least one element");
2596
+ const { point: R, scalar: k } = genPointScalarPair(rng);
2597
+ const verKey = commitments[0];
2598
+ const c = this.challenge(id, verKey, R);
2599
+ const mu = Fn2.add(k, Fn2.mul(coefficents[0], c));
2600
+ return Signature.encode(R, mu);
2601
+ },
2602
+ validate(id, commitment, proof) {
2603
+ if (commitment.length < 1)
2604
+ throw new Error("commitment should have at least one element");
2605
+ const { R, z } = Signature.decode(proof);
2606
+ const phi = parsePoint(commitment[0]);
2607
+ const c = this.challenge(id, phi, R);
2608
+ if (!R.equals(Point.BASE.multiply(z).subtract(phi.multiply(c))))
2609
+ throw new Error("invalid proof of knowledge");
2610
+ }
2611
+ };
2612
+ const Basic = {
2613
+ challenge: (R, PK, msg) => {
2614
+ if (opts.challenge)
2615
+ return opts.challenge(R, PK, msg);
2616
+ return H2(concatBytes2(serializePoint(R), serializePoint(PK), msg));
2617
+ },
2618
+ sign(msg, sk, rng = randomBytes2) {
2619
+ const { point: R, scalar: r } = genPointScalarPair(rng);
2620
+ const PK = Point.BASE.multiply(sk);
2621
+ const c = this.challenge(R, PK, msg);
2622
+ const z = Fn2.add(r, Fn2.mul(c, sk));
2623
+ return [R, z];
2624
+ },
2625
+ verify(msg, R, z, PK) {
2626
+ if (opts.adjustPoint)
2627
+ PK = opts.adjustPoint(PK);
2628
+ if (opts.adjustPoint)
2629
+ R = opts.adjustPoint(R);
2630
+ const c = this.challenge(R, PK, msg);
2631
+ const zB = Point.BASE.multiply(z);
2632
+ const cA = PK.multiply(c);
2633
+ let check = zB.subtract(cA).subtract(R);
2634
+ if (check.clearCofactor)
2635
+ check = check.clearCofactor();
2636
+ return Point.ZERO.equals(check);
2637
+ }
2638
+ };
2639
+ const validateSecretShare = (identifier, commitment, signingShare) => {
2640
+ if (!Point.BASE.multiply(signingShare).equals(evalutateVSS(identifier, commitment)))
2641
+ throw new Error("invalid secret share");
2642
+ };
2643
+ const Identifier = {
2644
+ fromNumber(n) {
2645
+ if (!Number.isSafeInteger(n))
2646
+ throw new Error("expected safe interger");
2647
+ return serializeIdentifier(BigInt(n));
2648
+ },
2649
+ // Not in spec, but in FROST implementation,
2650
+ // seems useful and nice, no need to sync identifiers (would require more interactions)
2651
+ derive(s) {
2652
+ if (typeof s !== "string")
2653
+ throw new Error("wrong identifier string: " + s);
2654
+ return serializeIdentifier(HID(utf8ToBytes(s)));
2655
+ }
2656
+ };
2657
+ const generateNonce = (secret, rng = randomBytes2) => H3(concatBytes2(rng(32), Fn2.toBytes(secret)));
2658
+ const getGroupCommitment = (GPK, commitmentList, msg) => {
2659
+ const CL = commitmentList.map((i) => [
2660
+ i.identifier,
2661
+ parseIdentifier(i.identifier),
2662
+ parsePoint(i.hiding),
2663
+ parsePoint(i.binding)
2664
+ ]);
2665
+ CL.sort((a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0);
2666
+ const Cbytes = [];
2667
+ for (const [_, id, hC, bC] of CL)
2668
+ Cbytes.push(Fn2.toBytes(id), serializePoint(hC), serializePoint(bC));
2669
+ const encodedCommitmentHash = H5(concatBytes2(...Cbytes));
2670
+ const rhoPrefix = concatBytes2(serializePoint(GPK), H4(msg), encodedCommitmentHash);
2671
+ const bindingFactors = {};
2672
+ for (const [i, id] of CL) {
2673
+ bindingFactors[i] = H1(concatBytes2(rhoPrefix, Fn2.toBytes(id)));
2674
+ }
2675
+ const points = [];
2676
+ const scalars = [];
2677
+ for (const [i, _, hC, bC] of CL) {
2678
+ if (Point.ZERO.equals(hC) || Point.ZERO.equals(bC))
2679
+ throw new Error("infinity commitment");
2680
+ points.push(hC, bC);
2681
+ scalars.push(Fn2.ONE, bindingFactors[i]);
2682
+ }
2683
+ const groupCommitment = msm(points, scalars);
2684
+ const identifiers = CL.map((i) => i[1]);
2685
+ return { identifiers, groupCommitment, bindingFactors };
2686
+ };
2687
+ const prepareShare = (PK, commitmentList, msg, identifier) => {
2688
+ const GPK = adjustPoint(parsePoint(PK));
2689
+ const id = parseIdentifier(identifier);
2690
+ const { identifiers, groupCommitment, bindingFactors } = getGroupCommitment(GPK, commitmentList, msg);
2691
+ const bindingFactor = bindingFactors[identifier];
2692
+ const lambda = deriveInterpolatingValue(identifiers, id);
2693
+ const challenge = Basic.challenge(groupCommitment, GPK, msg);
2694
+ return { lambda, challenge, bindingFactor, groupCommitment };
1899
2695
  };
2696
+ Object.freeze(Identifier);
2697
+ const frost = {
2698
+ Identifier,
2699
+ // DKG is Distributed Key Generation, not Trusted Dealer Key Generation.
2700
+ DKG: Object.freeze({
2701
+ // NOTE: we allow to pass secret scalar from user side,
2702
+ // this way it can be derived, instead of random generation
2703
+ round1: (id, signers, secret, rng = randomBytes2) => {
2704
+ validateSigners(signers);
2705
+ const idNum = parseIdentifier(id);
2706
+ const { coefficients, commitment } = generateSecretPolynomial(signers, secret, void 0, rng);
2707
+ const proofOfKnowledge = ProofOfKnowledge.compute(idNum, coefficients, commitment, rng);
2708
+ const commitmentBytes = commitment.map(serializePoint);
2709
+ const round1Public = {
2710
+ identifier: serializeIdentifier(idNum),
2711
+ commitment: commitmentBytes,
2712
+ proofOfKnowledge
2713
+ };
2714
+ const round1Secret = {
2715
+ identifier: idNum,
2716
+ coefficients,
2717
+ commitment: commitment.map(serializePoint),
2718
+ // Copy threshold metadata instead of retaining the caller-owned object by reference.
2719
+ signers: { min: signers.min, max: signers.max },
2720
+ step: 1
2721
+ };
2722
+ return { public: round1Public, secret: round1Secret };
2723
+ },
2724
+ round2: (secret, others) => {
2725
+ if (others.length !== secret.signers.max - 1)
2726
+ throw new Error("wrong number of round1 packages");
2727
+ if (!secret.coefficients || secret.step === 3)
2728
+ throw new Error("round3 package used in round2");
2729
+ const res = {};
2730
+ for (const p of others) {
2731
+ if (p.commitment.length !== secret.signers.min)
2732
+ throw new Error("wrong number of commitments");
2733
+ const id = parseIdentifier(p.identifier);
2734
+ if (id === secret.identifier)
2735
+ throw new Error("duplicate id=" + serializeIdentifier(id));
2736
+ ProofOfKnowledge.validate(id, p.commitment, p.proofOfKnowledge);
2737
+ for (const c of p.commitment)
2738
+ parsePoint(c);
2739
+ if (res[p.identifier])
2740
+ throw new Error("Duplicate id=" + id);
2741
+ const signingShare = Fn2.toBytes(polynomialEvaluate(id, secret.coefficients));
2742
+ res[p.identifier] = {
2743
+ identifier: serializeIdentifier(secret.identifier),
2744
+ signingShare
2745
+ };
2746
+ }
2747
+ secret.step = 2;
2748
+ return res;
2749
+ },
2750
+ round3: (secret, round1, round2) => {
2751
+ if (round1.length !== secret.signers.max - 1)
2752
+ throw new Error("wrong length of round1 packages");
2753
+ if (!secret.coefficients || secret.step !== 2)
2754
+ throw new Error("round2 package used in round3");
2755
+ if (round2.length !== round1.length)
2756
+ throw new Error("wrong length of round2 packages");
2757
+ const merged = {};
2758
+ for (const r1 of round1) {
2759
+ if (!r1.identifier || !r1.commitment)
2760
+ throw new Error("wrong round1 share");
2761
+ merged[r1.identifier] = { ...r1 };
2762
+ }
2763
+ for (const r2 of round2) {
2764
+ if (!r2.identifier || !r2.signingShare)
2765
+ throw new Error("wrong round2 share");
2766
+ if (!merged[r2.identifier])
2767
+ throw new Error("round1 share for " + r2.identifier + " is missing");
2768
+ merged[r2.identifier].signingShare = r2.signingShare;
2769
+ }
2770
+ if (Object.keys(merged).length !== round1.length)
2771
+ throw new Error("mismatch identifiers between rounds");
2772
+ let signingShare = Fn2.ZERO;
2773
+ if (secret.commitment.length !== secret.signers.min)
2774
+ throw new Error("wrong commitments length");
2775
+ const localCommitment = secret.commitment.map(parsePoint);
2776
+ const localShare = polynomialEvaluate(secret.identifier, secret.coefficients);
2777
+ validateSecretShare(secret.identifier, localCommitment, localShare);
2778
+ const localCommitmentBytes = localCommitment.map(serializePoint);
2779
+ const commitments = {
2780
+ [serializeIdentifier(secret.identifier)]: localCommitmentBytes
2781
+ };
2782
+ for (const k in merged) {
2783
+ const v = merged[k];
2784
+ if (!v.signingShare || !v.commitment)
2785
+ throw new Error("mismatch identifiers");
2786
+ const id = parseIdentifier(k);
2787
+ const signingSharePart = Fn2.fromBytes(v.signingShare);
2788
+ const commitment = v.commitment.map(parsePoint);
2789
+ validateSecretShare(secret.identifier, commitment, signingSharePart);
2790
+ signingShare = Fn2.add(signingShare, signingSharePart);
2791
+ const idSer = serializeIdentifier(id);
2792
+ if (commitments[idSer])
2793
+ throw new Error("duplicated id=" + idSer);
2794
+ commitments[idSer] = v.commitment;
2795
+ }
2796
+ signingShare = Fn2.add(signingShare, localShare);
2797
+ const mergedCommitment = new Array(secret.signers.min).fill(Point.ZERO);
2798
+ for (const k in commitments) {
2799
+ const v = commitments[k];
2800
+ if (v.length !== secret.signers.min)
2801
+ throw new Error("wrong commitments length");
2802
+ for (let i = 0; i < v.length; i++)
2803
+ mergedCommitment[i] = mergedCommitment[i].add(parsePoint(v[i]));
2804
+ }
2805
+ const mergedCommitmentBytes = mergedCommitment.map(serializePoint);
2806
+ const verifyingShares = {};
2807
+ for (const k in commitments)
2808
+ verifyingShares[k] = serializePoint(evalutateVSS(parseIdentifier(k), mergedCommitment));
2809
+ let res = {
2810
+ public: {
2811
+ signers: { min: secret.signers.min, max: secret.signers.max },
2812
+ commitments: mergedCommitmentBytes,
2813
+ verifyingShares: Object.fromEntries(Object.entries(verifyingShares).map(([k, v]) => [k, v.slice()]))
2814
+ },
2815
+ secret: {
2816
+ identifier: serializeIdentifier(secret.identifier),
2817
+ signingShare: Fn2.toBytes(signingShare)
2818
+ }
2819
+ };
2820
+ if (opts.adjustDKG)
2821
+ res = opts.adjustDKG(res);
2822
+ for (let i = 0; i < secret.coefficients.length; i++)
2823
+ secret.coefficients[i] -= secret.coefficients[i];
2824
+ delete secret.coefficients;
2825
+ secret.step = 3;
2826
+ return res;
2827
+ },
2828
+ clean(secret) {
2829
+ secret.identifier -= secret.identifier;
2830
+ if (secret.coefficients) {
2831
+ for (let i = 0; i < secret.coefficients.length; i++)
2832
+ secret.coefficients[i] -= secret.coefficients[i];
2833
+ }
2834
+ secret.step = 3;
2835
+ }
2836
+ }),
2837
+ // Trusted dealer setup
2838
+ // Generates keys for all participants
2839
+ trustedDealer(signers, identifiers, secret, rng = randomBytes2) {
2840
+ validateSigners(signers);
2841
+ if (identifiers === void 0) {
2842
+ identifiers = [];
2843
+ for (let i = 1; i <= signers.max; i++)
2844
+ identifiers.push(Identifier.fromNumber(i));
2845
+ } else {
2846
+ if (!Array.isArray(identifiers) || identifiers.length !== signers.max)
2847
+ throw new Error("identifiers should be array of " + signers.max);
2848
+ }
2849
+ const identifierNums = {};
2850
+ for (const id of identifiers) {
2851
+ const idNum = parseIdentifier(id);
2852
+ if (id in identifierNums)
2853
+ throw new Error("duplicated id=" + id);
2854
+ identifierNums[id] = idNum;
2855
+ }
2856
+ const sp = generateSecretPolynomial(signers, secret, void 0, rng);
2857
+ const commitmentBytes = sp.commitment.map(serializePoint);
2858
+ const secretShares = {};
2859
+ const verifyingShares = {};
2860
+ for (const id of identifiers) {
2861
+ const signingShare = polynomialEvaluate(identifierNums[id], sp.coefficients);
2862
+ verifyingShares[id] = serializePoint(Point.BASE.multiply(signingShare));
2863
+ secretShares[id] = {
2864
+ identifier: id,
2865
+ signingShare: Fn2.toBytes(signingShare)
2866
+ };
2867
+ }
2868
+ return {
2869
+ public: {
2870
+ signers: { min: signers.min, max: signers.max },
2871
+ commitments: commitmentBytes,
2872
+ verifyingShares
2873
+ },
2874
+ secretShares
2875
+ };
2876
+ },
2877
+ // Validate secret (from trusted dealer or DKG)
2878
+ validateSecret(secret, pub) {
2879
+ const id = parseIdentifier(secret.identifier);
2880
+ const commitment = pub.commitments.map(parsePoint);
2881
+ const signingShare = Fn2.fromBytes(secret.signingShare);
2882
+ validateSecretShare(id, commitment, signingShare);
2883
+ },
2884
+ // Actual signing
2885
+ // Round 1: each participant commit to nonces
2886
+ // Nonces kept private, commitments sent to coordinator (or every other participant)
2887
+ // NOTE: we don't need the message at this point, which lets a coordinator
2888
+ // keep multiple nonce commitments per participant in advance and skip
2889
+ // round1 for signing.
2890
+ // But then each participant needs to remember generated shares
2891
+ commit(secret, rng = randomBytes2) {
2892
+ const secretScalar = Fn2.fromBytes(secret.signingShare);
2893
+ const hiding = generateNonce(secretScalar, rng);
2894
+ const binding = generateNonce(secretScalar, rng);
2895
+ const nonces = { hiding: Fn2.toBytes(hiding), binding: Fn2.toBytes(binding) };
2896
+ return { nonces, commitments: nonceCommitments(secret.identifier, nonces) };
2897
+ },
2898
+ // Round2: sign. Each participant creates a signature share from the secret
2899
+ // and the selected nonce commitments.
2900
+ signShare(secret, pub, nonces, commitmentList, msg) {
2901
+ validateCommitmentsNum(pub.signers, commitmentList.length);
2902
+ const hidingNonce0 = Fn2.fromBytes(nonces.hiding);
2903
+ const bindingNonce0 = Fn2.fromBytes(nonces.binding);
2904
+ if (Fn2.is0(hidingNonce0) || Fn2.is0(bindingNonce0))
2905
+ throw new Error("signing nonces already used");
2906
+ const expectedCommitment = {
2907
+ identifier: secret.identifier,
2908
+ hiding: serializePoint(Point.BASE.multiply(hidingNonce0)),
2909
+ binding: serializePoint(Point.BASE.multiply(bindingNonce0))
2910
+ };
2911
+ const commitment = commitmentList.find((i) => i.identifier === secret.identifier);
2912
+ if (!commitment)
2913
+ throw new Error("missing signer commitment");
2914
+ if (bytesToHex2(commitment.hiding) !== bytesToHex2(expectedCommitment.hiding) || bytesToHex2(commitment.binding) !== bytesToHex2(expectedCommitment.binding))
2915
+ throw new Error("incorrect signer commitment");
2916
+ if (opts.adjustSecret)
2917
+ secret = opts.adjustSecret(secret, pub);
2918
+ if (opts.adjustPublic)
2919
+ pub = opts.adjustPublic(pub);
2920
+ const SK = Fn2.fromBytes(secret.signingShare);
2921
+ const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(pub.commitments[0], commitmentList, msg, secret.identifier);
2922
+ const N = opts.adjustNonces ? opts.adjustNonces(groupCommitment, nonces) : nonces;
2923
+ const hidingNonce = opts.adjustNonces ? Fn2.fromBytes(N.hiding) : hidingNonce0;
2924
+ const bindingNonce = opts.adjustNonces ? Fn2.fromBytes(N.binding) : bindingNonce0;
2925
+ const t = Fn2.mul(Fn2.mul(lambda, SK), challenge);
2926
+ const t2 = Fn2.mul(bindingNonce, bindingFactor);
2927
+ const r = Fn2.toBytes(Fn2.add(Fn2.add(hidingNonce, t2), t));
2928
+ nonces.hiding.fill(0);
2929
+ nonces.binding.fill(0);
2930
+ return r;
2931
+ },
2932
+ // Each participant (or coordinator) can verify signatures from other participants
2933
+ verifyShare(pub, commitmentList, msg, identifier, sigShare) {
2934
+ if (opts.adjustPublic)
2935
+ pub = opts.adjustPublic(pub);
2936
+ const comm = commitmentList.find((i) => i.identifier === identifier);
2937
+ if (!comm)
2938
+ throw new Error("cannot find identifier commitment");
2939
+ const PK = parsePoint(pub.verifyingShares[identifier]);
2940
+ const hidingNonceCommitment = parsePoint(comm.hiding);
2941
+ const bindingNonceCommitment = parsePoint(comm.binding);
2942
+ const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(pub.commitments[0], commitmentList, msg, identifier);
2943
+ let commShare = hidingNonceCommitment.add(bindingNonceCommitment.multiply(bindingFactor));
2944
+ if (opts.adjustGroupCommitmentShare)
2945
+ commShare = opts.adjustGroupCommitmentShare(groupCommitment, commShare);
2946
+ const l = Point.BASE.multiply(Fn2.fromBytes(sigShare));
2947
+ const r = commShare.add(PK.multiply(Fn2.mul(challenge, lambda)));
2948
+ return l.equals(r);
2949
+ },
2950
+ // Aggregate multiple signature shares into groupSignature
2951
+ aggregate(pub, commitmentList, msg, sigShares) {
2952
+ if (opts.adjustPublic)
2953
+ pub = opts.adjustPublic(pub);
2954
+ try {
2955
+ validateCommitmentsNum(pub.signers, commitmentList.length);
2956
+ } catch {
2957
+ throw new AggErr("aggregation failed", []);
2958
+ }
2959
+ const ids = commitmentList.map((i) => i.identifier);
2960
+ if (ids.length !== Object.keys(sigShares).length)
2961
+ throw new AggErr("aggregation failed", []);
2962
+ for (const id of ids) {
2963
+ if (!(id in sigShares) || !(id in pub.verifyingShares))
2964
+ throw new AggErr("aggregation failed", []);
2965
+ }
2966
+ const GPK = parsePoint(pub.commitments[0]);
2967
+ const { groupCommitment } = getGroupCommitment(GPK, commitmentList, msg);
2968
+ let z = Fn2.ZERO;
2969
+ for (const id of ids)
2970
+ z = Fn2.add(z, Fn2.fromBytes(sigShares[id]));
2971
+ if (!Basic.verify(msg, groupCommitment, z, GPK)) {
2972
+ const cheaters = [];
2973
+ for (const id of ids) {
2974
+ if (!this.verifyShare(pub, commitmentList, msg, id, sigShares[id]))
2975
+ cheaters.push(id);
2976
+ }
2977
+ throw new AggErr("aggregation failed", cheaters);
2978
+ }
2979
+ return Signature.encode(groupCommitment, z);
2980
+ },
2981
+ // Basic sign/verify using single key
2982
+ sign(msg, secretKey) {
2983
+ let sk = Fn2.fromBytes(secretKey);
2984
+ if (opts.adjustScalar)
2985
+ sk = opts.adjustScalar(sk);
2986
+ const [R, z] = Basic.sign(msg, sk);
2987
+ return Signature.encode(R, z);
2988
+ },
2989
+ verify(sig, msg, publicKey) {
2990
+ const PK = opts.parsePublicKey ? opts.parsePublicKey(publicKey) : parsePoint(publicKey);
2991
+ const { R, z } = Signature.decode(sig);
2992
+ return Basic.verify(msg, R, z, PK);
2993
+ },
2994
+ // Combine multiple secret shares to restore secret
2995
+ combineSecret(shares, signers) {
2996
+ validateSigners(signers);
2997
+ if (!Array.isArray(shares) || shares.length < signers.min)
2998
+ throw new Error("wrong secret shares array");
2999
+ const points = [];
3000
+ const seen = {};
3001
+ for (const s of shares) {
3002
+ const idNum = parseIdentifier(s.identifier);
3003
+ const id = serializeIdentifier(idNum);
3004
+ if (seen[id])
3005
+ throw new Error("duplicated id=" + id);
3006
+ seen[id] = true;
3007
+ points.push([idNum, Fn2.fromBytes(s.signingShare)]);
3008
+ }
3009
+ const xCoords = points.map(([x]) => x);
3010
+ let res = Fn2.ZERO;
3011
+ for (const [x, y] of points)
3012
+ res = Fn2.add(res, Fn2.mul(y, deriveInterpolatingValue(xCoords, x)));
3013
+ return Fn2.toBytes(res);
3014
+ },
3015
+ // Utils
3016
+ utils: Object.freeze({
3017
+ Fn: Fn2,
3018
+ // NOTE: we re-export it here because it may be different from Point.Fn (ed448 is fun!)
3019
+ // Test RNG overrides still go through noble's non-zero scalar derivation; this is not a raw
3020
+ // "bytes become scalar" escape hatch.
3021
+ randomScalar: (rng = randomBytes2) => Fn2.toBytes(genPointScalarPair(rng).scalar),
3022
+ generateSecretPolynomial: (signers, secret, coeffs, rng) => {
3023
+ const res = generateSecretPolynomial(signers, secret, coeffs, rng);
3024
+ return { ...res, commitment: res.commitment.map(serializePoint) };
3025
+ }
3026
+ })
3027
+ };
3028
+ return Object.freeze(frost);
1900
3029
  }
1901
3030
 
1902
- // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/montgomery.js
3031
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/montgomery.js
1903
3032
  var _0n5 = BigInt(0);
1904
3033
  var _1n5 = BigInt(1);
1905
3034
  var _2n3 = BigInt(2);
1906
3035
  function validateOpts(curve) {
1907
3036
  validateObject(curve, {
3037
+ P: "bigint",
3038
+ type: "string",
1908
3039
  adjustScalarBytes: "function",
1909
3040
  powPminus2: "function"
3041
+ }, {
3042
+ randomBytes: "function"
1910
3043
  });
1911
3044
  return Object.freeze({ ...curve });
1912
3045
  }
@@ -1916,7 +3049,7 @@ function montgomery(curveDef) {
1916
3049
  const is25519 = type === "x25519";
1917
3050
  if (!is25519 && type !== "x448")
1918
3051
  throw new Error("invalid type");
1919
- const randomBytes_ = rand || randomBytes;
3052
+ const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
1920
3053
  const montgomeryBits = is25519 ? 255 : 448;
1921
3054
  const fieldLen = is25519 ? 32 : 56;
1922
3055
  const Gu = is25519 ? BigInt(9) : BigInt(5);
@@ -1930,13 +3063,13 @@ function montgomery(curveDef) {
1930
3063
  return numberToBytesLE(modP(u), fieldLen);
1931
3064
  }
1932
3065
  function decodeU(u) {
1933
- const _u = copyBytes(abytes(u, fieldLen, "uCoordinate"));
3066
+ const _u = copyBytes(abytes2(u, fieldLen, "uCoordinate"));
1934
3067
  if (is25519)
1935
3068
  _u[31] &= 127;
1936
3069
  return modP(bytesToNumberLE(_u));
1937
3070
  }
1938
3071
  function decodeScalar(scalar) {
1939
- return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes(scalar, fieldLen, "scalar"))));
3072
+ return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
1940
3073
  }
1941
3074
  function scalarMult(scalar, u) {
1942
3075
  const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
@@ -1997,11 +3130,14 @@ function montgomery(curveDef) {
1997
3130
  publicKey: fieldLen,
1998
3131
  seed: fieldLen
1999
3132
  };
2000
- const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
2001
- abytes(seed, lengths.seed, "seed");
3133
+ const randomSecretKey = (seed) => {
3134
+ seed = seed === void 0 ? randomBytes_(fieldLen) : seed;
3135
+ abytes2(seed, lengths.seed, "seed");
2002
3136
  return seed;
2003
3137
  };
2004
3138
  const utils = { randomSecretKey };
3139
+ Object.freeze(lengths);
3140
+ Object.freeze(utils);
2005
3141
  return Object.freeze({
2006
3142
  keygen: createKeygen(randomSecretKey, getPublicKey),
2007
3143
  getSharedSecret,
@@ -2014,55 +3150,63 @@ function montgomery(curveDef) {
2014
3150
  });
2015
3151
  }
2016
3152
 
2017
- // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/abstract/oprf.js
2018
- function createORPF(opts) {
3153
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/oprf.js
3154
+ var _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar);
3155
+ function createOPRF(opts) {
2019
3156
  validateObject(opts, {
2020
3157
  name: "string",
2021
3158
  hash: "function",
2022
3159
  hashToScalar: "function",
2023
3160
  hashToGroup: "function"
2024
3161
  });
3162
+ validatePointCons(opts.Point);
2025
3163
  const { name, Point, hash } = opts;
2026
3164
  const { Fn: Fn2 } = Point;
2027
3165
  const hashToGroup = (msg, ctx) => opts.hashToGroup(msg, {
2028
- DST: concatBytes(asciiToBytes("HashToGroup-"), ctx)
3166
+ DST: concatBytes2(asciiToBytes("HashToGroup-"), ctx)
2029
3167
  });
2030
- const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes(_DST_scalar, ctx) });
2031
- const randomScalar = (rng = randomBytes) => {
3168
+ const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes2(_DST_scalarBytes, ctx) });
3169
+ const randomScalar = (rng = randomBytes2) => {
2032
3170
  const t = mapHashToField(rng(getMinHashLength(Fn2.ORDER)), Fn2.ORDER, Fn2.isLE);
2033
3171
  return Fn2.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
2034
3172
  };
2035
3173
  const msm = (points, scalars) => pippenger(Point, points, scalars);
2036
- const getCtx = (mode) => concatBytes(asciiToBytes("OPRFV1-"), new Uint8Array([mode]), asciiToBytes("-" + name));
3174
+ const getCtx = (mode) => concatBytes2(asciiToBytes("OPRFV1-"), new Uint8Array([mode]), asciiToBytes("-" + name));
2037
3175
  const ctxOPRF = getCtx(0);
2038
3176
  const ctxVOPRF = getCtx(1);
2039
3177
  const ctxPOPRF = getCtx(2);
2040
3178
  function encode(...args) {
2041
- const res = [];
3179
+ const res2 = [];
2042
3180
  for (const a of args) {
2043
3181
  if (typeof a === "number")
2044
- res.push(numberToBytesBE(a, 2));
3182
+ res2.push(numberToBytesBE(a, 2));
2045
3183
  else if (typeof a === "string")
2046
- res.push(asciiToBytes(a));
3184
+ res2.push(asciiToBytes(a));
2047
3185
  else {
2048
- abytes(a);
2049
- res.push(numberToBytesBE(a.length, 2), a);
3186
+ abytes2(a);
3187
+ res2.push(numberToBytesBE(a.length, 2), a);
2050
3188
  }
2051
3189
  }
2052
- return concatBytes(...res);
3190
+ return concatBytes2(...res2);
2053
3191
  }
3192
+ const inputBytes = (title, bytes) => {
3193
+ abytes2(bytes, void 0, title);
3194
+ if (bytes.length > 65535)
3195
+ throw new Error(`"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}`);
3196
+ return bytes;
3197
+ };
2054
3198
  const hashInput = (...bytes) => hash(encode(...bytes, "Finalize"));
2055
3199
  function getTranscripts(B, C, D, ctx) {
2056
3200
  const Bm = B.toBytes();
2057
- const seed = hash(encode(Bm, concatBytes(asciiToBytes("Seed-"), ctx)));
2058
- const res = [];
3201
+ const seed = hash(encode(Bm, concatBytes2(asciiToBytes("Seed-"), ctx)));
3202
+ const res2 = [];
2059
3203
  for (let i = 0; i < C.length; i++) {
2060
3204
  const Ci = C[i].toBytes();
2061
3205
  const Di = D[i].toBytes();
2062
3206
  const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, "Composite"), ctx);
2063
- res.push(di);
3207
+ res2.push(di);
2064
3208
  }
2065
- return res;
3209
+ return res2;
2066
3210
  }
2067
3211
  function computeComposites(B, C, D, ctx) {
2068
3212
  const T = getTranscripts(B, C, D, ctx);
@@ -2087,10 +3231,10 @@ function createORPF(opts) {
2087
3231
  const t3 = M.multiply(r);
2088
3232
  const c = challengeTranscript(B, M, Z, t2, t3, ctx);
2089
3233
  const s = Fn2.sub(r, Fn2.mul(c, k));
2090
- return concatBytes(...[c, s].map((i) => Fn2.toBytes(i)));
3234
+ return concatBytes2(...[c, s].map((i) => Fn2.toBytes(i)));
2091
3235
  }
2092
3236
  function verifyProof(ctx, B, C, D, proof) {
2093
- abytes(proof, 2 * Fn2.BYTES);
3237
+ abytes2(proof, 2 * Fn2.BYTES);
2094
3238
  const { M, Z } = computeComposites(B, C, D, ctx);
2095
3239
  const [c, s] = [proof.subarray(0, Fn2.BYTES), proof.subarray(Fn2.BYTES)].map((f) => Fn2.fromBytes(f));
2096
3240
  const t2 = Point.BASE.multiply(s).add(B.multiply(c));
@@ -2105,18 +3249,30 @@ function createORPF(opts) {
2105
3249
  return { secretKey: Fn2.toBytes(skS), publicKey: pkS.toBytes() };
2106
3250
  }
2107
3251
  function deriveKeyPair(ctx, seed, info) {
2108
- const dst = concatBytes(asciiToBytes("DeriveKeyPair"), ctx);
2109
- const msg = concatBytes(seed, encode(info), Uint8Array.of(0));
3252
+ abytes2(seed, 32, "seed");
3253
+ info = inputBytes("keyInfo", info);
3254
+ const dst = concatBytes2(asciiToBytes("DeriveKeyPair"), ctx);
3255
+ const msg = concatBytes2(seed, encode(info), Uint8Array.of(0));
2110
3256
  for (let counter = 0; counter <= 255; counter++) {
2111
3257
  msg[msg.length - 1] = counter;
2112
3258
  const skS = opts.hashToScalar(msg, { DST: dst });
2113
3259
  if (Fn2.is0(skS))
2114
3260
  continue;
2115
- return { secretKey: Fn2.toBytes(skS), publicKey: Point.BASE.multiply(skS).toBytes() };
3261
+ return {
3262
+ secretKey: Fn2.toBytes(skS),
3263
+ publicKey: Point.BASE.multiply(skS).toBytes()
3264
+ };
2116
3265
  }
2117
3266
  throw new Error("Cannot derive key");
2118
3267
  }
2119
- function blind(ctx, input, rng = randomBytes) {
3268
+ const wirePoint = (label, bytes) => {
3269
+ const point = Point.fromBytes(bytes);
3270
+ if (point.equals(Point.ZERO))
3271
+ throw new Error(label + " point at infinity");
3272
+ return point;
3273
+ };
3274
+ function blind(ctx, input, rng = randomBytes2) {
3275
+ input = inputBytes("input", input);
2120
3276
  const blind2 = randomScalar(rng);
2121
3277
  const inputPoint = hashToGroup(input, ctx);
2122
3278
  if (inputPoint.equals(Point.ZERO))
@@ -2125,6 +3281,7 @@ function createORPF(opts) {
2125
3281
  return { blind: Fn2.toBytes(blind2), blinded: blinded.toBytes() };
2126
3282
  }
2127
3283
  function evaluate(ctx, secretKey, input) {
3284
+ input = inputBytes("input", input);
2128
3285
  const skS = Fn2.fromBytes(secretKey);
2129
3286
  const inputPoint = hashToGroup(input, ctx);
2130
3287
  if (inputPoint.equals(Point.ZERO))
@@ -2132,47 +3289,48 @@ function createORPF(opts) {
2132
3289
  const unblinded = inputPoint.multiply(skS).toBytes();
2133
3290
  return hashInput(input, unblinded);
2134
3291
  }
2135
- const oprf = {
3292
+ const oprf = Object.freeze({
2136
3293
  generateKeyPair,
2137
3294
  deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),
2138
- blind: (input, rng = randomBytes) => blind(ctxOPRF, input, rng),
3295
+ blind: (input, rng = randomBytes2) => blind(ctxOPRF, input, rng),
2139
3296
  blindEvaluate(secretKey, blindedPoint) {
2140
3297
  const skS = Fn2.fromBytes(secretKey);
2141
- const elm = Point.fromBytes(blindedPoint);
3298
+ const elm = wirePoint("blinded", blindedPoint);
2142
3299
  return elm.multiply(skS).toBytes();
2143
3300
  },
2144
3301
  finalize(input, blindBytes, evaluatedBytes) {
3302
+ input = inputBytes("input", input);
2145
3303
  const blind2 = Fn2.fromBytes(blindBytes);
2146
- const evalPoint = Point.fromBytes(evaluatedBytes);
3304
+ const evalPoint = wirePoint("evaluated", evaluatedBytes);
2147
3305
  const unblinded = evalPoint.multiply(Fn2.inv(blind2)).toBytes();
2148
3306
  return hashInput(input, unblinded);
2149
3307
  },
2150
3308
  evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input)
2151
- };
2152
- const voprf = {
3309
+ });
3310
+ const voprf = Object.freeze({
2153
3311
  generateKeyPair,
2154
3312
  deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),
2155
- blind: (input, rng = randomBytes) => blind(ctxVOPRF, input, rng),
2156
- blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes) {
3313
+ blind: (input, rng = randomBytes2) => blind(ctxVOPRF, input, rng),
3314
+ blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes2) {
2157
3315
  if (!Array.isArray(blinded))
2158
3316
  throw new Error("expected array");
2159
3317
  const skS = Fn2.fromBytes(secretKey);
2160
- const pkS = Point.fromBytes(publicKey);
2161
- const blindedPoints = blinded.map(Point.fromBytes);
3318
+ const pkS = wirePoint("public key", publicKey);
3319
+ const blindedPoints = blinded.map((i) => wirePoint("blinded", i));
2162
3320
  const evaluated = blindedPoints.map((i) => i.multiply(skS));
2163
3321
  const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);
2164
3322
  return { evaluated: evaluated.map((i) => i.toBytes()), proof };
2165
3323
  },
2166
- blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes) {
2167
- const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);
2168
- return { evaluated: res.evaluated[0], proof: res.proof };
3324
+ blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes2) {
3325
+ const res2 = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);
3326
+ return { evaluated: res2.evaluated[0], proof: res2.proof };
2169
3327
  },
2170
3328
  finalizeBatch(items, publicKey, proof) {
2171
3329
  if (!Array.isArray(items))
2172
3330
  throw new Error("expected array");
2173
- const pkS = Point.fromBytes(publicKey);
2174
- const blindedPoints = items.map((i) => i.blinded).map(Point.fromBytes);
2175
- const evalPoints = items.map((i) => i.evaluated).map(Point.fromBytes);
3331
+ const pkS = wirePoint("public key", publicKey);
3332
+ const blindedPoints = items.map((i) => wirePoint("blinded", i.blinded));
3333
+ const evalPoints = items.map((i) => wirePoint("evaluated", i.evaluated));
2176
3334
  verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);
2177
3335
  return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated));
2178
3336
  },
@@ -2180,15 +3338,17 @@ function createORPF(opts) {
2180
3338
  return this.finalizeBatch([{ input, blind: blind2, evaluated, blinded }], publicKey, proof)[0];
2181
3339
  },
2182
3340
  evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input)
2183
- };
3341
+ });
2184
3342
  const poprf = (info) => {
3343
+ info = inputBytes("info", info);
2185
3344
  const m = hashToScalarPrefixed(encode("Info", info), ctxPOPRF);
2186
3345
  const T = Point.BASE.multiply(m);
2187
- return {
3346
+ return Object.freeze({
2188
3347
  generateKeyPair,
2189
3348
  deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),
2190
- blind(input, publicKey, rng = randomBytes) {
2191
- const pkS = Point.fromBytes(publicKey);
3349
+ blind(input, publicKey, rng = randomBytes2) {
3350
+ input = inputBytes("input", input);
3351
+ const pkS = wirePoint("public key", publicKey);
2192
3352
  const tweakedKey = T.add(pkS);
2193
3353
  if (tweakedKey.equals(Point.ZERO))
2194
3354
  throw new Error("tweakedKey point at infinity");
@@ -2203,37 +3363,39 @@ function createORPF(opts) {
2203
3363
  tweakedKey: tweakedKey.toBytes()
2204
3364
  };
2205
3365
  },
2206
- blindEvaluateBatch(secretKey, blinded, rng = randomBytes) {
3366
+ blindEvaluateBatch(secretKey, blinded, rng = randomBytes2) {
2207
3367
  if (!Array.isArray(blinded))
2208
3368
  throw new Error("expected array");
2209
3369
  const skS = Fn2.fromBytes(secretKey);
2210
3370
  const t = Fn2.add(skS, m);
2211
3371
  const invT = Fn2.inv(t);
2212
- const blindedPoints = blinded.map(Point.fromBytes);
3372
+ const blindedPoints = blinded.map((i) => wirePoint("blinded", i));
2213
3373
  const evalPoints = blindedPoints.map((i) => i.multiply(invT));
2214
3374
  const tweakedKey = Point.BASE.multiply(t);
2215
3375
  const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);
2216
3376
  return { evaluated: evalPoints.map((i) => i.toBytes()), proof };
2217
3377
  },
2218
- blindEvaluate(secretKey, blinded, rng = randomBytes) {
2219
- const res = this.blindEvaluateBatch(secretKey, [blinded], rng);
2220
- return { evaluated: res.evaluated[0], proof: res.proof };
3378
+ blindEvaluate(secretKey, blinded, rng = randomBytes2) {
3379
+ const res2 = this.blindEvaluateBatch(secretKey, [blinded], rng);
3380
+ return { evaluated: res2.evaluated[0], proof: res2.proof };
2221
3381
  },
2222
3382
  finalizeBatch(items, proof, tweakedKey) {
2223
3383
  if (!Array.isArray(items))
2224
3384
  throw new Error("expected array");
2225
- const evalPoints = items.map((i) => i.evaluated).map(Point.fromBytes);
2226
- verifyProof(ctxPOPRF, Point.fromBytes(tweakedKey), evalPoints, items.map((i) => i.blinded).map(Point.fromBytes), proof);
3385
+ const inputs = items.map((i) => inputBytes("input", i.input));
3386
+ const evalPoints = items.map((i) => wirePoint("evaluated", i.evaluated));
3387
+ verifyProof(ctxPOPRF, wirePoint("tweakedKey", tweakedKey), evalPoints, items.map((i) => wirePoint("blinded", i.blinded)), proof);
2227
3388
  return items.map((i, j) => {
2228
3389
  const blind2 = Fn2.fromBytes(i.blind);
2229
3390
  const point = evalPoints[j].multiply(Fn2.inv(blind2)).toBytes();
2230
- return hashInput(i.input, info, point);
3391
+ return hashInput(inputs[j], info, point);
2231
3392
  });
2232
3393
  },
2233
3394
  finalize(input, blind2, evaluated, blinded, proof, tweakedKey) {
2234
3395
  return this.finalizeBatch([{ input, blind: blind2, evaluated, blinded }], proof, tweakedKey)[0];
2235
3396
  },
2236
3397
  evaluate(secretKey, input) {
3398
+ input = inputBytes("input", input);
2237
3399
  const skS = Fn2.fromBytes(secretKey);
2238
3400
  const inputPoint = hashToGroup(input, ctxPOPRF);
2239
3401
  if (inputPoint.equals(Point.ZERO))
@@ -2243,19 +3405,20 @@ function createORPF(opts) {
2243
3405
  const unblinded = inputPoint.multiply(invT).toBytes();
2244
3406
  return hashInput(input, info, unblinded);
2245
3407
  }
2246
- };
3408
+ });
2247
3409
  };
2248
- return Object.freeze({ name, oprf, voprf, poprf, __tests: { Fn: Fn2 } });
3410
+ const res = { name, oprf, voprf, poprf, __tests: Object.freeze({ Fn: Fn2 }) };
3411
+ return Object.freeze(res);
2249
3412
  }
2250
3413
 
2251
- // ../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/ed25519.js
3414
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/ed25519.js
2252
3415
  var _0n6 = /* @__PURE__ */ BigInt(0);
2253
- var _1n6 = BigInt(1);
2254
- var _2n4 = BigInt(2);
3416
+ var _1n6 = /* @__PURE__ */ BigInt(1);
3417
+ var _2n4 = /* @__PURE__ */ BigInt(2);
2255
3418
  var _3n2 = /* @__PURE__ */ BigInt(3);
2256
- var _5n2 = BigInt(5);
2257
- var _8n3 = BigInt(8);
2258
- var ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
3419
+ var _5n2 = /* @__PURE__ */ BigInt(5);
3420
+ var _8n3 = /* @__PURE__ */ BigInt(8);
3421
+ var ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2259
3422
  var ed25519_CURVE = /* @__PURE__ */ (() => ({
2260
3423
  p: ed25519_CURVE_p,
2261
3424
  n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
@@ -2318,11 +3481,25 @@ function ed25519_domain(data, ctx, phflag) {
2318
3481
  return concatBytes(asciiToBytes("SigEd25519 no Ed25519 collisions"), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
2319
3482
  }
2320
3483
  function ed(opts) {
2321
- return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));
3484
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, zip215: true }, opts));
2322
3485
  }
2323
3486
  var ed25519 = /* @__PURE__ */ ed({});
2324
3487
  var ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain });
2325
3488
  var ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });
3489
+ var ed25519_FROST = /* @__PURE__ */ (() => createFROST({
3490
+ name: "FROST-ED25519-SHA512-v1",
3491
+ Point: ed25519_Point,
3492
+ validatePoint: (p) => {
3493
+ p.assertValidity();
3494
+ if (!p.isTorsionFree())
3495
+ throw new Error("bad point: not torsion-free");
3496
+ },
3497
+ hash: sha512,
3498
+ // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),
3499
+ // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats
3500
+ // that the same as omitted DST, even though custom hooks can still observe the empty bag.
3501
+ H2: ""
3502
+ }))();
2326
3503
  var x25519 = /* @__PURE__ */ (() => {
2327
3504
  const P = ed25519_CURVE_p;
2328
3505
  return montgomery({
@@ -2453,6 +3630,12 @@ var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2453
3630
  constructor(ep) {
2454
3631
  super(ep);
2455
3632
  }
3633
+ /**
3634
+ * Create one Ristretto255 point from affine Edwards coordinates.
3635
+ * This wraps the internal Edwards representative directly and is not a
3636
+ * canonical ristretto255 decoding path.
3637
+ * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
3638
+ */
2456
3639
  static fromAffine(ap) {
2457
3640
  return new __RistrettoPoint(ed25519_Point.fromAffine(ap));
2458
3641
  }
@@ -2492,7 +3675,7 @@ var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2492
3675
  /**
2493
3676
  * Converts ristretto-encoded string to ristretto point.
2494
3677
  * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2495
- * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
3678
+ * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2496
3679
  */
2497
3680
  static fromHex(hex) {
2498
3681
  return __RistrettoPoint.fromBytes(hexToBytes(hex));
@@ -2546,8 +3729,12 @@ var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2546
3729
  return this.equals(__RistrettoPoint.ZERO);
2547
3730
  }
2548
3731
  };
2549
- var ristretto255 = { Point: _RistrettoPoint };
2550
- var ristretto255_hasher = {
3732
+ Object.freeze(_RistrettoPoint.BASE);
3733
+ Object.freeze(_RistrettoPoint.ZERO);
3734
+ Object.freeze(_RistrettoPoint.prototype);
3735
+ Object.freeze(_RistrettoPoint);
3736
+ var ristretto255 = /* @__PURE__ */ Object.freeze({ Point: _RistrettoPoint });
3737
+ var ristretto255_hasher = Object.freeze({
2551
3738
  Point: _RistrettoPoint,
2552
3739
  /**
2553
3740
  * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
@@ -2558,11 +3745,13 @@ var ristretto255_hasher = {
2558
3745
  * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
2559
3746
  (os2ip -> bytes255ToNumberLE)
2560
3747
  * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
2561
- * * hashToScalar is undefined in RFC9380 for ristretto, we are using version from OPRF here, using bytes255ToNumblerLE will create different result if we use bytes255ToNumberLE as os2ip
3748
+ * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
3749
+ version here. Using `bytes255ToNumblerLE` will create a different result
3750
+ if we use `bytes255ToNumberLE` as os2ip
2562
3751
  * * current version is closest to spec.
2563
3752
  */
2564
3753
  hashToCurve(msg, options) {
2565
- const DST = options?.DST || "ristretto255_XMD:SHA-512_R255MAP_RO_";
3754
+ const DST = options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2566
3755
  const xmd = expand_message_xmd(msg, DST, 64, sha512);
2567
3756
  return ristretto255_hasher.deriveToCurve(xmd);
2568
3757
  },
@@ -2574,8 +3763,10 @@ var ristretto255_hasher = {
2574
3763
  * HashToCurve-like construction based on RFC 9496 (Element Derivation).
2575
3764
  * Converts 64 uniform random bytes into a curve point.
2576
3765
  *
2577
- * WARNING: This represents an older hash-to-curve construction, preceding the finalization of RFC 9380.
2578
- * It was later reused as a component in the newer `hash_to_ristretto255` function defined in RFC 9380.
3766
+ * WARNING: This represents an older hash-to-curve construction from before
3767
+ * RFC 9380 was finalized.
3768
+ * It was later reused as a component in the newer
3769
+ * `hash_to_ristretto255` function defined in RFC 9380.
2579
3770
  */
2580
3771
  deriveToCurve(bytes) {
2581
3772
  abytes(bytes, 64);
@@ -2585,15 +3776,23 @@ var ristretto255_hasher = {
2585
3776
  const R2 = calcElligatorRistrettoMap(r2);
2586
3777
  return new _RistrettoPoint(R1.add(R2));
2587
3778
  }
2588
- };
2589
- var ristretto255_oprf = /* @__PURE__ */ (() => createORPF({
3779
+ });
3780
+ var ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({
2590
3781
  name: "ristretto255-SHA512",
2591
3782
  Point: _RistrettoPoint,
2592
3783
  hash: sha512,
2593
3784
  hashToGroup: ristretto255_hasher.hashToCurve,
2594
3785
  hashToScalar: ristretto255_hasher.hashToScalar
2595
3786
  }))();
2596
- var ED25519_TORSION_SUBGROUP = [
3787
+ var ristretto255_FROST = /* @__PURE__ */ (() => createFROST({
3788
+ name: "FROST-RISTRETTO255-SHA512-v1",
3789
+ Point: _RistrettoPoint,
3790
+ validatePoint: (p) => {
3791
+ p.assertValidity();
3792
+ },
3793
+ hash: sha512
3794
+ }))();
3795
+ var ED25519_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([
2597
3796
  "0100000000000000000000000000000000000000000000000000000000000000",
2598
3797
  "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
2599
3798
  "0000000000000000000000000000000000000000000000000000000000000080",
@@ -2602,25 +3801,26 @@ var ED25519_TORSION_SUBGROUP = [
2602
3801
  "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
2603
3802
  "0000000000000000000000000000000000000000000000000000000000000000",
2604
3803
  "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"
2605
- ];
3804
+ ]);
2606
3805
 
2607
3806
  export {
3807
+ hexToBytes,
3808
+ sha256,
2608
3809
  ed25519,
2609
3810
  ed25519ctx,
2610
3811
  ed25519ph,
3812
+ ed25519_FROST,
2611
3813
  x25519,
2612
3814
  _map_to_curve_elligator2_curve25519,
2613
3815
  ed25519_hasher,
2614
3816
  ristretto255,
2615
3817
  ristretto255_hasher,
2616
3818
  ristretto255_oprf,
3819
+ ristretto255_FROST,
2617
3820
  ED25519_TORSION_SUBGROUP
2618
3821
  };
2619
3822
  /*! Bundled license information:
2620
3823
 
2621
- @noble/hashes/utils.js:
2622
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2623
-
2624
3824
  @noble/curves/utils.js:
2625
3825
  @noble/curves/abstract/modular.js:
2626
3826
  @noble/curves/abstract/curve.js:
@@ -2630,4 +3830,4 @@ export {
2630
3830
  @noble/curves/ed25519.js:
2631
3831
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2632
3832
  */
2633
- //# sourceMappingURL=chunk-FSS45ZX3.js.map
3833
+ //# sourceMappingURL=chunk-DLYE6U2Z.js.map