@sentio/sdk-bundle 2.62.1-rc.1 → 2.62.1-rc.2

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.
Files changed (75) hide show
  1. package/lib/aptos/builtin/0x1.js +5 -5
  2. package/lib/aptos/builtin/0x3.js +6 -6
  3. package/lib/aptos/builtin/0x4.js +6 -6
  4. package/lib/aptos/builtin/index.js +7 -7
  5. package/lib/aptos/ext/index.js +5 -5
  6. package/lib/aptos/index.js +5 -5
  7. package/lib/{chunk-PFY5KFQM.js → chunk-35FWRY45.js} +2 -2
  8. package/lib/{chunk-J6EIXHMB.js → chunk-B5DTCANS.js} +5 -5
  9. package/lib/{chunk-X6R7OLNU.js → chunk-BBAJWF26.js} +423 -200
  10. package/lib/{chunk-X6R7OLNU.js.map → chunk-BBAJWF26.js.map} +1 -1
  11. package/lib/{chunk-WH7VZ4UN.js → chunk-C4IWDMJP.js} +4 -4
  12. package/lib/{chunk-LU7Y242I.js → chunk-E6NA7NG4.js} +4577 -4327
  13. package/lib/chunk-E6NA7NG4.js.map +1 -0
  14. package/lib/{chunk-EFLNW4OX.js → chunk-EZWWCMDA.js} +21 -2
  15. package/lib/{chunk-EFLNW4OX.js.map → chunk-EZWWCMDA.js.map} +1 -1
  16. package/lib/{chunk-Q7ODO5TY.js → chunk-ITEA4P7X.js} +2 -2
  17. package/lib/{chunk-SMMLF2M7.js → chunk-KDONV5MN.js} +14 -14
  18. package/lib/{chunk-SMMLF2M7.js.map → chunk-KDONV5MN.js.map} +1 -1
  19. package/lib/{chunk-DYIDZUKA.js → chunk-KPSHXWBW.js} +2 -2
  20. package/lib/{chunk-ELPMWEYR.js → chunk-KVGG6FSO.js} +6 -6
  21. package/lib/{chunk-3BBCYBWP.js → chunk-N2YKY3T4.js} +3 -3
  22. package/lib/{chunk-MXADICA7.js → chunk-OK7JSSAW.js} +4 -4
  23. package/lib/{chunk-OP4CCBFE.js → chunk-QQKOOATP.js} +3 -3
  24. package/lib/{chunk-HUXUX4SZ.js → chunk-RZH2OJ62.js} +27 -7
  25. package/lib/chunk-RZH2OJ62.js.map +1 -0
  26. package/lib/{chunk-QUTU42TG.js → chunk-TXEQKSWM.js} +55 -5
  27. package/lib/chunk-TXEQKSWM.js.map +1 -0
  28. package/lib/{chunk-4YIX74TT.js → chunk-VGE55IGX.js} +2 -2
  29. package/lib/{chunk-X3SSOBOF.js → chunk-WYM4IYMI.js} +1888 -1859
  30. package/lib/chunk-WYM4IYMI.js.map +1 -0
  31. package/lib/{chunk-ONUOP6MS.js → chunk-XPAVUR3M.js} +7 -7
  32. package/lib/{chunk-ONUOP6MS.js.map → chunk-XPAVUR3M.js.map} +1 -1
  33. package/lib/{chunk-SGFYE2BW.js → chunk-ZCVHUL7O.js} +163 -6
  34. package/lib/{chunk-SGFYE2BW.js.map → chunk-ZCVHUL7O.js.map} +1 -1
  35. package/lib/{chunk-2VKG4TJH.js → chunk-ZWXYSR6T.js} +4 -4
  36. package/lib/eth/builtin/eacaggregatorproxy.js +1 -1
  37. package/lib/eth/builtin/erc1155.js +2 -2
  38. package/lib/eth/builtin/erc20.js +1 -1
  39. package/lib/eth/builtin/erc721.js +1 -1
  40. package/lib/eth/builtin/index.js +3 -3
  41. package/lib/eth/builtin/weth9.js +2 -2
  42. package/lib/eth/index.js +1 -1
  43. package/lib/iota/builtin/0x1.js +8 -8
  44. package/lib/iota/builtin/0x2.js +9 -9
  45. package/lib/iota/builtin/0x3.js +10 -10
  46. package/lib/iota/builtin/index.js +10 -10
  47. package/lib/iota/ext/index.js +5 -5
  48. package/lib/iota/index.js +7 -7
  49. package/lib/move/index.js +1 -1
  50. package/lib/solana/builtin/index.js +3 -3
  51. package/lib/solana/index.js +3 -3
  52. package/lib/sui/builtin/0x1.js +8 -8
  53. package/lib/sui/builtin/0x2.js +11 -9
  54. package/lib/sui/builtin/0x3.js +10 -10
  55. package/lib/sui/builtin/index.js +10 -10
  56. package/lib/sui/ext/index.js +5 -5
  57. package/lib/sui/index.js +7 -7
  58. package/lib/testing/index.js +9 -9
  59. package/lib/utils/index.js +1 -1
  60. package/package.json +2 -2
  61. package/lib/chunk-HUXUX4SZ.js.map +0 -1
  62. package/lib/chunk-LU7Y242I.js.map +0 -1
  63. package/lib/chunk-QUTU42TG.js.map +0 -1
  64. package/lib/chunk-X3SSOBOF.js.map +0 -1
  65. /package/lib/{chunk-PFY5KFQM.js.map → chunk-35FWRY45.js.map} +0 -0
  66. /package/lib/{chunk-J6EIXHMB.js.map → chunk-B5DTCANS.js.map} +0 -0
  67. /package/lib/{chunk-WH7VZ4UN.js.map → chunk-C4IWDMJP.js.map} +0 -0
  68. /package/lib/{chunk-Q7ODO5TY.js.map → chunk-ITEA4P7X.js.map} +0 -0
  69. /package/lib/{chunk-DYIDZUKA.js.map → chunk-KPSHXWBW.js.map} +0 -0
  70. /package/lib/{chunk-ELPMWEYR.js.map → chunk-KVGG6FSO.js.map} +0 -0
  71. /package/lib/{chunk-3BBCYBWP.js.map → chunk-N2YKY3T4.js.map} +0 -0
  72. /package/lib/{chunk-MXADICA7.js.map → chunk-OK7JSSAW.js.map} +0 -0
  73. /package/lib/{chunk-OP4CCBFE.js.map → chunk-QQKOOATP.js.map} +0 -0
  74. /package/lib/{chunk-4YIX74TT.js.map → chunk-VGE55IGX.js.map} +0 -0
  75. /package/lib/{chunk-2VKG4TJH.js.map → chunk-ZWXYSR6T.js.map} +0 -0
