@motebit/crypto 2.0.0 → 3.0.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,11 +1,5 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // ../../node_modules/.pnpm/@noble+ed25519@3.0.1/node_modules/@noble/ed25519/index.js
8
- var ed25519_CURVE = {
1
+ // ../../node_modules/.pnpm/@noble+ed25519@3.1.0/node_modules/@noble/ed25519/index.js
2
+ var ed25519_CURVE = Object.freeze({
9
3
  p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
10
4
  n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
11
5
  h: 8n,
@@ -13,7 +7,7 @@ var ed25519_CURVE = {
13
7
  d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
14
8
  Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
15
9
  Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
16
- };
10
+ });
17
11
  var { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;
18
12
  var L = 32;
19
13
  var captureTrace = (...args) => {
@@ -28,7 +22,7 @@ var err = (message = "") => {
28
22
  };
29
23
  var isBig = (n) => typeof n === "bigint";
30
24
  var isStr = (s) => typeof s === "string";
31
- var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
25
+ var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
32
26
  var abytes = (value, length, title = "") => {
33
27
  const bytes = isBytes(value);
34
28
  const len = value?.length;
@@ -37,7 +31,8 @@ var abytes = (value, length, title = "") => {
37
31
  const prefix = title && `"${title}" `;
38
32
  const ofLen = needsLen ? ` of length ${length}` : "";
39
33
  const got = bytes ? `length=${len}` : `type=${typeof value}`;
40
- err(prefix + "expected Uint8Array" + ofLen + ", got " + got);
34
+ const msg = prefix + "expected Uint8Array" + ofLen + ", got " + got;
35
+ throw bytes ? new RangeError(msg) : new TypeError(msg);
41
36
  }
42
37
  return value;
43
38
  };
@@ -76,7 +71,10 @@ var hexToBytes = (hex) => {
76
71
  var cr = () => globalThis?.crypto;
77
72
  var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
78
73
  var concatBytes = (...arrs) => {
79
- const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
74
+ let len = 0;
75
+ for (const a of arrs)
76
+ len += abytes(a).length;
77
+ const r = u8n(len);
80
78
  let pad = 0;
81
79
  arrs.forEach((a) => {
82
80
  r.set(a, pad);
@@ -89,7 +87,13 @@ var randomBytes = (len = L) => {
89
87
  return c.getRandomValues(u8n(len));
90
88
  };
91
89
  var big = BigInt;
92
- var assertRange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
90
+ var assertRange = (n, min, max, msg = "bad number: out of range") => {
91
+ if (!isBig(n))
92
+ throw new TypeError(msg);
93
+ if (min <= n && n < max)
94
+ return n;
95
+ throw new RangeError(msg);
96
+ };
93
97
  var M = (a, b = P) => {
94
98
  const r = a % b;
95
99
  return r >= 0n ? r : b + r;
@@ -114,6 +118,13 @@ var invert = (num, md) => {
114
118
  }
115
119
  return b === 1n ? M(x, md) : err("no inverse");
116
120
  };
121
+ var callHash = (name) => {
122
+ const fn = hashes[name];
123
+ if (typeof fn !== "function")
124
+ err("hashes." + name + " not set");
125
+ return fn;
126
+ };
127
+ var checkDigest = (value) => abytes(value, 64, "digest");
117
128
  var apoint = (p) => p instanceof Point ? p : err("Point expected");
118
129
  var B256 = 2n ** 256n;
119
130
  var Point = class _Point {
@@ -123,6 +134,8 @@ var Point = class _Point {
123
134
  Y;
124
135
  Z;
125
136
  T;
137
+ // Constructor only bounds-checks and freezes XYZT coordinates; it does not prove the point is
138
+ // on-curve or that T matches X*Y/Z.
126
139
  constructor(X, Y, Z, T) {
127
140
  const max = B256;
128
141
  this.X = assertRange(X, 0n, max);
@@ -137,7 +150,7 @@ var Point = class _Point {
137
150
  static fromAffine(p) {
138
151
  return new _Point(p.x, p.y, 1n, modP(p.x * p.y));
139
152
  }
140
- /** RFC8032 5.1.3: Uint8Array to Point. */
153
+ /** RFC8032 5.1.3: Bytes to Point. */
141
154
  static fromBytes(hex, zip215 = false) {
142
155
  const d = _d;
143
156
  const normed = u8fr(abytes(hex, L));
@@ -252,16 +265,19 @@ var Point = class _Point {
252
265
  return this.add(apoint(other).negate());
253
266
  }
254
267
  /**
255
- * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
268
+ * Point-by-scalar multiplication. Safe mode requires `1 <= n < CURVE.n`.
269
+ * Unsafe mode additionally permits `n = 0` and returns the identity point for that case.
256
270
  * Uses {@link wNAF} for base point.
257
271
  * Uses fake point to mitigate side-channel leakage.
258
- * @param n scalar by which point is multiplied
259
- * @param safe safe mode guards against timing attacks; unsafe mode is faster
272
+ * @param n - scalar by which point is multiplied
273
+ * @param safe - safe mode guards against timing attacks; unsafe mode is faster
260
274
  */
261
275
  multiply(n, safe = true) {
262
- if (!safe && (n === 0n || this.is0()))
276
+ if (!safe && n === 0n)
263
277
  return I;
264
278
  assertRange(n, 1n, N);
279
+ if (!safe && this.is0())
280
+ return I;
265
281
  if (n === 1n)
266
282
  return this;
267
283
  if (this.equals(G))
@@ -345,8 +361,8 @@ var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
345
361
  var uvRatio = (u, v) => {
346
362
  const v3 = modP(v * modP(v * v));
347
363
  const v7 = modP(modP(v3 * v3) * v);
348
- const pow3 = pow_2_252_3(modP(u * v7)).pow_p_5_8;
349
- let x = modP(u * modP(v3 * pow3));
364
+ const pow = pow_2_252_3(modP(u * v7)).pow_p_5_8;
365
+ let x = modP(u * modP(v3 * pow));
350
366
  const vx2 = modP(v * modP(x * x));
351
367
  const root1 = x;
352
368
  const root2 = modP(x * RM1);
@@ -362,13 +378,14 @@ var uvRatio = (u, v) => {
362
378
  return { isValid: useRoot1 || useRoot2, value: x };
363
379
  };
364
380
  var modL_LE = (hash) => modN(bytesToNumberLE(hash));
365
- var sha512a = (...m) => hashes.sha512Async(concatBytes(...m));
381
+ var sha512a = (...m) => Promise.resolve(callHash("sha512Async")(concatBytes(...m))).then(checkDigest);
366
382
  var hash2extK = (hashed) => {
367
- const head = hashed.slice(0, 32);
383
+ const copy = u8fr(hashed);
384
+ const head = copy.slice(0, 32);
368
385
  head[0] &= 248;
369
386
  head[31] &= 127;
370
387
  head[31] |= 64;
371
- const prefix = hashed.slice(32, 64);
388
+ const prefix = copy.slice(32, 64);
372
389
  const scalar = modL_LE(head);
373
390
  const point = G.multiply(scalar);
374
391
  const pointBytes = point.toBytes();
@@ -399,7 +416,7 @@ var _verify = (sig, msg, publicKey, options = defaultVerifyOpts) => {
399
416
  sig = abytes(sig, 64);
400
417
  msg = abytes(msg);
401
418
  publicKey = abytes(publicKey, L);
402
- const { zip215 } = options;
419
+ const { zip215 = true } = options;
403
420
  const r = sig.subarray(0, L);
404
421
  const s = bytesToNumberLE(sig.subarray(L, L * 2));
405
422
  let A, R, SB;
@@ -409,7 +426,7 @@ var _verify = (sig, msg, publicKey, options = defaultVerifyOpts) => {
409
426
  A = Point.fromBytes(publicKey, zip215);
410
427
  R = Point.fromBytes(r, zip215);
411
428
  SB = G.multiply(s, false);
412
- hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
429
+ hashable = concatBytes(r, publicKey, msg);
413
430
  finished = true;
414
431
  } catch (error) {
415
432
  }
@@ -433,7 +450,10 @@ var hashes = {
433
450
  },
434
451
  sha512: void 0
435
452
  };
436
- var randomSecretKey = (seed = randomBytes(L)) => seed;
453
+ var randomSecretKey = (seed) => {
454
+ seed = seed === void 0 ? randomBytes(L) : seed;
455
+ return abytes(seed, L);
456
+ };
437
457
  var keygenAsync = async (seed) => {
438
458
  const secretKey = randomSecretKey(seed);
439
459
  const publicKey = await getPublicKeyAsync(secretKey);
@@ -494,15 +514,44 @@ var wNAF = (n) => {
494
514
  return { p, f };
495
515
  };
496
516
 
497
- // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/_assert.js
517
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js
498
518
  function isBytes2(a) {
499
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
519
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
520
+ }
521
+ function anumber(n, title = "") {
522
+ if (typeof n !== "number") {
523
+ const prefix = title && `"${title}" `;
524
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
525
+ }
526
+ if (!Number.isSafeInteger(n) || n < 0) {
527
+ const prefix = title && `"${title}" `;
528
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
529
+ }
530
+ }
531
+ function abytes2(value, length, title = "") {
532
+ const bytes = isBytes2(value);
533
+ const len = value?.length;
534
+ const needsLen = length !== void 0;
535
+ if (!bytes || needsLen && len !== length) {
536
+ const prefix = title && `"${title}" `;
537
+ const ofLen = needsLen ? ` of length ${length}` : "";
538
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
539
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
540
+ if (!bytes)
541
+ throw new TypeError(message);
542
+ throw new RangeError(message);
543
+ }
544
+ return value;
500
545
  }
501
- function abytes2(b, ...lengths) {
502
- if (!isBytes2(b))
503
- throw new Error("Uint8Array expected");
504
- if (lengths.length > 0 && !lengths.includes(b.length))
505
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
546
+ function ahash(h2) {
547
+ if (typeof h2 !== "function" || typeof h2.create !== "function")
548
+ throw new TypeError("Hash must wrapped by utils.createHasher");
549
+ anumber(h2.outputLen);
550
+ anumber(h2.blockLen);
551
+ if (h2.outputLen < 1)
552
+ throw new Error('"outputLen" must be >= 1');
553
+ if (h2.blockLen < 1)
554
+ throw new Error('"blockLen" must be >= 1');
506
555
  }
507
556
  function aexists(instance, checkFinished = true) {
508
557
  if (instance.destroyed)
@@ -511,75 +560,148 @@ function aexists(instance, checkFinished = true) {
511
560
  throw new Error("Hash#digest() has already been called");
512
561
  }
513
562
  function aoutput(out, instance) {
514
- abytes2(out);
563
+ abytes2(out, void 0, "digestInto() output");
515
564
  const min = instance.outputLen;
516
565
  if (out.length < min) {
517
- throw new Error("digestInto() expects output buffer of length at least " + min);
566
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
518
567
  }
519
568
  }
520
-
521
- // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/utils.js
522
- var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
523
- var rotr = (word, shift) => word << 32 - shift | word >>> shift;
524
- function utf8ToBytes(str) {
525
- if (typeof str !== "string")
526
- throw new Error("utf8ToBytes expected string, got " + typeof str);
527
- return new Uint8Array(new TextEncoder().encode(str));
528
- }
529
- function toBytes(data) {
530
- if (typeof data === "string")
531
- data = utf8ToBytes(data);
532
- abytes2(data);
533
- return data;
534
- }
535
- var Hash = class {
536
- // Safe version that clones internal state
537
- clone() {
538
- return this._cloneInto();
569
+ function clean(...arrays) {
570
+ for (let i = 0; i < arrays.length; i++) {
571
+ arrays[i].fill(0);
539
572
  }
540
- };
541
- function wrapConstructor(hashCons) {
542
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
543
- const tmp = hashCons();
573
+ }
574
+ function createView(arr) {
575
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
576
+ }
577
+ function rotr(word, shift) {
578
+ return word << 32 - shift | word >>> shift;
579
+ }
580
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
581
+ // @ts-ignore
582
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
583
+ ))();
584
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
585
+ function bytesToHex2(bytes) {
586
+ abytes2(bytes);
587
+ if (hasHexBuiltin)
588
+ return bytes.toHex();
589
+ let hex = "";
590
+ for (let i = 0; i < bytes.length; i++) {
591
+ hex += hexes[bytes[i]];
592
+ }
593
+ return hex;
594
+ }
595
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
596
+ function asciiToBase16(ch) {
597
+ if (ch >= asciis._0 && ch <= asciis._9)
598
+ return ch - asciis._0;
599
+ if (ch >= asciis.A && ch <= asciis.F)
600
+ return ch - (asciis.A - 10);
601
+ if (ch >= asciis.a && ch <= asciis.f)
602
+ return ch - (asciis.a - 10);
603
+ return;
604
+ }
605
+ function hexToBytes2(hex) {
606
+ if (typeof hex !== "string")
607
+ throw new TypeError("hex string expected, got " + typeof hex);
608
+ if (hasHexBuiltin) {
609
+ try {
610
+ return Uint8Array.fromHex(hex);
611
+ } catch (error) {
612
+ if (error instanceof SyntaxError)
613
+ throw new RangeError(error.message);
614
+ throw error;
615
+ }
616
+ }
617
+ const hl = hex.length;
618
+ const al = hl / 2;
619
+ if (hl % 2)
620
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
621
+ const array = new Uint8Array(al);
622
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
623
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
624
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
625
+ if (n1 === void 0 || n2 === void 0) {
626
+ const char = hex[hi] + hex[hi + 1];
627
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
628
+ }
629
+ array[ai] = n1 * 16 + n2;
630
+ }
631
+ return array;
632
+ }
633
+ function concatBytes2(...arrays) {
634
+ let sum = 0;
635
+ for (let i = 0; i < arrays.length; i++) {
636
+ const a = arrays[i];
637
+ abytes2(a);
638
+ sum += a.length;
639
+ }
640
+ const res = new Uint8Array(sum);
641
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
642
+ const a = arrays[i];
643
+ res.set(a, pad);
644
+ pad += a.length;
645
+ }
646
+ return res;
647
+ }
648
+ function createHasher(hashCons, info = {}) {
649
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
650
+ const tmp = hashCons(void 0);
544
651
  hashC.outputLen = tmp.outputLen;
545
652
  hashC.blockLen = tmp.blockLen;
546
- hashC.create = () => hashCons();
547
- return hashC;
653
+ hashC.canXOF = tmp.canXOF;
654
+ hashC.create = (opts) => hashCons(opts);
655
+ Object.assign(hashC, info);
656
+ return Object.freeze(hashC);
548
657
  }
658
+ function randomBytes2(bytesLength = 32) {
659
+ anumber(bytesLength, "bytesLength");
660
+ const cr2 = typeof globalThis === "object" ? globalThis.crypto : null;
661
+ if (typeof cr2?.getRandomValues !== "function")
662
+ throw new Error("crypto.getRandomValues must be defined");
663
+ if (bytesLength > 65536)
664
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
665
+ return cr2.getRandomValues(new Uint8Array(bytesLength));
666
+ }
667
+ var oidNist = (suffix) => ({
668
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
669
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
670
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
671
+ });
549
672
 
550
- // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/_md.js
551
- function setBigUint64(view, byteOffset, value, isLE) {
552
- if (typeof view.setBigUint64 === "function")
553
- return view.setBigUint64(byteOffset, value, isLE);
554
- const _32n2 = BigInt(32);
555
- const _u32_max = BigInt(4294967295);
556
- const wh = Number(value >> _32n2 & _u32_max);
557
- const wl = Number(value & _u32_max);
558
- const h2 = isLE ? 4 : 0;
559
- const l = isLE ? 0 : 4;
560
- view.setUint32(byteOffset + h2, wh, isLE);
561
- view.setUint32(byteOffset + l, wl, isLE);
562
- }
563
- var Chi = (a, b, c) => a & b ^ ~a & c;
564
- var Maj = (a, b, c) => a & b ^ a & c ^ b & c;
565
- var HashMD = class extends Hash {
673
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js
674
+ function Chi(a, b, c) {
675
+ return a & b ^ ~a & c;
676
+ }
677
+ function Maj(a, b, c) {
678
+ return a & b ^ a & c ^ b & c;
679
+ }
680
+ var HashMD = class {
681
+ blockLen;
682
+ outputLen;
683
+ canXOF = false;
684
+ padOffset;
685
+ isLE;
686
+ // For partial updates less than block size
687
+ buffer;
688
+ view;
689
+ finished = false;
690
+ length = 0;
691
+ pos = 0;
692
+ destroyed = false;
566
693
  constructor(blockLen, outputLen, padOffset, isLE) {
567
- super();
568
694
  this.blockLen = blockLen;
569
695
  this.outputLen = outputLen;
570
696
  this.padOffset = padOffset;
571
697
  this.isLE = isLE;
572
- this.finished = false;
573
- this.length = 0;
574
- this.pos = 0;
575
- this.destroyed = false;
576
698
  this.buffer = new Uint8Array(blockLen);
577
699
  this.view = createView(this.buffer);
578
700
  }
579
701
  update(data) {
580
702
  aexists(this);
703
+ abytes2(data);
581
704
  const { view, buffer, blockLen } = this;
582
- data = toBytes(data);
583
705
  const len = data.length;
584
706
  for (let pos = 0; pos < len; ) {
585
707
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -608,19 +730,19 @@ var HashMD = class extends Hash {
608
730
  const { buffer, view, blockLen, isLE } = this;
609
731
  let { pos } = this;
610
732
  buffer[pos++] = 128;
611
- this.buffer.subarray(pos).fill(0);
733
+ clean(this.buffer.subarray(pos));
612
734
  if (this.padOffset > blockLen - pos) {
613
735
  this.process(view, 0);
614
736
  pos = 0;
615
737
  }
616
738
  for (let i = pos; i < blockLen; i++)
617
739
  buffer[i] = 0;
618
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
740
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
619
741
  this.process(view, 0);
620
742
  const oview = createView(out);
621
743
  const len = this.outputLen;
622
744
  if (len % 4)
623
- throw new Error("_sha2: outputLen should be aligned to 32bit");
745
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
624
746
  const outLen = len / 4;
625
747
  const state = this.get();
626
748
  if (outLen > state.length)
@@ -636,20 +758,51 @@ var HashMD = class extends Hash {
636
758
  return res;
637
759
  }
638
760
  _cloneInto(to) {
639
- to || (to = new this.constructor());
761
+ to ||= new this.constructor();
640
762
  to.set(...this.get());
641
763
  const { blockLen, buffer, length, finished, destroyed, pos } = this;
764
+ to.destroyed = destroyed;
765
+ to.finished = finished;
642
766
  to.length = length;
643
767
  to.pos = pos;
644
- to.finished = finished;
645
- to.destroyed = destroyed;
646
768
  if (length % blockLen)
647
769
  to.buffer.set(buffer);
648
770
  return to;
649
771
  }
772
+ clone() {
773
+ return this._cloneInto();
774
+ }
650
775
  };
776
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
777
+ 1779033703,
778
+ 3144134277,
779
+ 1013904242,
780
+ 2773480762,
781
+ 1359893119,
782
+ 2600822924,
783
+ 528734635,
784
+ 1541459225
785
+ ]);
786
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
787
+ 1779033703,
788
+ 4089235720,
789
+ 3144134277,
790
+ 2227873595,
791
+ 1013904242,
792
+ 4271175723,
793
+ 2773480762,
794
+ 1595750129,
795
+ 1359893119,
796
+ 2917565137,
797
+ 2600822924,
798
+ 725511199,
799
+ 528734635,
800
+ 4215389547,
801
+ 1541459225,
802
+ 327033209
803
+ ]);
651
804
 
652
- // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/_u64.js
805
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js
653
806
  var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
654
807
  var _32n = /* @__PURE__ */ BigInt(32);
655
808
  function fromBig(n, le = false) {
@@ -658,27 +811,21 @@ function fromBig(n, le = false) {
658
811
  return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
659
812
  }
660
813
  function split(lst, le = false) {
661
- let Ah = new Uint32Array(lst.length);
662
- let Al = new Uint32Array(lst.length);
663
- for (let i = 0; i < lst.length; i++) {
814
+ const len = lst.length;
815
+ let Ah = new Uint32Array(len);
816
+ let Al = new Uint32Array(len);
817
+ for (let i = 0; i < len; i++) {
664
818
  const { h: h2, l } = fromBig(lst[i], le);
665
819
  [Ah[i], Al[i]] = [h2, l];
666
820
  }
667
821
  return [Ah, Al];
668
822
  }
669
- var toBig = (h2, l) => BigInt(h2 >>> 0) << _32n | BigInt(l >>> 0);
670
823
  var shrSH = (h2, _l, s) => h2 >>> s;
671
824
  var shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
672
825
  var rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
673
826
  var rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
674
827
  var rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
675
828
  var rotrBL = (h2, l, s) => h2 >>> s - 32 | l << 64 - s;
676
- var rotr32H = (_h, l) => l;
677
- var rotr32L = (h2, _l) => h2;
678
- var rotlSH = (h2, l, s) => h2 << s | l >>> 32 - s;
679
- var rotlSL = (h2, l, s) => l << s | h2 >>> 32 - s;
680
- var rotlBH = (h2, l, s) => l << s - 32 | h2 >>> 64 - s;
681
- var rotlBL = (h2, l, s) => h2 << s - 32 | l >>> 64 - s;
682
829
  function add(Ah, Al, Bh, Bl) {
683
830
  const l = (Al >>> 0) + (Bl >>> 0);
684
831
  return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
@@ -689,34 +836,154 @@ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0
689
836
  var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
690
837
  var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
691
838
  var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
692
- var u64 = {
693
- fromBig,
694
- split,
695
- toBig,
696
- shrSH,
697
- shrSL,
698
- rotrSH,
699
- rotrSL,
700
- rotrBH,
701
- rotrBL,
702
- rotr32H,
703
- rotr32L,
704
- rotlSH,
705
- rotlSL,
706
- rotlBH,
707
- rotlBL,
708
- add,
709
- add3L,
710
- add3H,
711
- add4L,
712
- add4H,
713
- add5H,
714
- add5L
715
- };
716
- var u64_default = u64;
717
839
 
718
- // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/sha512.js
719
- var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64_default.split([
840
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js
841
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
842
+ 1116352408,
843
+ 1899447441,
844
+ 3049323471,
845
+ 3921009573,
846
+ 961987163,
847
+ 1508970993,
848
+ 2453635748,
849
+ 2870763221,
850
+ 3624381080,
851
+ 310598401,
852
+ 607225278,
853
+ 1426881987,
854
+ 1925078388,
855
+ 2162078206,
856
+ 2614888103,
857
+ 3248222580,
858
+ 3835390401,
859
+ 4022224774,
860
+ 264347078,
861
+ 604807628,
862
+ 770255983,
863
+ 1249150122,
864
+ 1555081692,
865
+ 1996064986,
866
+ 2554220882,
867
+ 2821834349,
868
+ 2952996808,
869
+ 3210313671,
870
+ 3336571891,
871
+ 3584528711,
872
+ 113926993,
873
+ 338241895,
874
+ 666307205,
875
+ 773529912,
876
+ 1294757372,
877
+ 1396182291,
878
+ 1695183700,
879
+ 1986661051,
880
+ 2177026350,
881
+ 2456956037,
882
+ 2730485921,
883
+ 2820302411,
884
+ 3259730800,
885
+ 3345764771,
886
+ 3516065817,
887
+ 3600352804,
888
+ 4094571909,
889
+ 275423344,
890
+ 430227734,
891
+ 506948616,
892
+ 659060556,
893
+ 883997877,
894
+ 958139571,
895
+ 1322822218,
896
+ 1537002063,
897
+ 1747873779,
898
+ 1955562222,
899
+ 2024104815,
900
+ 2227730452,
901
+ 2361852424,
902
+ 2428436474,
903
+ 2756734187,
904
+ 3204031479,
905
+ 3329325298
906
+ ]);
907
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
908
+ var SHA2_32B = class extends HashMD {
909
+ constructor(outputLen) {
910
+ super(64, outputLen, 8, false);
911
+ }
912
+ get() {
913
+ const { A, B, C: C2, D, E, F, G: G2, H } = this;
914
+ return [A, B, C2, D, E, F, G2, H];
915
+ }
916
+ // prettier-ignore
917
+ set(A, B, C2, D, E, F, G2, H) {
918
+ this.A = A | 0;
919
+ this.B = B | 0;
920
+ this.C = C2 | 0;
921
+ this.D = D | 0;
922
+ this.E = E | 0;
923
+ this.F = F | 0;
924
+ this.G = G2 | 0;
925
+ this.H = H | 0;
926
+ }
927
+ process(view, offset) {
928
+ for (let i = 0; i < 16; i++, offset += 4)
929
+ SHA256_W[i] = view.getUint32(offset, false);
930
+ for (let i = 16; i < 64; i++) {
931
+ const W15 = SHA256_W[i - 15];
932
+ const W2 = SHA256_W[i - 2];
933
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
934
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
935
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
936
+ }
937
+ let { A, B, C: C2, D, E, F, G: G2, H } = this;
938
+ for (let i = 0; i < 64; i++) {
939
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
940
+ const T1 = H + sigma1 + Chi(E, F, G2) + SHA256_K[i] + SHA256_W[i] | 0;
941
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
942
+ const T2 = sigma0 + Maj(A, B, C2) | 0;
943
+ H = G2;
944
+ G2 = F;
945
+ F = E;
946
+ E = D + T1 | 0;
947
+ D = C2;
948
+ C2 = B;
949
+ B = A;
950
+ A = T1 + T2 | 0;
951
+ }
952
+ A = A + this.A | 0;
953
+ B = B + this.B | 0;
954
+ C2 = C2 + this.C | 0;
955
+ D = D + this.D | 0;
956
+ E = E + this.E | 0;
957
+ F = F + this.F | 0;
958
+ G2 = G2 + this.G | 0;
959
+ H = H + this.H | 0;
960
+ this.set(A, B, C2, D, E, F, G2, H);
961
+ }
962
+ roundClean() {
963
+ clean(SHA256_W);
964
+ }
965
+ destroy() {
966
+ this.destroyed = true;
967
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
968
+ clean(this.buffer);
969
+ }
970
+ };
971
+ var _SHA256 = class extends SHA2_32B {
972
+ // We cannot use array here since array allows indexing by variable
973
+ // which means optimizer/compiler cannot use registers.
974
+ A = SHA256_IV[0] | 0;
975
+ B = SHA256_IV[1] | 0;
976
+ C = SHA256_IV[2] | 0;
977
+ D = SHA256_IV[3] | 0;
978
+ E = SHA256_IV[4] | 0;
979
+ F = SHA256_IV[5] | 0;
980
+ G = SHA256_IV[6] | 0;
981
+ H = SHA256_IV[7] | 0;
982
+ constructor() {
983
+ super(32);
984
+ }
985
+ };
986
+ var K512 = /* @__PURE__ */ (() => split([
720
987
  "0x428a2f98d728ae22",
721
988
  "0x7137449123ef65cd",
722
989
  "0xb5c0fbcfec4d3b2f",
@@ -798,27 +1065,13 @@ var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64_default.split([
798
1065
  "0x5fcb6fab3ad6faec",
799
1066
  "0x6c44198c4a475817"
800
1067
  ].map((n) => BigInt(n))))();
1068
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1069
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
801
1070
  var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
802
1071
  var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
803
- var SHA512 = class extends HashMD {
804
- constructor() {
805
- super(128, 64, 16, false);
806
- this.Ah = 1779033703 | 0;
807
- this.Al = 4089235720 | 0;
808
- this.Bh = 3144134277 | 0;
809
- this.Bl = 2227873595 | 0;
810
- this.Ch = 1013904242 | 0;
811
- this.Cl = 4271175723 | 0;
812
- this.Dh = 2773480762 | 0;
813
- this.Dl = 1595750129 | 0;
814
- this.Eh = 1359893119 | 0;
815
- this.El = 2917565137 | 0;
816
- this.Fh = 2600822924 | 0;
817
- this.Fl = 725511199 | 0;
818
- this.Gh = 528734635 | 0;
819
- this.Gl = 4215389547 | 0;
820
- this.Hh = 1541459225 | 0;
821
- this.Hl = 327033209 | 0;
1072
+ var SHA2_64B = class extends HashMD {
1073
+ constructor(outputLen) {
1074
+ super(128, outputLen, 16, false);
822
1075
  }
823
1076
  // prettier-ignore
824
1077
  get() {
@@ -852,28 +1105,28 @@ var SHA512 = class extends HashMD {
852
1105
  for (let i = 16; i < 80; i++) {
853
1106
  const W15h = SHA512_W_H[i - 15] | 0;
854
1107
  const W15l = SHA512_W_L[i - 15] | 0;
855
- const s0h = u64_default.rotrSH(W15h, W15l, 1) ^ u64_default.rotrSH(W15h, W15l, 8) ^ u64_default.shrSH(W15h, W15l, 7);
856
- const s0l = u64_default.rotrSL(W15h, W15l, 1) ^ u64_default.rotrSL(W15h, W15l, 8) ^ u64_default.shrSL(W15h, W15l, 7);
1108
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1109
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
857
1110
  const W2h = SHA512_W_H[i - 2] | 0;
858
1111
  const W2l = SHA512_W_L[i - 2] | 0;
859
- const s1h = u64_default.rotrSH(W2h, W2l, 19) ^ u64_default.rotrBH(W2h, W2l, 61) ^ u64_default.shrSH(W2h, W2l, 6);
860
- const s1l = u64_default.rotrSL(W2h, W2l, 19) ^ u64_default.rotrBL(W2h, W2l, 61) ^ u64_default.shrSL(W2h, W2l, 6);
861
- const SUMl = u64_default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
862
- const SUMh = u64_default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1112
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1113
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1114
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1115
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
863
1116
  SHA512_W_H[i] = SUMh | 0;
864
1117
  SHA512_W_L[i] = SUMl | 0;
865
1118
  }
866
1119
  let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
867
1120
  for (let i = 0; i < 80; i++) {
868
- const sigma1h = u64_default.rotrSH(Eh, El, 14) ^ u64_default.rotrSH(Eh, El, 18) ^ u64_default.rotrBH(Eh, El, 41);
869
- const sigma1l = u64_default.rotrSL(Eh, El, 14) ^ u64_default.rotrSL(Eh, El, 18) ^ u64_default.rotrBL(Eh, El, 41);
1121
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1122
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
870
1123
  const CHIh = Eh & Fh ^ ~Eh & Gh;
871
1124
  const CHIl = El & Fl ^ ~El & Gl;
872
- const T1ll = u64_default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
873
- const T1h = u64_default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1125
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1126
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
874
1127
  const T1l = T1ll | 0;
875
- const sigma0h = u64_default.rotrSH(Ah, Al, 28) ^ u64_default.rotrBH(Ah, Al, 34) ^ u64_default.rotrBH(Ah, Al, 39);
876
- const sigma0l = u64_default.rotrSL(Ah, Al, 28) ^ u64_default.rotrBL(Ah, Al, 34) ^ u64_default.rotrBL(Ah, Al, 39);
1128
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1129
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
877
1130
  const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
878
1131
  const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
879
1132
  Hh = Gh | 0;
@@ -882,747 +1135,131 @@ var SHA512 = class extends HashMD {
882
1135
  Gl = Fl | 0;
883
1136
  Fh = Eh | 0;
884
1137
  Fl = El | 0;
885
- ({ h: Eh, l: El } = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1138
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
886
1139
  Dh = Ch | 0;
887
1140
  Dl = Cl | 0;
888
1141
  Ch = Bh | 0;
889
1142
  Cl = Bl | 0;
890
1143
  Bh = Ah | 0;
891
1144
  Bl = Al | 0;
892
- const All = u64_default.add3L(T1l, sigma0l, MAJl);
893
- Ah = u64_default.add3H(All, T1h, sigma0h, MAJh);
1145
+ const All = add3L(T1l, sigma0l, MAJl);
1146
+ Ah = add3H(All, T1h, sigma0h, MAJh);
894
1147
  Al = All | 0;
895
1148
  }
896
- ({ h: Ah, l: Al } = u64_default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
897
- ({ h: Bh, l: Bl } = u64_default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
898
- ({ h: Ch, l: Cl } = u64_default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
899
- ({ h: Dh, l: Dl } = u64_default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
900
- ({ h: Eh, l: El } = u64_default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
901
- ({ h: Fh, l: Fl } = u64_default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
902
- ({ h: Gh, l: Gl } = u64_default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
903
- ({ h: Hh, l: Hl } = u64_default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1149
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1150
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1151
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1152
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1153
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1154
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1155
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1156
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
904
1157
  this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
905
1158
  }
906
1159
  roundClean() {
907
- SHA512_W_H.fill(0);
908
- SHA512_W_L.fill(0);
1160
+ clean(SHA512_W_H, SHA512_W_L);
909
1161
  }
910
1162
  destroy() {
911
- this.buffer.fill(0);
1163
+ this.destroyed = true;
1164
+ clean(this.buffer);
912
1165
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
913
1166
  }
914
1167
  };
915
- var sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
1168
+ var _SHA512 = class extends SHA2_64B {
1169
+ Ah = SHA512_IV[0] | 0;
1170
+ Al = SHA512_IV[1] | 0;
1171
+ Bh = SHA512_IV[2] | 0;
1172
+ Bl = SHA512_IV[3] | 0;
1173
+ Ch = SHA512_IV[4] | 0;
1174
+ Cl = SHA512_IV[5] | 0;
1175
+ Dh = SHA512_IV[6] | 0;
1176
+ Dl = SHA512_IV[7] | 0;
1177
+ Eh = SHA512_IV[8] | 0;
1178
+ El = SHA512_IV[9] | 0;
1179
+ Fh = SHA512_IV[10] | 0;
1180
+ Fl = SHA512_IV[11] | 0;
1181
+ Gh = SHA512_IV[12] | 0;
1182
+ Gl = SHA512_IV[13] | 0;
1183
+ Hh = SHA512_IV[14] | 0;
1184
+ Hl = SHA512_IV[15] | 0;
1185
+ constructor() {
1186
+ super(64);
1187
+ }
1188
+ };
1189
+ var sha256 = /* @__PURE__ */ createHasher(
1190
+ () => new _SHA256(),
1191
+ /* @__PURE__ */ oidNist(1)
1192
+ );
1193
+ var sha512 = /* @__PURE__ */ createHasher(
1194
+ () => new _SHA512(),
1195
+ /* @__PURE__ */ oidNist(3)
1196
+ );
916
1197
 
917
- // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/sha256.js
918
- var SHA256_K = /* @__PURE__ */ new Uint32Array([
919
- 1116352408,
920
- 1899447441,
921
- 3049323471,
922
- 3921009573,
923
- 961987163,
924
- 1508970993,
925
- 2453635748,
926
- 2870763221,
927
- 3624381080,
928
- 310598401,
929
- 607225278,
930
- 1426881987,
931
- 1925078388,
932
- 2162078206,
933
- 2614888103,
934
- 3248222580,
935
- 3835390401,
936
- 4022224774,
937
- 264347078,
938
- 604807628,
939
- 770255983,
940
- 1249150122,
941
- 1555081692,
942
- 1996064986,
943
- 2554220882,
944
- 2821834349,
945
- 2952996808,
946
- 3210313671,
947
- 3336571891,
948
- 3584528711,
949
- 113926993,
950
- 338241895,
951
- 666307205,
952
- 773529912,
953
- 1294757372,
954
- 1396182291,
955
- 1695183700,
956
- 1986661051,
957
- 2177026350,
958
- 2456956037,
959
- 2730485921,
960
- 2820302411,
961
- 3259730800,
962
- 3345764771,
963
- 3516065817,
964
- 3600352804,
965
- 4094571909,
966
- 275423344,
967
- 430227734,
968
- 506948616,
969
- 659060556,
970
- 883997877,
971
- 958139571,
972
- 1322822218,
973
- 1537002063,
974
- 1747873779,
975
- 1955562222,
976
- 2024104815,
977
- 2227730452,
978
- 2361852424,
979
- 2428436474,
980
- 2756734187,
981
- 3204031479,
982
- 3329325298
983
- ]);
984
- var SHA256_IV = /* @__PURE__ */ new Uint32Array([
985
- 1779033703,
986
- 3144134277,
987
- 1013904242,
988
- 2773480762,
989
- 1359893119,
990
- 2600822924,
991
- 528734635,
992
- 1541459225
993
- ]);
994
- var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
995
- var SHA256 = class extends HashMD {
996
- constructor() {
997
- super(64, 32, 8, false);
998
- this.A = SHA256_IV[0] | 0;
999
- this.B = SHA256_IV[1] | 0;
1000
- this.C = SHA256_IV[2] | 0;
1001
- this.D = SHA256_IV[3] | 0;
1002
- this.E = SHA256_IV[4] | 0;
1003
- this.F = SHA256_IV[5] | 0;
1004
- this.G = SHA256_IV[6] | 0;
1005
- this.H = SHA256_IV[7] | 0;
1006
- }
1007
- get() {
1008
- const { A, B, C: C2, D, E, F, G: G2, H } = this;
1009
- return [A, B, C2, D, E, F, G2, H];
1010
- }
1011
- // prettier-ignore
1012
- set(A, B, C2, D, E, F, G2, H) {
1013
- this.A = A | 0;
1014
- this.B = B | 0;
1015
- this.C = C2 | 0;
1016
- this.D = D | 0;
1017
- this.E = E | 0;
1018
- this.F = F | 0;
1019
- this.G = G2 | 0;
1020
- this.H = H | 0;
1021
- }
1022
- process(view, offset) {
1023
- for (let i = 0; i < 16; i++, offset += 4)
1024
- SHA256_W[i] = view.getUint32(offset, false);
1025
- for (let i = 16; i < 64; i++) {
1026
- const W15 = SHA256_W[i - 15];
1027
- const W2 = SHA256_W[i - 2];
1028
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
1029
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
1030
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
1031
- }
1032
- let { A, B, C: C2, D, E, F, G: G2, H } = this;
1033
- for (let i = 0; i < 64; i++) {
1034
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1035
- const T1 = H + sigma1 + Chi(E, F, G2) + SHA256_K[i] + SHA256_W[i] | 0;
1036
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
1037
- const T2 = sigma0 + Maj(A, B, C2) | 0;
1038
- H = G2;
1039
- G2 = F;
1040
- F = E;
1041
- E = D + T1 | 0;
1042
- D = C2;
1043
- C2 = B;
1044
- B = A;
1045
- A = T1 + T2 | 0;
1046
- }
1047
- A = A + this.A | 0;
1048
- B = B + this.B | 0;
1049
- C2 = C2 + this.C | 0;
1050
- D = D + this.D | 0;
1051
- E = E + this.E | 0;
1052
- F = F + this.F | 0;
1053
- G2 = G2 + this.G | 0;
1054
- H = H + this.H | 0;
1055
- this.set(A, B, C2, D, E, F, G2, H);
1056
- }
1057
- roundClean() {
1058
- SHA256_W.fill(0);
1059
- }
1060
- destroy() {
1061
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
1062
- this.buffer.fill(0);
1063
- }
1064
- };
1065
- var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
1066
-
1067
- // ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/_assert.js
1068
- function anumber(n) {
1069
- if (!Number.isSafeInteger(n) || n < 0)
1070
- throw new Error("positive integer expected, got " + n);
1071
- }
1072
- function isBytes3(a) {
1073
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1074
- }
1075
- function abytes3(b, ...lengths) {
1076
- if (!isBytes3(b))
1077
- throw new Error("Uint8Array expected");
1078
- if (lengths.length > 0 && !lengths.includes(b.length))
1079
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
1080
- }
1081
- function ahash(h2) {
1082
- if (typeof h2 !== "function" || typeof h2.create !== "function")
1083
- throw new Error("Hash should be wrapped by utils.wrapConstructor");
1084
- anumber(h2.outputLen);
1085
- anumber(h2.blockLen);
1086
- }
1087
- function aexists2(instance, checkFinished = true) {
1088
- if (instance.destroyed)
1089
- throw new Error("Hash instance has been destroyed");
1090
- if (checkFinished && instance.finished)
1091
- throw new Error("Hash#digest() has already been called");
1092
- }
1093
- function aoutput2(out, instance) {
1094
- abytes3(out);
1095
- const min = instance.outputLen;
1096
- if (out.length < min) {
1097
- throw new Error("digestInto() expects output buffer of length at least " + min);
1098
- }
1099
- }
1100
-
1101
- // ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/crypto.js
1102
- var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
1103
-
1104
- // ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/utils.js
1105
- var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1106
- var rotr2 = (word, shift) => word << 32 - shift | word >>> shift;
1107
- function utf8ToBytes2(str) {
1108
- if (typeof str !== "string")
1109
- throw new Error("utf8ToBytes expected string, got " + typeof str);
1110
- return new Uint8Array(new TextEncoder().encode(str));
1111
- }
1112
- function toBytes2(data) {
1113
- if (typeof data === "string")
1114
- data = utf8ToBytes2(data);
1115
- abytes3(data);
1116
- return data;
1117
- }
1118
- function concatBytes2(...arrays) {
1119
- let sum = 0;
1120
- for (let i = 0; i < arrays.length; i++) {
1121
- const a = arrays[i];
1122
- abytes3(a);
1123
- sum += a.length;
1124
- }
1125
- const res = new Uint8Array(sum);
1126
- for (let i = 0, pad = 0; i < arrays.length; i++) {
1127
- const a = arrays[i];
1128
- res.set(a, pad);
1129
- pad += a.length;
1130
- }
1131
- return res;
1132
- }
1133
- var Hash2 = class {
1134
- // Safe version that clones internal state
1135
- clone() {
1136
- return this._cloneInto();
1137
- }
1138
- };
1139
- function wrapConstructor2(hashCons) {
1140
- const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
1141
- const tmp = hashCons();
1142
- hashC.outputLen = tmp.outputLen;
1143
- hashC.blockLen = tmp.blockLen;
1144
- hashC.create = () => hashCons();
1145
- return hashC;
1146
- }
1147
- function randomBytes2(bytesLength = 32) {
1148
- if (crypto && typeof crypto.getRandomValues === "function") {
1149
- return crypto.getRandomValues(new Uint8Array(bytesLength));
1150
- }
1151
- if (crypto && typeof crypto.randomBytes === "function") {
1152
- return crypto.randomBytes(bytesLength);
1153
- }
1154
- throw new Error("crypto.getRandomValues must be defined");
1155
- }
1156
-
1157
- // ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/_md.js
1158
- function setBigUint642(view, byteOffset, value, isLE) {
1159
- if (typeof view.setBigUint64 === "function")
1160
- return view.setBigUint64(byteOffset, value, isLE);
1161
- const _32n2 = BigInt(32);
1162
- const _u32_max = BigInt(4294967295);
1163
- const wh = Number(value >> _32n2 & _u32_max);
1164
- const wl = Number(value & _u32_max);
1165
- const h2 = isLE ? 4 : 0;
1166
- const l = isLE ? 0 : 4;
1167
- view.setUint32(byteOffset + h2, wh, isLE);
1168
- view.setUint32(byteOffset + l, wl, isLE);
1169
- }
1170
- var Chi2 = (a, b, c) => a & b ^ ~a & c;
1171
- var Maj2 = (a, b, c) => a & b ^ a & c ^ b & c;
1172
- var HashMD2 = class extends Hash2 {
1173
- constructor(blockLen, outputLen, padOffset, isLE) {
1174
- super();
1175
- this.blockLen = blockLen;
1176
- this.outputLen = outputLen;
1177
- this.padOffset = padOffset;
1178
- this.isLE = isLE;
1179
- this.finished = false;
1180
- this.length = 0;
1181
- this.pos = 0;
1182
- this.destroyed = false;
1183
- this.buffer = new Uint8Array(blockLen);
1184
- this.view = createView2(this.buffer);
1185
- }
1186
- update(data) {
1187
- aexists2(this);
1188
- const { view, buffer, blockLen } = this;
1189
- data = toBytes2(data);
1190
- const len = data.length;
1191
- for (let pos = 0; pos < len; ) {
1192
- const take = Math.min(blockLen - this.pos, len - pos);
1193
- if (take === blockLen) {
1194
- const dataView = createView2(data);
1195
- for (; blockLen <= len - pos; pos += blockLen)
1196
- this.process(dataView, pos);
1197
- continue;
1198
- }
1199
- buffer.set(data.subarray(pos, pos + take), this.pos);
1200
- this.pos += take;
1201
- pos += take;
1202
- if (this.pos === blockLen) {
1203
- this.process(view, 0);
1204
- this.pos = 0;
1205
- }
1206
- }
1207
- this.length += data.length;
1208
- this.roundClean();
1209
- return this;
1210
- }
1211
- digestInto(out) {
1212
- aexists2(this);
1213
- aoutput2(out, this);
1214
- this.finished = true;
1215
- const { buffer, view, blockLen, isLE } = this;
1216
- let { pos } = this;
1217
- buffer[pos++] = 128;
1218
- this.buffer.subarray(pos).fill(0);
1219
- if (this.padOffset > blockLen - pos) {
1220
- this.process(view, 0);
1221
- pos = 0;
1222
- }
1223
- for (let i = pos; i < blockLen; i++)
1224
- buffer[i] = 0;
1225
- setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE);
1226
- this.process(view, 0);
1227
- const oview = createView2(out);
1228
- const len = this.outputLen;
1229
- if (len % 4)
1230
- throw new Error("_sha2: outputLen should be aligned to 32bit");
1231
- const outLen = len / 4;
1232
- const state = this.get();
1233
- if (outLen > state.length)
1234
- throw new Error("_sha2: outputLen bigger than state");
1235
- for (let i = 0; i < outLen; i++)
1236
- oview.setUint32(4 * i, state[i], isLE);
1237
- }
1238
- digest() {
1239
- const { buffer, outputLen } = this;
1240
- this.digestInto(buffer);
1241
- const res = buffer.slice(0, outputLen);
1242
- this.destroy();
1243
- return res;
1244
- }
1245
- _cloneInto(to) {
1246
- to || (to = new this.constructor());
1247
- to.set(...this.get());
1248
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
1249
- to.length = length;
1250
- to.pos = pos;
1251
- to.finished = finished;
1252
- to.destroyed = destroyed;
1253
- if (length % blockLen)
1254
- to.buffer.set(buffer);
1255
- return to;
1256
- }
1257
- };
1258
-
1259
- // ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/sha256.js
1260
- var SHA256_K2 = /* @__PURE__ */ new Uint32Array([
1261
- 1116352408,
1262
- 1899447441,
1263
- 3049323471,
1264
- 3921009573,
1265
- 961987163,
1266
- 1508970993,
1267
- 2453635748,
1268
- 2870763221,
1269
- 3624381080,
1270
- 310598401,
1271
- 607225278,
1272
- 1426881987,
1273
- 1925078388,
1274
- 2162078206,
1275
- 2614888103,
1276
- 3248222580,
1277
- 3835390401,
1278
- 4022224774,
1279
- 264347078,
1280
- 604807628,
1281
- 770255983,
1282
- 1249150122,
1283
- 1555081692,
1284
- 1996064986,
1285
- 2554220882,
1286
- 2821834349,
1287
- 2952996808,
1288
- 3210313671,
1289
- 3336571891,
1290
- 3584528711,
1291
- 113926993,
1292
- 338241895,
1293
- 666307205,
1294
- 773529912,
1295
- 1294757372,
1296
- 1396182291,
1297
- 1695183700,
1298
- 1986661051,
1299
- 2177026350,
1300
- 2456956037,
1301
- 2730485921,
1302
- 2820302411,
1303
- 3259730800,
1304
- 3345764771,
1305
- 3516065817,
1306
- 3600352804,
1307
- 4094571909,
1308
- 275423344,
1309
- 430227734,
1310
- 506948616,
1311
- 659060556,
1312
- 883997877,
1313
- 958139571,
1314
- 1322822218,
1315
- 1537002063,
1316
- 1747873779,
1317
- 1955562222,
1318
- 2024104815,
1319
- 2227730452,
1320
- 2361852424,
1321
- 2428436474,
1322
- 2756734187,
1323
- 3204031479,
1324
- 3329325298
1325
- ]);
1326
- var SHA256_IV2 = /* @__PURE__ */ new Uint32Array([
1327
- 1779033703,
1328
- 3144134277,
1329
- 1013904242,
1330
- 2773480762,
1331
- 1359893119,
1332
- 2600822924,
1333
- 528734635,
1334
- 1541459225
1335
- ]);
1336
- var SHA256_W2 = /* @__PURE__ */ new Uint32Array(64);
1337
- var SHA2562 = class extends HashMD2 {
1338
- constructor() {
1339
- super(64, 32, 8, false);
1340
- this.A = SHA256_IV2[0] | 0;
1341
- this.B = SHA256_IV2[1] | 0;
1342
- this.C = SHA256_IV2[2] | 0;
1343
- this.D = SHA256_IV2[3] | 0;
1344
- this.E = SHA256_IV2[4] | 0;
1345
- this.F = SHA256_IV2[5] | 0;
1346
- this.G = SHA256_IV2[6] | 0;
1347
- this.H = SHA256_IV2[7] | 0;
1348
- }
1349
- get() {
1350
- const { A, B, C: C2, D, E, F, G: G2, H } = this;
1351
- return [A, B, C2, D, E, F, G2, H];
1352
- }
1353
- // prettier-ignore
1354
- set(A, B, C2, D, E, F, G2, H) {
1355
- this.A = A | 0;
1356
- this.B = B | 0;
1357
- this.C = C2 | 0;
1358
- this.D = D | 0;
1359
- this.E = E | 0;
1360
- this.F = F | 0;
1361
- this.G = G2 | 0;
1362
- this.H = H | 0;
1363
- }
1364
- process(view, offset) {
1365
- for (let i = 0; i < 16; i++, offset += 4)
1366
- SHA256_W2[i] = view.getUint32(offset, false);
1367
- for (let i = 16; i < 64; i++) {
1368
- const W15 = SHA256_W2[i - 15];
1369
- const W2 = SHA256_W2[i - 2];
1370
- const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3;
1371
- const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10;
1372
- SHA256_W2[i] = s1 + SHA256_W2[i - 7] + s0 + SHA256_W2[i - 16] | 0;
1373
- }
1374
- let { A, B, C: C2, D, E, F, G: G2, H } = this;
1375
- for (let i = 0; i < 64; i++) {
1376
- const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25);
1377
- const T1 = H + sigma1 + Chi2(E, F, G2) + SHA256_K2[i] + SHA256_W2[i] | 0;
1378
- const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22);
1379
- const T2 = sigma0 + Maj2(A, B, C2) | 0;
1380
- H = G2;
1381
- G2 = F;
1382
- F = E;
1383
- E = D + T1 | 0;
1384
- D = C2;
1385
- C2 = B;
1386
- B = A;
1387
- A = T1 + T2 | 0;
1388
- }
1389
- A = A + this.A | 0;
1390
- B = B + this.B | 0;
1391
- C2 = C2 + this.C | 0;
1392
- D = D + this.D | 0;
1393
- E = E + this.E | 0;
1394
- F = F + this.F | 0;
1395
- G2 = G2 + this.G | 0;
1396
- H = H + this.H | 0;
1397
- this.set(A, B, C2, D, E, F, G2, H);
1398
- }
1399
- roundClean() {
1400
- SHA256_W2.fill(0);
1401
- }
1402
- destroy() {
1403
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
1404
- this.buffer.fill(0);
1405
- }
1406
- };
1407
- var sha2562 = /* @__PURE__ */ wrapConstructor2(() => new SHA2562());
1408
-
1409
- // ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/hmac.js
1410
- var HMAC = class extends Hash2 {
1411
- constructor(hash, _key) {
1412
- super();
1413
- this.finished = false;
1414
- this.destroyed = false;
1415
- ahash(hash);
1416
- const key = toBytes2(_key);
1417
- this.iHash = hash.create();
1418
- if (typeof this.iHash.update !== "function")
1419
- throw new Error("Expected instance of class which extends utils.Hash");
1420
- this.blockLen = this.iHash.blockLen;
1421
- this.outputLen = this.iHash.outputLen;
1422
- const blockLen = this.blockLen;
1423
- const pad = new Uint8Array(blockLen);
1424
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1425
- for (let i = 0; i < pad.length; i++)
1426
- pad[i] ^= 54;
1427
- this.iHash.update(pad);
1428
- this.oHash = hash.create();
1429
- for (let i = 0; i < pad.length; i++)
1430
- pad[i] ^= 54 ^ 92;
1431
- this.oHash.update(pad);
1432
- pad.fill(0);
1433
- }
1434
- update(buf) {
1435
- aexists2(this);
1436
- this.iHash.update(buf);
1437
- return this;
1438
- }
1439
- digestInto(out) {
1440
- aexists2(this);
1441
- abytes3(out, this.outputLen);
1442
- this.finished = true;
1443
- this.iHash.digestInto(out);
1444
- this.oHash.update(out);
1445
- this.oHash.digestInto(out);
1446
- this.destroy();
1447
- }
1448
- digest() {
1449
- const out = new Uint8Array(this.oHash.outputLen);
1450
- this.digestInto(out);
1451
- return out;
1452
- }
1453
- _cloneInto(to) {
1454
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
1455
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1456
- to = to;
1457
- to.finished = finished;
1458
- to.destroyed = destroyed;
1459
- to.blockLen = blockLen;
1460
- to.outputLen = outputLen;
1461
- to.oHash = oHash._cloneInto(to.oHash);
1462
- to.iHash = iHash._cloneInto(to.iHash);
1463
- return to;
1464
- }
1465
- destroy() {
1466
- this.destroyed = true;
1467
- this.oHash.destroy();
1468
- this.iHash.destroy();
1469
- }
1470
- };
1471
- var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
1472
- hmac.create = (hash, key) => new HMAC(hash, key);
1473
-
1474
- // ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/utils.js
1475
- var utils_exports = {};
1476
- __export(utils_exports, {
1477
- aInRange: () => aInRange,
1478
- abool: () => abool,
1479
- abytes: () => abytes4,
1480
- bitGet: () => bitGet,
1481
- bitLen: () => bitLen,
1482
- bitMask: () => bitMask,
1483
- bitSet: () => bitSet,
1484
- bytesToHex: () => bytesToHex2,
1485
- bytesToNumberBE: () => bytesToNumberBE,
1486
- bytesToNumberLE: () => bytesToNumberLE2,
1487
- concatBytes: () => concatBytes3,
1488
- createHmacDrbg: () => createHmacDrbg,
1489
- ensureBytes: () => ensureBytes,
1490
- equalBytes: () => equalBytes,
1491
- hexToBytes: () => hexToBytes2,
1492
- hexToNumber: () => hexToNumber,
1493
- inRange: () => inRange,
1494
- isBytes: () => isBytes4,
1495
- memoized: () => memoized,
1496
- notImplemented: () => notImplemented,
1497
- numberToBytesBE: () => numberToBytesBE,
1498
- numberToBytesLE: () => numberToBytesLE,
1499
- numberToHexUnpadded: () => numberToHexUnpadded,
1500
- numberToVarBytesBE: () => numberToVarBytesBE,
1501
- utf8ToBytes: () => utf8ToBytes3,
1502
- validateObject: () => validateObject
1503
- });
1198
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/utils.js
1199
+ var abytes3 = (value, length, title) => abytes2(value, length, title);
1200
+ var anumber2 = anumber;
1201
+ var bytesToHex3 = bytesToHex2;
1202
+ var concatBytes3 = (...arrays) => concatBytes2(...arrays);
1203
+ var hexToBytes3 = (hex) => hexToBytes2(hex);
1204
+ var isBytes3 = isBytes2;
1205
+ var randomBytes3 = (bytesLength) => randomBytes2(bytesLength);
1504
1206
  var _0n = /* @__PURE__ */ BigInt(0);
1505
1207
  var _1n = /* @__PURE__ */ BigInt(1);
1506
- var _2n = /* @__PURE__ */ BigInt(2);
1507
- function isBytes4(a) {
1508
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1509
- }
1510
- function abytes4(item) {
1511
- if (!isBytes4(item))
1512
- throw new Error("Uint8Array expected");
1208
+ function abool(value, title = "") {
1209
+ if (typeof value !== "boolean") {
1210
+ const prefix = title && `"${title}" `;
1211
+ throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
1212
+ }
1213
+ return value;
1513
1214
  }
1514
- function abool(title, value) {
1515
- if (typeof value !== "boolean")
1516
- throw new Error(title + " boolean expected, got " + value);
1215
+ function abignumber(n) {
1216
+ if (typeof n === "bigint") {
1217
+ if (!isPosBig(n))
1218
+ throw new RangeError("positive bigint expected, got " + n);
1219
+ } else
1220
+ anumber2(n);
1221
+ return n;
1517
1222
  }
1518
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
1519
- function bytesToHex2(bytes) {
1520
- abytes4(bytes);
1521
- let hex = "";
1522
- for (let i = 0; i < bytes.length; i++) {
1523
- hex += hexes[bytes[i]];
1223
+ function asafenumber(value, title = "") {
1224
+ if (typeof value !== "number") {
1225
+ const prefix = title && `"${title}" `;
1226
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
1227
+ }
1228
+ if (!Number.isSafeInteger(value)) {
1229
+ const prefix = title && `"${title}" `;
1230
+ throw new RangeError(prefix + "expected safe integer, got " + value);
1524
1231
  }
1525
- return hex;
1526
1232
  }
1527
1233
  function numberToHexUnpadded(num) {
1528
- const hex = num.toString(16);
1234
+ const hex = abignumber(num).toString(16);
1529
1235
  return hex.length & 1 ? "0" + hex : hex;
1530
1236
  }
1531
1237
  function hexToNumber(hex) {
1532
1238
  if (typeof hex !== "string")
1533
- throw new Error("hex string expected, got " + typeof hex);
1239
+ throw new TypeError("hex string expected, got " + typeof hex);
1534
1240
  return hex === "" ? _0n : BigInt("0x" + hex);
1535
1241
  }
1536
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
1537
- function asciiToBase16(ch) {
1538
- if (ch >= asciis._0 && ch <= asciis._9)
1539
- return ch - asciis._0;
1540
- if (ch >= asciis.A && ch <= asciis.F)
1541
- return ch - (asciis.A - 10);
1542
- if (ch >= asciis.a && ch <= asciis.f)
1543
- return ch - (asciis.a - 10);
1544
- return;
1545
- }
1546
- function hexToBytes2(hex) {
1547
- if (typeof hex !== "string")
1548
- throw new Error("hex string expected, got " + typeof hex);
1549
- const hl = hex.length;
1550
- const al = hl / 2;
1551
- if (hl % 2)
1552
- throw new Error("hex string expected, got unpadded hex of length " + hl);
1553
- const array = new Uint8Array(al);
1554
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1555
- const n1 = asciiToBase16(hex.charCodeAt(hi));
1556
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1557
- if (n1 === void 0 || n2 === void 0) {
1558
- const char = hex[hi] + hex[hi + 1];
1559
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1560
- }
1561
- array[ai] = n1 * 16 + n2;
1562
- }
1563
- return array;
1564
- }
1565
1242
  function bytesToNumberBE(bytes) {
1566
1243
  return hexToNumber(bytesToHex2(bytes));
1567
1244
  }
1568
1245
  function bytesToNumberLE2(bytes) {
1569
- abytes4(bytes);
1570
- return hexToNumber(bytesToHex2(Uint8Array.from(bytes).reverse()));
1246
+ return hexToNumber(bytesToHex2(copyBytes(abytes2(bytes)).reverse()));
1571
1247
  }
1572
1248
  function numberToBytesBE(n, len) {
1573
- return hexToBytes2(n.toString(16).padStart(len * 2, "0"));
1249
+ anumber(len);
1250
+ if (len === 0)
1251
+ throw new RangeError("zero length");
1252
+ n = abignumber(n);
1253
+ const hex = n.toString(16);
1254
+ if (hex.length > len * 2)
1255
+ throw new RangeError("number too large");
1256
+ return hexToBytes2(hex.padStart(len * 2, "0"));
1574
1257
  }
1575
1258
  function numberToBytesLE(n, len) {
1576
1259
  return numberToBytesBE(n, len).reverse();
1577
1260
  }
1578
- function numberToVarBytesBE(n) {
1579
- return hexToBytes2(numberToHexUnpadded(n));
1580
- }
1581
- function ensureBytes(title, hex, expectedLength) {
1582
- let res;
1583
- if (typeof hex === "string") {
1584
- try {
1585
- res = hexToBytes2(hex);
1586
- } catch (e) {
1587
- throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
1588
- }
1589
- } else if (isBytes4(hex)) {
1590
- res = Uint8Array.from(hex);
1591
- } else {
1592
- throw new Error(title + " must be hex string or Uint8Array");
1593
- }
1594
- const len = res.length;
1595
- if (typeof expectedLength === "number" && len !== expectedLength)
1596
- throw new Error(title + " of length " + expectedLength + " expected, got " + len);
1597
- return res;
1598
- }
1599
- function concatBytes3(...arrays) {
1600
- let sum = 0;
1601
- for (let i = 0; i < arrays.length; i++) {
1602
- const a = arrays[i];
1603
- abytes4(a);
1604
- sum += a.length;
1605
- }
1606
- const res = new Uint8Array(sum);
1607
- for (let i = 0, pad = 0; i < arrays.length; i++) {
1608
- const a = arrays[i];
1609
- res.set(a, pad);
1610
- pad += a.length;
1611
- }
1612
- return res;
1613
- }
1614
- function equalBytes(a, b) {
1615
- if (a.length !== b.length)
1616
- return false;
1617
- let diff = 0;
1618
- for (let i = 0; i < a.length; i++)
1619
- diff |= a[i] ^ b[i];
1620
- return diff === 0;
1621
- }
1622
- function utf8ToBytes3(str) {
1623
- if (typeof str !== "string")
1624
- throw new Error("string expected");
1625
- return new Uint8Array(new TextEncoder().encode(str));
1261
+ function copyBytes(bytes) {
1262
+ return Uint8Array.from(abytes3(bytes));
1626
1263
  }
1627
1264
  var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
1628
1265
  function inRange(n, min, max) {
@@ -1630,30 +1267,27 @@ function inRange(n, min, max) {
1630
1267
  }
1631
1268
  function aInRange(title, n, min, max) {
1632
1269
  if (!inRange(n, min, max))
1633
- throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1270
+ throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1634
1271
  }
1635
1272
  function bitLen(n) {
1273
+ if (n < _0n)
1274
+ throw new Error("expected non-negative bigint, got " + n);
1636
1275
  let len;
1637
1276
  for (len = 0; n > _0n; n >>= _1n, len += 1)
1638
1277
  ;
1639
1278
  return len;
1640
1279
  }
1641
- function bitGet(n, pos) {
1642
- return n >> BigInt(pos) & _1n;
1643
- }
1644
- function bitSet(n, pos, value) {
1645
- return n | (value ? _1n : _0n) << BigInt(pos);
1646
- }
1647
- var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
1648
- var u8n2 = (data) => new Uint8Array(data);
1649
- var u8fr2 = (arr) => Uint8Array.from(arr);
1280
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
1650
1281
  function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1651
- if (typeof hashLen !== "number" || hashLen < 2)
1652
- throw new Error("hashLen must be a number");
1653
- if (typeof qByteLen !== "number" || qByteLen < 2)
1654
- throw new Error("qByteLen must be a number");
1282
+ anumber(hashLen, "hashLen");
1283
+ anumber(qByteLen, "qByteLen");
1655
1284
  if (typeof hmacFn !== "function")
1656
- throw new Error("hmacFn must be a function");
1285
+ throw new TypeError("hmacFn must be a function");
1286
+ const u8n2 = (len) => new Uint8Array(len);
1287
+ const NULL = Uint8Array.of();
1288
+ const byte0 = Uint8Array.of(0);
1289
+ const byte1 = Uint8Array.of(1);
1290
+ const _maxDrbgIters = 1e3;
1657
1291
  let v = u8n2(hashLen);
1658
1292
  let k = u8n2(hashLen);
1659
1293
  let i = 0;
@@ -1662,18 +1296,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1662
1296
  k.fill(0);
1663
1297
  i = 0;
1664
1298
  };
1665
- const h2 = (...b) => hmacFn(k, v, ...b);
1666
- const reseed = (seed = u8n2()) => {
1667
- k = h2(u8fr2([0]), seed);
1299
+ const h2 = (...msgs) => hmacFn(k, concatBytes3(v, ...msgs));
1300
+ const reseed = (seed = NULL) => {
1301
+ k = h2(byte0, seed);
1668
1302
  v = h2();
1669
1303
  if (seed.length === 0)
1670
1304
  return;
1671
- k = h2(u8fr2([1]), seed);
1305
+ k = h2(byte1, seed);
1672
1306
  v = h2();
1673
1307
  };
1674
1308
  const gen = () => {
1675
- if (i++ >= 1e3)
1676
- throw new Error("drbg: tried 1000 values");
1309
+ if (i++ >= _maxDrbgIters)
1310
+ throw new Error("drbg: tried max amount of iterations");
1677
1311
  let len = 0;
1678
1312
  const out = [];
1679
1313
  while (len < qByteLen) {
@@ -1688,87 +1322,48 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1688
1322
  reset();
1689
1323
  reseed(seed);
1690
1324
  let res = void 0;
1691
- while (!(res = pred(gen())))
1325
+ while ((res = pred(gen())) === void 0)
1692
1326
  reseed();
1693
1327
  reset();
1694
1328
  return res;
1695
1329
  };
1696
1330
  return genUntil;
1697
1331
  }
1698
- var validatorFns = {
1699
- bigint: (val) => typeof val === "bigint",
1700
- function: (val) => typeof val === "function",
1701
- boolean: (val) => typeof val === "boolean",
1702
- string: (val) => typeof val === "string",
1703
- stringOrUint8Array: (val) => typeof val === "string" || isBytes4(val),
1704
- isSafeInteger: (val) => Number.isSafeInteger(val),
1705
- array: (val) => Array.isArray(val),
1706
- field: (val, object) => object.Fp.isValid(val),
1707
- hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
1708
- };
1709
- function validateObject(object, validators, optValidators = {}) {
1710
- const checkField = (fieldName, type, isOptional) => {
1711
- const checkVal = validatorFns[type];
1712
- if (typeof checkVal !== "function")
1713
- throw new Error("invalid validator function");
1332
+ function validateObject(object, fields = {}, optFields = {}) {
1333
+ if (Object.prototype.toString.call(object) !== "[object Object]")
1334
+ throw new TypeError("expected valid options object");
1335
+ function checkField(fieldName, expectedType, isOpt) {
1336
+ if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
1337
+ throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
1714
1338
  const val = object[fieldName];
1715
- if (isOptional && val === void 0)
1339
+ if (isOpt && val === void 0)
1716
1340
  return;
1717
- if (!checkVal(val, object)) {
1718
- throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
1719
- }
1720
- };
1721
- for (const [fieldName, type] of Object.entries(validators))
1722
- checkField(fieldName, type, false);
1723
- for (const [fieldName, type] of Object.entries(optValidators))
1724
- checkField(fieldName, type, true);
1725
- return object;
1726
- }
1727
- var notImplemented = () => {
1728
- throw new Error("not implemented");
1729
- };
1730
- function memoized(fn) {
1731
- const map = /* @__PURE__ */ new WeakMap();
1732
- return (arg, ...args) => {
1733
- const val = map.get(arg);
1734
- if (val !== void 0)
1735
- return val;
1736
- const computed = fn(arg, ...args);
1737
- map.set(arg, computed);
1738
- return computed;
1739
- };
1341
+ const current = typeof val;
1342
+ if (current !== expectedType || val === null)
1343
+ throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
1344
+ }
1345
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
1346
+ iter(fields, false);
1347
+ iter(optFields, true);
1740
1348
  }
1741
1349
 
1742
- // ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/modular.js
1743
- var _0n2 = BigInt(0);
1744
- var _1n2 = BigInt(1);
1745
- var _2n2 = /* @__PURE__ */ BigInt(2);
1350
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/modular.js
1351
+ var _0n2 = /* @__PURE__ */ BigInt(0);
1352
+ var _1n2 = /* @__PURE__ */ BigInt(1);
1353
+ var _2n = /* @__PURE__ */ BigInt(2);
1746
1354
  var _3n = /* @__PURE__ */ BigInt(3);
1747
1355
  var _4n = /* @__PURE__ */ BigInt(4);
1748
1356
  var _5n = /* @__PURE__ */ BigInt(5);
1357
+ var _7n = /* @__PURE__ */ BigInt(7);
1749
1358
  var _8n = /* @__PURE__ */ BigInt(8);
1750
1359
  var _9n = /* @__PURE__ */ BigInt(9);
1751
1360
  var _16n = /* @__PURE__ */ BigInt(16);
1752
1361
  function mod(a, b) {
1362
+ if (b <= _0n2)
1363
+ throw new Error("mod: expected positive modulus, got " + b);
1753
1364
  const result = a % b;
1754
1365
  return result >= _0n2 ? result : b + result;
1755
1366
  }
1756
- function pow(num, power, modulo) {
1757
- if (power < _0n2)
1758
- throw new Error("invalid exponent, negatives unsupported");
1759
- if (modulo <= _0n2)
1760
- throw new Error("invalid modulus");
1761
- if (modulo === _1n2)
1762
- return _0n2;
1763
- let res = _1n2;
1764
- while (power > _0n2) {
1765
- if (power & _1n2)
1766
- res = res * num % modulo;
1767
- num = num * num % modulo;
1768
- power >>= _1n2;
1769
- }
1770
- return res;
1771
- }
1772
1367
  function invert2(number, modulo) {
1773
1368
  if (number === _0n2)
1774
1369
  throw new Error("invert: expected non-zero number");
@@ -1779,7 +1374,7 @@ function invert2(number, modulo) {
1779
1374
  let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
1780
1375
  while (a !== _0n2) {
1781
1376
  const q = b / a;
1782
- const r = b % a;
1377
+ const r = b - a * q;
1783
1378
  const m = x - u * q;
1784
1379
  const n = y - v * q;
1785
1380
  b = a, a = r, x = u, y = v, u = m, v = n;
@@ -1789,75 +1384,109 @@ function invert2(number, modulo) {
1789
1384
  throw new Error("invert: does not exist");
1790
1385
  return mod(x, modulo);
1791
1386
  }
1387
+ function assertIsSquare(Fp, root, n) {
1388
+ const F = Fp;
1389
+ if (!F.eql(F.sqr(root), n))
1390
+ throw new Error("Cannot find square root");
1391
+ }
1392
+ function sqrt3mod4(Fp, n) {
1393
+ const F = Fp;
1394
+ const p1div4 = (F.ORDER + _1n2) / _4n;
1395
+ const root = F.pow(n, p1div4);
1396
+ assertIsSquare(F, root, n);
1397
+ return root;
1398
+ }
1399
+ function sqrt5mod8(Fp, n) {
1400
+ const F = Fp;
1401
+ const p5div8 = (F.ORDER - _5n) / _8n;
1402
+ const n2 = F.mul(n, _2n);
1403
+ const v = F.pow(n2, p5div8);
1404
+ const nv = F.mul(n, v);
1405
+ const i = F.mul(F.mul(nv, _2n), v);
1406
+ const root = F.mul(nv, F.sub(i, F.ONE));
1407
+ assertIsSquare(F, root, n);
1408
+ return root;
1409
+ }
1410
+ function sqrt9mod16(P2) {
1411
+ const Fp_ = Field(P2);
1412
+ const tn = tonelliShanks(P2);
1413
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1414
+ const c2 = tn(Fp_, c1);
1415
+ const c3 = tn(Fp_, Fp_.neg(c1));
1416
+ const c4 = (P2 + _7n) / _16n;
1417
+ return ((Fp, n) => {
1418
+ const F = Fp;
1419
+ let tv1 = F.pow(n, c4);
1420
+ let tv2 = F.mul(tv1, c1);
1421
+ const tv3 = F.mul(tv1, c2);
1422
+ const tv4 = F.mul(tv1, c3);
1423
+ const e1 = F.eql(F.sqr(tv2), n);
1424
+ const e2 = F.eql(F.sqr(tv3), n);
1425
+ tv1 = F.cmov(tv1, tv2, e1);
1426
+ tv2 = F.cmov(tv4, tv3, e2);
1427
+ const e3 = F.eql(F.sqr(tv2), n);
1428
+ const root = F.cmov(tv1, tv2, e3);
1429
+ assertIsSquare(F, root, n);
1430
+ return root;
1431
+ });
1432
+ }
1792
1433
  function tonelliShanks(P2) {
1793
- const legendreC = (P2 - _1n2) / _2n2;
1794
- let Q, S, Z;
1795
- for (Q = P2 - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++)
1796
- ;
1797
- for (Z = _2n2; Z < P2 && pow(Z, legendreC, P2) !== P2 - _1n2; Z++) {
1798
- if (Z > 1e3)
1799
- throw new Error("Cannot find square root: likely non-prime P");
1800
- }
1801
- if (S === 1) {
1802
- const p1div4 = (P2 + _1n2) / _4n;
1803
- return function tonelliFast(Fp, n) {
1804
- const root = Fp.pow(n, p1div4);
1805
- if (!Fp.eql(Fp.sqr(root), n))
1806
- throw new Error("Cannot find square root");
1807
- return root;
1808
- };
1809
- }
1810
- const Q1div2 = (Q + _1n2) / _2n2;
1434
+ if (P2 < _3n)
1435
+ throw new Error("sqrt is not defined for small field");
1436
+ let Q = P2 - _1n2;
1437
+ let S = 0;
1438
+ while (Q % _2n === _0n2) {
1439
+ Q /= _2n;
1440
+ S++;
1441
+ }
1442
+ let Z = _2n;
1443
+ const _Fp = Field(P2);
1444
+ while (FpLegendre(_Fp, Z) === 1) {
1445
+ if (Z++ > 1e3)
1446
+ throw new Error("Cannot find square root: probably non-prime P");
1447
+ }
1448
+ if (S === 1)
1449
+ return sqrt3mod4;
1450
+ let cc = _Fp.pow(Z, Q);
1451
+ const Q1div2 = (Q + _1n2) / _2n;
1811
1452
  return function tonelliSlow(Fp, n) {
1812
- if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
1453
+ const F = Fp;
1454
+ if (F.is0(n))
1455
+ return n;
1456
+ if (FpLegendre(F, n) !== 1)
1813
1457
  throw new Error("Cannot find square root");
1814
- let r = S;
1815
- let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q);
1816
- let x = Fp.pow(n, Q1div2);
1817
- let b = Fp.pow(n, Q);
1818
- while (!Fp.eql(b, Fp.ONE)) {
1819
- if (Fp.eql(b, Fp.ZERO))
1820
- return Fp.ZERO;
1821
- let m = 1;
1822
- for (let t2 = Fp.sqr(b); m < r; m++) {
1823
- if (Fp.eql(t2, Fp.ONE))
1824
- break;
1825
- t2 = Fp.sqr(t2);
1458
+ let M2 = S;
1459
+ let c = F.mul(F.ONE, cc);
1460
+ let t = F.pow(n, Q);
1461
+ let R = F.pow(n, Q1div2);
1462
+ while (!F.eql(t, F.ONE)) {
1463
+ if (F.is0(t))
1464
+ return F.ZERO;
1465
+ let i = 1;
1466
+ let t_tmp = F.sqr(t);
1467
+ while (!F.eql(t_tmp, F.ONE)) {
1468
+ i++;
1469
+ t_tmp = F.sqr(t_tmp);
1470
+ if (i === M2)
1471
+ throw new Error("Cannot find square root");
1826
1472
  }
1827
- const ge = Fp.pow(g, _1n2 << BigInt(r - m - 1));
1828
- g = Fp.sqr(ge);
1829
- x = Fp.mul(x, ge);
1830
- b = Fp.mul(b, g);
1831
- r = m;
1832
- }
1833
- return x;
1473
+ const exponent = _1n2 << BigInt(M2 - i - 1);
1474
+ const b = F.pow(c, exponent);
1475
+ M2 = i;
1476
+ c = F.sqr(b);
1477
+ t = F.mul(t, c);
1478
+ R = F.mul(R, b);
1479
+ }
1480
+ return R;
1834
1481
  };
1835
1482
  }
1836
1483
  function FpSqrt(P2) {
1837
- if (P2 % _4n === _3n) {
1838
- const p1div4 = (P2 + _1n2) / _4n;
1839
- return function sqrt3mod4(Fp, n) {
1840
- const root = Fp.pow(n, p1div4);
1841
- if (!Fp.eql(Fp.sqr(root), n))
1842
- throw new Error("Cannot find square root");
1843
- return root;
1844
- };
1845
- }
1846
- if (P2 % _8n === _5n) {
1847
- const c1 = (P2 - _5n) / _8n;
1848
- return function sqrt5mod8(Fp, n) {
1849
- const n2 = Fp.mul(n, _2n2);
1850
- const v = Fp.pow(n2, c1);
1851
- const nv = Fp.mul(n, v);
1852
- const i = Fp.mul(Fp.mul(nv, _2n2), v);
1853
- const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
1854
- if (!Fp.eql(Fp.sqr(root), n))
1855
- throw new Error("Cannot find square root");
1856
- return root;
1857
- };
1858
- }
1859
- if (P2 % _16n === _9n) {
1860
- }
1484
+ if (P2 % _4n === _3n)
1485
+ return sqrt3mod4;
1486
+ if (P2 % _8n === _5n)
1487
+ return sqrt5mod8;
1488
+ if (P2 % _16n === _9n)
1489
+ return sqrt9mod16(P2);
1861
1490
  return tonelliShanks(P2);
1862
1491
  }
1863
1492
  var FIELD_FIELDS = [
@@ -1882,113 +1511,228 @@ var FIELD_FIELDS = [
1882
1511
  function validateField(field) {
1883
1512
  const initial = {
1884
1513
  ORDER: "bigint",
1885
- MASK: "bigint",
1886
- BYTES: "isSafeInteger",
1887
- BITS: "isSafeInteger"
1514
+ BYTES: "number",
1515
+ BITS: "number"
1888
1516
  };
1889
1517
  const opts = FIELD_FIELDS.reduce((map, val) => {
1890
1518
  map[val] = "function";
1891
1519
  return map;
1892
1520
  }, initial);
1893
- return validateObject(field, opts);
1894
- }
1895
- function FpPow(f, num, power) {
1521
+ validateObject(field, opts);
1522
+ asafenumber(field.BYTES, "BYTES");
1523
+ asafenumber(field.BITS, "BITS");
1524
+ if (field.BYTES < 1 || field.BITS < 1)
1525
+ throw new Error("invalid field: expected BYTES/BITS > 0");
1526
+ if (field.ORDER <= _1n2)
1527
+ throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
1528
+ return field;
1529
+ }
1530
+ function FpPow(Fp, num, power) {
1531
+ const F = Fp;
1896
1532
  if (power < _0n2)
1897
1533
  throw new Error("invalid exponent, negatives unsupported");
1898
1534
  if (power === _0n2)
1899
- return f.ONE;
1535
+ return F.ONE;
1900
1536
  if (power === _1n2)
1901
1537
  return num;
1902
- let p = f.ONE;
1538
+ let p = F.ONE;
1903
1539
  let d = num;
1904
1540
  while (power > _0n2) {
1905
1541
  if (power & _1n2)
1906
- p = f.mul(p, d);
1907
- d = f.sqr(d);
1542
+ p = F.mul(p, d);
1543
+ d = F.sqr(d);
1908
1544
  power >>= _1n2;
1909
1545
  }
1910
1546
  return p;
1911
1547
  }
1912
- function FpInvertBatch(f, nums) {
1913
- const tmp = new Array(nums.length);
1914
- const lastMultiplied = nums.reduce((acc, num, i) => {
1915
- if (f.is0(num))
1548
+ function FpInvertBatch(Fp, nums, passZero = false) {
1549
+ const F = Fp;
1550
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
1551
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1552
+ if (F.is0(num))
1916
1553
  return acc;
1917
- tmp[i] = acc;
1918
- return f.mul(acc, num);
1919
- }, f.ONE);
1920
- const inverted = f.inv(lastMultiplied);
1554
+ inverted[i] = acc;
1555
+ return F.mul(acc, num);
1556
+ }, F.ONE);
1557
+ const invertedAcc = F.inv(multipliedAcc);
1921
1558
  nums.reduceRight((acc, num, i) => {
1922
- if (f.is0(num))
1559
+ if (F.is0(num))
1923
1560
  return acc;
1924
- tmp[i] = f.mul(acc, tmp[i]);
1925
- return f.mul(acc, num);
1926
- }, inverted);
1927
- return tmp;
1561
+ inverted[i] = F.mul(acc, inverted[i]);
1562
+ return F.mul(acc, num);
1563
+ }, invertedAcc);
1564
+ return inverted;
1565
+ }
1566
+ function FpLegendre(Fp, n) {
1567
+ const F = Fp;
1568
+ const p1mod2 = (F.ORDER - _1n2) / _2n;
1569
+ const powered = F.pow(n, p1mod2);
1570
+ const yes = F.eql(powered, F.ONE);
1571
+ const zero = F.eql(powered, F.ZERO);
1572
+ const no = F.eql(powered, F.neg(F.ONE));
1573
+ if (!yes && !zero && !no)
1574
+ throw new Error("invalid Legendre symbol result");
1575
+ return yes ? 1 : zero ? 0 : -1;
1928
1576
  }
1929
1577
  function nLength(n, nBitLength) {
1930
- const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
1578
+ if (nBitLength !== void 0)
1579
+ anumber2(nBitLength);
1580
+ if (n <= _0n2)
1581
+ throw new Error("invalid n length: expected positive n, got " + n);
1582
+ if (nBitLength !== void 0 && nBitLength < 1)
1583
+ throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
1584
+ const bits = bitLen(n);
1585
+ if (nBitLength !== void 0 && nBitLength < bits)
1586
+ throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
1587
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
1931
1588
  const nByteLength = Math.ceil(_nBitLength / 8);
1932
1589
  return { nBitLength: _nBitLength, nByteLength };
1933
1590
  }
1934
- function Field(ORDER, bitLen2, isLE = false, redef = {}) {
1935
- if (ORDER <= _0n2)
1936
- throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
1937
- const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
1938
- if (BYTES > 2048)
1939
- throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1940
- let sqrtP;
1941
- const f = Object.freeze({
1942
- ORDER,
1943
- BITS,
1944
- BYTES,
1945
- MASK: bitMask(BITS),
1946
- ZERO: _0n2,
1947
- ONE: _1n2,
1948
- create: (num) => mod(num, ORDER),
1949
- isValid: (num) => {
1950
- if (typeof num !== "bigint")
1951
- throw new Error("invalid field element: expected bigint, got " + typeof num);
1952
- return _0n2 <= num && num < ORDER;
1953
- },
1954
- is0: (num) => num === _0n2,
1955
- isOdd: (num) => (num & _1n2) === _1n2,
1956
- neg: (num) => mod(-num, ORDER),
1957
- eql: (lhs, rhs) => lhs === rhs,
1958
- sqr: (num) => mod(num * num, ORDER),
1959
- add: (lhs, rhs) => mod(lhs + rhs, ORDER),
1960
- sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
1961
- mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
1962
- pow: (num, power) => FpPow(f, num, power),
1963
- div: (lhs, rhs) => mod(lhs * invert2(rhs, ORDER), ORDER),
1964
- // Same as above, but doesn't normalize
1965
- sqrN: (num) => num * num,
1966
- addN: (lhs, rhs) => lhs + rhs,
1967
- subN: (lhs, rhs) => lhs - rhs,
1968
- mulN: (lhs, rhs) => lhs * rhs,
1969
- inv: (num) => invert2(num, ORDER),
1970
- sqrt: redef.sqrt || ((n) => {
1971
- if (!sqrtP)
1972
- sqrtP = FpSqrt(ORDER);
1973
- return sqrtP(f, n);
1974
- }),
1975
- invertBatch: (lst) => FpInvertBatch(f, lst),
1976
- // TODO: do we really need constant cmov?
1977
- // We don't have const-time bigints anyway, so probably will be not very useful
1978
- cmov: (a, b, c) => c ? b : a,
1979
- toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
1980
- fromBytes: (bytes) => {
1981
- if (bytes.length !== BYTES)
1982
- throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1983
- return isLE ? bytesToNumberLE2(bytes) : bytesToNumberBE(bytes);
1984
- }
1985
- });
1986
- return Object.freeze(f);
1591
+ var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
1592
+ var _Field = class {
1593
+ ORDER;
1594
+ BITS;
1595
+ BYTES;
1596
+ isLE;
1597
+ ZERO = _0n2;
1598
+ ONE = _1n2;
1599
+ _lengths;
1600
+ _mod;
1601
+ constructor(ORDER, opts = {}) {
1602
+ if (ORDER <= _1n2)
1603
+ throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
1604
+ let _nbitLength = void 0;
1605
+ this.isLE = false;
1606
+ if (opts != null && typeof opts === "object") {
1607
+ if (typeof opts.BITS === "number")
1608
+ _nbitLength = opts.BITS;
1609
+ if (typeof opts.sqrt === "function")
1610
+ Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
1611
+ if (typeof opts.isLE === "boolean")
1612
+ this.isLE = opts.isLE;
1613
+ if (opts.allowedLengths)
1614
+ this._lengths = Object.freeze(opts.allowedLengths.slice());
1615
+ if (typeof opts.modFromBytes === "boolean")
1616
+ this._mod = opts.modFromBytes;
1617
+ }
1618
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
1619
+ if (nByteLength > 2048)
1620
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1621
+ this.ORDER = ORDER;
1622
+ this.BITS = nBitLength;
1623
+ this.BYTES = nByteLength;
1624
+ Object.freeze(this);
1625
+ }
1626
+ create(num) {
1627
+ return mod(num, this.ORDER);
1628
+ }
1629
+ isValid(num) {
1630
+ if (typeof num !== "bigint")
1631
+ throw new TypeError("invalid field element: expected bigint, got " + typeof num);
1632
+ return _0n2 <= num && num < this.ORDER;
1633
+ }
1634
+ is0(num) {
1635
+ return num === _0n2;
1636
+ }
1637
+ // is valid and invertible
1638
+ isValidNot0(num) {
1639
+ return !this.is0(num) && this.isValid(num);
1640
+ }
1641
+ isOdd(num) {
1642
+ return (num & _1n2) === _1n2;
1643
+ }
1644
+ neg(num) {
1645
+ return mod(-num, this.ORDER);
1646
+ }
1647
+ eql(lhs, rhs) {
1648
+ return lhs === rhs;
1649
+ }
1650
+ sqr(num) {
1651
+ return mod(num * num, this.ORDER);
1652
+ }
1653
+ add(lhs, rhs) {
1654
+ return mod(lhs + rhs, this.ORDER);
1655
+ }
1656
+ sub(lhs, rhs) {
1657
+ return mod(lhs - rhs, this.ORDER);
1658
+ }
1659
+ mul(lhs, rhs) {
1660
+ return mod(lhs * rhs, this.ORDER);
1661
+ }
1662
+ pow(num, power) {
1663
+ return FpPow(this, num, power);
1664
+ }
1665
+ div(lhs, rhs) {
1666
+ return mod(lhs * invert2(rhs, this.ORDER), this.ORDER);
1667
+ }
1668
+ // Same as above, but doesn't normalize
1669
+ sqrN(num) {
1670
+ return num * num;
1671
+ }
1672
+ addN(lhs, rhs) {
1673
+ return lhs + rhs;
1674
+ }
1675
+ subN(lhs, rhs) {
1676
+ return lhs - rhs;
1677
+ }
1678
+ mulN(lhs, rhs) {
1679
+ return lhs * rhs;
1680
+ }
1681
+ inv(num) {
1682
+ return invert2(num, this.ORDER);
1683
+ }
1684
+ sqrt(num) {
1685
+ let sqrt = FIELD_SQRT.get(this);
1686
+ if (!sqrt)
1687
+ FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
1688
+ return sqrt(this, num);
1689
+ }
1690
+ toBytes(num) {
1691
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1692
+ }
1693
+ fromBytes(bytes, skipValidation = false) {
1694
+ abytes3(bytes);
1695
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
1696
+ if (allowedLengths) {
1697
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1698
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1699
+ }
1700
+ const padded = new Uint8Array(BYTES);
1701
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
1702
+ bytes = padded;
1703
+ }
1704
+ if (bytes.length !== BYTES)
1705
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1706
+ let scalar = isLE ? bytesToNumberLE2(bytes) : bytesToNumberBE(bytes);
1707
+ if (modFromBytes)
1708
+ scalar = mod(scalar, ORDER);
1709
+ if (!skipValidation) {
1710
+ if (!this.isValid(scalar))
1711
+ throw new Error("invalid field element: outside of range 0..ORDER");
1712
+ }
1713
+ return scalar;
1714
+ }
1715
+ // TODO: we don't need it here, move out to separate fn
1716
+ invertBatch(lst) {
1717
+ return FpInvertBatch(this, lst);
1718
+ }
1719
+ // We can't move this out because Fp6, Fp12 implement it
1720
+ // and it's unclear what to return in there.
1721
+ cmov(a, b, condition) {
1722
+ abool(condition, "condition");
1723
+ return condition ? b : a;
1724
+ }
1725
+ };
1726
+ Object.freeze(_Field.prototype);
1727
+ function Field(ORDER, opts = {}) {
1728
+ return new _Field(ORDER, opts);
1987
1729
  }
1988
1730
  function getFieldBytesLength(fieldOrder) {
1989
1731
  if (typeof fieldOrder !== "bigint")
1990
1732
  throw new Error("field order must be bigint");
1991
- const bitLength = fieldOrder.toString(2).length;
1733
+ if (fieldOrder <= _1n2)
1734
+ throw new Error("field order must be greater than 1");
1735
+ const bitLength = bitLen(fieldOrder - _1n2);
1992
1736
  return Math.ceil(bitLength / 8);
1993
1737
  }
1994
1738
  function getMinHashLength(fieldOrder) {
@@ -1996,289 +1740,382 @@ function getMinHashLength(fieldOrder) {
1996
1740
  return length + Math.ceil(length / 2);
1997
1741
  }
1998
1742
  function mapHashToField(key, fieldOrder, isLE = false) {
1743
+ abytes3(key);
1999
1744
  const len = key.length;
2000
1745
  const fieldLen = getFieldBytesLength(fieldOrder);
2001
- const minLen = getMinHashLength(fieldOrder);
2002
- if (len < 16 || len < minLen || len > 1024)
1746
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
1747
+ if (len < minLen || len > 1024)
2003
1748
  throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
2004
- const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE2(key);
1749
+ const num = isLE ? bytesToNumberLE2(key) : bytesToNumberBE(key);
2005
1750
  const reduced = mod(num, fieldOrder - _1n2) + _1n2;
2006
1751
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
2007
1752
  }
2008
1753
 
2009
- // ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/curve.js
2010
- var _0n3 = BigInt(0);
2011
- var _1n3 = BigInt(1);
2012
- function constTimeNegate(condition, item) {
1754
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/curve.js
1755
+ var _0n3 = /* @__PURE__ */ BigInt(0);
1756
+ var _1n3 = /* @__PURE__ */ BigInt(1);
1757
+ function negateCt(condition, item) {
2013
1758
  const neg = item.negate();
2014
1759
  return condition ? neg : item;
2015
1760
  }
1761
+ function normalizeZ(c, points) {
1762
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1763
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1764
+ }
2016
1765
  function validateW(W2, bits) {
2017
1766
  if (!Number.isSafeInteger(W2) || W2 <= 0 || W2 > bits)
2018
1767
  throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W2);
2019
1768
  }
2020
- function calcWOpts(W2, bits) {
2021
- validateW(W2, bits);
2022
- const windows = Math.ceil(bits / W2) + 1;
1769
+ function calcWOpts(W2, scalarBits2) {
1770
+ validateW(W2, scalarBits2);
1771
+ const windows = Math.ceil(scalarBits2 / W2) + 1;
2023
1772
  const windowSize = 2 ** (W2 - 1);
2024
- return { windows, windowSize };
2025
- }
2026
- function validateMSMPoints(points, c) {
2027
- if (!Array.isArray(points))
2028
- throw new Error("array expected");
2029
- points.forEach((p, i) => {
2030
- if (!(p instanceof c))
2031
- throw new Error("invalid point at index " + i);
2032
- });
2033
- }
2034
- function validateMSMScalars(scalars, field) {
2035
- if (!Array.isArray(scalars))
2036
- throw new Error("array of scalars expected");
2037
- scalars.forEach((s, i) => {
2038
- if (!field.isValid(s))
2039
- throw new Error("invalid scalar at index " + i);
2040
- });
1773
+ const maxNumber = 2 ** W2;
1774
+ const mask = bitMask(W2);
1775
+ const shiftBy = BigInt(W2);
1776
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1777
+ }
1778
+ function calcOffsets(n, window, wOpts) {
1779
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1780
+ let wbits = Number(n & mask);
1781
+ let nextN = n >> shiftBy;
1782
+ if (wbits > windowSize) {
1783
+ wbits -= maxNumber;
1784
+ nextN += _1n3;
1785
+ }
1786
+ const offsetStart = window * windowSize;
1787
+ const offset = offsetStart + Math.abs(wbits) - 1;
1788
+ const isZero = wbits === 0;
1789
+ const isNeg = wbits < 0;
1790
+ const isNegF = window % 2 !== 0;
1791
+ const offsetF = offsetStart;
1792
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
2041
1793
  }
2042
1794
  var pointPrecomputes = /* @__PURE__ */ new WeakMap();
2043
1795
  var pointWindowSizes = /* @__PURE__ */ new WeakMap();
2044
1796
  function getW(P2) {
2045
1797
  return pointWindowSizes.get(P2) || 1;
2046
1798
  }
2047
- function wNAF2(c, bits) {
2048
- return {
2049
- constTimeNegate,
2050
- hasPrecomputes(elm) {
2051
- return getW(elm) !== 1;
2052
- },
2053
- // non-const time multiplication ladder
2054
- unsafeLadder(elm, n, p = c.ZERO) {
2055
- let d = elm;
2056
- while (n > _0n3) {
2057
- if (n & _1n3)
2058
- p = p.add(d);
2059
- d = d.double();
2060
- n >>= _1n3;
2061
- }
2062
- return p;
2063
- },
2064
- /**
2065
- * Creates a wNAF precomputation window. Used for caching.
2066
- * Default window size is set by `utils.precompute()` and is equal to 8.
2067
- * Number of precomputed points depends on the curve size:
2068
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
2069
- * - 𝑊 is the window size
2070
- * - 𝑛 is the bitlength of the curve order.
2071
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
2072
- * @param elm Point instance
2073
- * @param W window size
2074
- * @returns precomputed point tables flattened to a single array
2075
- */
2076
- precomputeWindow(elm, W2) {
2077
- const { windows, windowSize } = calcWOpts(W2, bits);
2078
- const points = [];
2079
- let p = elm;
2080
- let base = p;
2081
- for (let window = 0; window < windows; window++) {
2082
- base = p;
1799
+ function assert0(n) {
1800
+ if (n !== _0n3)
1801
+ throw new Error("invalid wNAF");
1802
+ }
1803
+ var wNAF2 = class {
1804
+ BASE;
1805
+ ZERO;
1806
+ Fn;
1807
+ bits;
1808
+ // Parametrized with a given Point class (not individual point)
1809
+ constructor(Point2, bits) {
1810
+ this.BASE = Point2.BASE;
1811
+ this.ZERO = Point2.ZERO;
1812
+ this.Fn = Point2.Fn;
1813
+ this.bits = bits;
1814
+ }
1815
+ // non-const time multiplication ladder
1816
+ _unsafeLadder(elm, n, p = this.ZERO) {
1817
+ let d = elm;
1818
+ while (n > _0n3) {
1819
+ if (n & _1n3)
1820
+ p = p.add(d);
1821
+ d = d.double();
1822
+ n >>= _1n3;
1823
+ }
1824
+ return p;
1825
+ }
1826
+ /**
1827
+ * Creates a wNAF precomputation window. Used for caching.
1828
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1829
+ * Number of precomputed points depends on the curve size:
1830
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1831
+ * - 𝑊 is the window size
1832
+ * - 𝑛 is the bitlength of the curve order.
1833
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1834
+ * @param point - Point instance
1835
+ * @param W - window size
1836
+ * @returns precomputed point tables flattened to a single array
1837
+ */
1838
+ precomputeWindow(point, W2) {
1839
+ const { windows, windowSize } = calcWOpts(W2, this.bits);
1840
+ const points = [];
1841
+ let p = point;
1842
+ let base = p;
1843
+ for (let window = 0; window < windows; window++) {
1844
+ base = p;
1845
+ points.push(base);
1846
+ for (let i = 1; i < windowSize; i++) {
1847
+ base = base.add(p);
2083
1848
  points.push(base);
2084
- for (let i = 1; i < windowSize; i++) {
2085
- base = base.add(p);
2086
- points.push(base);
2087
- }
2088
- p = base.double();
2089
- }
2090
- return points;
2091
- },
2092
- /**
2093
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
2094
- * @param W window size
2095
- * @param precomputes precomputed tables
2096
- * @param n scalar (we don't check here, but should be less than curve order)
2097
- * @returns real and fake (for const-time) points
2098
- */
2099
- wNAF(W2, precomputes, n) {
2100
- const { windows, windowSize } = calcWOpts(W2, bits);
2101
- let p = c.ZERO;
2102
- let f = c.BASE;
2103
- const mask = BigInt(2 ** W2 - 1);
2104
- const maxNumber = 2 ** W2;
2105
- const shiftBy = BigInt(W2);
2106
- for (let window = 0; window < windows; window++) {
2107
- const offset = window * windowSize;
2108
- let wbits = Number(n & mask);
2109
- n >>= shiftBy;
2110
- if (wbits > windowSize) {
2111
- wbits -= maxNumber;
2112
- n += _1n3;
2113
- }
2114
- const offset1 = offset;
2115
- const offset2 = offset + Math.abs(wbits) - 1;
2116
- const cond1 = window % 2 !== 0;
2117
- const cond2 = wbits < 0;
2118
- if (wbits === 0) {
2119
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
2120
- } else {
2121
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
2122
- }
2123
1849
  }
2124
- return { p, f };
2125
- },
2126
- /**
2127
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
2128
- * @param W window size
2129
- * @param precomputes precomputed tables
2130
- * @param n scalar (we don't check here, but should be less than curve order)
2131
- * @param acc accumulator point to add result of multiplication
2132
- * @returns point
2133
- */
2134
- wNAFUnsafe(W2, precomputes, n, acc = c.ZERO) {
2135
- const { windows, windowSize } = calcWOpts(W2, bits);
2136
- const mask = BigInt(2 ** W2 - 1);
2137
- const maxNumber = 2 ** W2;
2138
- const shiftBy = BigInt(W2);
2139
- for (let window = 0; window < windows; window++) {
2140
- const offset = window * windowSize;
2141
- if (n === _0n3)
2142
- break;
2143
- let wbits = Number(n & mask);
2144
- n >>= shiftBy;
2145
- if (wbits > windowSize) {
2146
- wbits -= maxNumber;
2147
- n += _1n3;
2148
- }
2149
- if (wbits === 0)
2150
- continue;
2151
- let curr = precomputes[offset + Math.abs(wbits) - 1];
2152
- if (wbits < 0)
2153
- curr = curr.negate();
2154
- acc = acc.add(curr);
1850
+ p = base.double();
1851
+ }
1852
+ return points;
1853
+ }
1854
+ /**
1855
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1856
+ * More compact implementation:
1857
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1858
+ * @returns real and fake (for const-time) points
1859
+ */
1860
+ wNAF(W2, precomputes, n) {
1861
+ if (!this.Fn.isValid(n))
1862
+ throw new Error("invalid scalar");
1863
+ let p = this.ZERO;
1864
+ let f = this.BASE;
1865
+ const wo = calcWOpts(W2, this.bits);
1866
+ for (let window = 0; window < wo.windows; window++) {
1867
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1868
+ n = nextN;
1869
+ if (isZero) {
1870
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
1871
+ } else {
1872
+ p = p.add(negateCt(isNeg, precomputes[offset]));
2155
1873
  }
2156
- return acc;
2157
- },
2158
- getPrecomputes(W2, P2, transform) {
2159
- let comp = pointPrecomputes.get(P2);
2160
- if (!comp) {
2161
- comp = this.precomputeWindow(P2, W2);
2162
- if (W2 !== 1)
2163
- pointPrecomputes.set(P2, transform(comp));
1874
+ }
1875
+ assert0(n);
1876
+ return { p, f };
1877
+ }
1878
+ /**
1879
+ * Implements unsafe EC multiplication using precomputed tables
1880
+ * and w-ary non-adjacent form.
1881
+ * @param acc - accumulator point to add result of multiplication
1882
+ * @returns point
1883
+ */
1884
+ wNAFUnsafe(W2, precomputes, n, acc = this.ZERO) {
1885
+ const wo = calcWOpts(W2, this.bits);
1886
+ for (let window = 0; window < wo.windows; window++) {
1887
+ if (n === _0n3)
1888
+ break;
1889
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1890
+ n = nextN;
1891
+ if (isZero) {
1892
+ continue;
1893
+ } else {
1894
+ const item = precomputes[offset];
1895
+ acc = acc.add(isNeg ? item.negate() : item);
2164
1896
  }
2165
- return comp;
2166
- },
2167
- wNAFCached(P2, n, transform) {
2168
- const W2 = getW(P2);
2169
- return this.wNAF(W2, this.getPrecomputes(W2, P2, transform), n);
2170
- },
2171
- wNAFCachedUnsafe(P2, n, transform, prev) {
2172
- const W2 = getW(P2);
2173
- if (W2 === 1)
2174
- return this.unsafeLadder(P2, n, prev);
2175
- return this.wNAFUnsafe(W2, this.getPrecomputes(W2, P2, transform), n, prev);
2176
- },
2177
- // We calculate precomputes for elliptic curve point multiplication
2178
- // using windowed method. This specifies window size and
2179
- // stores precomputed values. Usually only base point would be precomputed.
2180
- setWindowSize(P2, W2) {
2181
- validateW(W2, bits);
2182
- pointWindowSizes.set(P2, W2);
2183
- pointPrecomputes.delete(P2);
2184
1897
  }
1898
+ assert0(n);
1899
+ return acc;
1900
+ }
1901
+ getPrecomputes(W2, point, transform) {
1902
+ let comp = pointPrecomputes.get(point);
1903
+ if (!comp) {
1904
+ comp = this.precomputeWindow(point, W2);
1905
+ if (W2 !== 1) {
1906
+ if (typeof transform === "function")
1907
+ comp = transform(comp);
1908
+ pointPrecomputes.set(point, comp);
1909
+ }
1910
+ }
1911
+ return comp;
1912
+ }
1913
+ cached(point, scalar, transform) {
1914
+ const W2 = getW(point);
1915
+ return this.wNAF(W2, this.getPrecomputes(W2, point, transform), scalar);
1916
+ }
1917
+ unsafe(point, scalar, transform, prev) {
1918
+ const W2 = getW(point);
1919
+ if (W2 === 1)
1920
+ return this._unsafeLadder(point, scalar, prev);
1921
+ return this.wNAFUnsafe(W2, this.getPrecomputes(W2, point, transform), scalar, prev);
1922
+ }
1923
+ // We calculate precomputes for elliptic curve point multiplication
1924
+ // using windowed method. This specifies window size and
1925
+ // stores precomputed values. Usually only base point would be precomputed.
1926
+ createCache(P2, W2) {
1927
+ validateW(W2, this.bits);
1928
+ pointWindowSizes.set(P2, W2);
1929
+ pointPrecomputes.delete(P2);
1930
+ }
1931
+ hasCache(elm) {
1932
+ return getW(elm) !== 1;
1933
+ }
1934
+ };
1935
+ function mulEndoUnsafe(Point2, point, k1, k2) {
1936
+ let acc = point;
1937
+ let p1 = Point2.ZERO;
1938
+ let p2 = Point2.ZERO;
1939
+ while (k1 > _0n3 || k2 > _0n3) {
1940
+ if (k1 & _1n3)
1941
+ p1 = p1.add(acc);
1942
+ if (k2 & _1n3)
1943
+ p2 = p2.add(acc);
1944
+ acc = acc.double();
1945
+ k1 >>= _1n3;
1946
+ k2 >>= _1n3;
1947
+ }
1948
+ return { p1, p2 };
1949
+ }
1950
+ function createField(order, field, isLE) {
1951
+ if (field) {
1952
+ if (field.ORDER !== order)
1953
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1954
+ validateField(field);
1955
+ return field;
1956
+ } else {
1957
+ return Field(order, { isLE });
1958
+ }
1959
+ }
1960
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1961
+ if (FpFnLE === void 0)
1962
+ FpFnLE = type === "edwards";
1963
+ if (!CURVE || typeof CURVE !== "object")
1964
+ throw new Error(`expected valid ${type} CURVE object`);
1965
+ for (const p of ["p", "n", "h"]) {
1966
+ const val = CURVE[p];
1967
+ if (!(typeof val === "bigint" && val > _0n3))
1968
+ throw new Error(`CURVE.${p} must be positive bigint`);
1969
+ }
1970
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1971
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1972
+ const _b = type === "weierstrass" ? "b" : "d";
1973
+ const params = ["Gx", "Gy", "a", _b];
1974
+ for (const p of params) {
1975
+ if (!Fp.isValid(CURVE[p]))
1976
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1977
+ }
1978
+ CURVE = Object.freeze(Object.assign({}, CURVE));
1979
+ return { CURVE, Fp, Fn };
1980
+ }
1981
+ function createKeygen(randomSecretKey2, getPublicKey) {
1982
+ return function keygen(seed) {
1983
+ const secretKey = randomSecretKey2(seed);
1984
+ return { secretKey, publicKey: getPublicKey(secretKey) };
2185
1985
  };
2186
1986
  }
2187
- function pippenger(c, fieldN, points, scalars) {
2188
- validateMSMPoints(points, c);
2189
- validateMSMScalars(scalars, fieldN);
2190
- if (points.length !== scalars.length)
2191
- throw new Error("arrays of points and scalars must have equal length");
2192
- const zero = c.ZERO;
2193
- const wbits = bitLen(BigInt(points.length));
2194
- const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1;
2195
- const MASK = (1 << windowSize) - 1;
2196
- const buckets = new Array(MASK + 1).fill(zero);
2197
- const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
2198
- let sum = zero;
2199
- for (let i = lastBits; i >= 0; i -= windowSize) {
2200
- buckets.fill(zero);
2201
- for (let j = 0; j < scalars.length; j++) {
2202
- const scalar = scalars[j];
2203
- const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK));
2204
- buckets[wbits2] = buckets[wbits2].add(points[j]);
2205
- }
2206
- let resI = zero;
2207
- for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
2208
- sumI = sumI.add(buckets[j]);
2209
- resI = resI.add(sumI);
2210
- }
2211
- sum = sum.add(resI);
2212
- if (i !== 0)
2213
- for (let j = 0; j < windowSize; j++)
2214
- sum = sum.double();
2215
- }
2216
- return sum;
2217
- }
2218
- function validateBasic(curve) {
2219
- validateField(curve.Fp);
2220
- validateObject(curve, {
2221
- n: "bigint",
2222
- h: "bigint",
2223
- Gx: "field",
2224
- Gy: "field"
2225
- }, {
2226
- nBitLength: "isSafeInteger",
2227
- nByteLength: "isSafeInteger"
2228
- });
2229
- return Object.freeze({
2230
- ...nLength(curve.n, curve.nBitLength),
2231
- ...curve,
2232
- ...{ p: curve.Fp.ORDER }
2233
- });
2234
- }
2235
1987
 
2236
- // ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/weierstrass.js
2237
- function validateSigVerOpts(opts) {
2238
- if (opts.lowS !== void 0)
2239
- abool("lowS", opts.lowS);
2240
- if (opts.prehash !== void 0)
2241
- abool("prehash", opts.prehash);
2242
- }
2243
- function validatePointOpts(curve) {
2244
- const opts = validateBasic(curve);
2245
- validateObject(opts, {
2246
- a: "field",
2247
- b: "field"
2248
- }, {
2249
- allowedPrivateKeyLengths: "array",
2250
- wrapPrivateKey: "boolean",
2251
- isTorsionFree: "function",
2252
- clearCofactor: "function",
2253
- allowInfinityPoint: "boolean",
2254
- fromBytes: "function",
2255
- toBytes: "function"
2256
- });
2257
- const { endo, Fp, a } = opts;
2258
- if (endo) {
2259
- if (!Fp.eql(a, Fp.ZERO)) {
2260
- throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");
2261
- }
2262
- if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
2263
- throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function");
2264
- }
1988
+ // ../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js
1989
+ var _HMAC = class {
1990
+ oHash;
1991
+ iHash;
1992
+ blockLen;
1993
+ outputLen;
1994
+ canXOF = false;
1995
+ finished = false;
1996
+ destroyed = false;
1997
+ constructor(hash, key) {
1998
+ ahash(hash);
1999
+ abytes2(key, void 0, "key");
2000
+ this.iHash = hash.create();
2001
+ if (typeof this.iHash.update !== "function")
2002
+ throw new Error("Expected instance of class which extends utils.Hash");
2003
+ this.blockLen = this.iHash.blockLen;
2004
+ this.outputLen = this.iHash.outputLen;
2005
+ const blockLen = this.blockLen;
2006
+ const pad = new Uint8Array(blockLen);
2007
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2008
+ for (let i = 0; i < pad.length; i++)
2009
+ pad[i] ^= 54;
2010
+ this.iHash.update(pad);
2011
+ this.oHash = hash.create();
2012
+ for (let i = 0; i < pad.length; i++)
2013
+ pad[i] ^= 54 ^ 92;
2014
+ this.oHash.update(pad);
2015
+ clean(pad);
2265
2016
  }
2266
- return Object.freeze({ ...opts });
2267
- }
2268
- var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports;
2017
+ update(buf) {
2018
+ aexists(this);
2019
+ this.iHash.update(buf);
2020
+ return this;
2021
+ }
2022
+ digestInto(out) {
2023
+ aexists(this);
2024
+ aoutput(out, this);
2025
+ this.finished = true;
2026
+ const buf = out.subarray(0, this.outputLen);
2027
+ this.iHash.digestInto(buf);
2028
+ this.oHash.update(buf);
2029
+ this.oHash.digestInto(buf);
2030
+ this.destroy();
2031
+ }
2032
+ digest() {
2033
+ const out = new Uint8Array(this.oHash.outputLen);
2034
+ this.digestInto(out);
2035
+ return out;
2036
+ }
2037
+ _cloneInto(to) {
2038
+ to ||= Object.create(Object.getPrototypeOf(this), {});
2039
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
2040
+ to = to;
2041
+ to.finished = finished;
2042
+ to.destroyed = destroyed;
2043
+ to.blockLen = blockLen;
2044
+ to.outputLen = outputLen;
2045
+ to.oHash = oHash._cloneInto(to.oHash);
2046
+ to.iHash = iHash._cloneInto(to.iHash);
2047
+ return to;
2048
+ }
2049
+ clone() {
2050
+ return this._cloneInto();
2051
+ }
2052
+ destroy() {
2053
+ this.destroyed = true;
2054
+ this.oHash.destroy();
2055
+ this.iHash.destroy();
2056
+ }
2057
+ };
2058
+ var hmac = /* @__PURE__ */ (() => {
2059
+ const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
2060
+ hmac_.create = (hash, key) => new _HMAC(hash, key);
2061
+ return hmac_;
2062
+ })();
2063
+
2064
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/weierstrass.js
2065
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
2066
+ function _splitEndoScalar(k, basis, n) {
2067
+ aInRange("scalar", k, _0n4, n);
2068
+ const [[a1, b1], [a2, b2]] = basis;
2069
+ const c1 = divNearest(b2 * k, n);
2070
+ const c2 = divNearest(-b1 * k, n);
2071
+ let k1 = k - c1 * a1 - c2 * a2;
2072
+ let k2 = -c1 * b1 - c2 * b2;
2073
+ const k1neg = k1 < _0n4;
2074
+ const k2neg = k2 < _0n4;
2075
+ if (k1neg)
2076
+ k1 = -k1;
2077
+ if (k2neg)
2078
+ k2 = -k2;
2079
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
2080
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
2081
+ throw new Error("splitScalar (endomorphism): failed for k");
2082
+ }
2083
+ return { k1neg, k1, k2neg, k2 };
2084
+ }
2085
+ function validateSigFormat(format) {
2086
+ if (!["compact", "recovered", "der"].includes(format))
2087
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
2088
+ return format;
2089
+ }
2090
+ function validateSigOpts(opts, def) {
2091
+ validateObject(opts);
2092
+ const optsn = {};
2093
+ for (let optName of Object.keys(def)) {
2094
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
2095
+ }
2096
+ abool(optsn.lowS, "lowS");
2097
+ abool(optsn.prehash, "prehash");
2098
+ if (optsn.format !== void 0)
2099
+ validateSigFormat(optsn.format);
2100
+ return optsn;
2101
+ }
2102
+ var DERErr = class extends Error {
2103
+ constructor(m = "") {
2104
+ super(m);
2105
+ }
2106
+ };
2269
2107
  var DER = {
2270
2108
  // asn.1 DER encoding utils
2271
- Err: class DERErr extends Error {
2272
- constructor(m = "") {
2273
- super(m);
2274
- }
2275
- },
2109
+ Err: DERErr,
2276
2110
  // Basic building block is TLV (Tag-Length-Value)
2277
2111
  _tlv: {
2278
2112
  encode: (tag, data) => {
2279
2113
  const { Err: E } = DER;
2280
- if (tag < 0 || tag > 256)
2114
+ asafenumber(tag, "tag");
2115
+ if (tag < 0 || tag > 255)
2281
2116
  throw new E("tlv.encode: wrong tag");
2117
+ if (typeof data !== "string")
2118
+ throw new TypeError('"data" expected string, got type=' + typeof data);
2282
2119
  if (data.length & 1)
2283
2120
  throw new E("tlv.encode: unpadded data");
2284
2121
  const dataLen = data.length / 2;
@@ -2292,8 +2129,9 @@ var DER = {
2292
2129
  // v - value, l - left bytes (unparsed)
2293
2130
  decode(tag, data) {
2294
2131
  const { Err: E } = DER;
2132
+ data = abytes3(data, void 0, "DER data");
2295
2133
  let pos = 0;
2296
- if (tag < 0 || tag > 256)
2134
+ if (tag < 0 || tag > 255)
2297
2135
  throw new E("tlv.encode: wrong tag");
2298
2136
  if (data.length < 2 || data[pos++] !== tag)
2299
2137
  throw new E("tlv.decode: wrong tlv");
@@ -2332,6 +2170,7 @@ var DER = {
2332
2170
  _int: {
2333
2171
  encode(num) {
2334
2172
  const { Err: E } = DER;
2173
+ abignumber(num);
2335
2174
  if (num < _0n4)
2336
2175
  throw new E("integer: negative integers are not allowed");
2337
2176
  let hex = numberToHexUnpadded(num);
@@ -2343,17 +2182,18 @@ var DER = {
2343
2182
  },
2344
2183
  decode(data) {
2345
2184
  const { Err: E } = DER;
2185
+ if (data.length < 1)
2186
+ throw new E("invalid signature integer: empty");
2346
2187
  if (data[0] & 128)
2347
2188
  throw new E("invalid signature integer: negative");
2348
- if (data[0] === 0 && !(data[1] & 128))
2189
+ if (data.length > 1 && data[0] === 0 && !(data[1] & 128))
2349
2190
  throw new E("invalid signature integer: unnecessary leading zero");
2350
- return b2n(data);
2191
+ return bytesToNumberBE(data);
2351
2192
  }
2352
2193
  },
2353
- toSig(hex) {
2194
+ toSig(bytes) {
2354
2195
  const { Err: E, _int: int, _tlv: tlv } = DER;
2355
- const data = typeof hex === "string" ? h2b(hex) : hex;
2356
- abytes4(data);
2196
+ const data = abytes3(bytes, void 0, "signature");
2357
2197
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
2358
2198
  if (seqLeftBytes.length)
2359
2199
  throw new E("invalid signature: left bytes after parsing");
@@ -2371,119 +2211,170 @@ var DER = {
2371
2211
  return tlv.encode(48, seq);
2372
2212
  }
2373
2213
  };
2374
- var _0n4 = BigInt(0);
2375
- var _1n4 = BigInt(1);
2376
- var _2n3 = BigInt(2);
2377
- var _3n2 = BigInt(3);
2378
- var _4n2 = BigInt(4);
2379
- function weierstrassPoints(opts) {
2380
- const CURVE = validatePointOpts(opts);
2381
- const { Fp } = CURVE;
2382
- const Fn = Field(CURVE.n, CURVE.nBitLength);
2383
- const toBytes3 = CURVE.toBytes || ((_c, point, _isCompressed) => {
2384
- const a = point.toAffine();
2385
- return concatBytes3(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
2214
+ Object.freeze(DER._tlv);
2215
+ Object.freeze(DER._int);
2216
+ Object.freeze(DER);
2217
+ var _0n4 = /* @__PURE__ */ BigInt(0);
2218
+ var _1n4 = /* @__PURE__ */ BigInt(1);
2219
+ var _2n2 = /* @__PURE__ */ BigInt(2);
2220
+ var _3n2 = /* @__PURE__ */ BigInt(3);
2221
+ var _4n2 = /* @__PURE__ */ BigInt(4);
2222
+ function weierstrass(params, extraOpts = {}) {
2223
+ const validated = createCurveFields("weierstrass", params, extraOpts);
2224
+ const Fp = validated.Fp;
2225
+ const Fn = validated.Fn;
2226
+ let CURVE = validated.CURVE;
2227
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
2228
+ validateObject(extraOpts, {}, {
2229
+ allowInfinityPoint: "boolean",
2230
+ clearCofactor: "function",
2231
+ isTorsionFree: "function",
2232
+ fromBytes: "function",
2233
+ toBytes: "function",
2234
+ endo: "object"
2386
2235
  });
2387
- const fromBytes = CURVE.fromBytes || ((bytes) => {
2236
+ const { endo, allowInfinityPoint } = extraOpts;
2237
+ if (endo) {
2238
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
2239
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
2240
+ }
2241
+ }
2242
+ const lengths = getWLengths(Fp, Fn);
2243
+ function assertCompressionIsSupported() {
2244
+ if (!Fp.isOdd)
2245
+ throw new Error("compression is not supported: Field does not have .isOdd()");
2246
+ }
2247
+ function pointToBytes(_c, point, isCompressed) {
2248
+ if (allowInfinityPoint && point.is0())
2249
+ return Uint8Array.of(0);
2250
+ const { x, y } = point.toAffine();
2251
+ const bx = Fp.toBytes(x);
2252
+ abool(isCompressed, "isCompressed");
2253
+ if (isCompressed) {
2254
+ assertCompressionIsSupported();
2255
+ const hasEvenY = !Fp.isOdd(y);
2256
+ return concatBytes3(pprefix(hasEvenY), bx);
2257
+ } else {
2258
+ return concatBytes3(Uint8Array.of(4), bx, Fp.toBytes(y));
2259
+ }
2260
+ }
2261
+ function pointFromBytes(bytes) {
2262
+ abytes3(bytes, void 0, "Point");
2263
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
2264
+ const length = bytes.length;
2265
+ const head = bytes[0];
2388
2266
  const tail = bytes.subarray(1);
2389
- const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
2390
- const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
2391
- return { x, y };
2392
- });
2267
+ if (allowInfinityPoint && length === 1 && head === 0)
2268
+ return { x: Fp.ZERO, y: Fp.ZERO };
2269
+ if (length === comp && (head === 2 || head === 3)) {
2270
+ const x = Fp.fromBytes(tail);
2271
+ if (!Fp.isValid(x))
2272
+ throw new Error("bad point: is not on curve, wrong x");
2273
+ const y2 = weierstrassEquation(x);
2274
+ let y;
2275
+ try {
2276
+ y = Fp.sqrt(y2);
2277
+ } catch (sqrtError) {
2278
+ const err2 = sqrtError instanceof Error ? ": " + sqrtError.message : "";
2279
+ throw new Error("bad point: is not on curve, sqrt error" + err2);
2280
+ }
2281
+ assertCompressionIsSupported();
2282
+ const evenY = Fp.isOdd(y);
2283
+ const evenH = (head & 1) === 1;
2284
+ if (evenH !== evenY)
2285
+ y = Fp.neg(y);
2286
+ return { x, y };
2287
+ } else if (length === uncomp && head === 4) {
2288
+ const L2 = Fp.BYTES;
2289
+ const x = Fp.fromBytes(tail.subarray(0, L2));
2290
+ const y = Fp.fromBytes(tail.subarray(L2, L2 * 2));
2291
+ if (!isValidXY(x, y))
2292
+ throw new Error("bad point: is not on curve");
2293
+ return { x, y };
2294
+ } else {
2295
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
2296
+ }
2297
+ }
2298
+ const encodePoint = extraOpts.toBytes === void 0 ? pointToBytes : extraOpts.toBytes;
2299
+ const decodePoint = extraOpts.fromBytes === void 0 ? pointFromBytes : extraOpts.fromBytes;
2393
2300
  function weierstrassEquation(x) {
2394
- const { a, b } = CURVE;
2395
2301
  const x2 = Fp.sqr(x);
2396
2302
  const x3 = Fp.mul(x2, x);
2397
- return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
2398
- }
2399
- if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
2400
- throw new Error("bad generator point: equation left != right");
2401
- function isWithinCurveOrder(num) {
2402
- return inRange(num, _1n4, CURVE.n);
2403
- }
2404
- function normPrivateKeyToScalar(key) {
2405
- const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N2 } = CURVE;
2406
- if (lengths && typeof key !== "bigint") {
2407
- if (isBytes4(key))
2408
- key = bytesToHex2(key);
2409
- if (typeof key !== "string" || !lengths.includes(key.length))
2410
- throw new Error("invalid private key");
2411
- key = key.padStart(nByteLength * 2, "0");
2412
- }
2413
- let num;
2414
- try {
2415
- num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
2416
- } catch (error) {
2417
- throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
2418
- }
2419
- if (wrapPrivateKey)
2420
- num = mod(num, N2);
2421
- aInRange("private key", num, _1n4, N2);
2422
- return num;
2423
- }
2424
- function assertPrjPoint(other) {
2425
- if (!(other instanceof Point2))
2426
- throw new Error("ProjectivePoint expected");
2303
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
2427
2304
  }
2428
- const toAffineMemo = memoized((p, iz) => {
2429
- const { px: x, py: y, pz: z } = p;
2430
- if (Fp.eql(z, Fp.ONE))
2431
- return { x, y };
2432
- const is0 = p.is0();
2433
- if (iz == null)
2434
- iz = is0 ? Fp.ONE : Fp.inv(z);
2435
- const ax = Fp.mul(x, iz);
2436
- const ay = Fp.mul(y, iz);
2437
- const zz = Fp.mul(z, iz);
2438
- if (is0)
2439
- return { x: Fp.ZERO, y: Fp.ZERO };
2440
- if (!Fp.eql(zz, Fp.ONE))
2441
- throw new Error("invZ was invalid");
2442
- return { x: ax, y: ay };
2443
- });
2444
- const assertValidMemo = memoized((p) => {
2445
- if (p.is0()) {
2446
- if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
2447
- return;
2448
- throw new Error("bad point: ZERO");
2449
- }
2450
- const { x, y } = p.toAffine();
2451
- if (!Fp.isValid(x) || !Fp.isValid(y))
2452
- throw new Error("bad point: x or y not FE");
2305
+ function isValidXY(x, y) {
2453
2306
  const left = Fp.sqr(y);
2454
2307
  const right = weierstrassEquation(x);
2455
- if (!Fp.eql(left, right))
2456
- throw new Error("bad point: equation left != right");
2457
- if (!p.isTorsionFree())
2458
- throw new Error("bad point: not in prime-order subgroup");
2459
- return true;
2460
- });
2308
+ return Fp.eql(left, right);
2309
+ }
2310
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
2311
+ throw new Error("bad curve params: generator point");
2312
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
2313
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
2314
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
2315
+ throw new Error("bad curve params: a or b");
2316
+ function acoord(title, n, banZero = false) {
2317
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
2318
+ throw new Error(`bad point coordinate ${title}`);
2319
+ return n;
2320
+ }
2321
+ function aprjpoint(other) {
2322
+ if (!(other instanceof Point2))
2323
+ throw new Error("Weierstrass Point expected");
2324
+ }
2325
+ function splitEndoScalarN(k) {
2326
+ if (!endo || !endo.basises)
2327
+ throw new Error("no endo");
2328
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
2329
+ }
2330
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
2331
+ k2p = new Point2(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
2332
+ k1p = negateCt(k1neg, k1p);
2333
+ k2p = negateCt(k2neg, k2p);
2334
+ return k1p.add(k2p);
2335
+ }
2461
2336
  class Point2 {
2462
- constructor(px, py, pz) {
2463
- this.px = px;
2464
- this.py = py;
2465
- this.pz = pz;
2466
- if (px == null || !Fp.isValid(px))
2467
- throw new Error("x required");
2468
- if (py == null || !Fp.isValid(py))
2469
- throw new Error("y required");
2470
- if (pz == null || !Fp.isValid(pz))
2471
- throw new Error("z required");
2337
+ // base / generator point
2338
+ static BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp.ONE);
2339
+ // zero / infinity / identity point
2340
+ static ZERO = new Point2(Fp.ZERO, Fp.ONE, Fp.ZERO);
2341
+ // 0, 1, 0
2342
+ // math field
2343
+ static Fp = Fp;
2344
+ // scalar field
2345
+ static Fn = Fn;
2346
+ X;
2347
+ Y;
2348
+ Z;
2349
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2350
+ constructor(X, Y, Z) {
2351
+ this.X = acoord("x", X);
2352
+ this.Y = acoord("y", Y, true);
2353
+ this.Z = acoord("z", Z);
2472
2354
  Object.freeze(this);
2473
2355
  }
2474
- // Does not validate if the point is on-curve.
2475
- // Use fromHex instead, or call assertValidity() later.
2356
+ static CURVE() {
2357
+ return CURVE;
2358
+ }
2359
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2476
2360
  static fromAffine(p) {
2477
2361
  const { x, y } = p || {};
2478
2362
  if (!p || !Fp.isValid(x) || !Fp.isValid(y))
2479
2363
  throw new Error("invalid affine point");
2480
2364
  if (p instanceof Point2)
2481
2365
  throw new Error("projective point not allowed");
2482
- const is0 = (i) => Fp.eql(i, Fp.ZERO);
2483
- if (is0(x) && is0(y))
2366
+ if (Fp.is0(x) && Fp.is0(y))
2484
2367
  return Point2.ZERO;
2485
2368
  return new Point2(x, y, Fp.ONE);
2486
2369
  }
2370
+ static fromBytes(bytes) {
2371
+ const P2 = Point2.fromAffine(decodePoint(abytes3(bytes, void 0, "point")));
2372
+ P2.assertValidity();
2373
+ return P2;
2374
+ }
2375
+ static fromHex(hex) {
2376
+ return Point2.fromBytes(hexToBytes3(hex));
2377
+ }
2487
2378
  get x() {
2488
2379
  return this.toAffine().x;
2489
2380
  }
@@ -2491,62 +2382,52 @@ function weierstrassPoints(opts) {
2491
2382
  return this.toAffine().y;
2492
2383
  }
2493
2384
  /**
2494
- * Takes a bunch of Projective Points but executes only one
2495
- * inversion on all of them. Inversion is very slow operation,
2496
- * so this improves performance massively.
2497
- * Optimization: converts a list of projective points to a list of identical points with Z=1.
2385
+ *
2386
+ * @param windowSize
2387
+ * @param isLazy - true will defer table computation until the first multiplication
2388
+ * @returns
2498
2389
  */
2499
- static normalizeZ(points) {
2500
- const toInv = Fp.invertBatch(points.map((p) => p.pz));
2501
- return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine);
2502
- }
2503
- /**
2504
- * Converts hash string or Uint8Array to Point.
2505
- * @param hex short/long ECDSA hex
2506
- */
2507
- static fromHex(hex) {
2508
- const P2 = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
2509
- P2.assertValidity();
2510
- return P2;
2511
- }
2512
- // Multiplies generator point by privateKey.
2513
- static fromPrivateKey(privateKey) {
2514
- return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey));
2515
- }
2516
- // Multiscalar Multiplication
2517
- static msm(points, scalars) {
2518
- return pippenger(Point2, Fn, points, scalars);
2519
- }
2520
- // "Private method", don't use it directly
2521
- _setWindowSize(windowSize) {
2522
- wnaf.setWindowSize(this, windowSize);
2390
+ precompute(windowSize = 8, isLazy = true) {
2391
+ wnaf.createCache(this, windowSize);
2392
+ if (!isLazy)
2393
+ this.multiply(_3n2);
2394
+ return this;
2523
2395
  }
2524
- // A point on curve is valid if it conforms to equation.
2396
+ // TODO: return `this`
2397
+ /** A point on curve is valid if it conforms to equation. */
2525
2398
  assertValidity() {
2526
- assertValidMemo(this);
2399
+ const p = this;
2400
+ if (p.is0()) {
2401
+ if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))
2402
+ return;
2403
+ throw new Error("bad point: ZERO");
2404
+ }
2405
+ const { x, y } = p.toAffine();
2406
+ if (!Fp.isValid(x) || !Fp.isValid(y))
2407
+ throw new Error("bad point: x or y not field elements");
2408
+ if (!isValidXY(x, y))
2409
+ throw new Error("bad point: equation left != right");
2410
+ if (!p.isTorsionFree())
2411
+ throw new Error("bad point: not in prime-order subgroup");
2527
2412
  }
2528
2413
  hasEvenY() {
2529
2414
  const { y } = this.toAffine();
2530
- if (Fp.isOdd)
2531
- return !Fp.isOdd(y);
2532
- throw new Error("Field doesn't support isOdd");
2415
+ if (!Fp.isOdd)
2416
+ throw new Error("Field doesn't support isOdd");
2417
+ return !Fp.isOdd(y);
2533
2418
  }
2534
- /**
2535
- * Compare one point to another.
2536
- */
2419
+ /** Compare one point to another. */
2537
2420
  equals(other) {
2538
- assertPrjPoint(other);
2539
- const { px: X1, py: Y1, pz: Z1 } = this;
2540
- const { px: X2, py: Y2, pz: Z2 } = other;
2421
+ aprjpoint(other);
2422
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2423
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2541
2424
  const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
2542
2425
  const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
2543
2426
  return U1 && U2;
2544
2427
  }
2545
- /**
2546
- * Flips point to one corresponding to (x, -y) in Affine coordinates.
2547
- */
2428
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
2548
2429
  negate() {
2549
- return new Point2(this.px, Fp.neg(this.py), this.pz);
2430
+ return new Point2(this.X, Fp.neg(this.Y), this.Z);
2550
2431
  }
2551
2432
  // Renes-Costello-Batina exception-free doubling formula.
2552
2433
  // There is 30% faster Jacobian formula, but it is not complete.
@@ -2555,7 +2436,7 @@ function weierstrassPoints(opts) {
2555
2436
  double() {
2556
2437
  const { a, b } = CURVE;
2557
2438
  const b3 = Fp.mul(b, _3n2);
2558
- const { px: X1, py: Y1, pz: Z1 } = this;
2439
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2559
2440
  let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2560
2441
  let t0 = Fp.mul(X1, X1);
2561
2442
  let t1 = Fp.mul(Y1, Y1);
@@ -2595,9 +2476,9 @@ function weierstrassPoints(opts) {
2595
2476
  // https://eprint.iacr.org/2015/1060, algorithm 1
2596
2477
  // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2597
2478
  add(other) {
2598
- assertPrjPoint(other);
2599
- const { px: X1, py: Y1, pz: Z1 } = this;
2600
- const { px: X2, py: Y2, pz: Z2 } = other;
2479
+ aprjpoint(other);
2480
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2481
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2601
2482
  let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2602
2483
  const a = CURVE.a;
2603
2484
  const b3 = Fp.mul(CURVE.b, _3n2);
@@ -2644,254 +2525,315 @@ function weierstrassPoints(opts) {
2644
2525
  return new Point2(X3, Y3, Z3);
2645
2526
  }
2646
2527
  subtract(other) {
2528
+ aprjpoint(other);
2647
2529
  return this.add(other.negate());
2648
2530
  }
2649
2531
  is0() {
2650
2532
  return this.equals(Point2.ZERO);
2651
2533
  }
2652
- wNAF(n) {
2653
- return wnaf.wNAFCached(this, n, Point2.normalizeZ);
2654
- }
2655
- /**
2656
- * Non-constant-time multiplication. Uses double-and-add algorithm.
2657
- * It's faster, but should only be used when you don't care about
2658
- * an exposed private key e.g. sig verification, which works over *public* keys.
2659
- */
2660
- multiplyUnsafe(sc) {
2661
- const { endo, n: N2 } = CURVE;
2662
- aInRange("scalar", sc, _0n4, N2);
2663
- const I2 = Point2.ZERO;
2664
- if (sc === _0n4)
2665
- return I2;
2666
- if (this.is0() || sc === _1n4)
2667
- return this;
2668
- if (!endo || wnaf.hasPrecomputes(this))
2669
- return wnaf.wNAFCachedUnsafe(this, sc, Point2.normalizeZ);
2670
- let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
2671
- let k1p = I2;
2672
- let k2p = I2;
2673
- let d = this;
2674
- while (k1 > _0n4 || k2 > _0n4) {
2675
- if (k1 & _1n4)
2676
- k1p = k1p.add(d);
2677
- if (k2 & _1n4)
2678
- k2p = k2p.add(d);
2679
- d = d.double();
2680
- k1 >>= _1n4;
2681
- k2 >>= _1n4;
2682
- }
2683
- if (k1neg)
2684
- k1p = k1p.negate();
2685
- if (k2neg)
2686
- k2p = k2p.negate();
2687
- k2p = new Point2(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
2688
- return k1p.add(k2p);
2689
- }
2690
2534
  /**
2691
2535
  * Constant time multiplication.
2692
2536
  * Uses wNAF method. Windowed method may be 10% faster,
2693
2537
  * but takes 2x longer to generate and consumes 2x memory.
2694
2538
  * Uses precomputes when available.
2695
2539
  * Uses endomorphism for Koblitz curves.
2696
- * @param scalar by which the point would be multiplied
2540
+ * @param scalar - by which the point would be multiplied
2697
2541
  * @returns New point
2698
2542
  */
2699
2543
  multiply(scalar) {
2700
- const { endo, n: N2 } = CURVE;
2701
- aInRange("scalar", scalar, _1n4, N2);
2544
+ const { endo: endo2 } = extraOpts;
2545
+ if (!Fn.isValidNot0(scalar))
2546
+ throw new RangeError("invalid scalar: out of range");
2702
2547
  let point, fake;
2703
- if (endo) {
2704
- const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
2705
- let { p: k1p, f: f1p } = this.wNAF(k1);
2706
- let { p: k2p, f: f2p } = this.wNAF(k2);
2707
- k1p = wnaf.constTimeNegate(k1neg, k1p);
2708
- k2p = wnaf.constTimeNegate(k2neg, k2p);
2709
- k2p = new Point2(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
2710
- point = k1p.add(k2p);
2711
- fake = f1p.add(f2p);
2548
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point2, p));
2549
+ if (endo2) {
2550
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
2551
+ const { p: k1p, f: k1f } = mul(k1);
2552
+ const { p: k2p, f: k2f } = mul(k2);
2553
+ fake = k1f.add(k2f);
2554
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
2712
2555
  } else {
2713
- const { p, f } = this.wNAF(scalar);
2556
+ const { p, f } = mul(scalar);
2714
2557
  point = p;
2715
2558
  fake = f;
2716
2559
  }
2717
- return Point2.normalizeZ([point, fake])[0];
2560
+ return normalizeZ(Point2, [point, fake])[0];
2561
+ }
2562
+ /**
2563
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
2564
+ * It's faster, but should only be used when you don't care about
2565
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
2566
+ */
2567
+ multiplyUnsafe(scalar) {
2568
+ const { endo: endo2 } = extraOpts;
2569
+ const p = this;
2570
+ const sc = scalar;
2571
+ if (!Fn.isValid(sc))
2572
+ throw new RangeError("invalid scalar: out of range");
2573
+ if (sc === _0n4 || p.is0())
2574
+ return Point2.ZERO;
2575
+ if (sc === _1n4)
2576
+ return p;
2577
+ if (wnaf.hasCache(this))
2578
+ return this.multiply(sc);
2579
+ if (endo2) {
2580
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
2581
+ const { p1, p2 } = mulEndoUnsafe(Point2, p, k1, k2);
2582
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
2583
+ } else {
2584
+ return wnaf.unsafe(p, sc);
2585
+ }
2718
2586
  }
2719
2587
  /**
2720
- * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
2721
- * Not using Strauss-Shamir trick: precomputation tables are faster.
2722
- * The trick could be useful if both P and Q are not G (not in our case).
2723
- * @returns non-zero affine point
2588
+ * Converts Projective point to affine (x, y) coordinates.
2589
+ * (X, Y, Z) (x=X/Z, y=Y/Z).
2590
+ * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
2724
2591
  */
2725
- multiplyAndAddUnsafe(Q, a, b) {
2726
- const G2 = Point2.BASE;
2727
- const mul = (P2, a2) => a2 === _0n4 || a2 === _1n4 || !P2.equals(G2) ? P2.multiplyUnsafe(a2) : P2.multiply(a2);
2728
- const sum = mul(this, a).add(mul(Q, b));
2729
- return sum.is0() ? void 0 : sum;
2730
- }
2731
- // Converts Projective point to affine (x, y) coordinates.
2732
- // Can accept precomputed Z^-1 - for example, from invertBatch.
2733
- // (x, y, z) (x=x/z, y=y/z)
2734
- toAffine(iz) {
2735
- return toAffineMemo(this, iz);
2592
+ toAffine(invertedZ) {
2593
+ const p = this;
2594
+ let iz = invertedZ;
2595
+ const { X, Y, Z } = p;
2596
+ if (Fp.eql(Z, Fp.ONE))
2597
+ return { x: X, y: Y };
2598
+ const is0 = p.is0();
2599
+ if (iz == null)
2600
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
2601
+ const x = Fp.mul(X, iz);
2602
+ const y = Fp.mul(Y, iz);
2603
+ const zz = Fp.mul(Z, iz);
2604
+ if (is0)
2605
+ return { x: Fp.ZERO, y: Fp.ZERO };
2606
+ if (!Fp.eql(zz, Fp.ONE))
2607
+ throw new Error("invZ was invalid");
2608
+ return { x, y };
2736
2609
  }
2610
+ /**
2611
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
2612
+ * Always torsion-free for cofactor=1 curves.
2613
+ */
2737
2614
  isTorsionFree() {
2738
- const { h: cofactor, isTorsionFree } = CURVE;
2615
+ const { isTorsionFree } = extraOpts;
2739
2616
  if (cofactor === _1n4)
2740
2617
  return true;
2741
2618
  if (isTorsionFree)
2742
2619
  return isTorsionFree(Point2, this);
2743
- throw new Error("isTorsionFree() has not been declared for the elliptic curve");
2620
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
2744
2621
  }
2745
2622
  clearCofactor() {
2746
- const { h: cofactor, clearCofactor } = CURVE;
2623
+ const { clearCofactor } = extraOpts;
2747
2624
  if (cofactor === _1n4)
2748
2625
  return this;
2749
2626
  if (clearCofactor)
2750
2627
  return clearCofactor(Point2, this);
2751
- return this.multiplyUnsafe(CURVE.h);
2628
+ return this.multiplyUnsafe(cofactor);
2629
+ }
2630
+ isSmallOrder() {
2631
+ if (cofactor === _1n4)
2632
+ return this.is0();
2633
+ return this.clearCofactor().is0();
2752
2634
  }
2753
- toRawBytes(isCompressed = true) {
2754
- abool("isCompressed", isCompressed);
2635
+ toBytes(isCompressed = true) {
2636
+ abool(isCompressed, "isCompressed");
2755
2637
  this.assertValidity();
2756
- return toBytes3(Point2, this, isCompressed);
2638
+ return encodePoint(Point2, this, isCompressed);
2757
2639
  }
2758
2640
  toHex(isCompressed = true) {
2759
- abool("isCompressed", isCompressed);
2760
- return bytesToHex2(this.toRawBytes(isCompressed));
2641
+ return bytesToHex3(this.toBytes(isCompressed));
2642
+ }
2643
+ toString() {
2644
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2761
2645
  }
2762
2646
  }
2763
- Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp.ONE);
2764
- Point2.ZERO = new Point2(Fp.ZERO, Fp.ONE, Fp.ZERO);
2765
- const _bits = CURVE.nBitLength;
2766
- const wnaf = wNAF2(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
2647
+ const bits = Fn.BITS;
2648
+ const wnaf = new wNAF2(Point2, extraOpts.endo ? Math.ceil(bits / 2) : bits);
2649
+ if (bits >= 8)
2650
+ Point2.BASE.precompute(8);
2651
+ Object.freeze(Point2.prototype);
2652
+ Object.freeze(Point2);
2653
+ return Point2;
2654
+ }
2655
+ function pprefix(hasEvenY) {
2656
+ return Uint8Array.of(hasEvenY ? 2 : 3);
2657
+ }
2658
+ function getWLengths(Fp, Fn) {
2767
2659
  return {
2768
- CURVE,
2769
- ProjectivePoint: Point2,
2770
- normPrivateKeyToScalar,
2771
- weierstrassEquation,
2772
- isWithinCurveOrder
2660
+ secretKey: Fn.BYTES,
2661
+ publicKey: 1 + Fp.BYTES,
2662
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
2663
+ publicKeyHasPrefix: true,
2664
+ // Raw compact `(r || s)` signature width; DER and recovered signatures use
2665
+ // different lengths outside this helper.
2666
+ signature: 2 * Fn.BYTES
2773
2667
  };
2774
2668
  }
2775
- function validateOpts(curve) {
2776
- const opts = validateBasic(curve);
2777
- validateObject(opts, {
2778
- hash: "hash",
2779
- hmac: "function",
2780
- randomBytes: "function"
2781
- }, {
2782
- bits2int: "function",
2783
- bits2int_modN: "function",
2784
- lowS: "boolean"
2669
+ function ecdh(Point2, ecdhOpts = {}) {
2670
+ const { Fn } = Point2;
2671
+ const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes3 : ecdhOpts.randomBytes;
2672
+ const lengths = Object.assign(getWLengths(Point2.Fp, Fn), {
2673
+ seed: Math.max(getMinHashLength(Fn.ORDER), 16)
2785
2674
  });
2786
- return Object.freeze({ lowS: true, ...opts });
2787
- }
2788
- function weierstrass(curveDef) {
2789
- const CURVE = validateOpts(curveDef);
2790
- const { Fp, n: CURVE_ORDER } = CURVE;
2791
- const compressedLen = Fp.BYTES + 1;
2792
- const uncompressedLen = 2 * Fp.BYTES + 1;
2793
- function modN2(a) {
2794
- return mod(a, CURVE_ORDER);
2795
- }
2796
- function invN(a) {
2797
- return invert2(a, CURVE_ORDER);
2798
- }
2799
- const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
2800
- ...CURVE,
2801
- toBytes(_c, point, isCompressed) {
2802
- const a = point.toAffine();
2803
- const x = Fp.toBytes(a.x);
2804
- const cat = concatBytes3;
2805
- abool("isCompressed", isCompressed);
2806
- if (isCompressed) {
2807
- return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
2808
- } else {
2809
- return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
2810
- }
2811
- },
2812
- fromBytes(bytes) {
2813
- const len = bytes.length;
2814
- const head = bytes[0];
2815
- const tail = bytes.subarray(1);
2816
- if (len === compressedLen && (head === 2 || head === 3)) {
2817
- const x = bytesToNumberBE(tail);
2818
- if (!inRange(x, _1n4, Fp.ORDER))
2819
- throw new Error("Point is not on curve");
2820
- const y2 = weierstrassEquation(x);
2821
- let y;
2822
- try {
2823
- y = Fp.sqrt(y2);
2824
- } catch (sqrtError) {
2825
- const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
2826
- throw new Error("Point is not on curve" + suffix);
2827
- }
2828
- const isYOdd = (y & _1n4) === _1n4;
2829
- const isHeadOdd = (head & 1) === 1;
2830
- if (isHeadOdd !== isYOdd)
2831
- y = Fp.neg(y);
2832
- return { x, y };
2833
- } else if (len === uncompressedLen && head === 4) {
2834
- const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
2835
- const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
2836
- return { x, y };
2837
- } else {
2838
- const cl = compressedLen;
2839
- const ul = uncompressedLen;
2840
- throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
2841
- }
2675
+ function isValidSecretKey(secretKey) {
2676
+ try {
2677
+ const num = Fn.fromBytes(secretKey);
2678
+ return Fn.isValidNot0(num);
2679
+ } catch (error) {
2680
+ return false;
2681
+ }
2682
+ }
2683
+ function isValidPublicKey(publicKey, isCompressed) {
2684
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
2685
+ try {
2686
+ const l = publicKey.length;
2687
+ if (isCompressed === true && l !== comp)
2688
+ return false;
2689
+ if (isCompressed === false && l !== publicKeyUncompressed)
2690
+ return false;
2691
+ return !!Point2.fromBytes(publicKey);
2692
+ } catch (error) {
2693
+ return false;
2842
2694
  }
2695
+ }
2696
+ function randomSecretKey2(seed) {
2697
+ seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
2698
+ return mapHashToField(abytes3(seed, lengths.seed, "seed"), Fn.ORDER);
2699
+ }
2700
+ function getPublicKey(secretKey, isCompressed = true) {
2701
+ return Point2.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
2702
+ }
2703
+ function isProbPub(item) {
2704
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
2705
+ const allowedLengths = Fn._lengths;
2706
+ if (!isBytes3(item))
2707
+ return void 0;
2708
+ const l = abytes3(item, void 0, "key").length;
2709
+ const isPub = l === publicKey || l === publicKeyUncompressed;
2710
+ const isSec = l === secretKey || !!allowedLengths?.includes(l);
2711
+ if (isPub && isSec)
2712
+ return void 0;
2713
+ return isPub;
2714
+ }
2715
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
2716
+ if (isProbPub(secretKeyA) === true)
2717
+ throw new Error("first arg must be private key");
2718
+ if (isProbPub(publicKeyB) === false)
2719
+ throw new Error("second arg must be public key");
2720
+ const s = Fn.fromBytes(secretKeyA);
2721
+ const b = Point2.fromBytes(publicKeyB);
2722
+ return b.multiply(s).toBytes(isCompressed);
2723
+ }
2724
+ const utils = {
2725
+ isValidSecretKey,
2726
+ isValidPublicKey,
2727
+ randomSecretKey: randomSecretKey2
2728
+ };
2729
+ const keygen = createKeygen(randomSecretKey2, getPublicKey);
2730
+ Object.freeze(utils);
2731
+ Object.freeze(lengths);
2732
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point: Point2, utils, lengths });
2733
+ }
2734
+ function ecdsa(Point2, hash, ecdsaOpts = {}) {
2735
+ const hash_ = hash;
2736
+ ahash(hash_);
2737
+ validateObject(ecdsaOpts, {}, {
2738
+ hmac: "function",
2739
+ lowS: "boolean",
2740
+ randomBytes: "function",
2741
+ bits2int: "function",
2742
+ bits2int_modN: "function"
2843
2743
  });
2844
- const numToNByteStr = (num) => bytesToHex2(numberToBytesBE(num, CURVE.nByteLength));
2744
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
2745
+ const randomBytes4 = ecdsaOpts.randomBytes === void 0 ? randomBytes3 : ecdsaOpts.randomBytes;
2746
+ const hmac2 = ecdsaOpts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : ecdsaOpts.hmac;
2747
+ const { Fp, Fn } = Point2;
2748
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
2749
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point2, ecdsaOpts);
2750
+ const defaultSigOpts = {
2751
+ prehash: true,
2752
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
2753
+ format: "compact",
2754
+ extraEntropy: false
2755
+ };
2756
+ const hasLargeRecoveryLifts = CURVE_ORDER * _2n2 + _1n4 < Fp.ORDER;
2845
2757
  function isBiggerThanHalfOrder(number) {
2846
2758
  const HALF = CURVE_ORDER >> _1n4;
2847
2759
  return number > HALF;
2848
2760
  }
2849
- function normalizeS(s) {
2850
- return isBiggerThanHalfOrder(s) ? modN2(-s) : s;
2761
+ function validateRS(title, num) {
2762
+ if (!Fn.isValidNot0(num))
2763
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
2764
+ return num;
2765
+ }
2766
+ function assertRecoverableCurve() {
2767
+ if (hasLargeRecoveryLifts)
2768
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
2769
+ }
2770
+ function validateSigLength(bytes, format) {
2771
+ validateSigFormat(format);
2772
+ const size = lengths.signature;
2773
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
2774
+ return abytes3(bytes, sizer);
2851
2775
  }
2852
- const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
2853
2776
  class Signature {
2777
+ r;
2778
+ s;
2779
+ recovery;
2854
2780
  constructor(r, s, recovery) {
2855
- this.r = r;
2856
- this.s = s;
2857
- this.recovery = recovery;
2858
- this.assertValidity();
2781
+ this.r = validateRS("r", r);
2782
+ this.s = validateRS("s", s);
2783
+ if (recovery != null) {
2784
+ assertRecoverableCurve();
2785
+ if (![0, 1, 2, 3].includes(recovery))
2786
+ throw new Error("invalid recovery id");
2787
+ this.recovery = recovery;
2788
+ }
2789
+ Object.freeze(this);
2859
2790
  }
2860
- // pair (bytes of r, bytes of s)
2861
- static fromCompact(hex) {
2862
- const l = CURVE.nByteLength;
2863
- hex = ensureBytes("compactSignature", hex, l * 2);
2864
- return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
2791
+ static fromBytes(bytes, format = defaultSigOpts.format) {
2792
+ validateSigLength(bytes, format);
2793
+ let recid;
2794
+ if (format === "der") {
2795
+ const { r: r2, s: s2 } = DER.toSig(abytes3(bytes));
2796
+ return new Signature(r2, s2);
2797
+ }
2798
+ if (format === "recovered") {
2799
+ recid = bytes[0];
2800
+ format = "compact";
2801
+ bytes = bytes.subarray(1);
2802
+ }
2803
+ const L2 = lengths.signature / 2;
2804
+ const r = bytes.subarray(0, L2);
2805
+ const s = bytes.subarray(L2, L2 * 2);
2806
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
2865
2807
  }
2866
- // DER encoded ECDSA signature
2867
- // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
2868
- static fromDER(hex) {
2869
- const { r, s } = DER.toSig(ensureBytes("DER", hex));
2870
- return new Signature(r, s);
2808
+ static fromHex(hex, format) {
2809
+ return this.fromBytes(hexToBytes3(hex), format);
2871
2810
  }
2872
- assertValidity() {
2873
- aInRange("r", this.r, _1n4, CURVE_ORDER);
2874
- aInRange("s", this.s, _1n4, CURVE_ORDER);
2811
+ assertRecovery() {
2812
+ const { recovery } = this;
2813
+ if (recovery == null)
2814
+ throw new Error("invalid recovery id: must be present");
2815
+ return recovery;
2875
2816
  }
2876
2817
  addRecoveryBit(recovery) {
2877
2818
  return new Signature(this.r, this.s, recovery);
2878
2819
  }
2879
- recoverPublicKey(msgHash) {
2880
- const { r, s, recovery: rec } = this;
2881
- const h2 = bits2int_modN(ensureBytes("msgHash", msgHash));
2882
- if (rec == null || ![0, 1, 2, 3].includes(rec))
2883
- throw new Error("recovery id invalid");
2884
- const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
2885
- if (radj >= Fp.ORDER)
2886
- throw new Error("recovery id 2 or 3 invalid");
2887
- const prefix = (rec & 1) === 0 ? "02" : "03";
2888
- const R = Point2.fromHex(prefix + numToNByteStr(radj));
2889
- const ir = invN(radj);
2890
- const u1 = modN2(-h2 * ir);
2891
- const u2 = modN2(s * ir);
2892
- const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2);
2893
- if (!Q)
2894
- throw new Error("point at infinify");
2820
+ // Unlike the top-level helper below, this method expects a digest that has
2821
+ // already been hashed to the curve's message representative.
2822
+ recoverPublicKey(messageHash) {
2823
+ const { r, s } = this;
2824
+ const recovery = this.assertRecovery();
2825
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
2826
+ if (!Fp.isValid(radj))
2827
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
2828
+ const x = Fp.toBytes(radj);
2829
+ const R = Point2.fromBytes(concatBytes3(pprefix((recovery & 1) === 0), x));
2830
+ const ir = Fn.inv(radj);
2831
+ const h2 = bits2int_modN(abytes3(messageHash, void 0, "msgHash"));
2832
+ const u1 = Fn.create(-h2 * ir);
2833
+ const u2 = Fn.create(s * ir);
2834
+ const Q = Point2.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
2835
+ if (Q.is0())
2836
+ throw new Error("invalid recovery: point at infinify");
2895
2837
  Q.assertValidity();
2896
2838
  return Q;
2897
2839
  }
@@ -2899,243 +2841,150 @@ function weierstrass(curveDef) {
2899
2841
  hasHighS() {
2900
2842
  return isBiggerThanHalfOrder(this.s);
2901
2843
  }
2902
- normalizeS() {
2903
- return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this;
2904
- }
2905
- // DER-encoded
2906
- toDERRawBytes() {
2907
- return hexToBytes2(this.toDERHex());
2908
- }
2909
- toDERHex() {
2910
- return DER.hexFromSig({ r: this.r, s: this.s });
2911
- }
2912
- // padded bytes of r, then padded bytes of s
2913
- toCompactRawBytes() {
2914
- return hexToBytes2(this.toCompactHex());
2915
- }
2916
- toCompactHex() {
2917
- return numToNByteStr(this.r) + numToNByteStr(this.s);
2918
- }
2919
- }
2920
- const utils = {
2921
- isValidPrivateKey(privateKey) {
2922
- try {
2923
- normPrivateKeyToScalar(privateKey);
2924
- return true;
2925
- } catch (error) {
2926
- return false;
2844
+ toBytes(format = defaultSigOpts.format) {
2845
+ validateSigFormat(format);
2846
+ if (format === "der")
2847
+ return hexToBytes3(DER.hexFromSig(this));
2848
+ const { r, s } = this;
2849
+ const rb = Fn.toBytes(r);
2850
+ const sb = Fn.toBytes(s);
2851
+ if (format === "recovered") {
2852
+ assertRecoverableCurve();
2853
+ return concatBytes3(Uint8Array.of(this.assertRecovery()), rb, sb);
2927
2854
  }
2928
- },
2929
- normPrivateKeyToScalar,
2930
- /**
2931
- * Produces cryptographically secure private key from random of size
2932
- * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
2933
- */
2934
- randomPrivateKey: () => {
2935
- const length = getMinHashLength(CURVE.n);
2936
- return mapHashToField(CURVE.randomBytes(length), CURVE.n);
2937
- },
2938
- /**
2939
- * Creates precompute table for an arbitrary EC point. Makes point "cached".
2940
- * Allows to massively speed-up `point.multiply(scalar)`.
2941
- * @returns cached point
2942
- * @example
2943
- * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
2944
- * fast.multiply(privKey); // much faster ECDH now
2945
- */
2946
- precompute(windowSize = 8, point = Point2.BASE) {
2947
- point._setWindowSize(windowSize);
2948
- point.multiply(BigInt(3));
2949
- return point;
2855
+ return concatBytes3(rb, sb);
2856
+ }
2857
+ toHex(format) {
2858
+ return bytesToHex3(this.toBytes(format));
2950
2859
  }
2951
- };
2952
- function getPublicKey(privateKey, isCompressed = true) {
2953
- return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed);
2954
- }
2955
- function isProbPub(item) {
2956
- const arr = isBytes4(item);
2957
- const str = typeof item === "string";
2958
- const len = (arr || str) && item.length;
2959
- if (arr)
2960
- return len === compressedLen || len === uncompressedLen;
2961
- if (str)
2962
- return len === 2 * compressedLen || len === 2 * uncompressedLen;
2963
- if (item instanceof Point2)
2964
- return true;
2965
- return false;
2966
- }
2967
- function getSharedSecret(privateA, publicB, isCompressed = true) {
2968
- if (isProbPub(privateA))
2969
- throw new Error("first arg must be private key");
2970
- if (!isProbPub(publicB))
2971
- throw new Error("second arg must be public key");
2972
- const b = Point2.fromHex(publicB);
2973
- return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
2974
2860
  }
2975
- const bits2int = CURVE.bits2int || function(bytes) {
2861
+ Object.freeze(Signature.prototype);
2862
+ Object.freeze(Signature);
2863
+ const bits2int = ecdsaOpts.bits2int === void 0 ? function bits2int_def(bytes) {
2976
2864
  if (bytes.length > 8192)
2977
2865
  throw new Error("input is too large");
2978
2866
  const num = bytesToNumberBE(bytes);
2979
- const delta = bytes.length * 8 - CURVE.nBitLength;
2867
+ const delta = bytes.length * 8 - fnBits;
2980
2868
  return delta > 0 ? num >> BigInt(delta) : num;
2981
- };
2982
- const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
2983
- return modN2(bits2int(bytes));
2984
- };
2985
- const ORDER_MASK = bitMask(CURVE.nBitLength);
2869
+ } : ecdsaOpts.bits2int;
2870
+ const bits2int_modN = ecdsaOpts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
2871
+ return Fn.create(bits2int(bytes));
2872
+ } : ecdsaOpts.bits2int_modN;
2873
+ const ORDER_MASK = bitMask(fnBits);
2986
2874
  function int2octets(num) {
2987
- aInRange("num < 2^" + CURVE.nBitLength, num, _0n4, ORDER_MASK);
2988
- return numberToBytesBE(num, CURVE.nByteLength);
2989
- }
2990
- function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
2991
- if (["recovered", "canonical"].some((k) => k in opts))
2992
- throw new Error("sign() legacy options not supported");
2993
- const { hash, randomBytes: randomBytes3 } = CURVE;
2994
- let { lowS, prehash, extraEntropy: ent } = opts;
2995
- if (lowS == null)
2996
- lowS = true;
2997
- msgHash = ensureBytes("msgHash", msgHash);
2998
- validateSigVerOpts(opts);
2999
- if (prehash)
3000
- msgHash = ensureBytes("prehashed msgHash", hash(msgHash));
3001
- const h1int = bits2int_modN(msgHash);
3002
- const d = normPrivateKeyToScalar(privateKey);
2875
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
2876
+ return Fn.toBytes(num);
2877
+ }
2878
+ function validateMsgAndHash(message, prehash) {
2879
+ abytes3(message, void 0, "message");
2880
+ return prehash ? abytes3(hash_(message), void 0, "prehashed message") : message;
2881
+ }
2882
+ function prepSig(message, secretKey, opts) {
2883
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
2884
+ message = validateMsgAndHash(message, prehash);
2885
+ const h1int = bits2int_modN(message);
2886
+ const d = Fn.fromBytes(secretKey);
2887
+ if (!Fn.isValidNot0(d))
2888
+ throw new Error("invalid private key");
3003
2889
  const seedArgs = [int2octets(d), int2octets(h1int)];
3004
- if (ent != null && ent !== false) {
3005
- const e = ent === true ? randomBytes3(Fp.BYTES) : ent;
3006
- seedArgs.push(ensureBytes("extraEntropy", e));
2890
+ if (extraEntropy != null && extraEntropy !== false) {
2891
+ const e = extraEntropy === true ? randomBytes4(lengths.secretKey) : extraEntropy;
2892
+ seedArgs.push(abytes3(e, void 0, "extraEntropy"));
3007
2893
  }
3008
2894
  const seed = concatBytes3(...seedArgs);
3009
2895
  const m = h1int;
3010
2896
  function k2sig(kBytes) {
3011
2897
  const k = bits2int(kBytes);
3012
- if (!isWithinCurveOrder(k))
2898
+ if (!Fn.isValidNot0(k))
3013
2899
  return;
3014
- const ik = invN(k);
2900
+ const ik = Fn.inv(k);
3015
2901
  const q = Point2.BASE.multiply(k).toAffine();
3016
- const r = modN2(q.x);
2902
+ const r = Fn.create(q.x);
3017
2903
  if (r === _0n4)
3018
2904
  return;
3019
- const s = modN2(ik * modN2(m + r * d));
2905
+ const s = Fn.create(ik * Fn.create(m + r * d));
3020
2906
  if (s === _0n4)
3021
2907
  return;
3022
2908
  let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
3023
2909
  let normS = s;
3024
2910
  if (lowS && isBiggerThanHalfOrder(s)) {
3025
- normS = normalizeS(s);
2911
+ normS = Fn.neg(s);
3026
2912
  recovery ^= 1;
3027
2913
  }
3028
- return new Signature(r, normS, recovery);
2914
+ return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
3029
2915
  }
3030
2916
  return { seed, k2sig };
3031
2917
  }
3032
- const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
3033
- const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
3034
- function sign(msgHash, privKey, opts = defaultSigOpts) {
3035
- const { seed, k2sig } = prepSig(msgHash, privKey, opts);
3036
- const C2 = CURVE;
3037
- const drbg = createHmacDrbg(C2.hash.outputLen, C2.nByteLength, C2.hmac);
3038
- return drbg(seed, k2sig);
3039
- }
3040
- Point2.BASE._setWindowSize(8);
3041
- function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
3042
- const sg = signature;
3043
- msgHash = ensureBytes("msgHash", msgHash);
3044
- publicKey = ensureBytes("publicKey", publicKey);
3045
- const { lowS, prehash, format } = opts;
3046
- validateSigVerOpts(opts);
3047
- if ("strict" in opts)
3048
- throw new Error("options.strict was renamed to lowS");
3049
- if (format !== void 0 && format !== "compact" && format !== "der")
3050
- throw new Error("format must be compact or der");
3051
- const isHex = typeof sg === "string" || isBytes4(sg);
3052
- const isObj = !isHex && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
3053
- if (!isHex && !isObj)
3054
- throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
3055
- let _sig = void 0;
3056
- let P2;
2918
+ function sign(message, secretKey, opts = {}) {
2919
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
2920
+ const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac2);
2921
+ const sig = drbg(seed, k2sig);
2922
+ return sig.toBytes(opts.format);
2923
+ }
2924
+ function verify(signature, message, publicKey, opts = {}) {
2925
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
2926
+ publicKey = abytes3(publicKey, void 0, "publicKey");
2927
+ message = validateMsgAndHash(message, prehash);
2928
+ if (!isBytes3(signature)) {
2929
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
2930
+ throw new Error("verify expects Uint8Array signature" + end);
2931
+ }
2932
+ validateSigLength(signature, format);
3057
2933
  try {
3058
- if (isObj)
3059
- _sig = new Signature(sg.r, sg.s);
3060
- if (isHex) {
3061
- try {
3062
- if (format !== "compact")
3063
- _sig = Signature.fromDER(sg);
3064
- } catch (derError) {
3065
- if (!(derError instanceof DER.Err))
3066
- throw derError;
3067
- }
3068
- if (!_sig && format !== "der")
3069
- _sig = Signature.fromCompact(sg);
3070
- }
3071
- P2 = Point2.fromHex(publicKey);
3072
- } catch (error) {
2934
+ const sig = Signature.fromBytes(signature, format);
2935
+ const P2 = Point2.fromBytes(publicKey);
2936
+ if (lowS && sig.hasHighS())
2937
+ return false;
2938
+ const { r, s } = sig;
2939
+ const h2 = bits2int_modN(message);
2940
+ const is = Fn.inv(s);
2941
+ const u1 = Fn.create(h2 * is);
2942
+ const u2 = Fn.create(r * is);
2943
+ const R = Point2.BASE.multiplyUnsafe(u1).add(P2.multiplyUnsafe(u2));
2944
+ if (R.is0())
2945
+ return false;
2946
+ const v = Fn.create(R.x);
2947
+ return v === r;
2948
+ } catch (e) {
3073
2949
  return false;
3074
2950
  }
3075
- if (!_sig)
3076
- return false;
3077
- if (lowS && _sig.hasHighS())
3078
- return false;
3079
- if (prehash)
3080
- msgHash = CURVE.hash(msgHash);
3081
- const { r, s } = _sig;
3082
- const h2 = bits2int_modN(msgHash);
3083
- const is = invN(s);
3084
- const u1 = modN2(h2 * is);
3085
- const u2 = modN2(r * is);
3086
- const R = Point2.BASE.multiplyAndAddUnsafe(P2, u1, u2)?.toAffine();
3087
- if (!R)
3088
- return false;
3089
- const v = modN2(R.x);
3090
- return v === r;
3091
2951
  }
3092
- return {
3093
- CURVE,
2952
+ function recoverPublicKey(signature, message, opts = {}) {
2953
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
2954
+ message = validateMsgAndHash(message, prehash);
2955
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
2956
+ }
2957
+ return Object.freeze({
2958
+ keygen,
3094
2959
  getPublicKey,
3095
2960
  getSharedSecret,
2961
+ utils,
2962
+ lengths,
2963
+ Point: Point2,
3096
2964
  sign,
3097
2965
  verify,
3098
- ProjectivePoint: Point2,
2966
+ recoverPublicKey,
3099
2967
  Signature,
3100
- utils
3101
- };
3102
- }
3103
-
3104
- // ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/_shortw_utils.js
3105
- function getHash(hash) {
3106
- return {
3107
- hash,
3108
- hmac: (key, ...msgs) => hmac(hash, key, concatBytes2(...msgs)),
3109
- randomBytes: randomBytes2
3110
- };
3111
- }
3112
- function createCurve(curveDef, defHash) {
3113
- const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
3114
- return Object.freeze({ ...create(defHash), create });
2968
+ hash: hash_
2969
+ });
3115
2970
  }
3116
2971
 
3117
- // ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/p256.js
3118
- var Fp256 = Field(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"));
3119
- var CURVE_A = Fp256.create(BigInt("-3"));
3120
- var CURVE_B = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");
3121
- var p256 = createCurve({
3122
- a: CURVE_A,
3123
- // Equation params: a, b
3124
- b: CURVE_B,
3125
- Fp: Fp256,
3126
- // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n
3127
- // Curve order, total count of valid points in the field
2972
+ // ../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/nist.js
2973
+ var p256_CURVE = /* @__PURE__ */ (() => ({
2974
+ p: BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),
3128
2975
  n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),
3129
- // Base (generator) point (x, y)
3130
- Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
3131
- Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),
3132
2976
  h: BigInt(1),
3133
- lowS: false
3134
- }, sha2562);
2977
+ a: BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),
2978
+ b: BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),
2979
+ Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
2980
+ Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")
2981
+ }))();
2982
+ var p256_Point = /* @__PURE__ */ weierstrass(p256_CURVE);
2983
+ var p256 = /* @__PURE__ */ ecdsa(p256_Point, sha256);
3135
2984
 
3136
2985
  // src/suite-dispatch.ts
3137
2986
  if (!hashes.sha512) {
3138
- hashes.sha512 = (msg) => sha512(msg);
2987
+ hashes.sha512 = sha512;
3139
2988
  }
3140
2989
  async function verifyBySuite(suite, canonicalBytes, signatureBytes, publicKeyBytes) {
3141
2990
  switch (suite) {
@@ -3188,18 +3037,18 @@ async function getPublicKeyBySuite(privateKey, suite) {
3188
3037
  function verifyP256EcdsaSha256(publicKeyCompressedHex, messageBytes, signatureDerBytes) {
3189
3038
  try {
3190
3039
  const digest = sha256(messageBytes);
3191
- const pubKeyBytes = hexToBytes3(publicKeyCompressedHex);
3192
- return p256.verify(signatureDerBytes, digest, pubKeyBytes, { prehash: false });
3040
+ const pubKeyBytes = hexToBytes4(publicKeyCompressedHex);
3041
+ return p256.verify(signatureDerBytes, digest, pubKeyBytes, { prehash: false, format: "der" });
3193
3042
  } catch {
3194
3043
  return false;
3195
3044
  }
3196
3045
  }
3197
- function hexToBytes3(hex) {
3198
- const clean = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
3199
- if (clean.length % 2 !== 0) throw new Error("hex length must be even");
3200
- const out = new Uint8Array(clean.length / 2);
3046
+ function hexToBytes4(hex) {
3047
+ const clean2 = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
3048
+ if (clean2.length % 2 !== 0) throw new Error("hex length must be even");
3049
+ const out = new Uint8Array(clean2.length / 2);
3201
3050
  for (let i = 0; i < out.length; i++) {
3202
- const byte = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
3051
+ const byte = parseInt(clean2.slice(i * 2, i * 2 + 2), 16);
3203
3052
  if (Number.isNaN(byte)) throw new Error(`invalid hex at position ${i * 2}`);
3204
3053
  out[i] = byte;
3205
3054
  }
@@ -3219,15 +3068,10 @@ export {
3219
3068
  @noble/ed25519/index.js:
3220
3069
  (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
3221
3070
 
3222
- @noble/hashes/esm/utils.js:
3223
- @noble/hashes/esm/utils.js:
3224
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3225
-
3226
- @noble/curves/esm/abstract/utils.js:
3227
- @noble/curves/esm/abstract/modular.js:
3228
- @noble/curves/esm/abstract/curve.js:
3229
- @noble/curves/esm/abstract/weierstrass.js:
3230
- @noble/curves/esm/_shortw_utils.js:
3231
- @noble/curves/esm/p256.js:
3071
+ @noble/curves/utils.js:
3072
+ @noble/curves/abstract/modular.js:
3073
+ @noble/curves/abstract/curve.js:
3074
+ @noble/curves/abstract/weierstrass.js:
3075
+ @noble/curves/nist.js:
3232
3076
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3233
3077
  */