@@ -5,6 +5,7 @@ import {
5
5
  HashMD,
6
6
  Maj,
7
7
  SHA256_IV,
8
+ SHA384_IV,
8
9
  SHA512_IV,
9
10
  abytes,
10
11
  add,
@@ -44,7 +45,7 @@ import {
44
45
  toBytes,
45
46
  u32,
46
47
  utf8ToBytes
47
- } from "./chunk-EFLNW4OX.js";
48
+ } from "./chunk-EZWWCMDA.js";
48
49
  import {
49
50
  __commonJS,
50
51
  __esm,
@@ -448,7 +449,7 @@ var init_utils2 = __esm({
448
449
  });
449
450
 
450
451
  // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
451
- var SHA256_K, SHA256_W, SHA256, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, sha256, sha512;
452
+ var SHA256_K, SHA256_W, SHA256, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, SHA384, sha256, sha512, sha384;
452
453
  var init_sha2 = __esm({
453
454
  "../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js"() {
454
455
  "use strict";
@@ -795,86 +796,33 @@ var init_sha2 = __esm({
795
796
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
796
797
  }
797
798
  };
798
- sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
799
- sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
800
- }
801
- });
802
-
803
- // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
804
- var HMAC, hmac;
805
- var init_hmac = __esm({
806
- "../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js"() {
807
- "use strict";
808
- init_utils();
809
- HMAC = class extends Hash {
799
+ SHA384 = class extends SHA512 {
810
800
  static {
811
- __name(this, "HMAC");
812
- }
813
- constructor(hash, _key) {
814
- super();
815
- this.finished = false;
816
- this.destroyed = false;
817
- ahash(hash);
818
- const key = toBytes(_key);
819
- this.iHash = hash.create();
820
- if (typeof this.iHash.update !== "function")
821
- throw new Error("Expected instance of class which extends utils.Hash");
822
- this.blockLen = this.iHash.blockLen;
823
- this.outputLen = this.iHash.outputLen;
824
- const blockLen = this.blockLen;
825
- const pad = new Uint8Array(blockLen);
826
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
827
- for (let i = 0; i < pad.length; i++)
828
- pad[i] ^= 54;
829
- this.iHash.update(pad);
830
- this.oHash = hash.create();
831
- for (let i = 0; i < pad.length; i++)
832
- pad[i] ^= 54 ^ 92;
833
- this.oHash.update(pad);
834
- clean(pad);
835
- }
836
- update(buf) {
837
- aexists(this);
838
- this.iHash.update(buf);
839
- return this;
840
- }
841
- digestInto(out) {
842
- aexists(this);
843
- abytes(out, this.outputLen);
844
- this.finished = true;
845
- this.iHash.digestInto(out);
846
- this.oHash.update(out);
847
- this.oHash.digestInto(out);
848
- this.destroy();
849
- }
850
- digest() {
851
- const out = new Uint8Array(this.oHash.outputLen);
852
- this.digestInto(out);
853
- return out;
854
- }
855
- _cloneInto(to) {
856
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
857
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
858
- to = to;
859
- to.finished = finished;
860
- to.destroyed = destroyed;
861
- to.blockLen = blockLen;
862
- to.outputLen = outputLen;
863
- to.oHash = oHash._cloneInto(to.oHash);
864
- to.iHash = iHash._cloneInto(to.iHash);
865
- return to;
866
- }
867
- clone() {
868
- return this._cloneInto();
869
- }
870
- destroy() {
871
- this.destroyed = true;
872
- this.oHash.destroy();
873
- this.iHash.destroy();
801
+ __name(this, "SHA384");
802
+ }
803
+ constructor() {
804
+ super(48);
805
+ this.Ah = SHA384_IV[0] | 0;
806
+ this.Al = SHA384_IV[1] | 0;
807
+ this.Bh = SHA384_IV[2] | 0;
808
+ this.Bl = SHA384_IV[3] | 0;
809
+ this.Ch = SHA384_IV[4] | 0;
810
+ this.Cl = SHA384_IV[5] | 0;
811
+ this.Dh = SHA384_IV[6] | 0;
812
+ this.Dl = SHA384_IV[7] | 0;
813
+ this.Eh = SHA384_IV[8] | 0;
814
+ this.El = SHA384_IV[9] | 0;
815
+ this.Fh = SHA384_IV[10] | 0;
816
+ this.Fl = SHA384_IV[11] | 0;
817
+ this.Gh = SHA384_IV[12] | 0;
818
+ this.Gl = SHA384_IV[13] | 0;
819
+ this.Hh = SHA384_IV[14] | 0;
820
+ this.Hl = SHA384_IV[15] | 0;
874
821
  }
875
822
  };
876
- hmac = /* @__PURE__ */ __name((hash, key, message) => new HMAC(hash, key).update(message).digest(), "hmac");
877
- hmac.create = (hash, key) => new HMAC(hash, key);
823
+ sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
824
+ sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
825
+ sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
878
826
  }
879
827
  });
880
828
 
@@ -1551,240 +1499,126 @@ var init_curve = __esm({
1551
1499
  }
1552
1500
  });
1553
1501
 
1554
- // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/weierstrass.js
1555
- function _splitEndoScalar(k, basis, n) {
1556
- const [[a1, b1], [a2, b2]] = basis;
1557
- const c1 = divNearest(b2 * k, n);
1558
- const c2 = divNearest(-b1 * k, n);
1559
- let k1 = k - c1 * a1 - c2 * a2;
1560
- let k2 = -c1 * b1 - c2 * b2;
1561
- const k1neg = k1 < _0n5;
1562
- const k2neg = k2 < _0n5;
1563
- if (k1neg)
1564
- k1 = -k1;
1565
- if (k2neg)
1566
- k2 = -k2;
1567
- const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n5;
1568
- if (k1 < _0n5 || k1 >= MAX_NUM || k2 < _0n5 || k2 >= MAX_NUM) {
1569
- throw new Error("splitScalar (endomorphism): failed, k=" + k);
1570
- }
1571
- return { k1neg, k1, k2neg, k2 };
1572
- }
1573
- function validateSigFormat(format) {
1574
- if (!["compact", "recovered", "der"].includes(format))
1575
- throw new Error('Signature format must be "compact", "recovered", or "der"');
1576
- return format;
1577
- }
1578
- function validateSigOpts(opts, def) {
1579
- const optsn = {};
1580
- for (let optName of Object.keys(def)) {
1581
- optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
1582
- }
1583
- _abool2(optsn.lowS, "lowS");
1584
- _abool2(optsn.prehash, "prehash");
1585
- if (optsn.format !== void 0)
1586
- validateSigFormat(optsn.format);
1587
- return optsn;
1588
- }
1589
- function _normFnElement(Fn2, key) {
1590
- const { BYTES: expected } = Fn2;
1591
- let num;
1592
- if (typeof key === "bigint") {
1593
- num = key;
1594
- } else {
1595
- let bytes = ensureBytes("private key", key);
1596
- try {
1597
- num = Fn2.fromBytes(bytes);
1598
- } catch (error) {
1599
- throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
1600
- }
1601
- }
1602
- if (!Fn2.isValidNot0(num))
1603
- throw new Error("invalid private key: out of range [1..N-1]");
1604
- return num;
1502
+ // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/edwards.js
1503
+ function isEdValidXY(Fp2, CURVE, x, y) {
1504
+ const x2 = Fp2.sqr(x);
1505
+ const y2 = Fp2.sqr(y);
1506
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
1507
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
1508
+ return Fp2.eql(left, right);
1605
1509
  }
1606
- function weierstrassN(params, extraOpts = {}) {
1607
- const validated = _createCurveFields("weierstrass", params, extraOpts);
1510
+ function edwards(params, extraOpts = {}) {
1511
+ const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
1608
1512
  const { Fp: Fp2, Fn: Fn2 } = validated;
1609
1513
  let CURVE = validated.CURVE;
1610
- const { h: cofactor, n: CURVE_ORDER } = CURVE;
1611
- _validateObject(extraOpts, {}, {
1612
- allowInfinityPoint: "boolean",
1613
- clearCofactor: "function",
1614
- isTorsionFree: "function",
1615
- fromBytes: "function",
1616
- toBytes: "function",
1617
- endo: "object",
1618
- wrapPrivateKey: "boolean"
1619
- });
1620
- const { endo } = extraOpts;
1621
- if (endo) {
1622
- if (!Fp2.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
1623
- throw new Error('invalid endo: expected "beta": bigint and "basises": array');
1624
- }
1625
- }
1626
- const lengths = getWLengths(Fp2, Fn2);
1627
- function assertCompressionIsSupported() {
1628
- if (!Fp2.isOdd)
1629
- throw new Error("compression is not supported: Field does not have .isOdd()");
1630
- }
1631
- __name(assertCompressionIsSupported, "assertCompressionIsSupported");
1632
- function pointToBytes(_c, point, isCompressed) {
1633
- const { x, y } = point.toAffine();
1634
- const bx = Fp2.toBytes(x);
1635
- _abool2(isCompressed, "isCompressed");
1636
- if (isCompressed) {
1637
- assertCompressionIsSupported();
1638
- const hasEvenY = !Fp2.isOdd(y);
1639
- return concatBytes(pprefix(hasEvenY), bx);
1640
- } else {
1641
- return concatBytes(Uint8Array.of(4), bx, Fp2.toBytes(y));
1642
- }
1643
- }
1644
- __name(pointToBytes, "pointToBytes");
1645
- function pointFromBytes(bytes) {
1646
- _abytes2(bytes, void 0, "Point");
1647
- const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
1648
- const length = bytes.length;
1649
- const head = bytes[0];
1650
- const tail = bytes.subarray(1);
1651
- if (length === comp && (head === 2 || head === 3)) {
1652
- const x = Fp2.fromBytes(tail);
1653
- if (!Fp2.isValid(x))
1654
- throw new Error("bad point: is not on curve, wrong x");
1655
- const y2 = weierstrassEquation(x);
1656
- let y;
1657
- try {
1658
- y = Fp2.sqrt(y2);
1659
- } catch (sqrtError) {
1660
- const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1661
- throw new Error("bad point: is not on curve, sqrt error" + err);
1662
- }
1663
- assertCompressionIsSupported();
1664
- const isYOdd = Fp2.isOdd(y);
1665
- const isHeadOdd = (head & 1) === 1;
1666
- if (isHeadOdd !== isYOdd)
1667
- y = Fp2.neg(y);
1668
- return { x, y };
1669
- } else if (length === uncomp && head === 4) {
1670
- const L = Fp2.BYTES;
1671
- const x = Fp2.fromBytes(tail.subarray(0, L));
1672
- const y = Fp2.fromBytes(tail.subarray(L, L * 2));
1673
- if (!isValidXY(x, y))
1674
- throw new Error("bad point: is not on curve");
1675
- return { x, y };
1676
- } else {
1677
- throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
1514
+ const { h: cofactor } = CURVE;
1515
+ _validateObject(extraOpts, {}, { uvRatio: "function" });
1516
+ const MASK = _2n3 << BigInt(Fn2.BYTES * 8) - _1n5;
1517
+ const modP = /* @__PURE__ */ __name((n) => Fp2.create(n), "modP");
1518
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
1519
+ try {
1520
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
1521
+ } catch (e) {
1522
+ return { isValid: false, value: _0n5 };
1678
1523
  }
1679
- }
1680
- __name(pointFromBytes, "pointFromBytes");
1681
- const encodePoint = extraOpts.toBytes || pointToBytes;
1682
- const decodePoint = extraOpts.fromBytes || pointFromBytes;
1683
- function weierstrassEquation(x) {
1684
- const x2 = Fp2.sqr(x);
1685
- const x3 = Fp2.mul(x2, x);
1686
- return Fp2.add(Fp2.add(x3, Fp2.mul(x, CURVE.a)), CURVE.b);
1687
- }
1688
- __name(weierstrassEquation, "weierstrassEquation");
1689
- function isValidXY(x, y) {
1690
- const left = Fp2.sqr(y);
1691
- const right = weierstrassEquation(x);
1692
- return Fp2.eql(left, right);
1693
- }
1694
- __name(isValidXY, "isValidXY");
1695
- if (!isValidXY(CURVE.Gx, CURVE.Gy))
1524
+ });
1525
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1696
1526
  throw new Error("bad curve params: generator point");
1697
- const _4a3 = Fp2.mul(Fp2.pow(CURVE.a, _3n2), _4n2);
1698
- const _27b2 = Fp2.mul(Fp2.sqr(CURVE.b), BigInt(27));
1699
- if (Fp2.is0(Fp2.add(_4a3, _27b2)))
1700
- throw new Error("bad curve params: a or b");
1701
1527
  function acoord(title, n, banZero = false) {
1702
- if (!Fp2.isValid(n) || banZero && Fp2.is0(n))
1703
- throw new Error(`bad point coordinate ${title}`);
1528
+ const min = banZero ? _1n5 : _0n5;
1529
+ aInRange("coordinate " + title, n, min, MASK);
1704
1530
  return n;
1705
1531
  }
1706
1532
  __name(acoord, "acoord");
1707
- function aprjpoint(other) {
1533
+ function aextpoint(other) {
1708
1534
  if (!(other instanceof Point))
1709
- throw new Error("ProjectivePoint expected");
1710
- }
1711
- __name(aprjpoint, "aprjpoint");
1712
- function splitEndoScalarN(k) {
1713
- if (!endo || !endo.basises)
1714
- throw new Error("no endo");
1715
- return _splitEndoScalar(k, endo.basises, Fn2.ORDER);
1535
+ throw new Error("ExtendedPoint expected");
1716
1536
  }
1717
- __name(splitEndoScalarN, "splitEndoScalarN");
1537
+ __name(aextpoint, "aextpoint");
1718
1538
  const toAffineMemo = memoized((p, iz) => {
1719
1539
  const { X, Y, Z } = p;
1720
- if (Fp2.eql(Z, Fp2.ONE))
1721
- return { x: X, y: Y };
1722
1540
  const is0 = p.is0();
1723
1541
  if (iz == null)
1724
- iz = is0 ? Fp2.ONE : Fp2.inv(Z);
1725
- const x = Fp2.mul(X, iz);
1726
- const y = Fp2.mul(Y, iz);
1727
- const zz = Fp2.mul(Z, iz);
1728
- if (is0)
1729
- return { x: Fp2.ZERO, y: Fp2.ZERO };
1730
- if (!Fp2.eql(zz, Fp2.ONE))
1542
+ iz = is0 ? _8n2 : Fp2.inv(Z);
1543
+ const x = modP(X * iz);
1544
+ const y = modP(Y * iz);
1545
+ const zz = Fp2.mul(Z, iz);
1546
+ if (is0)
1547
+ return { x: _0n5, y: _1n5 };
1548
+ if (zz !== _1n5)
1731
1549
  throw new Error("invZ was invalid");
1732
1550
  return { x, y };
1733
1551
  });
1734
1552
  const assertValidMemo = memoized((p) => {
1735
- if (p.is0()) {
1736
- if (extraOpts.allowInfinityPoint && !Fp2.is0(p.Y))
1737
- return;
1553
+ const { a, d } = CURVE;
1554
+ if (p.is0())
1738
1555
  throw new Error("bad point: ZERO");
1739
- }
1740
- const { x, y } = p.toAffine();
1741
- if (!Fp2.isValid(x) || !Fp2.isValid(y))
1742
- throw new Error("bad point: x or y not field elements");
1743
- if (!isValidXY(x, y))
1744
- throw new Error("bad point: equation left != right");
1745
- if (!p.isTorsionFree())
1746
- throw new Error("bad point: not in prime-order subgroup");
1556
+ const { X, Y, Z, T } = p;
1557
+ const X2 = modP(X * X);
1558
+ const Y2 = modP(Y * Y);
1559
+ const Z2 = modP(Z * Z);
1560
+ const Z4 = modP(Z2 * Z2);
1561
+ const aX2 = modP(X2 * a);
1562
+ const left = modP(Z2 * modP(aX2 + Y2));
1563
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1564
+ if (left !== right)
1565
+ throw new Error("bad point: equation left != right (1)");
1566
+ const XY = modP(X * Y);
1567
+ const ZT = modP(Z * T);
1568
+ if (XY !== ZT)
1569
+ throw new Error("bad point: equation left != right (2)");
1747
1570
  return true;
1748
1571
  });
1749
- function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
1750
- k2p = new Point(Fp2.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
1751
- k1p = negateCt(k1neg, k1p);
1752
- k2p = negateCt(k2neg, k2p);
1753
- return k1p.add(k2p);
1754
- }
1755
- __name(finishEndo, "finishEndo");
1756
1572
  class Point {
1757
1573
  static {
1758
1574
  __name(this, "Point");
1759
1575
  }
1760
- /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1761
- constructor(X, Y, Z) {
1576
+ constructor(X, Y, Z, T) {
1762
1577
  this.X = acoord("x", X);
1763
- this.Y = acoord("y", Y, true);
1764
- this.Z = acoord("z", Z);
1578
+ this.Y = acoord("y", Y);
1579
+ this.Z = acoord("z", Z, true);
1580
+ this.T = acoord("t", T);
1765
1581
  Object.freeze(this);
1766
1582
  }
1767
1583
  static CURVE() {
1768
1584
  return CURVE;
1769
1585
  }
1770
- /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1771
1586
  static fromAffine(p) {
1772
- const { x, y } = p || {};
1773
- if (!p || !Fp2.isValid(x) || !Fp2.isValid(y))
1774
- throw new Error("invalid affine point");
1775
1587
  if (p instanceof Point)
1776
- throw new Error("projective point not allowed");
1777
- if (Fp2.is0(x) && Fp2.is0(y))
1778
- return Point.ZERO;
1779
- return new Point(x, y, Fp2.ONE);
1588
+ throw new Error("extended point not allowed");
1589
+ const { x, y } = p || {};
1590
+ acoord("x", x);
1591
+ acoord("y", y);
1592
+ return new Point(x, y, _1n5, modP(x * y));
1780
1593
  }
1781
- static fromBytes(bytes) {
1782
- const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
1783
- P.assertValidity();
1784
- return P;
1594
+ // Uses algo from RFC8032 5.1.3.
1595
+ static fromBytes(bytes, zip215 = false) {
1596
+ const len = Fp2.BYTES;
1597
+ const { a, d } = CURVE;
1598
+ bytes = copyBytes(_abytes2(bytes, len, "point"));
1599
+ _abool2(zip215, "zip215");
1600
+ const normed = copyBytes(bytes);
1601
+ const lastByte = bytes[len - 1];
1602
+ normed[len - 1] = lastByte & ~128;
1603
+ const y = bytesToNumberLE(normed);
1604
+ const max = zip215 ? MASK : Fp2.ORDER;
1605
+ aInRange("point.y", y, _0n5, max);
1606
+ const y2 = modP(y * y);
1607
+ const u = modP(y2 - _1n5);
1608
+ const v = modP(d * y2 - a);
1609
+ let { isValid, value: x } = uvRatio2(u, v);
1610
+ if (!isValid)
1611
+ throw new Error("bad point: invalid y coordinate");
1612
+ const isXOdd = (x & _1n5) === _1n5;
1613
+ const isLastByteOdd = (lastByte & 128) !== 0;
1614
+ if (!zip215 && x === _0n5 && isLastByteOdd)
1615
+ throw new Error("bad point: x=0 and x_0=1");
1616
+ if (isLastByteOdd !== isXOdd)
1617
+ x = modP(-x);
1618
+ return Point.fromAffine({ x, y });
1785
1619
  }
1786
- static fromHex(hex) {
1787
- return Point.fromBytes(ensureBytes("pointHex", hex));
1620
+ static fromHex(bytes, zip215 = false) {
1621
+ return Point.fromBytes(ensureBytes("point", bytes), zip215);
1788
1622
  }
1789
1623
  get x() {
1790
1624
  return this.toAffine().x;
@@ -1792,255 +1626,146 @@ function weierstrassN(params, extraOpts = {}) {
1792
1626
  get y() {
1793
1627
  return this.toAffine().y;
1794
1628
  }
1795
- /**
1796
- *
1797
- * @param windowSize
1798
- * @param isLazy true will defer table computation until the first multiplication
1799
- * @returns
1800
- */
1801
1629
  precompute(windowSize = 8, isLazy = true) {
1802
1630
  wnaf.createCache(this, windowSize);
1803
1631
  if (!isLazy)
1804
- this.multiply(_3n2);
1632
+ this.multiply(_2n3);
1805
1633
  return this;
1806
1634
  }
1807
- // TODO: return `this`
1808
- /** A point on curve is valid if it conforms to equation. */
1635
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
1809
1636
  assertValidity() {
1810
1637
  assertValidMemo(this);
1811
1638
  }
1812
- hasEvenY() {
1813
- const { y } = this.toAffine();
1814
- if (!Fp2.isOdd)
1815
- throw new Error("Field doesn't support isOdd");
1816
- return !Fp2.isOdd(y);
1817
- }
1818
- /** Compare one point to another. */
1639
+ // Compare one point to another.
1819
1640
  equals(other) {
1820
- aprjpoint(other);
1641
+ aextpoint(other);
1821
1642
  const { X: X1, Y: Y1, Z: Z1 } = this;
1822
1643
  const { X: X2, Y: Y2, Z: Z2 } = other;
1823
- const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
1824
- const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
1825
- return U1 && U2;
1644
+ const X1Z2 = modP(X1 * Z2);
1645
+ const X2Z1 = modP(X2 * Z1);
1646
+ const Y1Z2 = modP(Y1 * Z2);
1647
+ const Y2Z1 = modP(Y2 * Z1);
1648
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1649
+ }
1650
+ is0() {
1651
+ return this.equals(Point.ZERO);
1826
1652
  }
1827
- /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
1828
1653
  negate() {
1829
- return new Point(this.X, Fp2.neg(this.Y), this.Z);
1654
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1830
1655
  }
1831
- // Renes-Costello-Batina exception-free doubling formula.
1832
- // There is 30% faster Jacobian formula, but it is not complete.
1833
- // https://eprint.iacr.org/2015/1060, algorithm 3
1834
- // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1656
+ // Fast algo for doubling Extended Point.
1657
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1658
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
1835
1659
  double() {
1836
- const { a, b } = CURVE;
1837
- const b3 = Fp2.mul(b, _3n2);
1660
+ const { a } = CURVE;
1838
1661
  const { X: X1, Y: Y1, Z: Z1 } = this;
1839
- let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
1840
- let t0 = Fp2.mul(X1, X1);
1841
- let t1 = Fp2.mul(Y1, Y1);
1842
- let t2 = Fp2.mul(Z1, Z1);
1843
- let t3 = Fp2.mul(X1, Y1);
1844
- t3 = Fp2.add(t3, t3);
1845
- Z3 = Fp2.mul(X1, Z1);
1846
- Z3 = Fp2.add(Z3, Z3);
1847
- X3 = Fp2.mul(a, Z3);
1848
- Y3 = Fp2.mul(b3, t2);
1849
- Y3 = Fp2.add(X3, Y3);
1850
- X3 = Fp2.sub(t1, Y3);
1851
- Y3 = Fp2.add(t1, Y3);
1852
- Y3 = Fp2.mul(X3, Y3);
1853
- X3 = Fp2.mul(t3, X3);
1854
- Z3 = Fp2.mul(b3, Z3);
1855
- t2 = Fp2.mul(a, t2);
1856
- t3 = Fp2.sub(t0, t2);
1857
- t3 = Fp2.mul(a, t3);
1858
- t3 = Fp2.add(t3, Z3);
1859
- Z3 = Fp2.add(t0, t0);
1860
- t0 = Fp2.add(Z3, t0);
1861
- t0 = Fp2.add(t0, t2);
1862
- t0 = Fp2.mul(t0, t3);
1863
- Y3 = Fp2.add(Y3, t0);
1864
- t2 = Fp2.mul(Y1, Z1);
1865
- t2 = Fp2.add(t2, t2);
1866
- t0 = Fp2.mul(t2, t3);
1867
- X3 = Fp2.sub(X3, t0);
1868
- Z3 = Fp2.mul(t2, t1);
1869
- Z3 = Fp2.add(Z3, Z3);
1870
- Z3 = Fp2.add(Z3, Z3);
1871
- return new Point(X3, Y3, Z3);
1662
+ const A = modP(X1 * X1);
1663
+ const B = modP(Y1 * Y1);
1664
+ const C = modP(_2n3 * modP(Z1 * Z1));
1665
+ const D = modP(a * A);
1666
+ const x1y1 = X1 + Y1;
1667
+ const E = modP(modP(x1y1 * x1y1) - A - B);
1668
+ const G = D + B;
1669
+ const F = G - C;
1670
+ const H = D - B;
1671
+ const X3 = modP(E * F);
1672
+ const Y3 = modP(G * H);
1673
+ const T3 = modP(E * H);
1674
+ const Z3 = modP(F * G);
1675
+ return new Point(X3, Y3, Z3, T3);
1872
1676
  }
1873
- // Renes-Costello-Batina exception-free addition formula.
1874
- // There is 30% faster Jacobian formula, but it is not complete.
1875
- // https://eprint.iacr.org/2015/1060, algorithm 1
1876
- // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
1677
+ // Fast algo for adding 2 Extended Points.
1678
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1679
+ // Cost: 9M + 1*a + 1*d + 7add.
1877
1680
  add(other) {
1878
- aprjpoint(other);
1879
- const { X: X1, Y: Y1, Z: Z1 } = this;
1880
- const { X: X2, Y: Y2, Z: Z2 } = other;
1881
- let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
1882
- const a = CURVE.a;
1883
- const b3 = Fp2.mul(CURVE.b, _3n2);
1884
- let t0 = Fp2.mul(X1, X2);
1885
- let t1 = Fp2.mul(Y1, Y2);
1886
- let t2 = Fp2.mul(Z1, Z2);
1887
- let t3 = Fp2.add(X1, Y1);
1888
- let t4 = Fp2.add(X2, Y2);
1889
- t3 = Fp2.mul(t3, t4);
1890
- t4 = Fp2.add(t0, t1);
1891
- t3 = Fp2.sub(t3, t4);
1892
- t4 = Fp2.add(X1, Z1);
1893
- let t5 = Fp2.add(X2, Z2);
1894
- t4 = Fp2.mul(t4, t5);
1895
- t5 = Fp2.add(t0, t2);
1896
- t4 = Fp2.sub(t4, t5);
1897
- t5 = Fp2.add(Y1, Z1);
1898
- X3 = Fp2.add(Y2, Z2);
1899
- t5 = Fp2.mul(t5, X3);
1900
- X3 = Fp2.add(t1, t2);
1901
- t5 = Fp2.sub(t5, X3);
1902
- Z3 = Fp2.mul(a, t4);
1903
- X3 = Fp2.mul(b3, t2);
1904
- Z3 = Fp2.add(X3, Z3);
1905
- X3 = Fp2.sub(t1, Z3);
1906
- Z3 = Fp2.add(t1, Z3);
1907
- Y3 = Fp2.mul(X3, Z3);
1908
- t1 = Fp2.add(t0, t0);
1909
- t1 = Fp2.add(t1, t0);
1910
- t2 = Fp2.mul(a, t2);
1911
- t4 = Fp2.mul(b3, t4);
1912
- t1 = Fp2.add(t1, t2);
1913
- t2 = Fp2.sub(t0, t2);
1914
- t2 = Fp2.mul(a, t2);
1915
- t4 = Fp2.add(t4, t2);
1916
- t0 = Fp2.mul(t1, t4);
1917
- Y3 = Fp2.add(Y3, t0);
1918
- t0 = Fp2.mul(t5, t4);
1919
- X3 = Fp2.mul(t3, X3);
1920
- X3 = Fp2.sub(X3, t0);
1921
- t0 = Fp2.mul(t3, t1);
1922
- Z3 = Fp2.mul(t5, Z3);
1923
- Z3 = Fp2.add(Z3, t0);
1924
- return new Point(X3, Y3, Z3);
1681
+ aextpoint(other);
1682
+ const { a, d } = CURVE;
1683
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1684
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1685
+ const A = modP(X1 * X2);
1686
+ const B = modP(Y1 * Y2);
1687
+ const C = modP(T1 * d * T2);
1688
+ const D = modP(Z1 * Z2);
1689
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1690
+ const F = D - C;
1691
+ const G = D + C;
1692
+ const H = modP(B - a * A);
1693
+ const X3 = modP(E * F);
1694
+ const Y3 = modP(G * H);
1695
+ const T3 = modP(E * H);
1696
+ const Z3 = modP(F * G);
1697
+ return new Point(X3, Y3, Z3, T3);
1925
1698
  }
1926
1699
  subtract(other) {
1927
1700
  return this.add(other.negate());
1928
1701
  }
1929
- is0() {
1930
- return this.equals(Point.ZERO);
1702
+ // Constant-time multiplication.
1703
+ multiply(scalar) {
1704
+ if (!Fn2.isValidNot0(scalar))
1705
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
1706
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1707
+ return normalizeZ(Point, [p, f])[0];
1931
1708
  }
1932
- /**
1933
- * Constant time multiplication.
1934
- * Uses wNAF method. Windowed method may be 10% faster,
1935
- * but takes 2x longer to generate and consumes 2x memory.
1936
- * Uses precomputes when available.
1937
- * Uses endomorphism for Koblitz curves.
1938
- * @param scalar by which the point would be multiplied
1939
- * @returns New point
1940
- */
1941
- multiply(scalar) {
1942
- const { endo: endo2 } = extraOpts;
1943
- if (!Fn2.isValidNot0(scalar))
1944
- throw new Error("invalid scalar: out of range");
1945
- let point, fake;
1946
- const mul = /* @__PURE__ */ __name((n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p)), "mul");
1947
- if (endo2) {
1948
- const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
1949
- const { p: k1p, f: k1f } = mul(k1);
1950
- const { p: k2p, f: k2f } = mul(k2);
1951
- fake = k1f.add(k2f);
1952
- point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
1953
- } else {
1954
- const { p, f } = mul(scalar);
1955
- point = p;
1956
- fake = f;
1957
- }
1958
- return normalizeZ(Point, [point, fake])[0];
1959
- }
1960
- /**
1961
- * Non-constant-time multiplication. Uses double-and-add algorithm.
1962
- * It's faster, but should only be used when you don't care about
1963
- * an exposed secret key e.g. sig verification, which works over *public* keys.
1964
- */
1965
- multiplyUnsafe(sc) {
1966
- const { endo: endo2 } = extraOpts;
1967
- const p = this;
1968
- if (!Fn2.isValid(sc))
1969
- throw new Error("invalid scalar: out of range");
1970
- if (sc === _0n5 || p.is0())
1709
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
1710
+ // It's faster, but should only be used when you don't care about
1711
+ // an exposed private key e.g. sig verification.
1712
+ // Does NOT allow scalars higher than CURVE.n.
1713
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
1714
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
1715
+ if (!Fn2.isValid(scalar))
1716
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
1717
+ if (scalar === _0n5)
1971
1718
  return Point.ZERO;
1972
- if (sc === _1n5)
1973
- return p;
1974
- if (wnaf.hasCache(this))
1975
- return this.multiply(sc);
1976
- if (endo2) {
1977
- const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
1978
- const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
1979
- return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
1980
- } else {
1981
- return wnaf.unsafe(p, sc);
1982
- }
1719
+ if (this.is0() || scalar === _1n5)
1720
+ return this;
1721
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
1983
1722
  }
1984
- multiplyAndAddUnsafe(Q, a, b) {
1985
- const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
1986
- return sum.is0() ? void 0 : sum;
1723
+ // Checks if point is of small order.
1724
+ // If you add something to small order point, you will have "dirty"
1725
+ // point with torsion component.
1726
+ // Multiplies point by cofactor and checks if the result is 0.
1727
+ isSmallOrder() {
1728
+ return this.multiplyUnsafe(cofactor).is0();
1987
1729
  }
1988
- /**
1989
- * Converts Projective point to affine (x, y) coordinates.
1990
- * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
1991
- */
1730
+ // Multiplies point by curve order and checks if the result is 0.
1731
+ // Returns `false` is the point is dirty.
1732
+ isTorsionFree() {
1733
+ return wnaf.unsafe(this, CURVE.n).is0();
1734
+ }
1735
+ // Converts Extended point to default (x, y) coordinates.
1736
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1992
1737
  toAffine(invertedZ) {
1993
1738
  return toAffineMemo(this, invertedZ);
1994
1739
  }
1995
- /**
1996
- * Checks whether Point is free of torsion elements (is in prime subgroup).
1997
- * Always torsion-free for cofactor=1 curves.
1998
- */
1999
- isTorsionFree() {
2000
- const { isTorsionFree } = extraOpts;
2001
- if (cofactor === _1n5)
2002
- return true;
2003
- if (isTorsionFree)
2004
- return isTorsionFree(Point, this);
2005
- return wnaf.unsafe(this, CURVE_ORDER).is0();
2006
- }
2007
1740
  clearCofactor() {
2008
- const { clearCofactor } = extraOpts;
2009
1741
  if (cofactor === _1n5)
2010
1742
  return this;
2011
- if (clearCofactor)
2012
- return clearCofactor(Point, this);
2013
1743
  return this.multiplyUnsafe(cofactor);
2014
1744
  }
2015
- isSmallOrder() {
2016
- return this.multiplyUnsafe(cofactor).is0();
2017
- }
2018
- toBytes(isCompressed = true) {
2019
- _abool2(isCompressed, "isCompressed");
2020
- this.assertValidity();
2021
- return encodePoint(Point, this, isCompressed);
1745
+ toBytes() {
1746
+ const { x, y } = this.toAffine();
1747
+ const bytes = Fp2.toBytes(y);
1748
+ bytes[bytes.length - 1] |= x & _1n5 ? 128 : 0;
1749
+ return bytes;
2022
1750
  }
2023
- toHex(isCompressed = true) {
2024
- return bytesToHex(this.toBytes(isCompressed));
1751
+ toHex() {
1752
+ return bytesToHex(this.toBytes());
2025
1753
  }
2026
1754
  toString() {
2027
1755
  return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2028
1756
  }
2029
1757
  // TODO: remove
2030
- get px() {
1758
+ get ex() {
2031
1759
  return this.X;
2032
1760
  }
2033
- get py() {
2034
- return this.X;
1761
+ get ey() {
1762
+ return this.Y;
2035
1763
  }
2036
- get pz() {
1764
+ get ez() {
2037
1765
  return this.Z;
2038
1766
  }
2039
- toRawBytes(isCompressed = true) {
2040
- return this.toBytes(isCompressed);
2041
- }
2042
- _setWindowSize(windowSize) {
2043
- this.precompute(windowSize);
1767
+ get et() {
1768
+ return this.T;
2044
1769
  }
2045
1770
  static normalizeZ(points) {
2046
1771
  return normalizeZ(Point, points);
@@ -2048,648 +1773,336 @@ function weierstrassN(params, extraOpts = {}) {
2048
1773
  static msm(points, scalars) {
2049
1774
  return pippenger(Point, Fn2, points, scalars);
2050
1775
  }
2051
- static fromPrivateKey(privateKey) {
2052
- return Point.BASE.multiply(_normFnElement(Fn2, privateKey));
1776
+ _setWindowSize(windowSize) {
1777
+ this.precompute(windowSize);
1778
+ }
1779
+ toRawBytes() {
1780
+ return this.toBytes();
2053
1781
  }
2054
1782
  }
2055
- Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE);
2056
- Point.ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO);
1783
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n5, modP(CURVE.Gx * CURVE.Gy));
1784
+ Point.ZERO = new Point(_0n5, _1n5, _1n5, _0n5);
2057
1785
  Point.Fp = Fp2;
2058
1786
  Point.Fn = Fn2;
2059
- const bits = Fn2.BITS;
2060
- const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
1787
+ const wnaf = new wNAF(Point, Fn2.BITS);
2061
1788
  Point.BASE.precompute(8);
2062
1789
  return Point;
2063
1790
  }
2064
- function pprefix(hasEvenY) {
2065
- return Uint8Array.of(hasEvenY ? 2 : 3);
2066
- }
2067
- function getWLengths(Fp2, Fn2) {
2068
- return {
2069
- secretKey: Fn2.BYTES,
2070
- publicKey: 1 + Fp2.BYTES,
2071
- publicKeyUncompressed: 1 + 2 * Fp2.BYTES,
2072
- publicKeyHasPrefix: true,
2073
- signature: 2 * Fn2.BYTES
2074
- };
2075
- }
2076
- function ecdh(Point, ecdhOpts = {}) {
2077
- const { Fn: Fn2 } = Point;
2078
- const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
2079
- const lengths = Object.assign(getWLengths(Point.Fp, Fn2), { seed: getMinHashLength(Fn2.ORDER) });
2080
- function isValidSecretKey(secretKey) {
2081
- try {
2082
- return !!_normFnElement(Fn2, secretKey);
2083
- } catch (error) {
2084
- return false;
2085
- }
1791
+ function eddsa(Point, cHash, eddsaOpts = {}) {
1792
+ if (typeof cHash !== "function")
1793
+ throw new Error('"hash" function param is required');
1794
+ _validateObject(eddsaOpts, {}, {
1795
+ adjustScalarBytes: "function",
1796
+ randomBytes: "function",
1797
+ domain: "function",
1798
+ prehash: "function",
1799
+ mapToCurve: "function"
1800
+ });
1801
+ const { prehash } = eddsaOpts;
1802
+ const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
1803
+ const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
1804
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
1805
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
1806
+ _abool2(phflag, "phflag");
1807
+ if (ctx.length || phflag)
1808
+ throw new Error("Contexts/pre-hash are not supported");
1809
+ return data;
1810
+ });
1811
+ function modN_LE(hash) {
1812
+ return Fn2.create(bytesToNumberLE(hash));
2086
1813
  }
2087
- __name(isValidSecretKey, "isValidSecretKey");
2088
- function isValidPublicKey(publicKey, isCompressed) {
2089
- const { publicKey: comp, publicKeyUncompressed } = lengths;
2090
- try {
2091
- const l = publicKey.length;
2092
- if (isCompressed === true && l !== comp)
2093
- return false;
2094
- if (isCompressed === false && l !== publicKeyUncompressed)
2095
- return false;
2096
- return !!Point.fromBytes(publicKey);
2097
- } catch (error) {
2098
- return false;
2099
- }
1814
+ __name(modN_LE, "modN_LE");
1815
+ function getPrivateScalar(key) {
1816
+ const len = lengths.secretKey;
1817
+ key = ensureBytes("private key", key, len);
1818
+ const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
1819
+ const head = adjustScalarBytes2(hashed.slice(0, len));
1820
+ const prefix = hashed.slice(len, 2 * len);
1821
+ const scalar = modN_LE(head);
1822
+ return { head, prefix, scalar };
2100
1823
  }
2101
- __name(isValidPublicKey, "isValidPublicKey");
2102
- function randomSecretKey(seed = randomBytes_(lengths.seed)) {
2103
- return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn2.ORDER);
1824
+ __name(getPrivateScalar, "getPrivateScalar");
1825
+ function getExtendedPublicKey(secretKey) {
1826
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
1827
+ const point = BASE.multiply(scalar);
1828
+ const pointBytes = point.toBytes();
1829
+ return { head, prefix, scalar, point, pointBytes };
2104
1830
  }
2105
- __name(randomSecretKey, "randomSecretKey");
2106
- function getPublicKey(secretKey, isCompressed = true) {
2107
- return Point.BASE.multiply(_normFnElement(Fn2, secretKey)).toBytes(isCompressed);
1831
+ __name(getExtendedPublicKey, "getExtendedPublicKey");
1832
+ function getPublicKey(secretKey) {
1833
+ return getExtendedPublicKey(secretKey).pointBytes;
2108
1834
  }
2109
1835
  __name(getPublicKey, "getPublicKey");
2110
- function keygen(seed) {
2111
- const secretKey = randomSecretKey(seed);
2112
- return { secretKey, publicKey: getPublicKey(secretKey) };
1836
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
1837
+ const msg = concatBytes(...msgs);
1838
+ return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
2113
1839
  }
2114
- __name(keygen, "keygen");
2115
- function isProbPub(item) {
2116
- if (typeof item === "bigint")
2117
- return false;
2118
- if (item instanceof Point)
2119
- return true;
2120
- const { secretKey, publicKey, publicKeyUncompressed } = lengths;
2121
- if (Fn2.allowedLengths || secretKey === publicKey)
2122
- return void 0;
2123
- const l = ensureBytes("key", item).length;
2124
- return l === publicKey || l === publicKeyUncompressed;
1840
+ __name(hashDomainToScalar, "hashDomainToScalar");
1841
+ function sign(msg, secretKey, options = {}) {
1842
+ msg = ensureBytes("message", msg);
1843
+ if (prehash)
1844
+ msg = prehash(msg);
1845
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
1846
+ const r = hashDomainToScalar(options.context, prefix, msg);
1847
+ const R = BASE.multiply(r).toBytes();
1848
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
1849
+ const s = Fn2.create(r + k * scalar);
1850
+ if (!Fn2.isValid(s))
1851
+ throw new Error("sign failed: invalid s");
1852
+ const rs = concatBytes(R, Fn2.toBytes(s));
1853
+ return _abytes2(rs, lengths.signature, "result");
2125
1854
  }
2126
- __name(isProbPub, "isProbPub");
2127
- function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
2128
- if (isProbPub(secretKeyA) === true)
2129
- throw new Error("first arg must be private key");
2130
- if (isProbPub(publicKeyB) === false)
2131
- throw new Error("second arg must be public key");
2132
- const s = _normFnElement(Fn2, secretKeyA);
2133
- const b = Point.fromHex(publicKeyB);
2134
- return b.multiply(s).toBytes(isCompressed);
1855
+ __name(sign, "sign");
1856
+ const verifyOpts = { zip215: true };
1857
+ function verify(sig, msg, publicKey, options = verifyOpts) {
1858
+ const { context, zip215 } = options;
1859
+ const len = lengths.signature;
1860
+ sig = ensureBytes("signature", sig, len);
1861
+ msg = ensureBytes("message", msg);
1862
+ publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
1863
+ if (zip215 !== void 0)
1864
+ _abool2(zip215, "zip215");
1865
+ if (prehash)
1866
+ msg = prehash(msg);
1867
+ const mid = len / 2;
1868
+ const r = sig.subarray(0, mid);
1869
+ const s = bytesToNumberLE(sig.subarray(mid, len));
1870
+ let A, R, SB;
1871
+ try {
1872
+ A = Point.fromBytes(publicKey, zip215);
1873
+ R = Point.fromBytes(r, zip215);
1874
+ SB = BASE.multiplyUnsafe(s);
1875
+ } catch (error) {
1876
+ return false;
1877
+ }
1878
+ if (!zip215 && A.isSmallOrder())
1879
+ return false;
1880
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
1881
+ const RkA = R.add(A.multiplyUnsafe(k));
1882
+ return RkA.subtract(SB).clearCofactor().is0();
2135
1883
  }
2136
- __name(getSharedSecret, "getSharedSecret");
1884
+ __name(verify, "verify");
1885
+ const _size = Fp2.BYTES;
1886
+ const lengths = {
1887
+ secretKey: _size,
1888
+ publicKey: _size,
1889
+ signature: 2 * _size,
1890
+ seed: _size
1891
+ };
1892
+ function randomSecretKey(seed = randomBytes2(lengths.seed)) {
1893
+ return _abytes2(seed, lengths.seed, "seed");
1894
+ }
1895
+ __name(randomSecretKey, "randomSecretKey");
1896
+ function keygen(seed) {
1897
+ const secretKey = utils.randomSecretKey(seed);
1898
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1899
+ }
1900
+ __name(keygen, "keygen");
1901
+ function isValidSecretKey(key) {
1902
+ return isBytes(key) && key.length === Fn2.BYTES;
1903
+ }
1904
+ __name(isValidSecretKey, "isValidSecretKey");
1905
+ function isValidPublicKey(key, zip215) {
1906
+ try {
1907
+ return !!Point.fromBytes(key, zip215);
1908
+ } catch (error) {
1909
+ return false;
1910
+ }
1911
+ }
1912
+ __name(isValidPublicKey, "isValidPublicKey");
2137
1913
  const utils = {
1914
+ getExtendedPublicKey,
1915
+ randomSecretKey,
2138
1916
  isValidSecretKey,
2139
1917
  isValidPublicKey,
2140
- randomSecretKey,
2141
- // TODO: remove
2142
- isValidPrivateKey: isValidSecretKey,
1918
+ /**
1919
+ * Converts ed public key to x public key. Uses formula:
1920
+ * - ed25519:
1921
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
1922
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
1923
+ * - ed448:
1924
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
1925
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
1926
+ */
1927
+ toMontgomery(publicKey) {
1928
+ const { y } = Point.fromBytes(publicKey);
1929
+ const size = lengths.publicKey;
1930
+ const is25519 = size === 32;
1931
+ if (!is25519 && size !== 57)
1932
+ throw new Error("only defined for 25519 and 448");
1933
+ const u = is25519 ? Fp2.div(_1n5 + y, _1n5 - y) : Fp2.div(y - _1n5, y + _1n5);
1934
+ return Fp2.toBytes(u);
1935
+ },
1936
+ toMontgomeryPriv(secretKey) {
1937
+ const size = lengths.secretKey;
1938
+ _abytes2(secretKey, size);
1939
+ const hashed = cHash(secretKey.subarray(0, size));
1940
+ return adjustScalarBytes2(hashed).subarray(0, size);
1941
+ },
1942
+ /** @deprecated */
2143
1943
  randomPrivateKey: randomSecretKey,
2144
- normPrivateKeyToScalar: /* @__PURE__ */ __name((key) => _normFnElement(Fn2, key), "normPrivateKeyToScalar"),
1944
+ /** @deprecated */
2145
1945
  precompute(windowSize = 8, point = Point.BASE) {
2146
1946
  return point.precompute(windowSize, false);
2147
1947
  }
2148
1948
  };
2149
- return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
2150
- }
2151
- function ecdsa(Point, hash, ecdsaOpts = {}) {
2152
- ahash(hash);
2153
- _validateObject(ecdsaOpts, {}, {
2154
- hmac: "function",
2155
- lowS: "boolean",
2156
- randomBytes: "function",
2157
- bits2int: "function",
2158
- bits2int_modN: "function"
1949
+ return Object.freeze({
1950
+ keygen,
1951
+ getPublicKey,
1952
+ sign,
1953
+ verify,
1954
+ utils,
1955
+ Point,
1956
+ lengths
2159
1957
  });
2160
- const randomBytes2 = ecdsaOpts.randomBytes || randomBytes;
2161
- const hmac2 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
2162
- const { Fp: Fp2, Fn: Fn2 } = Point;
2163
- const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2;
2164
- const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
2165
- const defaultSigOpts = {
2166
- prehash: false,
2167
- lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
2168
- format: void 0,
2169
- //'compact' as ECDSASigFormat,
2170
- extraEntropy: false
1958
+ }
1959
+ function _eddsa_legacy_opts_to_new(c) {
1960
+ const CURVE = {
1961
+ a: c.a,
1962
+ d: c.d,
1963
+ p: c.Fp.ORDER,
1964
+ n: c.n,
1965
+ h: c.h,
1966
+ Gx: c.Gx,
1967
+ Gy: c.Gy
2171
1968
  };
2172
- const defaultSigOpts_format = "compact";
2173
- function isBiggerThanHalfOrder(number) {
2174
- const HALF = CURVE_ORDER >> _1n5;
2175
- return number > HALF;
2176
- }
2177
- __name(isBiggerThanHalfOrder, "isBiggerThanHalfOrder");
2178
- function validateRS(title, num) {
2179
- if (!Fn2.isValidNot0(num))
2180
- throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
2181
- return num;
2182
- }
2183
- __name(validateRS, "validateRS");
2184
- function validateSigLength(bytes, format) {
2185
- validateSigFormat(format);
2186
- const size = lengths.signature;
2187
- const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
2188
- return _abytes2(bytes, sizer, `${format} signature`);
2189
- }
2190
- __name(validateSigLength, "validateSigLength");
2191
- class Signature {
2192
- static {
2193
- __name(this, "Signature");
2194
- }
2195
- constructor(r, s, recovery) {
2196
- this.r = validateRS("r", r);
2197
- this.s = validateRS("s", s);
2198
- if (recovery != null)
2199
- this.recovery = recovery;
2200
- Object.freeze(this);
2201
- }
2202
- static fromBytes(bytes, format = defaultSigOpts_format) {
2203
- validateSigLength(bytes, format);
2204
- let recid;
2205
- if (format === "der") {
2206
- const { r: r2, s: s2 } = DER.toSig(_abytes2(bytes));
2207
- return new Signature(r2, s2);
1969
+ const Fp2 = c.Fp;
1970
+ const Fn2 = Field(CURVE.n, c.nBitLength, true);
1971
+ const curveOpts = { Fp: Fp2, Fn: Fn2, uvRatio: c.uvRatio };
1972
+ const eddsaOpts = {
1973
+ randomBytes: c.randomBytes,
1974
+ adjustScalarBytes: c.adjustScalarBytes,
1975
+ domain: c.domain,
1976
+ prehash: c.prehash,
1977
+ mapToCurve: c.mapToCurve
1978
+ };
1979
+ return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
1980
+ }
1981
+ function _eddsa_new_output_to_legacy(c, eddsa2) {
1982
+ const Point = eddsa2.Point;
1983
+ const legacy = Object.assign({}, eddsa2, {
1984
+ ExtendedPoint: Point,
1985
+ CURVE: c,
1986
+ nBitLength: Point.Fn.BITS,
1987
+ nByteLength: Point.Fn.BYTES
1988
+ });
1989
+ return legacy;
1990
+ }
1991
+ function twistedEdwards(c) {
1992
+ const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
1993
+ const Point = edwards(CURVE, curveOpts);
1994
+ const EDDSA = eddsa(Point, hash, eddsaOpts);
1995
+ return _eddsa_new_output_to_legacy(c, EDDSA);
1996
+ }
1997
+ var _0n5, _1n5, _2n3, _8n2, PrimeEdwardsPoint;
1998
+ var init_edwards = __esm({
1999
+ "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/edwards.js"() {
2000
+ "use strict";
2001
+ init_utils2();
2002
+ init_curve();
2003
+ init_modular();
2004
+ _0n5 = BigInt(0);
2005
+ _1n5 = BigInt(1);
2006
+ _2n3 = BigInt(2);
2007
+ _8n2 = BigInt(8);
2008
+ __name(isEdValidXY, "isEdValidXY");
2009
+ __name(edwards, "edwards");
2010
+ PrimeEdwardsPoint = class {
2011
+ static {
2012
+ __name(this, "PrimeEdwardsPoint");
2208
2013
  }
2209
- if (format === "recovered") {
2210
- recid = bytes[0];
2211
- format = "compact";
2212
- bytes = bytes.subarray(1);
2014
+ constructor(ep) {
2015
+ this.ep = ep;
2213
2016
  }
2214
- const L = Fn2.BYTES;
2215
- const r = bytes.subarray(0, L);
2216
- const s = bytes.subarray(L, L * 2);
2217
- return new Signature(Fn2.fromBytes(r), Fn2.fromBytes(s), recid);
2218
- }
2219
- static fromHex(hex, format) {
2220
- return this.fromBytes(hexToBytes(hex), format);
2221
- }
2222
- addRecoveryBit(recovery) {
2223
- return new Signature(this.r, this.s, recovery);
2224
- }
2225
- recoverPublicKey(messageHash) {
2226
- const FIELD_ORDER = Fp2.ORDER;
2227
- const { r, s, recovery: rec } = this;
2228
- if (rec == null || ![0, 1, 2, 3].includes(rec))
2229
- throw new Error("recovery id invalid");
2230
- const hasCofactor = CURVE_ORDER * _2n3 < FIELD_ORDER;
2231
- if (hasCofactor && rec > 1)
2232
- throw new Error("recovery id is ambiguous for h>1 curve");
2233
- const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
2234
- if (!Fp2.isValid(radj))
2235
- throw new Error("recovery id 2 or 3 invalid");
2236
- const x = Fp2.toBytes(radj);
2237
- const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
2238
- const ir = Fn2.inv(radj);
2239
- const h = bits2int_modN(ensureBytes("msgHash", messageHash));
2240
- const u1 = Fn2.create(-h * ir);
2241
- const u2 = Fn2.create(s * ir);
2242
- const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
2243
- if (Q.is0())
2244
- throw new Error("point at infinify");
2245
- Q.assertValidity();
2246
- return Q;
2247
- }
2248
- // Signatures should be low-s, to prevent malleability.
2249
- hasHighS() {
2250
- return isBiggerThanHalfOrder(this.s);
2251
- }
2252
- toBytes(format = defaultSigOpts_format) {
2253
- validateSigFormat(format);
2254
- if (format === "der")
2255
- return hexToBytes(DER.hexFromSig(this));
2256
- const r = Fn2.toBytes(this.r);
2257
- const s = Fn2.toBytes(this.s);
2258
- if (format === "recovered") {
2259
- if (this.recovery == null)
2260
- throw new Error("recovery bit must be present");
2261
- return concatBytes(Uint8Array.of(this.recovery), r, s);
2017
+ // Static methods that must be implemented by subclasses
2018
+ static fromBytes(_bytes) {
2019
+ notImplemented();
2262
2020
  }
2263
- return concatBytes(r, s);
2264
- }
2265
- toHex(format) {
2266
- return bytesToHex(this.toBytes(format));
2267
- }
2268
- // TODO: remove
2269
- assertValidity() {
2270
- }
2271
- static fromCompact(hex) {
2272
- return Signature.fromBytes(ensureBytes("sig", hex), "compact");
2273
- }
2274
- static fromDER(hex) {
2275
- return Signature.fromBytes(ensureBytes("sig", hex), "der");
2276
- }
2277
- normalizeS() {
2278
- return this.hasHighS() ? new Signature(this.r, Fn2.neg(this.s), this.recovery) : this;
2279
- }
2280
- toDERRawBytes() {
2281
- return this.toBytes("der");
2282
- }
2283
- toDERHex() {
2284
- return bytesToHex(this.toBytes("der"));
2285
- }
2286
- toCompactRawBytes() {
2287
- return this.toBytes("compact");
2288
- }
2289
- toCompactHex() {
2290
- return bytesToHex(this.toBytes("compact"));
2291
- }
2292
- }
2293
- const bits2int = ecdsaOpts.bits2int || /* @__PURE__ */ __name(function bits2int_def(bytes) {
2294
- if (bytes.length > 8192)
2295
- throw new Error("input is too large");
2296
- const num = bytesToNumberBE(bytes);
2297
- const delta = bytes.length * 8 - fnBits;
2298
- return delta > 0 ? num >> BigInt(delta) : num;
2299
- }, "bits2int_def");
2300
- const bits2int_modN = ecdsaOpts.bits2int_modN || /* @__PURE__ */ __name(function bits2int_modN_def(bytes) {
2301
- return Fn2.create(bits2int(bytes));
2302
- }, "bits2int_modN_def");
2303
- const ORDER_MASK = bitMask(fnBits);
2304
- function int2octets(num) {
2305
- aInRange("num < 2^" + fnBits, num, _0n5, ORDER_MASK);
2306
- return Fn2.toBytes(num);
2307
- }
2308
- __name(int2octets, "int2octets");
2309
- function validateMsgAndHash(message, prehash) {
2310
- _abytes2(message, void 0, "message");
2311
- return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
2312
- }
2313
- __name(validateMsgAndHash, "validateMsgAndHash");
2314
- function prepSig(message, privateKey, opts) {
2315
- if (["recovered", "canonical"].some((k) => k in opts))
2316
- throw new Error("sign() legacy options not supported");
2317
- const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
2318
- message = validateMsgAndHash(message, prehash);
2319
- const h1int = bits2int_modN(message);
2320
- const d = _normFnElement(Fn2, privateKey);
2321
- const seedArgs = [int2octets(d), int2octets(h1int)];
2322
- if (extraEntropy != null && extraEntropy !== false) {
2323
- const e = extraEntropy === true ? randomBytes2(lengths.secretKey) : extraEntropy;
2324
- seedArgs.push(ensureBytes("extraEntropy", e));
2325
- }
2326
- const seed = concatBytes(...seedArgs);
2327
- const m = h1int;
2328
- function k2sig(kBytes) {
2329
- const k = bits2int(kBytes);
2330
- if (!Fn2.isValidNot0(k))
2331
- return;
2332
- const ik = Fn2.inv(k);
2333
- const q = Point.BASE.multiply(k).toAffine();
2334
- const r = Fn2.create(q.x);
2335
- if (r === _0n5)
2336
- return;
2337
- const s = Fn2.create(ik * Fn2.create(m + r * d));
2338
- if (s === _0n5)
2339
- return;
2340
- let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n5);
2341
- let normS = s;
2342
- if (lowS && isBiggerThanHalfOrder(s)) {
2343
- normS = Fn2.neg(s);
2344
- recovery ^= 1;
2021
+ static fromHex(_hex) {
2022
+ notImplemented();
2345
2023
  }
2346
- return new Signature(r, normS, recovery);
2347
- }
2348
- __name(k2sig, "k2sig");
2349
- return { seed, k2sig };
2350
- }
2351
- __name(prepSig, "prepSig");
2352
- function sign(message, secretKey, opts = {}) {
2353
- message = ensureBytes("message", message);
2354
- const { seed, k2sig } = prepSig(message, secretKey, opts);
2355
- const drbg = createHmacDrbg(hash.outputLen, Fn2.BYTES, hmac2);
2356
- const sig = drbg(seed, k2sig);
2357
- return sig;
2358
- }
2359
- __name(sign, "sign");
2360
- function tryParsingSig(sg) {
2361
- let sig = void 0;
2362
- const isHex = typeof sg === "string" || isBytes(sg);
2363
- const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
2364
- if (!isHex && !isObj)
2365
- throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
2366
- if (isObj) {
2367
- sig = new Signature(sg.r, sg.s);
2368
- } else if (isHex) {
2369
- try {
2370
- sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
2371
- } catch (derError) {
2372
- if (!(derError instanceof DER.Err))
2373
- throw derError;
2024
+ get x() {
2025
+ return this.toAffine().x;
2374
2026
  }
2375
- if (!sig) {
2376
- try {
2377
- sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
2378
- } catch (error) {
2379
- return false;
2380
- }
2027
+ get y() {
2028
+ return this.toAffine().y;
2381
2029
  }
2382
- }
2383
- if (!sig)
2384
- return false;
2385
- return sig;
2386
- }
2387
- __name(tryParsingSig, "tryParsingSig");
2388
- function verify(signature, message, publicKey, opts = {}) {
2389
- const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
2390
- publicKey = ensureBytes("publicKey", publicKey);
2391
- message = validateMsgAndHash(ensureBytes("message", message), prehash);
2392
- if ("strict" in opts)
2393
- throw new Error("options.strict was renamed to lowS");
2394
- const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
2395
- if (sig === false)
2396
- return false;
2397
- try {
2398
- const P = Point.fromBytes(publicKey);
2399
- if (lowS && sig.hasHighS())
2400
- return false;
2401
- const { r, s } = sig;
2402
- const h = bits2int_modN(message);
2403
- const is = Fn2.inv(s);
2404
- const u1 = Fn2.create(h * is);
2405
- const u2 = Fn2.create(r * is);
2406
- const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
2407
- if (R.is0())
2030
+ // Common implementations
2031
+ clearCofactor() {
2032
+ return this;
2033
+ }
2034
+ assertValidity() {
2035
+ this.ep.assertValidity();
2036
+ }
2037
+ toAffine(invertedZ) {
2038
+ return this.ep.toAffine(invertedZ);
2039
+ }
2040
+ toHex() {
2041
+ return bytesToHex(this.toBytes());
2042
+ }
2043
+ toString() {
2044
+ return this.toHex();
2045
+ }
2046
+ isTorsionFree() {
2047
+ return true;
2048
+ }
2049
+ isSmallOrder() {
2408
2050
  return false;
2409
- const v = Fn2.create(R.x);
2410
- return v === r;
2411
- } catch (e) {
2412
- return false;
2413
- }
2051
+ }
2052
+ add(other) {
2053
+ this.assertSame(other);
2054
+ return this.init(this.ep.add(other.ep));
2055
+ }
2056
+ subtract(other) {
2057
+ this.assertSame(other);
2058
+ return this.init(this.ep.subtract(other.ep));
2059
+ }
2060
+ multiply(scalar) {
2061
+ return this.init(this.ep.multiply(scalar));
2062
+ }
2063
+ multiplyUnsafe(scalar) {
2064
+ return this.init(this.ep.multiplyUnsafe(scalar));
2065
+ }
2066
+ double() {
2067
+ return this.init(this.ep.double());
2068
+ }
2069
+ negate() {
2070
+ return this.init(this.ep.negate());
2071
+ }
2072
+ precompute(windowSize, isLazy) {
2073
+ return this.init(this.ep.precompute(windowSize, isLazy));
2074
+ }
2075
+ /** @deprecated use `toBytes` */
2076
+ toRawBytes() {
2077
+ return this.toBytes();
2078
+ }
2079
+ };
2080
+ __name(eddsa, "eddsa");
2081
+ __name(_eddsa_legacy_opts_to_new, "_eddsa_legacy_opts_to_new");
2082
+ __name(_eddsa_new_output_to_legacy, "_eddsa_new_output_to_legacy");
2083
+ __name(twistedEdwards, "twistedEdwards");
2414
2084
  }
2415
- __name(verify, "verify");
2416
- function recoverPublicKey(signature, message, opts = {}) {
2417
- const { prehash } = validateSigOpts(opts, defaultSigOpts);
2418
- message = validateMsgAndHash(message, prehash);
2419
- return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
2085
+ });
2086
+
2087
+ // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/hash-to-curve.js
2088
+ function i2osp(value, length) {
2089
+ anum(value);
2090
+ anum(length);
2091
+ if (value < 0 || value >= 1 << 8 * length)
2092
+ throw new Error("invalid I2OSP input: " + value);
2093
+ const res = Array.from({ length }).fill(0);
2094
+ for (let i = length - 1; i >= 0; i--) {
2095
+ res[i] = value & 255;
2096
+ value >>>= 8;
2420
2097
  }
2421
- __name(recoverPublicKey, "recoverPublicKey");
2422
- return Object.freeze({
2423
- keygen,
2424
- getPublicKey,
2425
- getSharedSecret,
2426
- utils,
2427
- lengths,
2428
- Point,
2429
- sign,
2430
- verify,
2431
- recoverPublicKey,
2432
- Signature,
2433
- hash
2434
- });
2098
+ return new Uint8Array(res);
2435
2099
  }
2436
- function weierstrassPoints(c) {
2437
- const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
2438
- const Point = weierstrassN(CURVE, curveOpts);
2439
- return _weierstrass_new_output_to_legacy(c, Point);
2440
- }
2441
- function _weierstrass_legacy_opts_to_new(c) {
2442
- const CURVE = {
2443
- a: c.a,
2444
- b: c.b,
2445
- p: c.Fp.ORDER,
2446
- n: c.n,
2447
- h: c.h,
2448
- Gx: c.Gx,
2449
- Gy: c.Gy
2450
- };
2451
- const Fp2 = c.Fp;
2452
- let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
2453
- const Fn2 = Field(CURVE.n, {
2454
- BITS: c.nBitLength,
2455
- allowedLengths,
2456
- modFromBytes: c.wrapPrivateKey
2457
- });
2458
- const curveOpts = {
2459
- Fp: Fp2,
2460
- Fn: Fn2,
2461
- allowInfinityPoint: c.allowInfinityPoint,
2462
- endo: c.endo,
2463
- isTorsionFree: c.isTorsionFree,
2464
- clearCofactor: c.clearCofactor,
2465
- fromBytes: c.fromBytes,
2466
- toBytes: c.toBytes
2467
- };
2468
- return { CURVE, curveOpts };
2469
- }
2470
- function _ecdsa_legacy_opts_to_new(c) {
2471
- const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
2472
- const ecdsaOpts = {
2473
- hmac: c.hmac,
2474
- randomBytes: c.randomBytes,
2475
- lowS: c.lowS,
2476
- bits2int: c.bits2int,
2477
- bits2int_modN: c.bits2int_modN
2478
- };
2479
- return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
2480
- }
2481
- function _legacyHelperEquat(Fp2, a, b) {
2482
- function weierstrassEquation(x) {
2483
- const x2 = Fp2.sqr(x);
2484
- const x3 = Fp2.mul(x2, x);
2485
- return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b);
2486
- }
2487
- __name(weierstrassEquation, "weierstrassEquation");
2488
- return weierstrassEquation;
2489
- }
2490
- function _weierstrass_new_output_to_legacy(c, Point) {
2491
- const { Fp: Fp2, Fn: Fn2 } = Point;
2492
- function isWithinCurveOrder(num) {
2493
- return inRange(num, _1n5, Fn2.ORDER);
2494
- }
2495
- __name(isWithinCurveOrder, "isWithinCurveOrder");
2496
- const weierstrassEquation = _legacyHelperEquat(Fp2, c.a, c.b);
2497
- return Object.assign({}, {
2498
- CURVE: c,
2499
- Point,
2500
- ProjectivePoint: Point,
2501
- normPrivateKeyToScalar: /* @__PURE__ */ __name((key) => _normFnElement(Fn2, key), "normPrivateKeyToScalar"),
2502
- weierstrassEquation,
2503
- isWithinCurveOrder
2504
- });
2505
- }
2506
- function _ecdsa_new_output_to_legacy(c, _ecdsa) {
2507
- const Point = _ecdsa.Point;
2508
- return Object.assign({}, _ecdsa, {
2509
- ProjectivePoint: Point,
2510
- CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
2511
- });
2512
- }
2513
- function weierstrass(c) {
2514
- const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
2515
- const Point = weierstrassN(CURVE, curveOpts);
2516
- const signs = ecdsa(Point, hash, ecdsaOpts);
2517
- return _ecdsa_new_output_to_legacy(c, signs);
2518
- }
2519
- var divNearest, DERErr, DER, _0n5, _1n5, _2n3, _3n2, _4n2;
2520
- var init_weierstrass = __esm({
2521
- "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/weierstrass.js"() {
2522
- "use strict";
2523
- init_hmac();
2524
- init_utils();
2525
- init_utils2();
2526
- init_curve();
2527
- init_modular();
2528
- divNearest = /* @__PURE__ */ __name((num, den) => (num + (num >= 0 ? den : -den) / _2n3) / den, "divNearest");
2529
- __name(_splitEndoScalar, "_splitEndoScalar");
2530
- __name(validateSigFormat, "validateSigFormat");
2531
- __name(validateSigOpts, "validateSigOpts");
2532
- DERErr = class extends Error {
2533
- static {
2534
- __name(this, "DERErr");
2535
- }
2536
- constructor(m = "") {
2537
- super(m);
2538
- }
2539
- };
2540
- DER = {
2541
- // asn.1 DER encoding utils
2542
- Err: DERErr,
2543
- // Basic building block is TLV (Tag-Length-Value)
2544
- _tlv: {
2545
- encode: /* @__PURE__ */ __name((tag, data) => {
2546
- const { Err: E } = DER;
2547
- if (tag < 0 || tag > 256)
2548
- throw new E("tlv.encode: wrong tag");
2549
- if (data.length & 1)
2550
- throw new E("tlv.encode: unpadded data");
2551
- const dataLen = data.length / 2;
2552
- const len = numberToHexUnpadded(dataLen);
2553
- if (len.length / 2 & 128)
2554
- throw new E("tlv.encode: long form length too big");
2555
- const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
2556
- const t = numberToHexUnpadded(tag);
2557
- return t + lenLen + len + data;
2558
- }, "encode"),
2559
- // v - value, l - left bytes (unparsed)
2560
- decode(tag, data) {
2561
- const { Err: E } = DER;
2562
- let pos = 0;
2563
- if (tag < 0 || tag > 256)
2564
- throw new E("tlv.encode: wrong tag");
2565
- if (data.length < 2 || data[pos++] !== tag)
2566
- throw new E("tlv.decode: wrong tlv");
2567
- const first = data[pos++];
2568
- const isLong = !!(first & 128);
2569
- let length = 0;
2570
- if (!isLong)
2571
- length = first;
2572
- else {
2573
- const lenLen = first & 127;
2574
- if (!lenLen)
2575
- throw new E("tlv.decode(long): indefinite length not supported");
2576
- if (lenLen > 4)
2577
- throw new E("tlv.decode(long): byte length is too big");
2578
- const lengthBytes = data.subarray(pos, pos + lenLen);
2579
- if (lengthBytes.length !== lenLen)
2580
- throw new E("tlv.decode: length bytes not complete");
2581
- if (lengthBytes[0] === 0)
2582
- throw new E("tlv.decode(long): zero leftmost byte");
2583
- for (const b of lengthBytes)
2584
- length = length << 8 | b;
2585
- pos += lenLen;
2586
- if (length < 128)
2587
- throw new E("tlv.decode(long): not minimal encoding");
2588
- }
2589
- const v = data.subarray(pos, pos + length);
2590
- if (v.length !== length)
2591
- throw new E("tlv.decode: wrong value length");
2592
- return { v, l: data.subarray(pos + length) };
2593
- }
2594
- },
2595
- // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
2596
- // since we always use positive integers here. It must always be empty:
2597
- // - add zero byte if exists
2598
- // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
2599
- _int: {
2600
- encode(num) {
2601
- const { Err: E } = DER;
2602
- if (num < _0n5)
2603
- throw new E("integer: negative integers are not allowed");
2604
- let hex = numberToHexUnpadded(num);
2605
- if (Number.parseInt(hex[0], 16) & 8)
2606
- hex = "00" + hex;
2607
- if (hex.length & 1)
2608
- throw new E("unexpected DER parsing assertion: unpadded hex");
2609
- return hex;
2610
- },
2611
- decode(data) {
2612
- const { Err: E } = DER;
2613
- if (data[0] & 128)
2614
- throw new E("invalid signature integer: negative");
2615
- if (data[0] === 0 && !(data[1] & 128))
2616
- throw new E("invalid signature integer: unnecessary leading zero");
2617
- return bytesToNumberBE(data);
2618
- }
2619
- },
2620
- toSig(hex) {
2621
- const { Err: E, _int: int, _tlv: tlv } = DER;
2622
- const data = ensureBytes("signature", hex);
2623
- const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
2624
- if (seqLeftBytes.length)
2625
- throw new E("invalid signature: left bytes after parsing");
2626
- const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
2627
- const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
2628
- if (sLeftBytes.length)
2629
- throw new E("invalid signature: left bytes after parsing");
2630
- return { r: int.decode(rBytes), s: int.decode(sBytes) };
2631
- },
2632
- hexFromSig(sig) {
2633
- const { _tlv: tlv, _int: int } = DER;
2634
- const rs = tlv.encode(2, int.encode(sig.r));
2635
- const ss = tlv.encode(2, int.encode(sig.s));
2636
- const seq = rs + ss;
2637
- return tlv.encode(48, seq);
2638
- }
2639
- };
2640
- _0n5 = BigInt(0);
2641
- _1n5 = BigInt(1);
2642
- _2n3 = BigInt(2);
2643
- _3n2 = BigInt(3);
2644
- _4n2 = BigInt(4);
2645
- __name(_normFnElement, "_normFnElement");
2646
- __name(weierstrassN, "weierstrassN");
2647
- __name(pprefix, "pprefix");
2648
- __name(getWLengths, "getWLengths");
2649
- __name(ecdh, "ecdh");
2650
- __name(ecdsa, "ecdsa");
2651
- __name(weierstrassPoints, "weierstrassPoints");
2652
- __name(_weierstrass_legacy_opts_to_new, "_weierstrass_legacy_opts_to_new");
2653
- __name(_ecdsa_legacy_opts_to_new, "_ecdsa_legacy_opts_to_new");
2654
- __name(_legacyHelperEquat, "_legacyHelperEquat");
2655
- __name(_weierstrass_new_output_to_legacy, "_weierstrass_new_output_to_legacy");
2656
- __name(_ecdsa_new_output_to_legacy, "_ecdsa_new_output_to_legacy");
2657
- __name(weierstrass, "weierstrass");
2658
- }
2659
- });
2660
-
2661
- // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/_shortw_utils.js
2662
- function createCurve(curveDef, defHash) {
2663
- const create = /* @__PURE__ */ __name((hash) => weierstrass({ ...curveDef, hash }), "create");
2664
- return { ...create(defHash), create };
2665
- }
2666
- var init_shortw_utils = __esm({
2667
- "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/_shortw_utils.js"() {
2668
- "use strict";
2669
- init_weierstrass();
2670
- __name(createCurve, "createCurve");
2671
- }
2672
- });
2673
-
2674
- // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/hash-to-curve.js
2675
- function i2osp(value, length) {
2676
- anum(value);
2677
- anum(length);
2678
- if (value < 0 || value >= 1 << 8 * length)
2679
- throw new Error("invalid I2OSP input: " + value);
2680
- const res = Array.from({ length }).fill(0);
2681
- for (let i = length - 1; i >= 0; i--) {
2682
- res[i] = value & 255;
2683
- value >>>= 8;
2684
- }
2685
- return new Uint8Array(res);
2686
- }
2687
- function strxor(a, b) {
2688
- const arr = new Uint8Array(a.length);
2689
- for (let i = 0; i < a.length; i++) {
2690
- arr[i] = a[i] ^ b[i];
2691
- }
2692
- return arr;
2100
+ function strxor(a, b) {
2101
+ const arr = new Uint8Array(a.length);
2102
+ for (let i = 0; i < a.length; i++) {
2103
+ arr[i] = a[i] ^ b[i];
2104
+ }
2105
+ return arr;
2693
2106
  }
2694
2107
  function anum(item) {
2695
2108
  if (!Number.isSafeInteger(item))
@@ -2840,520 +2253,1218 @@ var init_hash_to_curve = __esm({
2840
2253
  }
2841
2254
  });
2842
2255
 
2843
- // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/secp256k1.js
2844
- function sqrtMod(y) {
2845
- const P = secp256k1_CURVE.p;
2846
- const _3n4 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
2847
- const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
2848
- const b2 = y * y * y % P;
2849
- const b3 = b2 * b2 * y % P;
2850
- const b6 = pow2(b3, _3n4, P) * b3 % P;
2851
- const b9 = pow2(b6, _3n4, P) * b3 % P;
2852
- const b11 = pow2(b9, _2n4, P) * b2 % P;
2853
- const b22 = pow2(b11, _11n, P) * b11 % P;
2854
- const b44 = pow2(b22, _22n, P) * b22 % P;
2855
- const b88 = pow2(b44, _44n, P) * b44 % P;
2856
- const b176 = pow2(b88, _88n, P) * b88 % P;
2857
- const b220 = pow2(b176, _44n, P) * b44 % P;
2858
- const b223 = pow2(b220, _3n4, P) * b3 % P;
2859
- const t1 = pow2(b223, _23n, P) * b22 % P;
2860
- const t2 = pow2(t1, _6n, P) * b2 % P;
2861
- const root = pow2(t2, _2n4, P);
2862
- if (!Fpk1.eql(Fpk1.sqr(root), y))
2863
- throw new Error("Cannot find square root");
2864
- return root;
2256
+ // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/ed25519.js
2257
+ function ed25519_pow_2_252_3(x) {
2258
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2259
+ const P = ed25519_CURVE_p;
2260
+ const x2 = x * x % P;
2261
+ const b2 = x2 * x % P;
2262
+ const b4 = pow2(b2, _2n4, P) * b2 % P;
2263
+ const b5 = pow2(b4, _1n6, P) * x % P;
2264
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
2265
+ const b20 = pow2(b10, _10n, P) * b10 % P;
2266
+ const b40 = pow2(b20, _20n, P) * b20 % P;
2267
+ const b80 = pow2(b40, _40n, P) * b40 % P;
2268
+ const b160 = pow2(b80, _80n, P) * b80 % P;
2269
+ const b240 = pow2(b160, _80n, P) * b80 % P;
2270
+ const b250 = pow2(b240, _10n, P) * b10 % P;
2271
+ const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
2272
+ return { pow_p_5_8, b2 };
2865
2273
  }
2866
- var secp256k1_CURVE, secp256k1_ENDO, _2n4, Fpk1, secp256k1;
2867
- var init_secp256k1 = __esm({
2868
- "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/secp256k1.js"() {
2274
+ function adjustScalarBytes(bytes) {
2275
+ bytes[0] &= 248;
2276
+ bytes[31] &= 127;
2277
+ bytes[31] |= 64;
2278
+ return bytes;
2279
+ }
2280
+ function uvRatio(u, v) {
2281
+ const P = ed25519_CURVE_p;
2282
+ const v3 = mod(v * v * v, P);
2283
+ const v7 = mod(v3 * v3 * v, P);
2284
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2285
+ let x = mod(u * v3 * pow, P);
2286
+ const vx2 = mod(v * x * x, P);
2287
+ const root1 = x;
2288
+ const root2 = mod(x * ED25519_SQRT_M1, P);
2289
+ const useRoot1 = vx2 === u;
2290
+ const useRoot2 = vx2 === mod(-u, P);
2291
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2292
+ if (useRoot1)
2293
+ x = root1;
2294
+ if (useRoot2 || noRoot)
2295
+ x = root2;
2296
+ if (isNegativeLE(x, P))
2297
+ x = mod(-x, P);
2298
+ return { isValid: useRoot1 || useRoot2, value: x };
2299
+ }
2300
+ function calcElligatorRistrettoMap(r0) {
2301
+ const { d } = ed25519_CURVE;
2302
+ const P = ed25519_CURVE_p;
2303
+ const mod2 = /* @__PURE__ */ __name((n) => Fp.create(n), "mod");
2304
+ const r = mod2(SQRT_M1 * r0 * r0);
2305
+ const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
2306
+ let c = BigInt(-1);
2307
+ const D = mod2((c - d * r) * mod2(r + d));
2308
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
2309
+ let s_ = mod2(s * r0);
2310
+ if (!isNegativeLE(s_, P))
2311
+ s_ = mod2(-s_);
2312
+ if (!Ns_D_is_sq)
2313
+ s = s_;
2314
+ if (!Ns_D_is_sq)
2315
+ c = r;
2316
+ const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2317
+ const s2 = s * s;
2318
+ const W0 = mod2((s + s) * D);
2319
+ const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2320
+ const W2 = mod2(_1n6 - s2);
2321
+ const W3 = mod2(_1n6 + s2);
2322
+ return new ed25519.Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2323
+ }
2324
+ function ristretto255_map(bytes) {
2325
+ abytes(bytes, 64);
2326
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2327
+ const R1 = calcElligatorRistrettoMap(r1);
2328
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2329
+ const R2 = calcElligatorRistrettoMap(r2);
2330
+ return new _RistrettoPoint(R1.add(R2));
2331
+ }
2332
+ var _0n6, _1n6, _2n4, _3n2, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, Fp, Fn, ed25519Defaults, ed25519, SQRT_M1, SQRT_AD_MINUS_ONE, INVSQRT_A_MINUS_D, ONE_MINUS_D_SQ, D_MINUS_ONE_SQ, invertSqrt, MAX_255B, bytes255ToNumberLE, _RistrettoPoint;
2333
+ var init_ed25519 = __esm({
2334
+ "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/ed25519.js"() {
2869
2335
  "use strict";
2870
2336
  init_sha2();
2871
- init_shortw_utils();
2337
+ init_utils();
2338
+ init_curve();
2339
+ init_edwards();
2872
2340
  init_modular();
2873
- secp256k1_CURVE = {
2874
- p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
2875
- n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
2876
- h: BigInt(1),
2877
- a: BigInt(0),
2878
- b: BigInt(7),
2879
- Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
2880
- Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
2881
- };
2882
- secp256k1_ENDO = {
2883
- beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
2884
- basises: [
2885
- [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
2886
- [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
2887
- ]
2341
+ init_utils2();
2342
+ _0n6 = /* @__PURE__ */ BigInt(0);
2343
+ _1n6 = BigInt(1);
2344
+ _2n4 = BigInt(2);
2345
+ _3n2 = BigInt(3);
2346
+ _5n2 = BigInt(5);
2347
+ _8n3 = BigInt(8);
2348
+ ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2349
+ ed25519_CURVE = /* @__PURE__ */ (() => ({
2350
+ p: ed25519_CURVE_p,
2351
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
2352
+ h: _8n3,
2353
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
2354
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
2355
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2356
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2357
+ }))();
2358
+ __name(ed25519_pow_2_252_3, "ed25519_pow_2_252_3");
2359
+ __name(adjustScalarBytes, "adjustScalarBytes");
2360
+ ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2361
+ __name(uvRatio, "uvRatio");
2362
+ Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
2363
+ Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
2364
+ ed25519Defaults = /* @__PURE__ */ (() => ({
2365
+ ...ed25519_CURVE,
2366
+ Fp,
2367
+ hash: sha512,
2368
+ adjustScalarBytes,
2369
+ // dom2
2370
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
2371
+ // Constant-time, u/√v
2372
+ uvRatio
2373
+ }))();
2374
+ ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
2375
+ SQRT_M1 = ED25519_SQRT_M1;
2376
+ SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
2377
+ INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
2378
+ ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
2379
+ D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
2380
+ invertSqrt = /* @__PURE__ */ __name((number) => uvRatio(_1n6, number), "invertSqrt");
2381
+ MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2382
+ bytes255ToNumberLE = /* @__PURE__ */ __name((bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B), "bytes255ToNumberLE");
2383
+ __name(calcElligatorRistrettoMap, "calcElligatorRistrettoMap");
2384
+ __name(ristretto255_map, "ristretto255_map");
2385
+ _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2386
+ static {
2387
+ __name(this, "_RistrettoPoint");
2388
+ }
2389
+ constructor(ep) {
2390
+ super(ep);
2391
+ }
2392
+ static fromAffine(ap) {
2393
+ return new __RistrettoPoint(ed25519.Point.fromAffine(ap));
2394
+ }
2395
+ assertSame(other) {
2396
+ if (!(other instanceof __RistrettoPoint))
2397
+ throw new Error("RistrettoPoint expected");
2398
+ }
2399
+ init(ep) {
2400
+ return new __RistrettoPoint(ep);
2401
+ }
2402
+ /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
2403
+ static hashToCurve(hex) {
2404
+ return ristretto255_map(ensureBytes("ristrettoHash", hex, 64));
2405
+ }
2406
+ static fromBytes(bytes) {
2407
+ abytes(bytes, 32);
2408
+ const { a, d } = ed25519_CURVE;
2409
+ const P = ed25519_CURVE_p;
2410
+ const mod2 = /* @__PURE__ */ __name((n) => Fp.create(n), "mod");
2411
+ const s = bytes255ToNumberLE(bytes);
2412
+ if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2413
+ throw new Error("invalid ristretto255 encoding 1");
2414
+ const s2 = mod2(s * s);
2415
+ const u1 = mod2(_1n6 + a * s2);
2416
+ const u2 = mod2(_1n6 - a * s2);
2417
+ const u1_2 = mod2(u1 * u1);
2418
+ const u2_2 = mod2(u2 * u2);
2419
+ const v = mod2(a * d * u1_2 - u2_2);
2420
+ const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2421
+ const Dx = mod2(I * u2);
2422
+ const Dy = mod2(I * Dx * v);
2423
+ let x = mod2((s + s) * Dx);
2424
+ if (isNegativeLE(x, P))
2425
+ x = mod2(-x);
2426
+ const y = mod2(u1 * Dy);
2427
+ const t = mod2(x * y);
2428
+ if (!isValid || isNegativeLE(t, P) || y === _0n6)
2429
+ throw new Error("invalid ristretto255 encoding 2");
2430
+ return new __RistrettoPoint(new ed25519.Point(x, y, _1n6, t));
2431
+ }
2432
+ /**
2433
+ * Converts ristretto-encoded string to ristretto point.
2434
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2435
+ * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2436
+ */
2437
+ static fromHex(hex) {
2438
+ return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex, 32));
2439
+ }
2440
+ static msm(points, scalars) {
2441
+ return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
2442
+ }
2443
+ /**
2444
+ * Encodes ristretto point to Uint8Array.
2445
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2446
+ */
2447
+ toBytes() {
2448
+ let { X, Y, Z, T } = this.ep;
2449
+ const P = ed25519_CURVE_p;
2450
+ const mod2 = /* @__PURE__ */ __name((n) => Fp.create(n), "mod");
2451
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2452
+ const u2 = mod2(X * Y);
2453
+ const u2sq = mod2(u2 * u2);
2454
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2455
+ const D1 = mod2(invsqrt * u1);
2456
+ const D2 = mod2(invsqrt * u2);
2457
+ const zInv = mod2(D1 * D2 * T);
2458
+ let D;
2459
+ if (isNegativeLE(T * zInv, P)) {
2460
+ let _x = mod2(Y * SQRT_M1);
2461
+ let _y = mod2(X * SQRT_M1);
2462
+ X = _x;
2463
+ Y = _y;
2464
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
2465
+ } else {
2466
+ D = D2;
2467
+ }
2468
+ if (isNegativeLE(X * zInv, P))
2469
+ Y = mod2(-Y);
2470
+ let s = mod2((Z - Y) * D);
2471
+ if (isNegativeLE(s, P))
2472
+ s = mod2(-s);
2473
+ return Fp.toBytes(s);
2474
+ }
2475
+ /**
2476
+ * Compares two Ristretto points.
2477
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2478
+ */
2479
+ equals(other) {
2480
+ this.assertSame(other);
2481
+ const { X: X1, Y: Y1 } = this.ep;
2482
+ const { X: X2, Y: Y2 } = other.ep;
2483
+ const mod2 = /* @__PURE__ */ __name((n) => Fp.create(n), "mod");
2484
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2485
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2486
+ return one || two;
2487
+ }
2488
+ is0() {
2489
+ return this.equals(__RistrettoPoint.ZERO);
2490
+ }
2888
2491
  };
2889
- _2n4 = /* @__PURE__ */ BigInt(2);
2890
- __name(sqrtMod, "sqrtMod");
2891
- Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
2892
- secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
2492
+ _RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
2493
+ _RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
2494
+ _RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
2495
+ _RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
2893
2496
  }
2894
2497
  });
2895
2498
 
2896
- // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/edwards.js
2897
- function isEdValidXY(Fp2, CURVE, x, y) {
2898
- const x2 = Fp2.sqr(x);
2899
- const y2 = Fp2.sqr(y);
2900
- const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
2901
- const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
2902
- return Fp2.eql(left, right);
2903
- }
2904
- function edwards(params, extraOpts = {}) {
2905
- const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
2906
- const { Fp: Fp2, Fn: Fn2 } = validated;
2907
- let CURVE = validated.CURVE;
2908
- const { h: cofactor } = CURVE;
2909
- _validateObject(extraOpts, {}, { uvRatio: "function" });
2910
- const MASK = _2n5 << BigInt(Fn2.BYTES * 8) - _1n6;
2911
- const modP = /* @__PURE__ */ __name((n) => Fp2.create(n), "modP");
2912
- const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
2499
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
2500
+ var HMAC, hmac;
2501
+ var init_hmac = __esm({
2502
+ "../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js"() {
2503
+ "use strict";
2504
+ init_utils();
2505
+ HMAC = class extends Hash {
2506
+ static {
2507
+ __name(this, "HMAC");
2508
+ }
2509
+ constructor(hash, _key) {
2510
+ super();
2511
+ this.finished = false;
2512
+ this.destroyed = false;
2513
+ ahash(hash);
2514
+ const key = toBytes(_key);
2515
+ this.iHash = hash.create();
2516
+ if (typeof this.iHash.update !== "function")
2517
+ throw new Error("Expected instance of class which extends utils.Hash");
2518
+ this.blockLen = this.iHash.blockLen;
2519
+ this.outputLen = this.iHash.outputLen;
2520
+ const blockLen = this.blockLen;
2521
+ const pad = new Uint8Array(blockLen);
2522
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2523
+ for (let i = 0; i < pad.length; i++)
2524
+ pad[i] ^= 54;
2525
+ this.iHash.update(pad);
2526
+ this.oHash = hash.create();
2527
+ for (let i = 0; i < pad.length; i++)
2528
+ pad[i] ^= 54 ^ 92;
2529
+ this.oHash.update(pad);
2530
+ clean(pad);
2531
+ }
2532
+ update(buf) {
2533
+ aexists(this);
2534
+ this.iHash.update(buf);
2535
+ return this;
2536
+ }
2537
+ digestInto(out) {
2538
+ aexists(this);
2539
+ abytes(out, this.outputLen);
2540
+ this.finished = true;
2541
+ this.iHash.digestInto(out);
2542
+ this.oHash.update(out);
2543
+ this.oHash.digestInto(out);
2544
+ this.destroy();
2545
+ }
2546
+ digest() {
2547
+ const out = new Uint8Array(this.oHash.outputLen);
2548
+ this.digestInto(out);
2549
+ return out;
2550
+ }
2551
+ _cloneInto(to) {
2552
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
2553
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
2554
+ to = to;
2555
+ to.finished = finished;
2556
+ to.destroyed = destroyed;
2557
+ to.blockLen = blockLen;
2558
+ to.outputLen = outputLen;
2559
+ to.oHash = oHash._cloneInto(to.oHash);
2560
+ to.iHash = iHash._cloneInto(to.iHash);
2561
+ return to;
2562
+ }
2563
+ clone() {
2564
+ return this._cloneInto();
2565
+ }
2566
+ destroy() {
2567
+ this.destroyed = true;
2568
+ this.oHash.destroy();
2569
+ this.iHash.destroy();
2570
+ }
2571
+ };
2572
+ hmac = /* @__PURE__ */ __name((hash, key, message) => new HMAC(hash, key).update(message).digest(), "hmac");
2573
+ hmac.create = (hash, key) => new HMAC(hash, key);
2574
+ }
2575
+ });
2576
+
2577
+ // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/weierstrass.js
2578
+ function _splitEndoScalar(k, basis, n) {
2579
+ const [[a1, b1], [a2, b2]] = basis;
2580
+ const c1 = divNearest(b2 * k, n);
2581
+ const c2 = divNearest(-b1 * k, n);
2582
+ let k1 = k - c1 * a1 - c2 * a2;
2583
+ let k2 = -c1 * b1 - c2 * b2;
2584
+ const k1neg = k1 < _0n7;
2585
+ const k2neg = k2 < _0n7;
2586
+ if (k1neg)
2587
+ k1 = -k1;
2588
+ if (k2neg)
2589
+ k2 = -k2;
2590
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n7;
2591
+ if (k1 < _0n7 || k1 >= MAX_NUM || k2 < _0n7 || k2 >= MAX_NUM) {
2592
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
2593
+ }
2594
+ return { k1neg, k1, k2neg, k2 };
2595
+ }
2596
+ function validateSigFormat(format) {
2597
+ if (!["compact", "recovered", "der"].includes(format))
2598
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
2599
+ return format;
2600
+ }
2601
+ function validateSigOpts(opts, def) {
2602
+ const optsn = {};
2603
+ for (let optName of Object.keys(def)) {
2604
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
2605
+ }
2606
+ _abool2(optsn.lowS, "lowS");
2607
+ _abool2(optsn.prehash, "prehash");
2608
+ if (optsn.format !== void 0)
2609
+ validateSigFormat(optsn.format);
2610
+ return optsn;
2611
+ }
2612
+ function _normFnElement(Fn2, key) {
2613
+ const { BYTES: expected } = Fn2;
2614
+ let num;
2615
+ if (typeof key === "bigint") {
2616
+ num = key;
2617
+ } else {
2618
+ let bytes = ensureBytes("private key", key);
2913
2619
  try {
2914
- return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
2915
- } catch (e) {
2916
- return { isValid: false, value: _0n6 };
2620
+ num = Fn2.fromBytes(bytes);
2621
+ } catch (error) {
2622
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
2917
2623
  }
2624
+ }
2625
+ if (!Fn2.isValidNot0(num))
2626
+ throw new Error("invalid private key: out of range [1..N-1]");
2627
+ return num;
2628
+ }
2629
+ function weierstrassN(params, extraOpts = {}) {
2630
+ const validated = _createCurveFields("weierstrass", params, extraOpts);
2631
+ const { Fp: Fp2, Fn: Fn2 } = validated;
2632
+ let CURVE = validated.CURVE;
2633
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
2634
+ _validateObject(extraOpts, {}, {
2635
+ allowInfinityPoint: "boolean",
2636
+ clearCofactor: "function",
2637
+ isTorsionFree: "function",
2638
+ fromBytes: "function",
2639
+ toBytes: "function",
2640
+ endo: "object",
2641
+ wrapPrivateKey: "boolean"
2918
2642
  });
2919
- if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
2643
+ const { endo } = extraOpts;
2644
+ if (endo) {
2645
+ if (!Fp2.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
2646
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
2647
+ }
2648
+ }
2649
+ const lengths = getWLengths(Fp2, Fn2);
2650
+ function assertCompressionIsSupported() {
2651
+ if (!Fp2.isOdd)
2652
+ throw new Error("compression is not supported: Field does not have .isOdd()");
2653
+ }
2654
+ __name(assertCompressionIsSupported, "assertCompressionIsSupported");
2655
+ function pointToBytes(_c, point, isCompressed) {
2656
+ const { x, y } = point.toAffine();
2657
+ const bx = Fp2.toBytes(x);
2658
+ _abool2(isCompressed, "isCompressed");
2659
+ if (isCompressed) {
2660
+ assertCompressionIsSupported();
2661
+ const hasEvenY = !Fp2.isOdd(y);
2662
+ return concatBytes(pprefix(hasEvenY), bx);
2663
+ } else {
2664
+ return concatBytes(Uint8Array.of(4), bx, Fp2.toBytes(y));
2665
+ }
2666
+ }
2667
+ __name(pointToBytes, "pointToBytes");
2668
+ function pointFromBytes(bytes) {
2669
+ _abytes2(bytes, void 0, "Point");
2670
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
2671
+ const length = bytes.length;
2672
+ const head = bytes[0];
2673
+ const tail = bytes.subarray(1);
2674
+ if (length === comp && (head === 2 || head === 3)) {
2675
+ const x = Fp2.fromBytes(tail);
2676
+ if (!Fp2.isValid(x))
2677
+ throw new Error("bad point: is not on curve, wrong x");
2678
+ const y2 = weierstrassEquation(x);
2679
+ let y;
2680
+ try {
2681
+ y = Fp2.sqrt(y2);
2682
+ } catch (sqrtError) {
2683
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
2684
+ throw new Error("bad point: is not on curve, sqrt error" + err);
2685
+ }
2686
+ assertCompressionIsSupported();
2687
+ const isYOdd = Fp2.isOdd(y);
2688
+ const isHeadOdd = (head & 1) === 1;
2689
+ if (isHeadOdd !== isYOdd)
2690
+ y = Fp2.neg(y);
2691
+ return { x, y };
2692
+ } else if (length === uncomp && head === 4) {
2693
+ const L = Fp2.BYTES;
2694
+ const x = Fp2.fromBytes(tail.subarray(0, L));
2695
+ const y = Fp2.fromBytes(tail.subarray(L, L * 2));
2696
+ if (!isValidXY(x, y))
2697
+ throw new Error("bad point: is not on curve");
2698
+ return { x, y };
2699
+ } else {
2700
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
2701
+ }
2702
+ }
2703
+ __name(pointFromBytes, "pointFromBytes");
2704
+ const encodePoint = extraOpts.toBytes || pointToBytes;
2705
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
2706
+ function weierstrassEquation(x) {
2707
+ const x2 = Fp2.sqr(x);
2708
+ const x3 = Fp2.mul(x2, x);
2709
+ return Fp2.add(Fp2.add(x3, Fp2.mul(x, CURVE.a)), CURVE.b);
2710
+ }
2711
+ __name(weierstrassEquation, "weierstrassEquation");
2712
+ function isValidXY(x, y) {
2713
+ const left = Fp2.sqr(y);
2714
+ const right = weierstrassEquation(x);
2715
+ return Fp2.eql(left, right);
2716
+ }
2717
+ __name(isValidXY, "isValidXY");
2718
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
2920
2719
  throw new Error("bad curve params: generator point");
2720
+ const _4a3 = Fp2.mul(Fp2.pow(CURVE.a, _3n3), _4n2);
2721
+ const _27b2 = Fp2.mul(Fp2.sqr(CURVE.b), BigInt(27));
2722
+ if (Fp2.is0(Fp2.add(_4a3, _27b2)))
2723
+ throw new Error("bad curve params: a or b");
2921
2724
  function acoord(title, n, banZero = false) {
2922
- const min = banZero ? _1n6 : _0n6;
2923
- aInRange("coordinate " + title, n, min, MASK);
2725
+ if (!Fp2.isValid(n) || banZero && Fp2.is0(n))
2726
+ throw new Error(`bad point coordinate ${title}`);
2924
2727
  return n;
2925
2728
  }
2926
2729
  __name(acoord, "acoord");
2927
- function aextpoint(other) {
2730
+ function aprjpoint(other) {
2928
2731
  if (!(other instanceof Point))
2929
- throw new Error("ExtendedPoint expected");
2732
+ throw new Error("ProjectivePoint expected");
2930
2733
  }
2931
- __name(aextpoint, "aextpoint");
2734
+ __name(aprjpoint, "aprjpoint");
2735
+ function splitEndoScalarN(k) {
2736
+ if (!endo || !endo.basises)
2737
+ throw new Error("no endo");
2738
+ return _splitEndoScalar(k, endo.basises, Fn2.ORDER);
2739
+ }
2740
+ __name(splitEndoScalarN, "splitEndoScalarN");
2932
2741
  const toAffineMemo = memoized((p, iz) => {
2933
2742
  const { X, Y, Z } = p;
2743
+ if (Fp2.eql(Z, Fp2.ONE))
2744
+ return { x: X, y: Y };
2934
2745
  const is0 = p.is0();
2935
2746
  if (iz == null)
2936
- iz = is0 ? _8n2 : Fp2.inv(Z);
2937
- const x = modP(X * iz);
2938
- const y = modP(Y * iz);
2747
+ iz = is0 ? Fp2.ONE : Fp2.inv(Z);
2748
+ const x = Fp2.mul(X, iz);
2749
+ const y = Fp2.mul(Y, iz);
2939
2750
  const zz = Fp2.mul(Z, iz);
2940
2751
  if (is0)
2941
- return { x: _0n6, y: _1n6 };
2942
- if (zz !== _1n6)
2752
+ return { x: Fp2.ZERO, y: Fp2.ZERO };
2753
+ if (!Fp2.eql(zz, Fp2.ONE))
2943
2754
  throw new Error("invZ was invalid");
2944
2755
  return { x, y };
2945
2756
  });
2946
2757
  const assertValidMemo = memoized((p) => {
2947
- const { a, d } = CURVE;
2948
- if (p.is0())
2949
- throw new Error("bad point: ZERO");
2950
- const { X, Y, Z, T } = p;
2951
- const X2 = modP(X * X);
2952
- const Y2 = modP(Y * Y);
2953
- const Z2 = modP(Z * Z);
2954
- const Z4 = modP(Z2 * Z2);
2955
- const aX2 = modP(X2 * a);
2956
- const left = modP(Z2 * modP(aX2 + Y2));
2957
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
2958
- if (left !== right)
2959
- throw new Error("bad point: equation left != right (1)");
2960
- const XY = modP(X * Y);
2961
- const ZT = modP(Z * T);
2962
- if (XY !== ZT)
2963
- throw new Error("bad point: equation left != right (2)");
2758
+ if (p.is0()) {
2759
+ if (extraOpts.allowInfinityPoint && !Fp2.is0(p.Y))
2760
+ return;
2761
+ throw new Error("bad point: ZERO");
2762
+ }
2763
+ const { x, y } = p.toAffine();
2764
+ if (!Fp2.isValid(x) || !Fp2.isValid(y))
2765
+ throw new Error("bad point: x or y not field elements");
2766
+ if (!isValidXY(x, y))
2767
+ throw new Error("bad point: equation left != right");
2768
+ if (!p.isTorsionFree())
2769
+ throw new Error("bad point: not in prime-order subgroup");
2964
2770
  return true;
2965
2771
  });
2772
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
2773
+ k2p = new Point(Fp2.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
2774
+ k1p = negateCt(k1neg, k1p);
2775
+ k2p = negateCt(k2neg, k2p);
2776
+ return k1p.add(k2p);
2777
+ }
2778
+ __name(finishEndo, "finishEndo");
2966
2779
  class Point {
2967
2780
  static {
2968
2781
  __name(this, "Point");
2969
2782
  }
2970
- constructor(X, Y, Z, T) {
2971
- this.X = acoord("x", X);
2972
- this.Y = acoord("y", Y);
2973
- this.Z = acoord("z", Z, true);
2974
- this.T = acoord("t", T);
2975
- Object.freeze(this);
2783
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2784
+ constructor(X, Y, Z) {
2785
+ this.X = acoord("x", X);
2786
+ this.Y = acoord("y", Y, true);
2787
+ this.Z = acoord("z", Z);
2788
+ Object.freeze(this);
2789
+ }
2790
+ static CURVE() {
2791
+ return CURVE;
2792
+ }
2793
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2794
+ static fromAffine(p) {
2795
+ const { x, y } = p || {};
2796
+ if (!p || !Fp2.isValid(x) || !Fp2.isValid(y))
2797
+ throw new Error("invalid affine point");
2798
+ if (p instanceof Point)
2799
+ throw new Error("projective point not allowed");
2800
+ if (Fp2.is0(x) && Fp2.is0(y))
2801
+ return Point.ZERO;
2802
+ return new Point(x, y, Fp2.ONE);
2803
+ }
2804
+ static fromBytes(bytes) {
2805
+ const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
2806
+ P.assertValidity();
2807
+ return P;
2808
+ }
2809
+ static fromHex(hex) {
2810
+ return Point.fromBytes(ensureBytes("pointHex", hex));
2811
+ }
2812
+ get x() {
2813
+ return this.toAffine().x;
2814
+ }
2815
+ get y() {
2816
+ return this.toAffine().y;
2817
+ }
2818
+ /**
2819
+ *
2820
+ * @param windowSize
2821
+ * @param isLazy true will defer table computation until the first multiplication
2822
+ * @returns
2823
+ */
2824
+ precompute(windowSize = 8, isLazy = true) {
2825
+ wnaf.createCache(this, windowSize);
2826
+ if (!isLazy)
2827
+ this.multiply(_3n3);
2828
+ return this;
2829
+ }
2830
+ // TODO: return `this`
2831
+ /** A point on curve is valid if it conforms to equation. */
2832
+ assertValidity() {
2833
+ assertValidMemo(this);
2834
+ }
2835
+ hasEvenY() {
2836
+ const { y } = this.toAffine();
2837
+ if (!Fp2.isOdd)
2838
+ throw new Error("Field doesn't support isOdd");
2839
+ return !Fp2.isOdd(y);
2840
+ }
2841
+ /** Compare one point to another. */
2842
+ equals(other) {
2843
+ aprjpoint(other);
2844
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2845
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2846
+ const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
2847
+ const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
2848
+ return U1 && U2;
2849
+ }
2850
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
2851
+ negate() {
2852
+ return new Point(this.X, Fp2.neg(this.Y), this.Z);
2853
+ }
2854
+ // Renes-Costello-Batina exception-free doubling formula.
2855
+ // There is 30% faster Jacobian formula, but it is not complete.
2856
+ // https://eprint.iacr.org/2015/1060, algorithm 3
2857
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
2858
+ double() {
2859
+ const { a, b } = CURVE;
2860
+ const b3 = Fp2.mul(b, _3n3);
2861
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2862
+ let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
2863
+ let t0 = Fp2.mul(X1, X1);
2864
+ let t1 = Fp2.mul(Y1, Y1);
2865
+ let t2 = Fp2.mul(Z1, Z1);
2866
+ let t3 = Fp2.mul(X1, Y1);
2867
+ t3 = Fp2.add(t3, t3);
2868
+ Z3 = Fp2.mul(X1, Z1);
2869
+ Z3 = Fp2.add(Z3, Z3);
2870
+ X3 = Fp2.mul(a, Z3);
2871
+ Y3 = Fp2.mul(b3, t2);
2872
+ Y3 = Fp2.add(X3, Y3);
2873
+ X3 = Fp2.sub(t1, Y3);
2874
+ Y3 = Fp2.add(t1, Y3);
2875
+ Y3 = Fp2.mul(X3, Y3);
2876
+ X3 = Fp2.mul(t3, X3);
2877
+ Z3 = Fp2.mul(b3, Z3);
2878
+ t2 = Fp2.mul(a, t2);
2879
+ t3 = Fp2.sub(t0, t2);
2880
+ t3 = Fp2.mul(a, t3);
2881
+ t3 = Fp2.add(t3, Z3);
2882
+ Z3 = Fp2.add(t0, t0);
2883
+ t0 = Fp2.add(Z3, t0);
2884
+ t0 = Fp2.add(t0, t2);
2885
+ t0 = Fp2.mul(t0, t3);
2886
+ Y3 = Fp2.add(Y3, t0);
2887
+ t2 = Fp2.mul(Y1, Z1);
2888
+ t2 = Fp2.add(t2, t2);
2889
+ t0 = Fp2.mul(t2, t3);
2890
+ X3 = Fp2.sub(X3, t0);
2891
+ Z3 = Fp2.mul(t2, t1);
2892
+ Z3 = Fp2.add(Z3, Z3);
2893
+ Z3 = Fp2.add(Z3, Z3);
2894
+ return new Point(X3, Y3, Z3);
2895
+ }
2896
+ // Renes-Costello-Batina exception-free addition formula.
2897
+ // There is 30% faster Jacobian formula, but it is not complete.
2898
+ // https://eprint.iacr.org/2015/1060, algorithm 1
2899
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2900
+ add(other) {
2901
+ aprjpoint(other);
2902
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2903
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2904
+ let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
2905
+ const a = CURVE.a;
2906
+ const b3 = Fp2.mul(CURVE.b, _3n3);
2907
+ let t0 = Fp2.mul(X1, X2);
2908
+ let t1 = Fp2.mul(Y1, Y2);
2909
+ let t2 = Fp2.mul(Z1, Z2);
2910
+ let t3 = Fp2.add(X1, Y1);
2911
+ let t4 = Fp2.add(X2, Y2);
2912
+ t3 = Fp2.mul(t3, t4);
2913
+ t4 = Fp2.add(t0, t1);
2914
+ t3 = Fp2.sub(t3, t4);
2915
+ t4 = Fp2.add(X1, Z1);
2916
+ let t5 = Fp2.add(X2, Z2);
2917
+ t4 = Fp2.mul(t4, t5);
2918
+ t5 = Fp2.add(t0, t2);
2919
+ t4 = Fp2.sub(t4, t5);
2920
+ t5 = Fp2.add(Y1, Z1);
2921
+ X3 = Fp2.add(Y2, Z2);
2922
+ t5 = Fp2.mul(t5, X3);
2923
+ X3 = Fp2.add(t1, t2);
2924
+ t5 = Fp2.sub(t5, X3);
2925
+ Z3 = Fp2.mul(a, t4);
2926
+ X3 = Fp2.mul(b3, t2);
2927
+ Z3 = Fp2.add(X3, Z3);
2928
+ X3 = Fp2.sub(t1, Z3);
2929
+ Z3 = Fp2.add(t1, Z3);
2930
+ Y3 = Fp2.mul(X3, Z3);
2931
+ t1 = Fp2.add(t0, t0);
2932
+ t1 = Fp2.add(t1, t0);
2933
+ t2 = Fp2.mul(a, t2);
2934
+ t4 = Fp2.mul(b3, t4);
2935
+ t1 = Fp2.add(t1, t2);
2936
+ t2 = Fp2.sub(t0, t2);
2937
+ t2 = Fp2.mul(a, t2);
2938
+ t4 = Fp2.add(t4, t2);
2939
+ t0 = Fp2.mul(t1, t4);
2940
+ Y3 = Fp2.add(Y3, t0);
2941
+ t0 = Fp2.mul(t5, t4);
2942
+ X3 = Fp2.mul(t3, X3);
2943
+ X3 = Fp2.sub(X3, t0);
2944
+ t0 = Fp2.mul(t3, t1);
2945
+ Z3 = Fp2.mul(t5, Z3);
2946
+ Z3 = Fp2.add(Z3, t0);
2947
+ return new Point(X3, Y3, Z3);
2948
+ }
2949
+ subtract(other) {
2950
+ return this.add(other.negate());
2951
+ }
2952
+ is0() {
2953
+ return this.equals(Point.ZERO);
2954
+ }
2955
+ /**
2956
+ * Constant time multiplication.
2957
+ * Uses wNAF method. Windowed method may be 10% faster,
2958
+ * but takes 2x longer to generate and consumes 2x memory.
2959
+ * Uses precomputes when available.
2960
+ * Uses endomorphism for Koblitz curves.
2961
+ * @param scalar by which the point would be multiplied
2962
+ * @returns New point
2963
+ */
2964
+ multiply(scalar) {
2965
+ const { endo: endo2 } = extraOpts;
2966
+ if (!Fn2.isValidNot0(scalar))
2967
+ throw new Error("invalid scalar: out of range");
2968
+ let point, fake;
2969
+ const mul = /* @__PURE__ */ __name((n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p)), "mul");
2970
+ if (endo2) {
2971
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
2972
+ const { p: k1p, f: k1f } = mul(k1);
2973
+ const { p: k2p, f: k2f } = mul(k2);
2974
+ fake = k1f.add(k2f);
2975
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
2976
+ } else {
2977
+ const { p, f } = mul(scalar);
2978
+ point = p;
2979
+ fake = f;
2980
+ }
2981
+ return normalizeZ(Point, [point, fake])[0];
2982
+ }
2983
+ /**
2984
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
2985
+ * It's faster, but should only be used when you don't care about
2986
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
2987
+ */
2988
+ multiplyUnsafe(sc) {
2989
+ const { endo: endo2 } = extraOpts;
2990
+ const p = this;
2991
+ if (!Fn2.isValid(sc))
2992
+ throw new Error("invalid scalar: out of range");
2993
+ if (sc === _0n7 || p.is0())
2994
+ return Point.ZERO;
2995
+ if (sc === _1n7)
2996
+ return p;
2997
+ if (wnaf.hasCache(this))
2998
+ return this.multiply(sc);
2999
+ if (endo2) {
3000
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
3001
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
3002
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
3003
+ } else {
3004
+ return wnaf.unsafe(p, sc);
3005
+ }
3006
+ }
3007
+ multiplyAndAddUnsafe(Q, a, b) {
3008
+ const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
3009
+ return sum.is0() ? void 0 : sum;
3010
+ }
3011
+ /**
3012
+ * Converts Projective point to affine (x, y) coordinates.
3013
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
3014
+ */
3015
+ toAffine(invertedZ) {
3016
+ return toAffineMemo(this, invertedZ);
3017
+ }
3018
+ /**
3019
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
3020
+ * Always torsion-free for cofactor=1 curves.
3021
+ */
3022
+ isTorsionFree() {
3023
+ const { isTorsionFree } = extraOpts;
3024
+ if (cofactor === _1n7)
3025
+ return true;
3026
+ if (isTorsionFree)
3027
+ return isTorsionFree(Point, this);
3028
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
3029
+ }
3030
+ clearCofactor() {
3031
+ const { clearCofactor } = extraOpts;
3032
+ if (cofactor === _1n7)
3033
+ return this;
3034
+ if (clearCofactor)
3035
+ return clearCofactor(Point, this);
3036
+ return this.multiplyUnsafe(cofactor);
2976
3037
  }
2977
- static CURVE() {
2978
- return CURVE;
3038
+ isSmallOrder() {
3039
+ return this.multiplyUnsafe(cofactor).is0();
2979
3040
  }
2980
- static fromAffine(p) {
2981
- if (p instanceof Point)
2982
- throw new Error("extended point not allowed");
2983
- const { x, y } = p || {};
2984
- acoord("x", x);
2985
- acoord("y", y);
2986
- return new Point(x, y, _1n6, modP(x * y));
3041
+ toBytes(isCompressed = true) {
3042
+ _abool2(isCompressed, "isCompressed");
3043
+ this.assertValidity();
3044
+ return encodePoint(Point, this, isCompressed);
2987
3045
  }
2988
- // Uses algo from RFC8032 5.1.3.
2989
- static fromBytes(bytes, zip215 = false) {
2990
- const len = Fp2.BYTES;
2991
- const { a, d } = CURVE;
2992
- bytes = copyBytes(_abytes2(bytes, len, "point"));
2993
- _abool2(zip215, "zip215");
2994
- const normed = copyBytes(bytes);
2995
- const lastByte = bytes[len - 1];
2996
- normed[len - 1] = lastByte & ~128;
2997
- const y = bytesToNumberLE(normed);
2998
- const max = zip215 ? MASK : Fp2.ORDER;
2999
- aInRange("point.y", y, _0n6, max);
3000
- const y2 = modP(y * y);
3001
- const u = modP(y2 - _1n6);
3002
- const v = modP(d * y2 - a);
3003
- let { isValid, value: x } = uvRatio2(u, v);
3004
- if (!isValid)
3005
- throw new Error("bad point: invalid y coordinate");
3006
- const isXOdd = (x & _1n6) === _1n6;
3007
- const isLastByteOdd = (lastByte & 128) !== 0;
3008
- if (!zip215 && x === _0n6 && isLastByteOdd)
3009
- throw new Error("bad point: x=0 and x_0=1");
3010
- if (isLastByteOdd !== isXOdd)
3011
- x = modP(-x);
3012
- return Point.fromAffine({ x, y });
3046
+ toHex(isCompressed = true) {
3047
+ return bytesToHex(this.toBytes(isCompressed));
3013
3048
  }
3014
- static fromHex(bytes, zip215 = false) {
3015
- return Point.fromBytes(ensureBytes("point", bytes), zip215);
3049
+ toString() {
3050
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
3016
3051
  }
3017
- get x() {
3018
- return this.toAffine().x;
3052
+ // TODO: remove
3053
+ get px() {
3054
+ return this.X;
3019
3055
  }
3020
- get y() {
3021
- return this.toAffine().y;
3056
+ get py() {
3057
+ return this.X;
3022
3058
  }
3023
- precompute(windowSize = 8, isLazy = true) {
3024
- wnaf.createCache(this, windowSize);
3025
- if (!isLazy)
3026
- this.multiply(_2n5);
3027
- return this;
3059
+ get pz() {
3060
+ return this.Z;
3028
3061
  }
3029
- // Useful in fromAffine() - not for fromBytes(), which always created valid points.
3030
- assertValidity() {
3031
- assertValidMemo(this);
3062
+ toRawBytes(isCompressed = true) {
3063
+ return this.toBytes(isCompressed);
3032
3064
  }
3033
- // Compare one point to another.
3034
- equals(other) {
3035
- aextpoint(other);
3036
- const { X: X1, Y: Y1, Z: Z1 } = this;
3037
- const { X: X2, Y: Y2, Z: Z2 } = other;
3038
- const X1Z2 = modP(X1 * Z2);
3039
- const X2Z1 = modP(X2 * Z1);
3040
- const Y1Z2 = modP(Y1 * Z2);
3041
- const Y2Z1 = modP(Y2 * Z1);
3042
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
3065
+ _setWindowSize(windowSize) {
3066
+ this.precompute(windowSize);
3043
3067
  }
3044
- is0() {
3045
- return this.equals(Point.ZERO);
3068
+ static normalizeZ(points) {
3069
+ return normalizeZ(Point, points);
3046
3070
  }
3047
- negate() {
3048
- return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
3071
+ static msm(points, scalars) {
3072
+ return pippenger(Point, Fn2, points, scalars);
3049
3073
  }
3050
- // Fast algo for doubling Extended Point.
3051
- // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
3052
- // Cost: 4M + 4S + 1*a + 6add + 1*2.
3053
- double() {
3054
- const { a } = CURVE;
3055
- const { X: X1, Y: Y1, Z: Z1 } = this;
3056
- const A = modP(X1 * X1);
3057
- const B = modP(Y1 * Y1);
3058
- const C = modP(_2n5 * modP(Z1 * Z1));
3059
- const D = modP(a * A);
3060
- const x1y1 = X1 + Y1;
3061
- const E = modP(modP(x1y1 * x1y1) - A - B);
3062
- const G = D + B;
3063
- const F = G - C;
3064
- const H = D - B;
3065
- const X3 = modP(E * F);
3066
- const Y3 = modP(G * H);
3067
- const T3 = modP(E * H);
3068
- const Z3 = modP(F * G);
3069
- return new Point(X3, Y3, Z3, T3);
3074
+ static fromPrivateKey(privateKey) {
3075
+ return Point.BASE.multiply(_normFnElement(Fn2, privateKey));
3070
3076
  }
3071
- // Fast algo for adding 2 Extended Points.
3072
- // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
3073
- // Cost: 9M + 1*a + 1*d + 7add.
3074
- add(other) {
3075
- aextpoint(other);
3076
- const { a, d } = CURVE;
3077
- const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
3078
- const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
3079
- const A = modP(X1 * X2);
3080
- const B = modP(Y1 * Y2);
3081
- const C = modP(T1 * d * T2);
3082
- const D = modP(Z1 * Z2);
3083
- const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
3084
- const F = D - C;
3085
- const G = D + C;
3086
- const H = modP(B - a * A);
3087
- const X3 = modP(E * F);
3088
- const Y3 = modP(G * H);
3089
- const T3 = modP(E * H);
3090
- const Z3 = modP(F * G);
3091
- return new Point(X3, Y3, Z3, T3);
3077
+ }
3078
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE);
3079
+ Point.ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO);
3080
+ Point.Fp = Fp2;
3081
+ Point.Fn = Fn2;
3082
+ const bits = Fn2.BITS;
3083
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
3084
+ Point.BASE.precompute(8);
3085
+ return Point;
3086
+ }
3087
+ function pprefix(hasEvenY) {
3088
+ return Uint8Array.of(hasEvenY ? 2 : 3);
3089
+ }
3090
+ function getWLengths(Fp2, Fn2) {
3091
+ return {
3092
+ secretKey: Fn2.BYTES,
3093
+ publicKey: 1 + Fp2.BYTES,
3094
+ publicKeyUncompressed: 1 + 2 * Fp2.BYTES,
3095
+ publicKeyHasPrefix: true,
3096
+ signature: 2 * Fn2.BYTES
3097
+ };
3098
+ }
3099
+ function ecdh(Point, ecdhOpts = {}) {
3100
+ const { Fn: Fn2 } = Point;
3101
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
3102
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn2), { seed: getMinHashLength(Fn2.ORDER) });
3103
+ function isValidSecretKey(secretKey) {
3104
+ try {
3105
+ return !!_normFnElement(Fn2, secretKey);
3106
+ } catch (error) {
3107
+ return false;
3092
3108
  }
3093
- subtract(other) {
3094
- return this.add(other.negate());
3109
+ }
3110
+ __name(isValidSecretKey, "isValidSecretKey");
3111
+ function isValidPublicKey(publicKey, isCompressed) {
3112
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
3113
+ try {
3114
+ const l = publicKey.length;
3115
+ if (isCompressed === true && l !== comp)
3116
+ return false;
3117
+ if (isCompressed === false && l !== publicKeyUncompressed)
3118
+ return false;
3119
+ return !!Point.fromBytes(publicKey);
3120
+ } catch (error) {
3121
+ return false;
3095
3122
  }
3096
- // Constant-time multiplication.
3097
- multiply(scalar) {
3098
- if (!Fn2.isValidNot0(scalar))
3099
- throw new Error("invalid scalar: expected 1 <= sc < curve.n");
3100
- const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
3101
- return normalizeZ(Point, [p, f])[0];
3123
+ }
3124
+ __name(isValidPublicKey, "isValidPublicKey");
3125
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
3126
+ return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn2.ORDER);
3127
+ }
3128
+ __name(randomSecretKey, "randomSecretKey");
3129
+ function getPublicKey(secretKey, isCompressed = true) {
3130
+ return Point.BASE.multiply(_normFnElement(Fn2, secretKey)).toBytes(isCompressed);
3131
+ }
3132
+ __name(getPublicKey, "getPublicKey");
3133
+ function keygen(seed) {
3134
+ const secretKey = randomSecretKey(seed);
3135
+ return { secretKey, publicKey: getPublicKey(secretKey) };
3136
+ }
3137
+ __name(keygen, "keygen");
3138
+ function isProbPub(item) {
3139
+ if (typeof item === "bigint")
3140
+ return false;
3141
+ if (item instanceof Point)
3142
+ return true;
3143
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
3144
+ if (Fn2.allowedLengths || secretKey === publicKey)
3145
+ return void 0;
3146
+ const l = ensureBytes("key", item).length;
3147
+ return l === publicKey || l === publicKeyUncompressed;
3148
+ }
3149
+ __name(isProbPub, "isProbPub");
3150
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
3151
+ if (isProbPub(secretKeyA) === true)
3152
+ throw new Error("first arg must be private key");
3153
+ if (isProbPub(publicKeyB) === false)
3154
+ throw new Error("second arg must be public key");
3155
+ const s = _normFnElement(Fn2, secretKeyA);
3156
+ const b = Point.fromHex(publicKeyB);
3157
+ return b.multiply(s).toBytes(isCompressed);
3158
+ }
3159
+ __name(getSharedSecret, "getSharedSecret");
3160
+ const utils = {
3161
+ isValidSecretKey,
3162
+ isValidPublicKey,
3163
+ randomSecretKey,
3164
+ // TODO: remove
3165
+ isValidPrivateKey: isValidSecretKey,
3166
+ randomPrivateKey: randomSecretKey,
3167
+ normPrivateKeyToScalar: /* @__PURE__ */ __name((key) => _normFnElement(Fn2, key), "normPrivateKeyToScalar"),
3168
+ precompute(windowSize = 8, point = Point.BASE) {
3169
+ return point.precompute(windowSize, false);
3170
+ }
3171
+ };
3172
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
3173
+ }
3174
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
3175
+ ahash(hash);
3176
+ _validateObject(ecdsaOpts, {}, {
3177
+ hmac: "function",
3178
+ lowS: "boolean",
3179
+ randomBytes: "function",
3180
+ bits2int: "function",
3181
+ bits2int_modN: "function"
3182
+ });
3183
+ const randomBytes2 = ecdsaOpts.randomBytes || randomBytes;
3184
+ const hmac2 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
3185
+ const { Fp: Fp2, Fn: Fn2 } = Point;
3186
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2;
3187
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
3188
+ const defaultSigOpts = {
3189
+ prehash: false,
3190
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
3191
+ format: void 0,
3192
+ //'compact' as ECDSASigFormat,
3193
+ extraEntropy: false
3194
+ };
3195
+ const defaultSigOpts_format = "compact";
3196
+ function isBiggerThanHalfOrder(number) {
3197
+ const HALF = CURVE_ORDER >> _1n7;
3198
+ return number > HALF;
3199
+ }
3200
+ __name(isBiggerThanHalfOrder, "isBiggerThanHalfOrder");
3201
+ function validateRS(title, num) {
3202
+ if (!Fn2.isValidNot0(num))
3203
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
3204
+ return num;
3205
+ }
3206
+ __name(validateRS, "validateRS");
3207
+ function validateSigLength(bytes, format) {
3208
+ validateSigFormat(format);
3209
+ const size = lengths.signature;
3210
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
3211
+ return _abytes2(bytes, sizer, `${format} signature`);
3212
+ }
3213
+ __name(validateSigLength, "validateSigLength");
3214
+ class Signature {
3215
+ static {
3216
+ __name(this, "Signature");
3102
3217
  }
3103
- // Non-constant-time multiplication. Uses double-and-add algorithm.
3104
- // It's faster, but should only be used when you don't care about
3105
- // an exposed private key e.g. sig verification.
3106
- // Does NOT allow scalars higher than CURVE.n.
3107
- // Accepts optional accumulator to merge with multiply (important for sparse scalars)
3108
- multiplyUnsafe(scalar, acc = Point.ZERO) {
3109
- if (!Fn2.isValid(scalar))
3110
- throw new Error("invalid scalar: expected 0 <= sc < curve.n");
3111
- if (scalar === _0n6)
3112
- return Point.ZERO;
3113
- if (this.is0() || scalar === _1n6)
3114
- return this;
3115
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
3218
+ constructor(r, s, recovery) {
3219
+ this.r = validateRS("r", r);
3220
+ this.s = validateRS("s", s);
3221
+ if (recovery != null)
3222
+ this.recovery = recovery;
3223
+ Object.freeze(this);
3116
3224
  }
3117
- // Checks if point is of small order.
3118
- // If you add something to small order point, you will have "dirty"
3119
- // point with torsion component.
3120
- // Multiplies point by cofactor and checks if the result is 0.
3121
- isSmallOrder() {
3122
- return this.multiplyUnsafe(cofactor).is0();
3225
+ static fromBytes(bytes, format = defaultSigOpts_format) {
3226
+ validateSigLength(bytes, format);
3227
+ let recid;
3228
+ if (format === "der") {
3229
+ const { r: r2, s: s2 } = DER.toSig(_abytes2(bytes));
3230
+ return new Signature(r2, s2);
3231
+ }
3232
+ if (format === "recovered") {
3233
+ recid = bytes[0];
3234
+ format = "compact";
3235
+ bytes = bytes.subarray(1);
3236
+ }
3237
+ const L = Fn2.BYTES;
3238
+ const r = bytes.subarray(0, L);
3239
+ const s = bytes.subarray(L, L * 2);
3240
+ return new Signature(Fn2.fromBytes(r), Fn2.fromBytes(s), recid);
3123
3241
  }
3124
- // Multiplies point by curve order and checks if the result is 0.
3125
- // Returns `false` is the point is dirty.
3126
- isTorsionFree() {
3127
- return wnaf.unsafe(this, CURVE.n).is0();
3242
+ static fromHex(hex, format) {
3243
+ return this.fromBytes(hexToBytes(hex), format);
3128
3244
  }
3129
- // Converts Extended point to default (x, y) coordinates.
3130
- // Can accept precomputed Z^-1 - for example, from invertBatch.
3131
- toAffine(invertedZ) {
3132
- return toAffineMemo(this, invertedZ);
3245
+ addRecoveryBit(recovery) {
3246
+ return new Signature(this.r, this.s, recovery);
3133
3247
  }
3134
- clearCofactor() {
3135
- if (cofactor === _1n6)
3136
- return this;
3137
- return this.multiplyUnsafe(cofactor);
3248
+ recoverPublicKey(messageHash) {
3249
+ const FIELD_ORDER = Fp2.ORDER;
3250
+ const { r, s, recovery: rec } = this;
3251
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
3252
+ throw new Error("recovery id invalid");
3253
+ const hasCofactor = CURVE_ORDER * _2n5 < FIELD_ORDER;
3254
+ if (hasCofactor && rec > 1)
3255
+ throw new Error("recovery id is ambiguous for h>1 curve");
3256
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
3257
+ if (!Fp2.isValid(radj))
3258
+ throw new Error("recovery id 2 or 3 invalid");
3259
+ const x = Fp2.toBytes(radj);
3260
+ const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
3261
+ const ir = Fn2.inv(radj);
3262
+ const h = bits2int_modN(ensureBytes("msgHash", messageHash));
3263
+ const u1 = Fn2.create(-h * ir);
3264
+ const u2 = Fn2.create(s * ir);
3265
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
3266
+ if (Q.is0())
3267
+ throw new Error("point at infinify");
3268
+ Q.assertValidity();
3269
+ return Q;
3138
3270
  }
3139
- toBytes() {
3140
- const { x, y } = this.toAffine();
3141
- const bytes = Fp2.toBytes(y);
3142
- bytes[bytes.length - 1] |= x & _1n6 ? 128 : 0;
3143
- return bytes;
3271
+ // Signatures should be low-s, to prevent malleability.
3272
+ hasHighS() {
3273
+ return isBiggerThanHalfOrder(this.s);
3144
3274
  }
3145
- toHex() {
3146
- return bytesToHex(this.toBytes());
3275
+ toBytes(format = defaultSigOpts_format) {
3276
+ validateSigFormat(format);
3277
+ if (format === "der")
3278
+ return hexToBytes(DER.hexFromSig(this));
3279
+ const r = Fn2.toBytes(this.r);
3280
+ const s = Fn2.toBytes(this.s);
3281
+ if (format === "recovered") {
3282
+ if (this.recovery == null)
3283
+ throw new Error("recovery bit must be present");
3284
+ return concatBytes(Uint8Array.of(this.recovery), r, s);
3285
+ }
3286
+ return concatBytes(r, s);
3147
3287
  }
3148
- toString() {
3149
- return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
3288
+ toHex(format) {
3289
+ return bytesToHex(this.toBytes(format));
3150
3290
  }
3151
3291
  // TODO: remove
3152
- get ex() {
3153
- return this.X;
3292
+ assertValidity() {
3154
3293
  }
3155
- get ey() {
3156
- return this.Y;
3294
+ static fromCompact(hex) {
3295
+ return Signature.fromBytes(ensureBytes("sig", hex), "compact");
3157
3296
  }
3158
- get ez() {
3159
- return this.Z;
3297
+ static fromDER(hex) {
3298
+ return Signature.fromBytes(ensureBytes("sig", hex), "der");
3160
3299
  }
3161
- get et() {
3162
- return this.T;
3300
+ normalizeS() {
3301
+ return this.hasHighS() ? new Signature(this.r, Fn2.neg(this.s), this.recovery) : this;
3163
3302
  }
3164
- static normalizeZ(points) {
3165
- return normalizeZ(Point, points);
3303
+ toDERRawBytes() {
3304
+ return this.toBytes("der");
3166
3305
  }
3167
- static msm(points, scalars) {
3168
- return pippenger(Point, Fn2, points, scalars);
3306
+ toDERHex() {
3307
+ return bytesToHex(this.toBytes("der"));
3169
3308
  }
3170
- _setWindowSize(windowSize) {
3171
- this.precompute(windowSize);
3309
+ toCompactRawBytes() {
3310
+ return this.toBytes("compact");
3172
3311
  }
3173
- toRawBytes() {
3174
- return this.toBytes();
3312
+ toCompactHex() {
3313
+ return bytesToHex(this.toBytes("compact"));
3175
3314
  }
3176
3315
  }
3177
- Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n6, modP(CURVE.Gx * CURVE.Gy));
3178
- Point.ZERO = new Point(_0n6, _1n6, _1n6, _0n6);
3179
- Point.Fp = Fp2;
3180
- Point.Fn = Fn2;
3181
- const wnaf = new wNAF(Point, Fn2.BITS);
3182
- Point.BASE.precompute(8);
3183
- return Point;
3184
- }
3185
- function eddsa(Point, cHash, eddsaOpts = {}) {
3186
- if (typeof cHash !== "function")
3187
- throw new Error('"hash" function param is required');
3188
- _validateObject(eddsaOpts, {}, {
3189
- adjustScalarBytes: "function",
3190
- randomBytes: "function",
3191
- domain: "function",
3192
- prehash: "function",
3193
- mapToCurve: "function"
3194
- });
3195
- const { prehash } = eddsaOpts;
3196
- const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
3197
- const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
3198
- const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
3199
- const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
3200
- _abool2(phflag, "phflag");
3201
- if (ctx.length || phflag)
3202
- throw new Error("Contexts/pre-hash are not supported");
3203
- return data;
3204
- });
3205
- function modN_LE(hash) {
3206
- return Fn2.create(bytesToNumberLE(hash));
3207
- }
3208
- __name(modN_LE, "modN_LE");
3209
- function getPrivateScalar(key) {
3210
- const len = lengths.secretKey;
3211
- key = ensureBytes("private key", key, len);
3212
- const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
3213
- const head = adjustScalarBytes2(hashed.slice(0, len));
3214
- const prefix = hashed.slice(len, 2 * len);
3215
- const scalar = modN_LE(head);
3216
- return { head, prefix, scalar };
3217
- }
3218
- __name(getPrivateScalar, "getPrivateScalar");
3219
- function getExtendedPublicKey(secretKey) {
3220
- const { head, prefix, scalar } = getPrivateScalar(secretKey);
3221
- const point = BASE.multiply(scalar);
3222
- const pointBytes = point.toBytes();
3223
- return { head, prefix, scalar, point, pointBytes };
3316
+ const bits2int = ecdsaOpts.bits2int || /* @__PURE__ */ __name(function bits2int_def(bytes) {
3317
+ if (bytes.length > 8192)
3318
+ throw new Error("input is too large");
3319
+ const num = bytesToNumberBE(bytes);
3320
+ const delta = bytes.length * 8 - fnBits;
3321
+ return delta > 0 ? num >> BigInt(delta) : num;
3322
+ }, "bits2int_def");
3323
+ const bits2int_modN = ecdsaOpts.bits2int_modN || /* @__PURE__ */ __name(function bits2int_modN_def(bytes) {
3324
+ return Fn2.create(bits2int(bytes));
3325
+ }, "bits2int_modN_def");
3326
+ const ORDER_MASK = bitMask(fnBits);
3327
+ function int2octets(num) {
3328
+ aInRange("num < 2^" + fnBits, num, _0n7, ORDER_MASK);
3329
+ return Fn2.toBytes(num);
3224
3330
  }
3225
- __name(getExtendedPublicKey, "getExtendedPublicKey");
3226
- function getPublicKey(secretKey) {
3227
- return getExtendedPublicKey(secretKey).pointBytes;
3331
+ __name(int2octets, "int2octets");
3332
+ function validateMsgAndHash(message, prehash) {
3333
+ _abytes2(message, void 0, "message");
3334
+ return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
3228
3335
  }
3229
- __name(getPublicKey, "getPublicKey");
3230
- function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
3231
- const msg = concatBytes(...msgs);
3232
- return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
3336
+ __name(validateMsgAndHash, "validateMsgAndHash");
3337
+ function prepSig(message, privateKey, opts) {
3338
+ if (["recovered", "canonical"].some((k) => k in opts))
3339
+ throw new Error("sign() legacy options not supported");
3340
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
3341
+ message = validateMsgAndHash(message, prehash);
3342
+ const h1int = bits2int_modN(message);
3343
+ const d = _normFnElement(Fn2, privateKey);
3344
+ const seedArgs = [int2octets(d), int2octets(h1int)];
3345
+ if (extraEntropy != null && extraEntropy !== false) {
3346
+ const e = extraEntropy === true ? randomBytes2(lengths.secretKey) : extraEntropy;
3347
+ seedArgs.push(ensureBytes("extraEntropy", e));
3348
+ }
3349
+ const seed = concatBytes(...seedArgs);
3350
+ const m = h1int;
3351
+ function k2sig(kBytes) {
3352
+ const k = bits2int(kBytes);
3353
+ if (!Fn2.isValidNot0(k))
3354
+ return;
3355
+ const ik = Fn2.inv(k);
3356
+ const q = Point.BASE.multiply(k).toAffine();
3357
+ const r = Fn2.create(q.x);
3358
+ if (r === _0n7)
3359
+ return;
3360
+ const s = Fn2.create(ik * Fn2.create(m + r * d));
3361
+ if (s === _0n7)
3362
+ return;
3363
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n7);
3364
+ let normS = s;
3365
+ if (lowS && isBiggerThanHalfOrder(s)) {
3366
+ normS = Fn2.neg(s);
3367
+ recovery ^= 1;
3368
+ }
3369
+ return new Signature(r, normS, recovery);
3370
+ }
3371
+ __name(k2sig, "k2sig");
3372
+ return { seed, k2sig };
3233
3373
  }
3234
- __name(hashDomainToScalar, "hashDomainToScalar");
3235
- function sign(msg, secretKey, options = {}) {
3236
- msg = ensureBytes("message", msg);
3237
- if (prehash)
3238
- msg = prehash(msg);
3239
- const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
3240
- const r = hashDomainToScalar(options.context, prefix, msg);
3241
- const R = BASE.multiply(r).toBytes();
3242
- const k = hashDomainToScalar(options.context, R, pointBytes, msg);
3243
- const s = Fn2.create(r + k * scalar);
3244
- if (!Fn2.isValid(s))
3245
- throw new Error("sign failed: invalid s");
3246
- const rs = concatBytes(R, Fn2.toBytes(s));
3247
- return _abytes2(rs, lengths.signature, "result");
3374
+ __name(prepSig, "prepSig");
3375
+ function sign(message, secretKey, opts = {}) {
3376
+ message = ensureBytes("message", message);
3377
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
3378
+ const drbg = createHmacDrbg(hash.outputLen, Fn2.BYTES, hmac2);
3379
+ const sig = drbg(seed, k2sig);
3380
+ return sig;
3248
3381
  }
3249
3382
  __name(sign, "sign");
3250
- const verifyOpts = { zip215: true };
3251
- function verify(sig, msg, publicKey, options = verifyOpts) {
3252
- const { context, zip215 } = options;
3253
- const len = lengths.signature;
3254
- sig = ensureBytes("signature", sig, len);
3255
- msg = ensureBytes("message", msg);
3256
- publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
3257
- if (zip215 !== void 0)
3258
- _abool2(zip215, "zip215");
3259
- if (prehash)
3260
- msg = prehash(msg);
3261
- const mid = len / 2;
3262
- const r = sig.subarray(0, mid);
3263
- const s = bytesToNumberLE(sig.subarray(mid, len));
3264
- let A, R, SB;
3265
- try {
3266
- A = Point.fromBytes(publicKey, zip215);
3267
- R = Point.fromBytes(r, zip215);
3268
- SB = BASE.multiplyUnsafe(s);
3269
- } catch (error) {
3270
- return false;
3383
+ function tryParsingSig(sg) {
3384
+ let sig = void 0;
3385
+ const isHex = typeof sg === "string" || isBytes(sg);
3386
+ const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
3387
+ if (!isHex && !isObj)
3388
+ throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
3389
+ if (isObj) {
3390
+ sig = new Signature(sg.r, sg.s);
3391
+ } else if (isHex) {
3392
+ try {
3393
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
3394
+ } catch (derError) {
3395
+ if (!(derError instanceof DER.Err))
3396
+ throw derError;
3397
+ }
3398
+ if (!sig) {
3399
+ try {
3400
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
3401
+ } catch (error) {
3402
+ return false;
3403
+ }
3404
+ }
3271
3405
  }
3272
- if (!zip215 && A.isSmallOrder())
3406
+ if (!sig)
3273
3407
  return false;
3274
- const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
3275
- const RkA = R.add(A.multiplyUnsafe(k));
3276
- return RkA.subtract(SB).clearCofactor().is0();
3277
- }
3278
- __name(verify, "verify");
3279
- const _size = Fp2.BYTES;
3280
- const lengths = {
3281
- secretKey: _size,
3282
- publicKey: _size,
3283
- signature: 2 * _size,
3284
- seed: _size
3285
- };
3286
- function randomSecretKey(seed = randomBytes2(lengths.seed)) {
3287
- return _abytes2(seed, lengths.seed, "seed");
3288
- }
3289
- __name(randomSecretKey, "randomSecretKey");
3290
- function keygen(seed) {
3291
- const secretKey = utils.randomSecretKey(seed);
3292
- return { secretKey, publicKey: getPublicKey(secretKey) };
3293
- }
3294
- __name(keygen, "keygen");
3295
- function isValidSecretKey(key) {
3296
- return isBytes(key) && key.length === Fn2.BYTES;
3408
+ return sig;
3297
3409
  }
3298
- __name(isValidSecretKey, "isValidSecretKey");
3299
- function isValidPublicKey(key, zip215) {
3410
+ __name(tryParsingSig, "tryParsingSig");
3411
+ function verify(signature, message, publicKey, opts = {}) {
3412
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
3413
+ publicKey = ensureBytes("publicKey", publicKey);
3414
+ message = validateMsgAndHash(ensureBytes("message", message), prehash);
3415
+ if ("strict" in opts)
3416
+ throw new Error("options.strict was renamed to lowS");
3417
+ const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
3418
+ if (sig === false)
3419
+ return false;
3300
3420
  try {
3301
- return !!Point.fromBytes(key, zip215);
3302
- } catch (error) {
3421
+ const P = Point.fromBytes(publicKey);
3422
+ if (lowS && sig.hasHighS())
3423
+ return false;
3424
+ const { r, s } = sig;
3425
+ const h = bits2int_modN(message);
3426
+ const is = Fn2.inv(s);
3427
+ const u1 = Fn2.create(h * is);
3428
+ const u2 = Fn2.create(r * is);
3429
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
3430
+ if (R.is0())
3431
+ return false;
3432
+ const v = Fn2.create(R.x);
3433
+ return v === r;
3434
+ } catch (e) {
3303
3435
  return false;
3304
3436
  }
3305
3437
  }
3306
- __name(isValidPublicKey, "isValidPublicKey");
3307
- const utils = {
3308
- getExtendedPublicKey,
3309
- randomSecretKey,
3310
- isValidSecretKey,
3311
- isValidPublicKey,
3312
- /**
3313
- * Converts ed public key to x public key. Uses formula:
3314
- * - ed25519:
3315
- * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
3316
- * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
3317
- * - ed448:
3318
- * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
3319
- * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
3320
- */
3321
- toMontgomery(publicKey) {
3322
- const { y } = Point.fromBytes(publicKey);
3323
- const size = lengths.publicKey;
3324
- const is25519 = size === 32;
3325
- if (!is25519 && size !== 57)
3326
- throw new Error("only defined for 25519 and 448");
3327
- const u = is25519 ? Fp2.div(_1n6 + y, _1n6 - y) : Fp2.div(y - _1n6, y + _1n6);
3328
- return Fp2.toBytes(u);
3329
- },
3330
- toMontgomeryPriv(secretKey) {
3331
- const size = lengths.secretKey;
3332
- _abytes2(secretKey, size);
3333
- const hashed = cHash(secretKey.subarray(0, size));
3334
- return adjustScalarBytes2(hashed).subarray(0, size);
3335
- },
3336
- /** @deprecated */
3337
- randomPrivateKey: randomSecretKey,
3338
- /** @deprecated */
3339
- precompute(windowSize = 8, point = Point.BASE) {
3340
- return point.precompute(windowSize, false);
3341
- }
3342
- };
3438
+ __name(verify, "verify");
3439
+ function recoverPublicKey(signature, message, opts = {}) {
3440
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
3441
+ message = validateMsgAndHash(message, prehash);
3442
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
3443
+ }
3444
+ __name(recoverPublicKey, "recoverPublicKey");
3343
3445
  return Object.freeze({
3344
3446
  keygen,
3345
3447
  getPublicKey,
3346
- sign,
3347
- verify,
3448
+ getSharedSecret,
3348
3449
  utils,
3450
+ lengths,
3349
3451
  Point,
3350
- lengths
3452
+ sign,
3453
+ verify,
3454
+ recoverPublicKey,
3455
+ Signature,
3456
+ hash
3351
3457
  });
3352
3458
  }
3353
- function _eddsa_legacy_opts_to_new(c) {
3459
+ function weierstrassPoints(c) {
3460
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
3461
+ const Point = weierstrassN(CURVE, curveOpts);
3462
+ return _weierstrass_new_output_to_legacy(c, Point);
3463
+ }
3464
+ function _weierstrass_legacy_opts_to_new(c) {
3354
3465
  const CURVE = {
3355
3466
  a: c.a,
3356
- d: c.d,
3467
+ b: c.b,
3357
3468
  p: c.Fp.ORDER,
3358
3469
  n: c.n,
3359
3470
  h: c.h,
@@ -3361,363 +3472,278 @@ function _eddsa_legacy_opts_to_new(c) {
3361
3472
  Gy: c.Gy
3362
3473
  };
3363
3474
  const Fp2 = c.Fp;
3364
- const Fn2 = Field(CURVE.n, c.nBitLength, true);
3365
- const curveOpts = { Fp: Fp2, Fn: Fn2, uvRatio: c.uvRatio };
3366
- const eddsaOpts = {
3475
+ let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
3476
+ const Fn2 = Field(CURVE.n, {
3477
+ BITS: c.nBitLength,
3478
+ allowedLengths,
3479
+ modFromBytes: c.wrapPrivateKey
3480
+ });
3481
+ const curveOpts = {
3482
+ Fp: Fp2,
3483
+ Fn: Fn2,
3484
+ allowInfinityPoint: c.allowInfinityPoint,
3485
+ endo: c.endo,
3486
+ isTorsionFree: c.isTorsionFree,
3487
+ clearCofactor: c.clearCofactor,
3488
+ fromBytes: c.fromBytes,
3489
+ toBytes: c.toBytes
3490
+ };
3491
+ return { CURVE, curveOpts };
3492
+ }
3493
+ function _ecdsa_legacy_opts_to_new(c) {
3494
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
3495
+ const ecdsaOpts = {
3496
+ hmac: c.hmac,
3367
3497
  randomBytes: c.randomBytes,
3368
- adjustScalarBytes: c.adjustScalarBytes,
3369
- domain: c.domain,
3370
- prehash: c.prehash,
3371
- mapToCurve: c.mapToCurve
3498
+ lowS: c.lowS,
3499
+ bits2int: c.bits2int,
3500
+ bits2int_modN: c.bits2int_modN
3372
3501
  };
3373
- return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
3502
+ return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
3374
3503
  }
3375
- function _eddsa_new_output_to_legacy(c, eddsa2) {
3376
- const Point = eddsa2.Point;
3377
- const legacy = Object.assign({}, eddsa2, {
3378
- ExtendedPoint: Point,
3504
+ function _legacyHelperEquat(Fp2, a, b) {
3505
+ function weierstrassEquation(x) {
3506
+ const x2 = Fp2.sqr(x);
3507
+ const x3 = Fp2.mul(x2, x);
3508
+ return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b);
3509
+ }
3510
+ __name(weierstrassEquation, "weierstrassEquation");
3511
+ return weierstrassEquation;
3512
+ }
3513
+ function _weierstrass_new_output_to_legacy(c, Point) {
3514
+ const { Fp: Fp2, Fn: Fn2 } = Point;
3515
+ function isWithinCurveOrder(num) {
3516
+ return inRange(num, _1n7, Fn2.ORDER);
3517
+ }
3518
+ __name(isWithinCurveOrder, "isWithinCurveOrder");
3519
+ const weierstrassEquation = _legacyHelperEquat(Fp2, c.a, c.b);
3520
+ return Object.assign({}, {
3379
3521
  CURVE: c,
3380
- nBitLength: Point.Fn.BITS,
3381
- nByteLength: Point.Fn.BYTES
3522
+ Point,
3523
+ ProjectivePoint: Point,
3524
+ normPrivateKeyToScalar: /* @__PURE__ */ __name((key) => _normFnElement(Fn2, key), "normPrivateKeyToScalar"),
3525
+ weierstrassEquation,
3526
+ isWithinCurveOrder
3527
+ });
3528
+ }
3529
+ function _ecdsa_new_output_to_legacy(c, _ecdsa) {
3530
+ const Point = _ecdsa.Point;
3531
+ return Object.assign({}, _ecdsa, {
3532
+ ProjectivePoint: Point,
3533
+ CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
3382
3534
  });
3383
- return legacy;
3384
3535
  }
3385
- function twistedEdwards(c) {
3386
- const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
3387
- const Point = edwards(CURVE, curveOpts);
3388
- const EDDSA = eddsa(Point, hash, eddsaOpts);
3389
- return _eddsa_new_output_to_legacy(c, EDDSA);
3536
+ function weierstrass(c) {
3537
+ const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
3538
+ const Point = weierstrassN(CURVE, curveOpts);
3539
+ const signs = ecdsa(Point, hash, ecdsaOpts);
3540
+ return _ecdsa_new_output_to_legacy(c, signs);
3390
3541
  }
3391
- var _0n6, _1n6, _2n5, _8n2, PrimeEdwardsPoint;
3392
- var init_edwards = __esm({
3393
- "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/edwards.js"() {
3542
+ var divNearest, DERErr, DER, _0n7, _1n7, _2n5, _3n3, _4n2;
3543
+ var init_weierstrass = __esm({
3544
+ "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/abstract/weierstrass.js"() {
3394
3545
  "use strict";
3546
+ init_hmac();
3547
+ init_utils();
3395
3548
  init_utils2();
3396
3549
  init_curve();
3397
3550
  init_modular();
3398
- _0n6 = BigInt(0);
3399
- _1n6 = BigInt(1);
3400
- _2n5 = BigInt(2);
3401
- _8n2 = BigInt(8);
3402
- __name(isEdValidXY, "isEdValidXY");
3403
- __name(edwards, "edwards");
3404
- PrimeEdwardsPoint = class {
3551
+ divNearest = /* @__PURE__ */ __name((num, den) => (num + (num >= 0 ? den : -den) / _2n5) / den, "divNearest");
3552
+ __name(_splitEndoScalar, "_splitEndoScalar");
3553
+ __name(validateSigFormat, "validateSigFormat");
3554
+ __name(validateSigOpts, "validateSigOpts");
3555
+ DERErr = class extends Error {
3405
3556
  static {
3406
- __name(this, "PrimeEdwardsPoint");
3407
- }
3408
- constructor(ep) {
3409
- this.ep = ep;
3410
- }
3411
- // Static methods that must be implemented by subclasses
3412
- static fromBytes(_bytes) {
3413
- notImplemented();
3414
- }
3415
- static fromHex(_hex) {
3416
- notImplemented();
3417
- }
3418
- get x() {
3419
- return this.toAffine().x;
3420
- }
3421
- get y() {
3422
- return this.toAffine().y;
3423
- }
3424
- // Common implementations
3425
- clearCofactor() {
3426
- return this;
3427
- }
3428
- assertValidity() {
3429
- this.ep.assertValidity();
3430
- }
3431
- toAffine(invertedZ) {
3432
- return this.ep.toAffine(invertedZ);
3433
- }
3434
- toHex() {
3435
- return bytesToHex(this.toBytes());
3436
- }
3437
- toString() {
3438
- return this.toHex();
3439
- }
3440
- isTorsionFree() {
3441
- return true;
3442
- }
3443
- isSmallOrder() {
3444
- return false;
3445
- }
3446
- add(other) {
3447
- this.assertSame(other);
3448
- return this.init(this.ep.add(other.ep));
3449
- }
3450
- subtract(other) {
3451
- this.assertSame(other);
3452
- return this.init(this.ep.subtract(other.ep));
3453
- }
3454
- multiply(scalar) {
3455
- return this.init(this.ep.multiply(scalar));
3456
- }
3457
- multiplyUnsafe(scalar) {
3458
- return this.init(this.ep.multiplyUnsafe(scalar));
3459
- }
3460
- double() {
3461
- return this.init(this.ep.double());
3462
- }
3463
- negate() {
3464
- return this.init(this.ep.negate());
3465
- }
3466
- precompute(windowSize, isLazy) {
3467
- return this.init(this.ep.precompute(windowSize, isLazy));
3557
+ __name(this, "DERErr");
3468
3558
  }
3469
- /** @deprecated use `toBytes` */
3470
- toRawBytes() {
3471
- return this.toBytes();
3559
+ constructor(m = "") {
3560
+ super(m);
3472
3561
  }
3473
3562
  };
3474
- __name(eddsa, "eddsa");
3475
- __name(_eddsa_legacy_opts_to_new, "_eddsa_legacy_opts_to_new");
3476
- __name(_eddsa_new_output_to_legacy, "_eddsa_new_output_to_legacy");
3477
- __name(twistedEdwards, "twistedEdwards");
3478
- }
3479
- });
3480
-
3481
- // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/ed25519.js
3482
- function ed25519_pow_2_252_3(x) {
3483
- const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
3484
- const P = ed25519_CURVE_p;
3485
- const x2 = x * x % P;
3486
- const b2 = x2 * x % P;
3487
- const b4 = pow2(b2, _2n6, P) * b2 % P;
3488
- const b5 = pow2(b4, _1n7, P) * x % P;
3489
- const b10 = pow2(b5, _5n2, P) * b5 % P;
3490
- const b20 = pow2(b10, _10n, P) * b10 % P;
3491
- const b40 = pow2(b20, _20n, P) * b20 % P;
3492
- const b80 = pow2(b40, _40n, P) * b40 % P;
3493
- const b160 = pow2(b80, _80n, P) * b80 % P;
3494
- const b240 = pow2(b160, _80n, P) * b80 % P;
3495
- const b250 = pow2(b240, _10n, P) * b10 % P;
3496
- const pow_p_5_8 = pow2(b250, _2n6, P) * x % P;
3497
- return { pow_p_5_8, b2 };
3498
- }
3499
- function adjustScalarBytes(bytes) {
3500
- bytes[0] &= 248;
3501
- bytes[31] &= 127;
3502
- bytes[31] |= 64;
3503
- return bytes;
3504
- }
3505
- function uvRatio(u, v) {
3506
- const P = ed25519_CURVE_p;
3507
- const v3 = mod(v * v * v, P);
3508
- const v7 = mod(v3 * v3 * v, P);
3509
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
3510
- let x = mod(u * v3 * pow, P);
3511
- const vx2 = mod(v * x * x, P);
3512
- const root1 = x;
3513
- const root2 = mod(x * ED25519_SQRT_M1, P);
3514
- const useRoot1 = vx2 === u;
3515
- const useRoot2 = vx2 === mod(-u, P);
3516
- const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
3517
- if (useRoot1)
3518
- x = root1;
3519
- if (useRoot2 || noRoot)
3520
- x = root2;
3521
- if (isNegativeLE(x, P))
3522
- x = mod(-x, P);
3523
- return { isValid: useRoot1 || useRoot2, value: x };
3524
- }
3525
- function calcElligatorRistrettoMap(r0) {
3526
- const { d } = ed25519_CURVE;
3527
- const P = ed25519_CURVE_p;
3528
- const mod2 = /* @__PURE__ */ __name((n) => Fp.create(n), "mod");
3529
- const r = mod2(SQRT_M1 * r0 * r0);
3530
- const Ns = mod2((r + _1n7) * ONE_MINUS_D_SQ);
3531
- let c = BigInt(-1);
3532
- const D = mod2((c - d * r) * mod2(r + d));
3533
- let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
3534
- let s_ = mod2(s * r0);
3535
- if (!isNegativeLE(s_, P))
3536
- s_ = mod2(-s_);
3537
- if (!Ns_D_is_sq)
3538
- s = s_;
3539
- if (!Ns_D_is_sq)
3540
- c = r;
3541
- const Nt = mod2(c * (r - _1n7) * D_MINUS_ONE_SQ - D);
3542
- const s2 = s * s;
3543
- const W0 = mod2((s + s) * D);
3544
- const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
3545
- const W2 = mod2(_1n7 - s2);
3546
- const W3 = mod2(_1n7 + s2);
3547
- return new ed25519.Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
3563
+ DER = {
3564
+ // asn.1 DER encoding utils
3565
+ Err: DERErr,
3566
+ // Basic building block is TLV (Tag-Length-Value)
3567
+ _tlv: {
3568
+ encode: /* @__PURE__ */ __name((tag, data) => {
3569
+ const { Err: E } = DER;
3570
+ if (tag < 0 || tag > 256)
3571
+ throw new E("tlv.encode: wrong tag");
3572
+ if (data.length & 1)
3573
+ throw new E("tlv.encode: unpadded data");
3574
+ const dataLen = data.length / 2;
3575
+ const len = numberToHexUnpadded(dataLen);
3576
+ if (len.length / 2 & 128)
3577
+ throw new E("tlv.encode: long form length too big");
3578
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
3579
+ const t = numberToHexUnpadded(tag);
3580
+ return t + lenLen + len + data;
3581
+ }, "encode"),
3582
+ // v - value, l - left bytes (unparsed)
3583
+ decode(tag, data) {
3584
+ const { Err: E } = DER;
3585
+ let pos = 0;
3586
+ if (tag < 0 || tag > 256)
3587
+ throw new E("tlv.encode: wrong tag");
3588
+ if (data.length < 2 || data[pos++] !== tag)
3589
+ throw new E("tlv.decode: wrong tlv");
3590
+ const first = data[pos++];
3591
+ const isLong = !!(first & 128);
3592
+ let length = 0;
3593
+ if (!isLong)
3594
+ length = first;
3595
+ else {
3596
+ const lenLen = first & 127;
3597
+ if (!lenLen)
3598
+ throw new E("tlv.decode(long): indefinite length not supported");
3599
+ if (lenLen > 4)
3600
+ throw new E("tlv.decode(long): byte length is too big");
3601
+ const lengthBytes = data.subarray(pos, pos + lenLen);
3602
+ if (lengthBytes.length !== lenLen)
3603
+ throw new E("tlv.decode: length bytes not complete");
3604
+ if (lengthBytes[0] === 0)
3605
+ throw new E("tlv.decode(long): zero leftmost byte");
3606
+ for (const b of lengthBytes)
3607
+ length = length << 8 | b;
3608
+ pos += lenLen;
3609
+ if (length < 128)
3610
+ throw new E("tlv.decode(long): not minimal encoding");
3611
+ }
3612
+ const v = data.subarray(pos, pos + length);
3613
+ if (v.length !== length)
3614
+ throw new E("tlv.decode: wrong value length");
3615
+ return { v, l: data.subarray(pos + length) };
3616
+ }
3617
+ },
3618
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
3619
+ // since we always use positive integers here. It must always be empty:
3620
+ // - add zero byte if exists
3621
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
3622
+ _int: {
3623
+ encode(num) {
3624
+ const { Err: E } = DER;
3625
+ if (num < _0n7)
3626
+ throw new E("integer: negative integers are not allowed");
3627
+ let hex = numberToHexUnpadded(num);
3628
+ if (Number.parseInt(hex[0], 16) & 8)
3629
+ hex = "00" + hex;
3630
+ if (hex.length & 1)
3631
+ throw new E("unexpected DER parsing assertion: unpadded hex");
3632
+ return hex;
3633
+ },
3634
+ decode(data) {
3635
+ const { Err: E } = DER;
3636
+ if (data[0] & 128)
3637
+ throw new E("invalid signature integer: negative");
3638
+ if (data[0] === 0 && !(data[1] & 128))
3639
+ throw new E("invalid signature integer: unnecessary leading zero");
3640
+ return bytesToNumberBE(data);
3641
+ }
3642
+ },
3643
+ toSig(hex) {
3644
+ const { Err: E, _int: int, _tlv: tlv } = DER;
3645
+ const data = ensureBytes("signature", hex);
3646
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
3647
+ if (seqLeftBytes.length)
3648
+ throw new E("invalid signature: left bytes after parsing");
3649
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
3650
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
3651
+ if (sLeftBytes.length)
3652
+ throw new E("invalid signature: left bytes after parsing");
3653
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
3654
+ },
3655
+ hexFromSig(sig) {
3656
+ const { _tlv: tlv, _int: int } = DER;
3657
+ const rs = tlv.encode(2, int.encode(sig.r));
3658
+ const ss = tlv.encode(2, int.encode(sig.s));
3659
+ const seq = rs + ss;
3660
+ return tlv.encode(48, seq);
3661
+ }
3662
+ };
3663
+ _0n7 = BigInt(0);
3664
+ _1n7 = BigInt(1);
3665
+ _2n5 = BigInt(2);
3666
+ _3n3 = BigInt(3);
3667
+ _4n2 = BigInt(4);
3668
+ __name(_normFnElement, "_normFnElement");
3669
+ __name(weierstrassN, "weierstrassN");
3670
+ __name(pprefix, "pprefix");
3671
+ __name(getWLengths, "getWLengths");
3672
+ __name(ecdh, "ecdh");
3673
+ __name(ecdsa, "ecdsa");
3674
+ __name(weierstrassPoints, "weierstrassPoints");
3675
+ __name(_weierstrass_legacy_opts_to_new, "_weierstrass_legacy_opts_to_new");
3676
+ __name(_ecdsa_legacy_opts_to_new, "_ecdsa_legacy_opts_to_new");
3677
+ __name(_legacyHelperEquat, "_legacyHelperEquat");
3678
+ __name(_weierstrass_new_output_to_legacy, "_weierstrass_new_output_to_legacy");
3679
+ __name(_ecdsa_new_output_to_legacy, "_ecdsa_new_output_to_legacy");
3680
+ __name(weierstrass, "weierstrass");
3681
+ }
3682
+ });
3683
+
3684
+ // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/_shortw_utils.js
3685
+ function createCurve(curveDef, defHash) {
3686
+ const create = /* @__PURE__ */ __name((hash) => weierstrass({ ...curveDef, hash }), "create");
3687
+ return { ...create(defHash), create };
3548
3688
  }
3549
- function ristretto255_map(bytes) {
3550
- abytes(bytes, 64);
3551
- const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
3552
- const R1 = calcElligatorRistrettoMap(r1);
3553
- const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
3554
- const R2 = calcElligatorRistrettoMap(r2);
3555
- return new _RistrettoPoint(R1.add(R2));
3689
+ var init_shortw_utils = __esm({
3690
+ "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/_shortw_utils.js"() {
3691
+ "use strict";
3692
+ init_weierstrass();
3693
+ __name(createCurve, "createCurve");
3694
+ }
3695
+ });
3696
+
3697
+ // ../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/secp256k1.js
3698
+ function sqrtMod(y) {
3699
+ const P = secp256k1_CURVE.p;
3700
+ const _3n4 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
3701
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
3702
+ const b2 = y * y * y % P;
3703
+ const b3 = b2 * b2 * y % P;
3704
+ const b6 = pow2(b3, _3n4, P) * b3 % P;
3705
+ const b9 = pow2(b6, _3n4, P) * b3 % P;
3706
+ const b11 = pow2(b9, _2n6, P) * b2 % P;
3707
+ const b22 = pow2(b11, _11n, P) * b11 % P;
3708
+ const b44 = pow2(b22, _22n, P) * b22 % P;
3709
+ const b88 = pow2(b44, _44n, P) * b44 % P;
3710
+ const b176 = pow2(b88, _88n, P) * b88 % P;
3711
+ const b220 = pow2(b176, _44n, P) * b44 % P;
3712
+ const b223 = pow2(b220, _3n4, P) * b3 % P;
3713
+ const t1 = pow2(b223, _23n, P) * b22 % P;
3714
+ const t2 = pow2(t1, _6n, P) * b2 % P;
3715
+ const root = pow2(t2, _2n6, P);
3716
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
3717
+ throw new Error("Cannot find square root");
3718
+ return root;
3556
3719
  }
3557
- var _0n7, _1n7, _2n6, _3n3, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, Fp, Fn, ed25519Defaults, ed25519, SQRT_M1, SQRT_AD_MINUS_ONE, INVSQRT_A_MINUS_D, ONE_MINUS_D_SQ, D_MINUS_ONE_SQ, invertSqrt, MAX_255B, bytes255ToNumberLE, _RistrettoPoint;
3558
- var init_ed25519 = __esm({
3559
- "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/ed25519.js"() {
3720
+ var secp256k1_CURVE, secp256k1_ENDO, _2n6, Fpk1, secp256k1;
3721
+ var init_secp256k1 = __esm({
3722
+ "../../node_modules/.pnpm/@noble+curves@1.9.6/node_modules/@noble/curves/esm/secp256k1.js"() {
3560
3723
  "use strict";
3561
3724
  init_sha2();
3562
- init_utils();
3563
- init_curve();
3564
- init_edwards();
3725
+ init_shortw_utils();
3565
3726
  init_modular();
3566
- init_utils2();
3567
- _0n7 = /* @__PURE__ */ BigInt(0);
3568
- _1n7 = BigInt(1);
3569
- _2n6 = BigInt(2);
3570
- _3n3 = BigInt(3);
3571
- _5n2 = BigInt(5);
3572
- _8n3 = BigInt(8);
3573
- ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
3574
- ed25519_CURVE = /* @__PURE__ */ (() => ({
3575
- p: ed25519_CURVE_p,
3576
- n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
3577
- h: _8n3,
3578
- a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
3579
- d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
3580
- Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
3581
- Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
3582
- }))();
3583
- __name(ed25519_pow_2_252_3, "ed25519_pow_2_252_3");
3584
- __name(adjustScalarBytes, "adjustScalarBytes");
3585
- ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
3586
- __name(uvRatio, "uvRatio");
3587
- Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
3588
- Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
3589
- ed25519Defaults = /* @__PURE__ */ (() => ({
3590
- ...ed25519_CURVE,
3591
- Fp,
3592
- hash: sha512,
3593
- adjustScalarBytes,
3594
- // dom2
3595
- // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
3596
- // Constant-time, u/√v
3597
- uvRatio
3598
- }))();
3599
- ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
3600
- SQRT_M1 = ED25519_SQRT_M1;
3601
- SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
3602
- INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
3603
- ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
3604
- D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
3605
- invertSqrt = /* @__PURE__ */ __name((number) => uvRatio(_1n7, number), "invertSqrt");
3606
- MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
3607
- bytes255ToNumberLE = /* @__PURE__ */ __name((bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B), "bytes255ToNumberLE");
3608
- __name(calcElligatorRistrettoMap, "calcElligatorRistrettoMap");
3609
- __name(ristretto255_map, "ristretto255_map");
3610
- _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
3611
- static {
3612
- __name(this, "_RistrettoPoint");
3613
- }
3614
- constructor(ep) {
3615
- super(ep);
3616
- }
3617
- static fromAffine(ap) {
3618
- return new __RistrettoPoint(ed25519.Point.fromAffine(ap));
3619
- }
3620
- assertSame(other) {
3621
- if (!(other instanceof __RistrettoPoint))
3622
- throw new Error("RistrettoPoint expected");
3623
- }
3624
- init(ep) {
3625
- return new __RistrettoPoint(ep);
3626
- }
3627
- /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
3628
- static hashToCurve(hex) {
3629
- return ristretto255_map(ensureBytes("ristrettoHash", hex, 64));
3630
- }
3631
- static fromBytes(bytes) {
3632
- abytes(bytes, 32);
3633
- const { a, d } = ed25519_CURVE;
3634
- const P = ed25519_CURVE_p;
3635
- const mod2 = /* @__PURE__ */ __name((n) => Fp.create(n), "mod");
3636
- const s = bytes255ToNumberLE(bytes);
3637
- if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
3638
- throw new Error("invalid ristretto255 encoding 1");
3639
- const s2 = mod2(s * s);
3640
- const u1 = mod2(_1n7 + a * s2);
3641
- const u2 = mod2(_1n7 - a * s2);
3642
- const u1_2 = mod2(u1 * u1);
3643
- const u2_2 = mod2(u2 * u2);
3644
- const v = mod2(a * d * u1_2 - u2_2);
3645
- const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
3646
- const Dx = mod2(I * u2);
3647
- const Dy = mod2(I * Dx * v);
3648
- let x = mod2((s + s) * Dx);
3649
- if (isNegativeLE(x, P))
3650
- x = mod2(-x);
3651
- const y = mod2(u1 * Dy);
3652
- const t = mod2(x * y);
3653
- if (!isValid || isNegativeLE(t, P) || y === _0n7)
3654
- throw new Error("invalid ristretto255 encoding 2");
3655
- return new __RistrettoPoint(new ed25519.Point(x, y, _1n7, t));
3656
- }
3657
- /**
3658
- * Converts ristretto-encoded string to ristretto point.
3659
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
3660
- * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
3661
- */
3662
- static fromHex(hex) {
3663
- return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex, 32));
3664
- }
3665
- static msm(points, scalars) {
3666
- return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
3667
- }
3668
- /**
3669
- * Encodes ristretto point to Uint8Array.
3670
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
3671
- */
3672
- toBytes() {
3673
- let { X, Y, Z, T } = this.ep;
3674
- const P = ed25519_CURVE_p;
3675
- const mod2 = /* @__PURE__ */ __name((n) => Fp.create(n), "mod");
3676
- const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
3677
- const u2 = mod2(X * Y);
3678
- const u2sq = mod2(u2 * u2);
3679
- const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
3680
- const D1 = mod2(invsqrt * u1);
3681
- const D2 = mod2(invsqrt * u2);
3682
- const zInv = mod2(D1 * D2 * T);
3683
- let D;
3684
- if (isNegativeLE(T * zInv, P)) {
3685
- let _x = mod2(Y * SQRT_M1);
3686
- let _y = mod2(X * SQRT_M1);
3687
- X = _x;
3688
- Y = _y;
3689
- D = mod2(D1 * INVSQRT_A_MINUS_D);
3690
- } else {
3691
- D = D2;
3692
- }
3693
- if (isNegativeLE(X * zInv, P))
3694
- Y = mod2(-Y);
3695
- let s = mod2((Z - Y) * D);
3696
- if (isNegativeLE(s, P))
3697
- s = mod2(-s);
3698
- return Fp.toBytes(s);
3699
- }
3700
- /**
3701
- * Compares two Ristretto points.
3702
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
3703
- */
3704
- equals(other) {
3705
- this.assertSame(other);
3706
- const { X: X1, Y: Y1 } = this.ep;
3707
- const { X: X2, Y: Y2 } = other.ep;
3708
- const mod2 = /* @__PURE__ */ __name((n) => Fp.create(n), "mod");
3709
- const one = mod2(X1 * Y2) === mod2(Y1 * X2);
3710
- const two = mod2(Y1 * Y2) === mod2(X1 * X2);
3711
- return one || two;
3712
- }
3713
- is0() {
3714
- return this.equals(__RistrettoPoint.ZERO);
3715
- }
3727
+ secp256k1_CURVE = {
3728
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
3729
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
3730
+ h: BigInt(1),
3731
+ a: BigInt(0),
3732
+ b: BigInt(7),
3733
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
3734
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
3716
3735
  };
3717
- _RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
3718
- _RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
3719
- _RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
3720
- _RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
3736
+ secp256k1_ENDO = {
3737
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
3738
+ basises: [
3739
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
3740
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
3741
+ ]
3742
+ };
3743
+ _2n6 = /* @__PURE__ */ BigInt(2);
3744
+ __name(sqrtMod, "sqrtMod");
3745
+ Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
3746
+ secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
3721
3747
  }
3722
3748
  });
3723
3749
 
@@ -3902,11 +3928,12 @@ export {
3902
3928
  sha3_256,
3903
3929
  keccak_256,
3904
3930
  init_sha3,
3905
- hmac,
3906
- init_hmac,
3907
3931
  sha256,
3908
3932
  sha512,
3933
+ sha384,
3909
3934
  init_sha2,
3935
+ hmac,
3936
+ init_hmac,
3910
3937
  bytesToNumberBE,
3911
3938
  ensureBytes,
3912
3939
  bitLen,
@@ -3928,12 +3955,14 @@ export {
3928
3955
  weierstrassPoints,
3929
3956
  weierstrass,
3930
3957
  init_weierstrass,
3958
+ createCurve,
3959
+ init_shortw_utils,
3931
3960
  createHasher2 as createHasher,
3932
3961
  init_hash_to_curve,
3933
- secp256k1,
3934
- init_secp256k1,
3935
3962
  ed25519,
3936
3963
  init_ed25519,
3964
+ secp256k1,
3965
+ init_secp256k1,
3937
3966
  import_index,
3938
3967
  eventemitter3_default,
3939
3968
  init_eventemitter3
@@ -3949,19 +3978,19 @@ export {
3949
3978
  @noble/curves/esm/abstract/curve.js:
3950
3979
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3951
3980
 
3952
- @noble/curves/esm/abstract/weierstrass.js:
3981
+ @noble/curves/esm/abstract/edwards.js:
3953
3982
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3954
3983
 
3955
- @noble/curves/esm/_shortw_utils.js:
3984
+ @noble/curves/esm/ed25519.js:
3956
3985
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3957
3986
 
3958
- @noble/curves/esm/secp256k1.js:
3987
+ @noble/curves/esm/abstract/weierstrass.js:
3959
3988
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3960
3989
 
3961
- @noble/curves/esm/abstract/edwards.js:
3990
+ @noble/curves/esm/_shortw_utils.js:
3962
3991
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3963
3992
 
3964
- @noble/curves/esm/ed25519.js:
3993
+ @noble/curves/esm/secp256k1.js:
3965
3994
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3966
3995
  */
3967
- //# sourceMappingURL=chunk-X3SSOBOF.js.map
3996
+ //# sourceMappingURL=chunk-WYM4IYMI.js.map