@blockrun/llm 0.2.0 → 0.2.1

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.
@@ -7517,15 +7517,16 @@ var require_public_api = __commonJS({
7517
7517
  }
7518
7518
  });
7519
7519
 
7520
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/constants.js
7520
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/constants.js
7521
7521
  var require_constants = __commonJS({
7522
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/constants.js"(exports, module) {
7522
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/constants.js"(exports, module) {
7523
7523
  "use strict";
7524
7524
  var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
7525
7525
  var hasBlob = typeof Blob !== "undefined";
7526
7526
  if (hasBlob) BINARY_TYPES.push("blob");
7527
7527
  module.exports = {
7528
7528
  BINARY_TYPES,
7529
+ CLOSE_TIMEOUT: 3e4,
7529
7530
  EMPTY_BUFFER: Buffer.alloc(0),
7530
7531
  GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
7531
7532
  hasBlob,
@@ -7753,9 +7754,9 @@ var require_bufferutil = __commonJS({
7753
7754
  }
7754
7755
  });
7755
7756
 
7756
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/buffer-util.js
7757
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/buffer-util.js
7757
7758
  var require_buffer_util = __commonJS({
7758
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/buffer-util.js"(exports, module) {
7759
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/buffer-util.js"(exports, module) {
7759
7760
  "use strict";
7760
7761
  var { EMPTY_BUFFER } = require_constants();
7761
7762
  var FastBuffer = Buffer[Symbol.species];
@@ -7828,9 +7829,9 @@ var require_buffer_util = __commonJS({
7828
7829
  }
7829
7830
  });
7830
7831
 
7831
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/limiter.js
7832
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/limiter.js
7832
7833
  var require_limiter = __commonJS({
7833
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/limiter.js"(exports, module) {
7834
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/limiter.js"(exports, module) {
7834
7835
  "use strict";
7835
7836
  var kDone = /* @__PURE__ */ Symbol("kDone");
7836
7837
  var kRun = /* @__PURE__ */ Symbol("kRun");
@@ -7878,9 +7879,9 @@ var require_limiter = __commonJS({
7878
7879
  }
7879
7880
  });
7880
7881
 
7881
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/permessage-deflate.js
7882
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/permessage-deflate.js
7882
7883
  var require_permessage_deflate = __commonJS({
7883
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
7884
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
7884
7885
  "use strict";
7885
7886
  var zlib2 = __require("zlib");
7886
7887
  var bufferUtil = require_buffer_util();
@@ -8310,9 +8311,9 @@ var require_utf_8_validate = __commonJS({
8310
8311
  }
8311
8312
  });
8312
8313
 
8313
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/validation.js
8314
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/validation.js
8314
8315
  var require_validation = __commonJS({
8315
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/validation.js"(exports, module) {
8316
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/validation.js"(exports, module) {
8316
8317
  "use strict";
8317
8318
  var { isUtf8 } = __require("buffer");
8318
8319
  var { hasBlob } = require_constants();
@@ -8511,9 +8512,9 @@ var require_validation = __commonJS({
8511
8512
  }
8512
8513
  });
8513
8514
 
8514
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/receiver.js
8515
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/receiver.js
8515
8516
  var require_receiver = __commonJS({
8516
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/receiver.js"(exports, module) {
8517
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/receiver.js"(exports, module) {
8517
8518
  "use strict";
8518
8519
  var { Writable } = __require("stream");
8519
8520
  var PerMessageDeflate = require_permessage_deflate();
@@ -9103,9 +9104,9 @@ var require_receiver = __commonJS({
9103
9104
  }
9104
9105
  });
9105
9106
 
9106
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/sender.js
9107
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/sender.js
9107
9108
  var require_sender = __commonJS({
9108
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/sender.js"(exports, module) {
9109
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/sender.js"(exports, module) {
9109
9110
  "use strict";
9110
9111
  var { Duplex } = __require("stream");
9111
9112
  var { randomFillSync } = __require("crypto");
@@ -9591,9 +9592,9 @@ var require_sender = __commonJS({
9591
9592
  }
9592
9593
  });
9593
9594
 
9594
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/event-target.js
9595
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/event-target.js
9595
9596
  var require_event_target = __commonJS({
9596
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/event-target.js"(exports, module) {
9597
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/event-target.js"(exports, module) {
9597
9598
  "use strict";
9598
9599
  var { kForOnEventAttribute, kListener } = require_constants();
9599
9600
  var kCode = /* @__PURE__ */ Symbol("kCode");
@@ -9820,9 +9821,9 @@ var require_event_target = __commonJS({
9820
9821
  }
9821
9822
  });
9822
9823
 
9823
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/extension.js
9824
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/extension.js
9824
9825
  var require_extension = __commonJS({
9825
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/extension.js"(exports, module) {
9826
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/extension.js"(exports, module) {
9826
9827
  "use strict";
9827
9828
  var { tokenChars } = require_validation();
9828
9829
  function push(dest, name, elem) {
@@ -9973,9 +9974,9 @@ var require_extension = __commonJS({
9973
9974
  }
9974
9975
  });
9975
9976
 
9976
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/websocket.js
9977
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/websocket.js
9977
9978
  var require_websocket = __commonJS({
9978
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/websocket.js"(exports, module) {
9979
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/websocket.js"(exports, module) {
9979
9980
  "use strict";
9980
9981
  var EventEmitter2 = __require("events");
9981
9982
  var https2 = __require("https");
@@ -9991,6 +9992,7 @@ var require_websocket = __commonJS({
9991
9992
  var { isBlob: isBlob2 } = require_validation();
9992
9993
  var {
9993
9994
  BINARY_TYPES,
9995
+ CLOSE_TIMEOUT,
9994
9996
  EMPTY_BUFFER,
9995
9997
  GUID,
9996
9998
  kForOnEventAttribute,
@@ -10004,7 +10006,6 @@ var require_websocket = __commonJS({
10004
10006
  } = require_event_target();
10005
10007
  var { format, parse: parse2 } = require_extension();
10006
10008
  var { toBuffer: toBuffer2 } = require_buffer_util();
10007
- var closeTimeout = 30 * 1e3;
10008
10009
  var kAborted = /* @__PURE__ */ Symbol("kAborted");
10009
10010
  var protocolVersions = [8, 13];
10010
10011
  var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
@@ -10050,6 +10051,7 @@ var require_websocket = __commonJS({
10050
10051
  initAsClient(this, address, protocols, options);
10051
10052
  } else {
10052
10053
  this._autoPong = options.autoPong;
10054
+ this._closeTimeout = options.closeTimeout;
10053
10055
  this._isServer = true;
10054
10056
  }
10055
10057
  }
@@ -10451,6 +10453,7 @@ var require_websocket = __commonJS({
10451
10453
  const opts = {
10452
10454
  allowSynchronousEvents: true,
10453
10455
  autoPong: true,
10456
+ closeTimeout: CLOSE_TIMEOUT,
10454
10457
  protocolVersion: protocolVersions[1],
10455
10458
  maxPayload: 100 * 1024 * 1024,
10456
10459
  skipUTF8Validation: false,
@@ -10468,6 +10471,7 @@ var require_websocket = __commonJS({
10468
10471
  port: void 0
10469
10472
  };
10470
10473
  websocket._autoPong = opts.autoPong;
10474
+ websocket._closeTimeout = opts.closeTimeout;
10471
10475
  if (!protocolVersions.includes(opts.protocolVersion)) {
10472
10476
  throw new RangeError(
10473
10477
  `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
@@ -10810,7 +10814,7 @@ var require_websocket = __commonJS({
10810
10814
  function setCloseTimer(websocket) {
10811
10815
  websocket._closeTimer = setTimeout(
10812
10816
  websocket._socket.destroy.bind(websocket._socket),
10813
- closeTimeout
10817
+ websocket._closeTimeout
10814
10818
  );
10815
10819
  }
10816
10820
  function socketOnClose() {
@@ -10819,8 +10823,8 @@ var require_websocket = __commonJS({
10819
10823
  this.removeListener("data", socketOnData);
10820
10824
  this.removeListener("end", socketOnEnd);
10821
10825
  websocket._readyState = WebSocket3.CLOSING;
10822
- let chunk;
10823
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
10826
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
10827
+ const chunk = this.read(this._readableState.length);
10824
10828
  websocket._receiver.write(chunk);
10825
10829
  }
10826
10830
  websocket._receiver.end();
@@ -10856,9 +10860,9 @@ var require_websocket = __commonJS({
10856
10860
  }
10857
10861
  });
10858
10862
 
10859
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/stream.js
10863
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/stream.js
10860
10864
  var require_stream = __commonJS({
10861
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/stream.js"(exports, module) {
10865
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/stream.js"(exports, module) {
10862
10866
  "use strict";
10863
10867
  var WebSocket3 = require_websocket();
10864
10868
  var { Duplex } = __require("stream");
@@ -10954,9 +10958,9 @@ var require_stream = __commonJS({
10954
10958
  }
10955
10959
  });
10956
10960
 
10957
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/subprotocol.js
10961
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/subprotocol.js
10958
10962
  var require_subprotocol = __commonJS({
10959
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/subprotocol.js"(exports, module) {
10963
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/subprotocol.js"(exports, module) {
10960
10964
  "use strict";
10961
10965
  var { tokenChars } = require_validation();
10962
10966
  function parse2(header) {
@@ -10999,9 +11003,9 @@ var require_subprotocol = __commonJS({
10999
11003
  }
11000
11004
  });
11001
11005
 
11002
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/websocket-server.js
11006
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/websocket-server.js
11003
11007
  var require_websocket_server = __commonJS({
11004
- "node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/websocket-server.js"(exports, module) {
11008
+ "node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/lib/websocket-server.js"(exports, module) {
11005
11009
  "use strict";
11006
11010
  var EventEmitter2 = __require("events");
11007
11011
  var http2 = __require("http");
@@ -11011,7 +11015,7 @@ var require_websocket_server = __commonJS({
11011
11015
  var PerMessageDeflate = require_permessage_deflate();
11012
11016
  var subprotocol = require_subprotocol();
11013
11017
  var WebSocket3 = require_websocket();
11014
- var { GUID, kWebSocket } = require_constants();
11018
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
11015
11019
  var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
11016
11020
  var RUNNING = 0;
11017
11021
  var CLOSING = 1;
@@ -11030,6 +11034,9 @@ var require_websocket_server = __commonJS({
11030
11034
  * pending connections
11031
11035
  * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
11032
11036
  * track clients
11037
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
11038
+ * wait for the closing handshake to finish after `websocket.close()` is
11039
+ * called
11033
11040
  * @param {Function} [options.handleProtocols] A hook to handle protocols
11034
11041
  * @param {String} [options.host] The hostname where to bind the server
11035
11042
  * @param {Number} [options.maxPayload=104857600] The maximum allowed message
@@ -11058,6 +11065,7 @@ var require_websocket_server = __commonJS({
11058
11065
  perMessageDeflate: false,
11059
11066
  handleProtocols: null,
11060
11067
  clientTracking: true,
11068
+ closeTimeout: CLOSE_TIMEOUT,
11061
11069
  verifyClient: null,
11062
11070
  noServer: false,
11063
11071
  backlog: null,
@@ -11388,9 +11396,9 @@ var require_websocket_server = __commonJS({
11388
11396
  }
11389
11397
  });
11390
11398
 
11391
- // node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js
11399
+ // node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.js
11392
11400
  var require_eventemitter3 = __commonJS({
11393
- "node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js"(exports, module) {
11401
+ "node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.js"(exports, module) {
11394
11402
  "use strict";
11395
11403
  var has = Object.prototype.hasOwnProperty;
11396
11404
  var prefix = "~";
@@ -11615,6 +11623,52 @@ function byteSwap32(arr) {
11615
11623
  return arr;
11616
11624
  }
11617
11625
  var swap32IfBE = isLE ? (u) => u : byteSwap32;
11626
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
11627
+ // @ts-ignore
11628
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
11629
+ ))();
11630
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
11631
+ function bytesToHex(bytes) {
11632
+ abytes(bytes);
11633
+ if (hasHexBuiltin)
11634
+ return bytes.toHex();
11635
+ let hex = "";
11636
+ for (let i = 0; i < bytes.length; i++) {
11637
+ hex += hexes[bytes[i]];
11638
+ }
11639
+ return hex;
11640
+ }
11641
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
11642
+ function asciiToBase16(ch) {
11643
+ if (ch >= asciis._0 && ch <= asciis._9)
11644
+ return ch - asciis._0;
11645
+ if (ch >= asciis.A && ch <= asciis.F)
11646
+ return ch - (asciis.A - 10);
11647
+ if (ch >= asciis.a && ch <= asciis.f)
11648
+ return ch - (asciis.a - 10);
11649
+ return;
11650
+ }
11651
+ function hexToBytes(hex) {
11652
+ if (typeof hex !== "string")
11653
+ throw new Error("hex string expected, got " + typeof hex);
11654
+ if (hasHexBuiltin)
11655
+ return Uint8Array.fromHex(hex);
11656
+ const hl = hex.length;
11657
+ const al = hl / 2;
11658
+ if (hl % 2)
11659
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
11660
+ const array2 = new Uint8Array(al);
11661
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
11662
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
11663
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
11664
+ if (n1 === void 0 || n2 === void 0) {
11665
+ const char = hex[hi] + hex[hi + 1];
11666
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
11667
+ }
11668
+ array2[ai] = n1 * 16 + n2;
11669
+ }
11670
+ return array2;
11671
+ }
11618
11672
  function utf8ToBytes(str) {
11619
11673
  if (typeof str !== "string")
11620
11674
  throw new Error("string expected");
@@ -12176,19 +12230,27 @@ var SHA512 = class extends HashMD {
12176
12230
  var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
12177
12231
  var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
12178
12232
 
12179
- // node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/utils.js
12233
+ // node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js
12180
12234
  var _0n = /* @__PURE__ */ BigInt(0);
12181
12235
  var _1n = /* @__PURE__ */ BigInt(1);
12182
- function isBytes2(a) {
12183
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
12184
- }
12185
- function abytes2(item) {
12186
- if (!isBytes2(item))
12187
- throw new Error("Uint8Array expected");
12236
+ function _abool2(value, title = "") {
12237
+ if (typeof value !== "boolean") {
12238
+ const prefix = title && `"${title}"`;
12239
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
12240
+ }
12241
+ return value;
12188
12242
  }
12189
- function abool(title, value) {
12190
- if (typeof value !== "boolean")
12191
- throw new Error(title + " boolean expected, got " + value);
12243
+ function _abytes2(value, length, title = "") {
12244
+ const bytes = isBytes(value);
12245
+ const len = value?.length;
12246
+ const needsLen = length !== void 0;
12247
+ if (!bytes || needsLen && len !== length) {
12248
+ const prefix = title && `"${title}" `;
12249
+ const ofLen = needsLen ? ` of length ${length}` : "";
12250
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
12251
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
12252
+ }
12253
+ return value;
12192
12254
  }
12193
12255
  function numberToHexUnpadded(num) {
12194
12256
  const hex = num.toString(16);
@@ -12199,57 +12261,11 @@ function hexToNumber(hex) {
12199
12261
  throw new Error("hex string expected, got " + typeof hex);
12200
12262
  return hex === "" ? _0n : BigInt("0x" + hex);
12201
12263
  }
12202
- var hasHexBuiltin = (
12203
- // @ts-ignore
12204
- typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
12205
- );
12206
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
12207
- function bytesToHex(bytes) {
12208
- abytes2(bytes);
12209
- if (hasHexBuiltin)
12210
- return bytes.toHex();
12211
- let hex = "";
12212
- for (let i = 0; i < bytes.length; i++) {
12213
- hex += hexes[bytes[i]];
12214
- }
12215
- return hex;
12216
- }
12217
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
12218
- function asciiToBase16(ch) {
12219
- if (ch >= asciis._0 && ch <= asciis._9)
12220
- return ch - asciis._0;
12221
- if (ch >= asciis.A && ch <= asciis.F)
12222
- return ch - (asciis.A - 10);
12223
- if (ch >= asciis.a && ch <= asciis.f)
12224
- return ch - (asciis.a - 10);
12225
- return;
12226
- }
12227
- function hexToBytes(hex) {
12228
- if (typeof hex !== "string")
12229
- throw new Error("hex string expected, got " + typeof hex);
12230
- if (hasHexBuiltin)
12231
- return Uint8Array.fromHex(hex);
12232
- const hl = hex.length;
12233
- const al = hl / 2;
12234
- if (hl % 2)
12235
- throw new Error("hex string expected, got unpadded hex of length " + hl);
12236
- const array2 = new Uint8Array(al);
12237
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
12238
- const n1 = asciiToBase16(hex.charCodeAt(hi));
12239
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
12240
- if (n1 === void 0 || n2 === void 0) {
12241
- const char = hex[hi] + hex[hi + 1];
12242
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
12243
- }
12244
- array2[ai] = n1 * 16 + n2;
12245
- }
12246
- return array2;
12247
- }
12248
12264
  function bytesToNumberBE(bytes) {
12249
12265
  return hexToNumber(bytesToHex(bytes));
12250
12266
  }
12251
12267
  function bytesToNumberLE(bytes) {
12252
- abytes2(bytes);
12268
+ abytes(bytes);
12253
12269
  return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
12254
12270
  }
12255
12271
  function numberToBytesBE(n, len) {
@@ -12266,7 +12282,7 @@ function ensureBytes(title, hex, expectedLength) {
12266
12282
  } catch (e) {
12267
12283
  throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
12268
12284
  }
12269
- } else if (isBytes2(hex)) {
12285
+ } else if (isBytes(hex)) {
12270
12286
  res = Uint8Array.from(hex);
12271
12287
  } else {
12272
12288
  throw new Error(title + " must be hex string or Uint8Array");
@@ -12276,20 +12292,16 @@ function ensureBytes(title, hex, expectedLength) {
12276
12292
  throw new Error(title + " of length " + expectedLength + " expected, got " + len);
12277
12293
  return res;
12278
12294
  }
12279
- function concatBytes2(...arrays) {
12280
- let sum = 0;
12281
- for (let i = 0; i < arrays.length; i++) {
12282
- const a = arrays[i];
12283
- abytes2(a);
12284
- sum += a.length;
12285
- }
12286
- const res = new Uint8Array(sum);
12287
- for (let i = 0, pad = 0; i < arrays.length; i++) {
12288
- const a = arrays[i];
12289
- res.set(a, pad);
12290
- pad += a.length;
12291
- }
12292
- return res;
12295
+ function equalBytes(a, b) {
12296
+ if (a.length !== b.length)
12297
+ return false;
12298
+ let diff = 0;
12299
+ for (let i = 0; i < a.length; i++)
12300
+ diff |= a[i] ^ b[i];
12301
+ return diff === 0;
12302
+ }
12303
+ function copyBytes(bytes) {
12304
+ return Uint8Array.from(bytes);
12293
12305
  }
12294
12306
  var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
12295
12307
  function inRange(n, min, max) {
@@ -12306,8 +12318,6 @@ function bitLen(n) {
12306
12318
  return len;
12307
12319
  }
12308
12320
  var bitMask = (n) => (_1n << BigInt(n)) - _1n;
12309
- var u8n = (len) => new Uint8Array(len);
12310
- var u8fr = (arr) => Uint8Array.from(arr);
12311
12321
  function createHmacDrbg(hashLen, qByteLen, hmacFn) {
12312
12322
  if (typeof hashLen !== "number" || hashLen < 2)
12313
12323
  throw new Error("hashLen must be a number");
@@ -12315,6 +12325,8 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
12315
12325
  throw new Error("qByteLen must be a number");
12316
12326
  if (typeof hmacFn !== "function")
12317
12327
  throw new Error("hmacFn must be a function");
12328
+ const u8n = (len) => new Uint8Array(len);
12329
+ const u8of = (byte) => Uint8Array.of(byte);
12318
12330
  let v = u8n(hashLen);
12319
12331
  let k = u8n(hashLen);
12320
12332
  let i = 0;
@@ -12325,11 +12337,11 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
12325
12337
  };
12326
12338
  const h = (...b) => hmacFn(k, v, ...b);
12327
12339
  const reseed = (seed = u8n(0)) => {
12328
- k = h(u8fr([0]), seed);
12340
+ k = h(u8of(0), seed);
12329
12341
  v = h();
12330
12342
  if (seed.length === 0)
12331
12343
  return;
12332
- k = h(u8fr([1]), seed);
12344
+ k = h(u8of(1), seed);
12333
12345
  v = h();
12334
12346
  };
12335
12347
  const gen2 = () => {
@@ -12343,7 +12355,7 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
12343
12355
  out.push(sl);
12344
12356
  len += v.length;
12345
12357
  }
12346
- return concatBytes2(...out);
12358
+ return concatBytes(...out);
12347
12359
  };
12348
12360
  const genUntil = (seed, pred) => {
12349
12361
  reset();
@@ -12356,35 +12368,23 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
12356
12368
  };
12357
12369
  return genUntil;
12358
12370
  }
12359
- var validatorFns = {
12360
- bigint: (val) => typeof val === "bigint",
12361
- function: (val) => typeof val === "function",
12362
- boolean: (val) => typeof val === "boolean",
12363
- string: (val) => typeof val === "string",
12364
- stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val),
12365
- isSafeInteger: (val) => Number.isSafeInteger(val),
12366
- array: (val) => Array.isArray(val),
12367
- field: (val, object) => object.Fp.isValid(val),
12368
- hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
12369
- };
12370
- function validateObject(object, validators, optValidators = {}) {
12371
- const checkField = (fieldName, type2, isOptional) => {
12372
- const checkVal = validatorFns[type2];
12373
- if (typeof checkVal !== "function")
12374
- throw new Error("invalid validator function");
12371
+ function _validateObject(object, fields, optFields = {}) {
12372
+ if (!object || typeof object !== "object")
12373
+ throw new Error("expected valid options object");
12374
+ function checkField(fieldName, expectedType, isOpt) {
12375
12375
  const val = object[fieldName];
12376
- if (isOptional && val === void 0)
12376
+ if (isOpt && val === void 0)
12377
12377
  return;
12378
- if (!checkVal(val, object)) {
12379
- throw new Error("param " + String(fieldName) + " is invalid. Expected " + type2 + ", got " + val);
12380
- }
12381
- };
12382
- for (const [fieldName, type2] of Object.entries(validators))
12383
- checkField(fieldName, type2, false);
12384
- for (const [fieldName, type2] of Object.entries(optValidators))
12385
- checkField(fieldName, type2, true);
12386
- return object;
12378
+ const current = typeof val;
12379
+ if (current !== expectedType || val === null)
12380
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
12381
+ }
12382
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
12383
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
12387
12384
  }
12385
+ var notImplemented = () => {
12386
+ throw new Error("not implemented");
12387
+ };
12388
12388
  function memoized(fn) {
12389
12389
  const map = /* @__PURE__ */ new WeakMap();
12390
12390
  return (arg, ...args) => {
@@ -12397,14 +12397,17 @@ function memoized(fn) {
12397
12397
  };
12398
12398
  }
12399
12399
 
12400
- // node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/modular.js
12400
+ // node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js
12401
12401
  var _0n2 = BigInt(0);
12402
12402
  var _1n2 = BigInt(1);
12403
12403
  var _2n = /* @__PURE__ */ BigInt(2);
12404
12404
  var _3n = /* @__PURE__ */ BigInt(3);
12405
12405
  var _4n = /* @__PURE__ */ BigInt(4);
12406
12406
  var _5n = /* @__PURE__ */ BigInt(5);
12407
+ var _7n = /* @__PURE__ */ BigInt(7);
12407
12408
  var _8n = /* @__PURE__ */ BigInt(8);
12409
+ var _9n = /* @__PURE__ */ BigInt(9);
12410
+ var _16n = /* @__PURE__ */ BigInt(16);
12408
12411
  function mod(a, b) {
12409
12412
  const result = a % b;
12410
12413
  return result >= _0n2 ? result : b + result;
@@ -12437,11 +12440,14 @@ function invert(number2, modulo) {
12437
12440
  throw new Error("invert: does not exist");
12438
12441
  return mod(x, modulo);
12439
12442
  }
12443
+ function assertIsSquare(Fp2, root, n) {
12444
+ if (!Fp2.eql(Fp2.sqr(root), n))
12445
+ throw new Error("Cannot find square root");
12446
+ }
12440
12447
  function sqrt3mod4(Fp2, n) {
12441
12448
  const p1div4 = (Fp2.ORDER + _1n2) / _4n;
12442
12449
  const root = Fp2.pow(n, p1div4);
12443
- if (!Fp2.eql(Fp2.sqr(root), n))
12444
- throw new Error("Cannot find square root");
12450
+ assertIsSquare(Fp2, root, n);
12445
12451
  return root;
12446
12452
  }
12447
12453
  function sqrt5mod8(Fp2, n) {
@@ -12451,12 +12457,33 @@ function sqrt5mod8(Fp2, n) {
12451
12457
  const nv = Fp2.mul(n, v);
12452
12458
  const i = Fp2.mul(Fp2.mul(nv, _2n), v);
12453
12459
  const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
12454
- if (!Fp2.eql(Fp2.sqr(root), n))
12455
- throw new Error("Cannot find square root");
12460
+ assertIsSquare(Fp2, root, n);
12456
12461
  return root;
12457
12462
  }
12463
+ function sqrt9mod16(P) {
12464
+ const Fp_ = Field(P);
12465
+ const tn = tonelliShanks(P);
12466
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
12467
+ const c2 = tn(Fp_, c1);
12468
+ const c3 = tn(Fp_, Fp_.neg(c1));
12469
+ const c4 = (P + _7n) / _16n;
12470
+ return (Fp2, n) => {
12471
+ let tv1 = Fp2.pow(n, c4);
12472
+ let tv2 = Fp2.mul(tv1, c1);
12473
+ const tv3 = Fp2.mul(tv1, c2);
12474
+ const tv4 = Fp2.mul(tv1, c3);
12475
+ const e1 = Fp2.eql(Fp2.sqr(tv2), n);
12476
+ const e2 = Fp2.eql(Fp2.sqr(tv3), n);
12477
+ tv1 = Fp2.cmov(tv1, tv2, e1);
12478
+ tv2 = Fp2.cmov(tv4, tv3, e2);
12479
+ const e3 = Fp2.eql(Fp2.sqr(tv2), n);
12480
+ const root = Fp2.cmov(tv1, tv2, e3);
12481
+ assertIsSquare(Fp2, root, n);
12482
+ return root;
12483
+ };
12484
+ }
12458
12485
  function tonelliShanks(P) {
12459
- if (P < BigInt(3))
12486
+ if (P < _3n)
12460
12487
  throw new Error("sqrt is not defined for small field");
12461
12488
  let Q = P - _1n2;
12462
12489
  let S = 0;
@@ -12509,6 +12536,8 @@ function FpSqrt(P) {
12509
12536
  return sqrt3mod4;
12510
12537
  if (P % _8n === _5n)
12511
12538
  return sqrt5mod8;
12539
+ if (P % _16n === _9n)
12540
+ return sqrt9mod16(P);
12512
12541
  return tonelliShanks(P);
12513
12542
  }
12514
12543
  var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
@@ -12535,14 +12564,15 @@ function validateField(field) {
12535
12564
  const initial = {
12536
12565
  ORDER: "bigint",
12537
12566
  MASK: "bigint",
12538
- BYTES: "isSafeInteger",
12539
- BITS: "isSafeInteger"
12567
+ BYTES: "number",
12568
+ BITS: "number"
12540
12569
  };
12541
12570
  const opts = FIELD_FIELDS.reduce((map, val) => {
12542
12571
  map[val] = "function";
12543
12572
  return map;
12544
12573
  }, initial);
12545
- return validateObject(field, opts);
12574
+ _validateObject(field, opts);
12575
+ return field;
12546
12576
  }
12547
12577
  function FpPow(Fp2, num, power) {
12548
12578
  if (power < _0n2)
@@ -12595,10 +12625,33 @@ function nLength(n, nBitLength) {
12595
12625
  const nByteLength = Math.ceil(_nBitLength / 8);
12596
12626
  return { nBitLength: _nBitLength, nByteLength };
12597
12627
  }
12598
- function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
12628
+ function Field(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) {
12599
12629
  if (ORDER <= _0n2)
12600
12630
  throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
12601
- const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
12631
+ let _nbitLength = void 0;
12632
+ let _sqrt = void 0;
12633
+ let modFromBytes = false;
12634
+ let allowedLengths = void 0;
12635
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
12636
+ if (opts.sqrt || isLE2)
12637
+ throw new Error("cannot specify opts in two arguments");
12638
+ const _opts = bitLenOrOpts;
12639
+ if (_opts.BITS)
12640
+ _nbitLength = _opts.BITS;
12641
+ if (_opts.sqrt)
12642
+ _sqrt = _opts.sqrt;
12643
+ if (typeof _opts.isLE === "boolean")
12644
+ isLE2 = _opts.isLE;
12645
+ if (typeof _opts.modFromBytes === "boolean")
12646
+ modFromBytes = _opts.modFromBytes;
12647
+ allowedLengths = _opts.allowedLengths;
12648
+ } else {
12649
+ if (typeof bitLenOrOpts === "number")
12650
+ _nbitLength = bitLenOrOpts;
12651
+ if (opts.sqrt)
12652
+ _sqrt = opts.sqrt;
12653
+ }
12654
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
12602
12655
  if (BYTES > 2048)
12603
12656
  throw new Error("invalid field: expected ORDER of <= 2048 bytes");
12604
12657
  let sqrtP;
@@ -12610,6 +12663,7 @@ function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
12610
12663
  MASK: bitMask(BITS),
12611
12664
  ZERO: _0n2,
12612
12665
  ONE: _1n2,
12666
+ allowedLengths,
12613
12667
  create: (num) => mod(num, ORDER),
12614
12668
  isValid: (num) => {
12615
12669
  if (typeof num !== "bigint")
@@ -12617,6 +12671,8 @@ function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
12617
12671
  return _0n2 <= num && num < ORDER;
12618
12672
  },
12619
12673
  is0: (num) => num === _0n2,
12674
+ // is valid and invertible
12675
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
12620
12676
  isOdd: (num) => (num & _1n2) === _1n2,
12621
12677
  neg: (num) => mod(-num, ORDER),
12622
12678
  eql: (lhs, rhs) => lhs === rhs,
@@ -12632,16 +12688,31 @@ function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
12632
12688
  subN: (lhs, rhs) => lhs - rhs,
12633
12689
  mulN: (lhs, rhs) => lhs * rhs,
12634
12690
  inv: (num) => invert(num, ORDER),
12635
- sqrt: redef.sqrt || ((n) => {
12691
+ sqrt: _sqrt || ((n) => {
12636
12692
  if (!sqrtP)
12637
12693
  sqrtP = FpSqrt(ORDER);
12638
12694
  return sqrtP(f, n);
12639
12695
  }),
12640
12696
  toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
12641
- fromBytes: (bytes) => {
12697
+ fromBytes: (bytes, skipValidation = true) => {
12698
+ if (allowedLengths) {
12699
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
12700
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
12701
+ }
12702
+ const padded = new Uint8Array(BYTES);
12703
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
12704
+ bytes = padded;
12705
+ }
12642
12706
  if (bytes.length !== BYTES)
12643
12707
  throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
12644
- return isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
12708
+ let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
12709
+ if (modFromBytes)
12710
+ scalar = mod(scalar, ORDER);
12711
+ if (!skipValidation) {
12712
+ if (!f.isValid(scalar))
12713
+ throw new Error("invalid field element: outside of range 0..ORDER");
12714
+ }
12715
+ return scalar;
12645
12716
  },
12646
12717
  // TODO: we don't need it here, move out to separate fn
12647
12718
  invertBatch: (lst) => FpInvertBatch(f, lst),
@@ -12672,13 +12743,17 @@ function mapHashToField(key, fieldOrder, isLE2 = false) {
12672
12743
  return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
12673
12744
  }
12674
12745
 
12675
- // node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/curve.js
12746
+ // node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js
12676
12747
  var _0n3 = BigInt(0);
12677
12748
  var _1n3 = BigInt(1);
12678
- function constTimeNegate(condition, item) {
12749
+ function negateCt(condition, item) {
12679
12750
  const neg = item.negate();
12680
12751
  return condition ? neg : item;
12681
12752
  }
12753
+ function normalizeZ(c, points) {
12754
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
12755
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
12756
+ }
12682
12757
  function validateW(W, bits) {
12683
12758
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
12684
12759
  throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
@@ -12729,125 +12804,151 @@ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
12729
12804
  function getW(P) {
12730
12805
  return pointWindowSizes.get(P) || 1;
12731
12806
  }
12732
- function wNAF(c, bits) {
12733
- return {
12734
- constTimeNegate,
12735
- hasPrecomputes(elm) {
12736
- return getW(elm) !== 1;
12737
- },
12738
- // non-const time multiplication ladder
12739
- unsafeLadder(elm, n, p = c.ZERO) {
12740
- let d = elm;
12741
- while (n > _0n3) {
12742
- if (n & _1n3)
12743
- p = p.add(d);
12744
- d = d.double();
12745
- n >>= _1n3;
12746
- }
12747
- return p;
12748
- },
12749
- /**
12750
- * Creates a wNAF precomputation window. Used for caching.
12751
- * Default window size is set by `utils.precompute()` and is equal to 8.
12752
- * Number of precomputed points depends on the curve size:
12753
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
12754
- * - 𝑊 is the window size
12755
- * - 𝑛 is the bitlength of the curve order.
12756
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
12757
- * @param elm Point instance
12758
- * @param W window size
12759
- * @returns precomputed point tables flattened to a single array
12760
- */
12761
- precomputeWindow(elm, W) {
12762
- const { windows, windowSize } = calcWOpts(W, bits);
12763
- const points = [];
12764
- let p = elm;
12765
- let base = p;
12766
- for (let window2 = 0; window2 < windows; window2++) {
12767
- base = p;
12807
+ function assert0(n) {
12808
+ if (n !== _0n3)
12809
+ throw new Error("invalid wNAF");
12810
+ }
12811
+ var wNAF = class {
12812
+ // Parametrized with a given Point class (not individual point)
12813
+ constructor(Point, bits) {
12814
+ this.BASE = Point.BASE;
12815
+ this.ZERO = Point.ZERO;
12816
+ this.Fn = Point.Fn;
12817
+ this.bits = bits;
12818
+ }
12819
+ // non-const time multiplication ladder
12820
+ _unsafeLadder(elm, n, p = this.ZERO) {
12821
+ let d = elm;
12822
+ while (n > _0n3) {
12823
+ if (n & _1n3)
12824
+ p = p.add(d);
12825
+ d = d.double();
12826
+ n >>= _1n3;
12827
+ }
12828
+ return p;
12829
+ }
12830
+ /**
12831
+ * Creates a wNAF precomputation window. Used for caching.
12832
+ * Default window size is set by `utils.precompute()` and is equal to 8.
12833
+ * Number of precomputed points depends on the curve size:
12834
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
12835
+ * - 𝑊 is the window size
12836
+ * - 𝑛 is the bitlength of the curve order.
12837
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
12838
+ * @param point Point instance
12839
+ * @param W window size
12840
+ * @returns precomputed point tables flattened to a single array
12841
+ */
12842
+ precomputeWindow(point, W) {
12843
+ const { windows, windowSize } = calcWOpts(W, this.bits);
12844
+ const points = [];
12845
+ let p = point;
12846
+ let base = p;
12847
+ for (let window2 = 0; window2 < windows; window2++) {
12848
+ base = p;
12849
+ points.push(base);
12850
+ for (let i = 1; i < windowSize; i++) {
12851
+ base = base.add(p);
12768
12852
  points.push(base);
12769
- for (let i = 1; i < windowSize; i++) {
12770
- base = base.add(p);
12771
- points.push(base);
12772
- }
12773
- p = base.double();
12774
12853
  }
12775
- return points;
12776
- },
12777
- /**
12778
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
12779
- * @param W window size
12780
- * @param precomputes precomputed tables
12781
- * @param n scalar (we don't check here, but should be less than curve order)
12782
- * @returns real and fake (for const-time) points
12783
- */
12784
- wNAF(W, precomputes, n) {
12785
- let p = c.ZERO;
12786
- let f = c.BASE;
12787
- const wo = calcWOpts(W, bits);
12788
- for (let window2 = 0; window2 < wo.windows; window2++) {
12789
- const { nextN, offset: offset2, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo);
12790
- n = nextN;
12791
- if (isZero) {
12792
- f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
12793
- } else {
12794
- p = p.add(constTimeNegate(isNeg, precomputes[offset2]));
12795
- }
12854
+ p = base.double();
12855
+ }
12856
+ return points;
12857
+ }
12858
+ /**
12859
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
12860
+ * More compact implementation:
12861
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
12862
+ * @returns real and fake (for const-time) points
12863
+ */
12864
+ wNAF(W, precomputes, n) {
12865
+ if (!this.Fn.isValid(n))
12866
+ throw new Error("invalid scalar");
12867
+ let p = this.ZERO;
12868
+ let f = this.BASE;
12869
+ const wo = calcWOpts(W, this.bits);
12870
+ for (let window2 = 0; window2 < wo.windows; window2++) {
12871
+ const { nextN, offset: offset2, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo);
12872
+ n = nextN;
12873
+ if (isZero) {
12874
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
12875
+ } else {
12876
+ p = p.add(negateCt(isNeg, precomputes[offset2]));
12796
12877
  }
12797
- return { p, f };
12798
- },
12799
- /**
12800
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
12801
- * @param W window size
12802
- * @param precomputes precomputed tables
12803
- * @param n scalar (we don't check here, but should be less than curve order)
12804
- * @param acc accumulator point to add result of multiplication
12805
- * @returns point
12806
- */
12807
- wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
12808
- const wo = calcWOpts(W, bits);
12809
- for (let window2 = 0; window2 < wo.windows; window2++) {
12810
- if (n === _0n3)
12811
- break;
12812
- const { nextN, offset: offset2, isZero, isNeg } = calcOffsets(n, window2, wo);
12813
- n = nextN;
12814
- if (isZero) {
12815
- continue;
12816
- } else {
12817
- const item = precomputes[offset2];
12818
- acc = acc.add(isNeg ? item.negate() : item);
12819
- }
12878
+ }
12879
+ assert0(n);
12880
+ return { p, f };
12881
+ }
12882
+ /**
12883
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
12884
+ * @param acc accumulator point to add result of multiplication
12885
+ * @returns point
12886
+ */
12887
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
12888
+ const wo = calcWOpts(W, this.bits);
12889
+ for (let window2 = 0; window2 < wo.windows; window2++) {
12890
+ if (n === _0n3)
12891
+ break;
12892
+ const { nextN, offset: offset2, isZero, isNeg } = calcOffsets(n, window2, wo);
12893
+ n = nextN;
12894
+ if (isZero) {
12895
+ continue;
12896
+ } else {
12897
+ const item = precomputes[offset2];
12898
+ acc = acc.add(isNeg ? item.negate() : item);
12820
12899
  }
12821
- return acc;
12822
- },
12823
- getPrecomputes(W, P, transform) {
12824
- let comp = pointPrecomputes.get(P);
12825
- if (!comp) {
12826
- comp = this.precomputeWindow(P, W);
12827
- if (W !== 1)
12828
- pointPrecomputes.set(P, transform(comp));
12829
- }
12830
- return comp;
12831
- },
12832
- wNAFCached(P, n, transform) {
12833
- const W = getW(P);
12834
- return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
12835
- },
12836
- wNAFCachedUnsafe(P, n, transform, prev) {
12837
- const W = getW(P);
12838
- if (W === 1)
12839
- return this.unsafeLadder(P, n, prev);
12840
- return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
12841
- },
12842
- // We calculate precomputes for elliptic curve point multiplication
12843
- // using windowed method. This specifies window size and
12844
- // stores precomputed values. Usually only base point would be precomputed.
12845
- setWindowSize(P, W) {
12846
- validateW(W, bits);
12847
- pointWindowSizes.set(P, W);
12848
- pointPrecomputes.delete(P);
12849
12900
  }
12850
- };
12901
+ assert0(n);
12902
+ return acc;
12903
+ }
12904
+ getPrecomputes(W, point, transform) {
12905
+ let comp = pointPrecomputes.get(point);
12906
+ if (!comp) {
12907
+ comp = this.precomputeWindow(point, W);
12908
+ if (W !== 1) {
12909
+ if (typeof transform === "function")
12910
+ comp = transform(comp);
12911
+ pointPrecomputes.set(point, comp);
12912
+ }
12913
+ }
12914
+ return comp;
12915
+ }
12916
+ cached(point, scalar, transform) {
12917
+ const W = getW(point);
12918
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
12919
+ }
12920
+ unsafe(point, scalar, transform, prev) {
12921
+ const W = getW(point);
12922
+ if (W === 1)
12923
+ return this._unsafeLadder(point, scalar, prev);
12924
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
12925
+ }
12926
+ // We calculate precomputes for elliptic curve point multiplication
12927
+ // using windowed method. This specifies window size and
12928
+ // stores precomputed values. Usually only base point would be precomputed.
12929
+ createCache(P, W) {
12930
+ validateW(W, this.bits);
12931
+ pointWindowSizes.set(P, W);
12932
+ pointPrecomputes.delete(P);
12933
+ }
12934
+ hasCache(elm) {
12935
+ return getW(elm) !== 1;
12936
+ }
12937
+ };
12938
+ function mulEndoUnsafe(Point, point, k1, k2) {
12939
+ let acc = point;
12940
+ let p1 = Point.ZERO;
12941
+ let p2 = Point.ZERO;
12942
+ while (k1 > _0n3 || k2 > _0n3) {
12943
+ if (k1 & _1n3)
12944
+ p1 = p1.add(acc);
12945
+ if (k2 & _1n3)
12946
+ p2 = p2.add(acc);
12947
+ acc = acc.double();
12948
+ k1 >>= _1n3;
12949
+ k2 >>= _1n3;
12950
+ }
12951
+ return { p1, p2 };
12851
12952
  }
12852
12953
  function pippenger(c, fieldN, points, scalars) {
12853
12954
  validateMSMPoints(points, c);
@@ -12888,101 +12989,95 @@ function pippenger(c, fieldN, points, scalars) {
12888
12989
  }
12889
12990
  return sum;
12890
12991
  }
12891
- function validateBasic(curve) {
12892
- validateField(curve.Fp);
12893
- validateObject(curve, {
12894
- n: "bigint",
12895
- h: "bigint",
12896
- Gx: "field",
12897
- Gy: "field"
12898
- }, {
12899
- nBitLength: "isSafeInteger",
12900
- nByteLength: "isSafeInteger"
12901
- });
12902
- return Object.freeze({
12903
- ...nLength(curve.n, curve.nBitLength),
12904
- ...curve,
12905
- ...{ p: curve.Fp.ORDER }
12906
- });
12992
+ function createField(order, field, isLE2) {
12993
+ if (field) {
12994
+ if (field.ORDER !== order)
12995
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
12996
+ validateField(field);
12997
+ return field;
12998
+ } else {
12999
+ return Field(order, { isLE: isLE2 });
13000
+ }
13001
+ }
13002
+ function _createCurveFields(type2, CURVE, curveOpts = {}, FpFnLE) {
13003
+ if (FpFnLE === void 0)
13004
+ FpFnLE = type2 === "edwards";
13005
+ if (!CURVE || typeof CURVE !== "object")
13006
+ throw new Error(`expected valid ${type2} CURVE object`);
13007
+ for (const p of ["p", "n", "h"]) {
13008
+ const val = CURVE[p];
13009
+ if (!(typeof val === "bigint" && val > _0n3))
13010
+ throw new Error(`CURVE.${p} must be positive bigint`);
13011
+ }
13012
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
13013
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
13014
+ const _b = type2 === "weierstrass" ? "b" : "d";
13015
+ const params = ["Gx", "Gy", "a", _b];
13016
+ for (const p of params) {
13017
+ if (!Fp2.isValid(CURVE[p]))
13018
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
13019
+ }
13020
+ CURVE = Object.freeze(Object.assign({}, CURVE));
13021
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
12907
13022
  }
12908
13023
 
12909
- // node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/edwards.js
13024
+ // node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js
12910
13025
  var _0n4 = BigInt(0);
12911
13026
  var _1n4 = BigInt(1);
12912
13027
  var _2n2 = BigInt(2);
12913
13028
  var _8n2 = BigInt(8);
12914
- var VERIFY_DEFAULT = { zip215: true };
12915
- function validateOpts(curve) {
12916
- const opts = validateBasic(curve);
12917
- validateObject(curve, {
12918
- hash: "function",
12919
- a: "bigint",
12920
- d: "bigint",
12921
- randomBytes: "function"
12922
- }, {
12923
- adjustScalarBytes: "function",
12924
- domain: "function",
12925
- uvRatio: "function",
12926
- mapToCurve: "function"
12927
- });
12928
- return Object.freeze({ ...opts });
13029
+ function isEdValidXY(Fp2, CURVE, x, y) {
13030
+ const x2 = Fp2.sqr(x);
13031
+ const y2 = Fp2.sqr(y);
13032
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
13033
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
13034
+ return Fp2.eql(left, right);
12929
13035
  }
12930
- function twistedEdwards(curveDef) {
12931
- const CURVE = validateOpts(curveDef);
12932
- const { Fp: Fp2, n: CURVE_ORDER, prehash, hash: cHash, randomBytes: randomBytes2, nByteLength, h: cofactor } = CURVE;
12933
- const MASK = _2n2 << BigInt(nByteLength * 8) - _1n4;
12934
- const modP = Fp2.create;
12935
- const Fn = Field(CURVE.n, CURVE.nBitLength);
12936
- function isEdValidXY(x, y) {
12937
- const x2 = Fp2.sqr(x);
12938
- const y2 = Fp2.sqr(y);
12939
- const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
12940
- const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
12941
- return Fp2.eql(left, right);
12942
- }
12943
- if (!isEdValidXY(CURVE.Gx, CURVE.Gy))
12944
- throw new Error("bad curve params: generator point");
12945
- const uvRatio2 = CURVE.uvRatio || ((u, v) => {
13036
+ function edwards(params, extraOpts = {}) {
13037
+ const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
13038
+ const { Fp: Fp2, Fn: Fn2 } = validated;
13039
+ let CURVE = validated.CURVE;
13040
+ const { h: cofactor } = CURVE;
13041
+ _validateObject(extraOpts, {}, { uvRatio: "function" });
13042
+ const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
13043
+ const modP = (n) => Fp2.create(n);
13044
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
12946
13045
  try {
12947
- return { isValid: true, value: Fp2.sqrt(u * Fp2.inv(v)) };
13046
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
12948
13047
  } catch (e) {
12949
13048
  return { isValid: false, value: _0n4 };
12950
13049
  }
12951
13050
  });
12952
- const adjustScalarBytes2 = CURVE.adjustScalarBytes || ((bytes) => bytes);
12953
- const domain = CURVE.domain || ((data, ctx, phflag) => {
12954
- abool("phflag", phflag);
12955
- if (ctx.length || phflag)
12956
- throw new Error("Contexts/pre-hash are not supported");
12957
- return data;
12958
- });
12959
- function aCoordinate(title, n, banZero = false) {
13051
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
13052
+ throw new Error("bad curve params: generator point");
13053
+ function acoord(title, n, banZero = false) {
12960
13054
  const min = banZero ? _1n4 : _0n4;
12961
13055
  aInRange("coordinate " + title, n, min, MASK);
13056
+ return n;
12962
13057
  }
12963
13058
  function aextpoint(other) {
12964
13059
  if (!(other instanceof Point))
12965
13060
  throw new Error("ExtendedPoint expected");
12966
13061
  }
12967
13062
  const toAffineMemo = memoized((p, iz) => {
12968
- const { ex: x, ey: y, ez: z } = p;
13063
+ const { X, Y, Z } = p;
12969
13064
  const is0 = p.is0();
12970
13065
  if (iz == null)
12971
- iz = is0 ? _8n2 : Fp2.inv(z);
12972
- const ax = modP(x * iz);
12973
- const ay = modP(y * iz);
12974
- const zz = modP(z * iz);
13066
+ iz = is0 ? _8n2 : Fp2.inv(Z);
13067
+ const x = modP(X * iz);
13068
+ const y = modP(Y * iz);
13069
+ const zz = Fp2.mul(Z, iz);
12975
13070
  if (is0)
12976
13071
  return { x: _0n4, y: _1n4 };
12977
13072
  if (zz !== _1n4)
12978
13073
  throw new Error("invZ was invalid");
12979
- return { x: ax, y: ay };
13074
+ return { x, y };
12980
13075
  });
12981
13076
  const assertValidMemo = memoized((p) => {
12982
13077
  const { a, d } = CURVE;
12983
13078
  if (p.is0())
12984
13079
  throw new Error("bad point: ZERO");
12985
- const { ex: X, ey: Y, ez: Z, et: T } = p;
13080
+ const { X, Y, Z, T } = p;
12986
13081
  const X2 = modP(X * X);
12987
13082
  const Y2 = modP(Y * Y);
12988
13083
  const Z2 = modP(Z * Z);
@@ -12999,53 +13094,74 @@ function twistedEdwards(curveDef) {
12999
13094
  return true;
13000
13095
  });
13001
13096
  class Point {
13002
- constructor(ex, ey, ez, et) {
13003
- aCoordinate("x", ex);
13004
- aCoordinate("y", ey);
13005
- aCoordinate("z", ez, true);
13006
- aCoordinate("t", et);
13007
- this.ex = ex;
13008
- this.ey = ey;
13009
- this.ez = ez;
13010
- this.et = et;
13097
+ constructor(X, Y, Z, T) {
13098
+ this.X = acoord("x", X);
13099
+ this.Y = acoord("y", Y);
13100
+ this.Z = acoord("z", Z, true);
13101
+ this.T = acoord("t", T);
13011
13102
  Object.freeze(this);
13012
13103
  }
13013
- get x() {
13014
- return this.toAffine().x;
13015
- }
13016
- get y() {
13017
- return this.toAffine().y;
13104
+ static CURVE() {
13105
+ return CURVE;
13018
13106
  }
13019
13107
  static fromAffine(p) {
13020
13108
  if (p instanceof Point)
13021
13109
  throw new Error("extended point not allowed");
13022
13110
  const { x, y } = p || {};
13023
- aCoordinate("x", x);
13024
- aCoordinate("y", y);
13111
+ acoord("x", x);
13112
+ acoord("y", y);
13025
13113
  return new Point(x, y, _1n4, modP(x * y));
13026
13114
  }
13027
- static normalizeZ(points) {
13028
- const toInv = FpInvertBatch(Fp2, points.map((p) => p.ez));
13029
- return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
13115
+ // Uses algo from RFC8032 5.1.3.
13116
+ static fromBytes(bytes, zip215 = false) {
13117
+ const len = Fp2.BYTES;
13118
+ const { a, d } = CURVE;
13119
+ bytes = copyBytes(_abytes2(bytes, len, "point"));
13120
+ _abool2(zip215, "zip215");
13121
+ const normed = copyBytes(bytes);
13122
+ const lastByte = bytes[len - 1];
13123
+ normed[len - 1] = lastByte & ~128;
13124
+ const y = bytesToNumberLE(normed);
13125
+ const max = zip215 ? MASK : Fp2.ORDER;
13126
+ aInRange("point.y", y, _0n4, max);
13127
+ const y2 = modP(y * y);
13128
+ const u = modP(y2 - _1n4);
13129
+ const v = modP(d * y2 - a);
13130
+ let { isValid, value: x } = uvRatio2(u, v);
13131
+ if (!isValid)
13132
+ throw new Error("bad point: invalid y coordinate");
13133
+ const isXOdd = (x & _1n4) === _1n4;
13134
+ const isLastByteOdd = (lastByte & 128) !== 0;
13135
+ if (!zip215 && x === _0n4 && isLastByteOdd)
13136
+ throw new Error("bad point: x=0 and x_0=1");
13137
+ if (isLastByteOdd !== isXOdd)
13138
+ x = modP(-x);
13139
+ return Point.fromAffine({ x, y });
13030
13140
  }
13031
- // Multiscalar Multiplication
13032
- static msm(points, scalars) {
13033
- return pippenger(Point, Fn, points, scalars);
13141
+ static fromHex(bytes, zip215 = false) {
13142
+ return Point.fromBytes(ensureBytes("point", bytes), zip215);
13034
13143
  }
13035
- // "Private method", don't use it directly
13036
- _setWindowSize(windowSize) {
13037
- wnaf.setWindowSize(this, windowSize);
13144
+ get x() {
13145
+ return this.toAffine().x;
13146
+ }
13147
+ get y() {
13148
+ return this.toAffine().y;
13038
13149
  }
13039
- // Not required for fromHex(), which always creates valid points.
13040
- // Could be useful for fromAffine().
13150
+ precompute(windowSize = 8, isLazy = true) {
13151
+ wnaf.createCache(this, windowSize);
13152
+ if (!isLazy)
13153
+ this.multiply(_2n2);
13154
+ return this;
13155
+ }
13156
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
13041
13157
  assertValidity() {
13042
13158
  assertValidMemo(this);
13043
13159
  }
13044
13160
  // Compare one point to another.
13045
13161
  equals(other) {
13046
13162
  aextpoint(other);
13047
- const { ex: X1, ey: Y1, ez: Z1 } = this;
13048
- const { ex: X2, ey: Y2, ez: Z2 } = other;
13163
+ const { X: X1, Y: Y1, Z: Z1 } = this;
13164
+ const { X: X2, Y: Y2, Z: Z2 } = other;
13049
13165
  const X1Z2 = modP(X1 * Z2);
13050
13166
  const X2Z1 = modP(X2 * Z1);
13051
13167
  const Y1Z2 = modP(Y1 * Z2);
@@ -13056,27 +13172,27 @@ function twistedEdwards(curveDef) {
13056
13172
  return this.equals(Point.ZERO);
13057
13173
  }
13058
13174
  negate() {
13059
- return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
13175
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
13060
13176
  }
13061
13177
  // Fast algo for doubling Extended Point.
13062
13178
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
13063
13179
  // Cost: 4M + 4S + 1*a + 6add + 1*2.
13064
13180
  double() {
13065
13181
  const { a } = CURVE;
13066
- const { ex: X1, ey: Y1, ez: Z1 } = this;
13182
+ const { X: X1, Y: Y1, Z: Z1 } = this;
13067
13183
  const A = modP(X1 * X1);
13068
13184
  const B = modP(Y1 * Y1);
13069
13185
  const C = modP(_2n2 * modP(Z1 * Z1));
13070
13186
  const D = modP(a * A);
13071
13187
  const x1y1 = X1 + Y1;
13072
13188
  const E = modP(modP(x1y1 * x1y1) - A - B);
13073
- const G2 = D + B;
13074
- const F = G2 - C;
13189
+ const G = D + B;
13190
+ const F = G - C;
13075
13191
  const H = D - B;
13076
13192
  const X3 = modP(E * F);
13077
- const Y3 = modP(G2 * H);
13193
+ const Y3 = modP(G * H);
13078
13194
  const T3 = modP(E * H);
13079
- const Z3 = modP(F * G2);
13195
+ const Z3 = modP(F * G);
13080
13196
  return new Point(X3, Y3, Z3, T3);
13081
13197
  }
13082
13198
  // Fast algo for adding 2 Extended Points.
@@ -13085,34 +13201,31 @@ function twistedEdwards(curveDef) {
13085
13201
  add(other) {
13086
13202
  aextpoint(other);
13087
13203
  const { a, d } = CURVE;
13088
- const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
13089
- const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
13204
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
13205
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
13090
13206
  const A = modP(X1 * X2);
13091
13207
  const B = modP(Y1 * Y2);
13092
13208
  const C = modP(T1 * d * T2);
13093
13209
  const D = modP(Z1 * Z2);
13094
13210
  const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
13095
13211
  const F = D - C;
13096
- const G2 = D + C;
13212
+ const G = D + C;
13097
13213
  const H = modP(B - a * A);
13098
13214
  const X3 = modP(E * F);
13099
- const Y3 = modP(G2 * H);
13215
+ const Y3 = modP(G * H);
13100
13216
  const T3 = modP(E * H);
13101
- const Z3 = modP(F * G2);
13217
+ const Z3 = modP(F * G);
13102
13218
  return new Point(X3, Y3, Z3, T3);
13103
13219
  }
13104
13220
  subtract(other) {
13105
13221
  return this.add(other.negate());
13106
13222
  }
13107
- wNAF(n) {
13108
- return wnaf.wNAFCached(this, n, Point.normalizeZ);
13109
- }
13110
13223
  // Constant-time multiplication.
13111
13224
  multiply(scalar) {
13112
- const n = scalar;
13113
- aInRange("scalar", n, _1n4, CURVE_ORDER);
13114
- const { p, f } = this.wNAF(n);
13115
- return Point.normalizeZ([p, f])[0];
13225
+ if (!Fn2.isValidNot0(scalar))
13226
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
13227
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
13228
+ return normalizeZ(Point, [p, f])[0];
13116
13229
  }
13117
13230
  // Non-constant-time multiplication. Uses double-and-add algorithm.
13118
13231
  // It's faster, but should only be used when you don't care about
@@ -13120,13 +13233,13 @@ function twistedEdwards(curveDef) {
13120
13233
  // Does NOT allow scalars higher than CURVE.n.
13121
13234
  // Accepts optional accumulator to merge with multiply (important for sparse scalars)
13122
13235
  multiplyUnsafe(scalar, acc = Point.ZERO) {
13123
- const n = scalar;
13124
- aInRange("scalar", n, _0n4, CURVE_ORDER);
13125
- if (n === _0n4)
13126
- return I;
13127
- if (this.is0() || n === _1n4)
13236
+ if (!Fn2.isValid(scalar))
13237
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
13238
+ if (scalar === _0n4)
13239
+ return Point.ZERO;
13240
+ if (this.is0() || scalar === _1n4)
13128
13241
  return this;
13129
- return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
13242
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
13130
13243
  }
13131
13244
  // Checks if point is of small order.
13132
13245
  // If you add something to small order point, you will have "dirty"
@@ -13138,72 +13251,156 @@ function twistedEdwards(curveDef) {
13138
13251
  // Multiplies point by curve order and checks if the result is 0.
13139
13252
  // Returns `false` is the point is dirty.
13140
13253
  isTorsionFree() {
13141
- return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
13254
+ return wnaf.unsafe(this, CURVE.n).is0();
13142
13255
  }
13143
13256
  // Converts Extended point to default (x, y) coordinates.
13144
13257
  // Can accept precomputed Z^-1 - for example, from invertBatch.
13145
- toAffine(iz) {
13146
- return toAffineMemo(this, iz);
13258
+ toAffine(invertedZ) {
13259
+ return toAffineMemo(this, invertedZ);
13147
13260
  }
13148
13261
  clearCofactor() {
13149
- const { h: cofactor2 } = CURVE;
13150
- if (cofactor2 === _1n4)
13262
+ if (cofactor === _1n4)
13151
13263
  return this;
13152
- return this.multiplyUnsafe(cofactor2);
13264
+ return this.multiplyUnsafe(cofactor);
13153
13265
  }
13154
- // Converts hash string or Uint8Array to Point.
13155
- // Uses algo from RFC8032 5.1.3.
13156
- static fromHex(hex, zip215 = false) {
13157
- const { d, a } = CURVE;
13158
- const len = Fp2.BYTES;
13159
- hex = ensureBytes("pointHex", hex, len);
13160
- abool("zip215", zip215);
13161
- const normed = hex.slice();
13162
- const lastByte = hex[len - 1];
13163
- normed[len - 1] = lastByte & ~128;
13164
- const y = bytesToNumberLE(normed);
13165
- const max = zip215 ? MASK : Fp2.ORDER;
13166
- aInRange("pointHex.y", y, _0n4, max);
13167
- const y2 = modP(y * y);
13168
- const u = modP(y2 - _1n4);
13169
- const v = modP(d * y2 - a);
13170
- let { isValid, value: x } = uvRatio2(u, v);
13171
- if (!isValid)
13172
- throw new Error("Point.fromHex: invalid y coordinate");
13173
- const isXOdd = (x & _1n4) === _1n4;
13174
- const isLastByteOdd = (lastByte & 128) !== 0;
13175
- if (!zip215 && x === _0n4 && isLastByteOdd)
13176
- throw new Error("Point.fromHex: x=0 and x_0=1");
13177
- if (isLastByteOdd !== isXOdd)
13178
- x = modP(-x);
13179
- return Point.fromAffine({ x, y });
13180
- }
13181
- static fromPrivateKey(privKey) {
13182
- const { scalar } = getPrivateScalar(privKey);
13183
- return G.multiply(scalar);
13184
- }
13185
- toRawBytes() {
13266
+ toBytes() {
13186
13267
  const { x, y } = this.toAffine();
13187
- const bytes = numberToBytesLE(y, Fp2.BYTES);
13268
+ const bytes = Fp2.toBytes(y);
13188
13269
  bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
13189
13270
  return bytes;
13190
13271
  }
13191
13272
  toHex() {
13192
- return bytesToHex(this.toRawBytes());
13273
+ return bytesToHex(this.toBytes());
13274
+ }
13275
+ toString() {
13276
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
13277
+ }
13278
+ // TODO: remove
13279
+ get ex() {
13280
+ return this.X;
13281
+ }
13282
+ get ey() {
13283
+ return this.Y;
13284
+ }
13285
+ get ez() {
13286
+ return this.Z;
13287
+ }
13288
+ get et() {
13289
+ return this.T;
13290
+ }
13291
+ static normalizeZ(points) {
13292
+ return normalizeZ(Point, points);
13293
+ }
13294
+ static msm(points, scalars) {
13295
+ return pippenger(Point, Fn2, points, scalars);
13296
+ }
13297
+ _setWindowSize(windowSize) {
13298
+ this.precompute(windowSize);
13299
+ }
13300
+ toRawBytes() {
13301
+ return this.toBytes();
13193
13302
  }
13194
13303
  }
13195
13304
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
13196
13305
  Point.ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
13197
- const { BASE: G, ZERO: I } = Point;
13198
- const wnaf = wNAF(Point, nByteLength * 8);
13199
- function modN(a) {
13200
- return mod(a, CURVE_ORDER);
13306
+ Point.Fp = Fp2;
13307
+ Point.Fn = Fn2;
13308
+ const wnaf = new wNAF(Point, Fn2.BITS);
13309
+ Point.BASE.precompute(8);
13310
+ return Point;
13311
+ }
13312
+ var PrimeEdwardsPoint = class {
13313
+ constructor(ep) {
13314
+ this.ep = ep;
13315
+ }
13316
+ // Static methods that must be implemented by subclasses
13317
+ static fromBytes(_bytes) {
13318
+ notImplemented();
13319
+ }
13320
+ static fromHex(_hex) {
13321
+ notImplemented();
13322
+ }
13323
+ get x() {
13324
+ return this.toAffine().x;
13325
+ }
13326
+ get y() {
13327
+ return this.toAffine().y;
13328
+ }
13329
+ // Common implementations
13330
+ clearCofactor() {
13331
+ return this;
13332
+ }
13333
+ assertValidity() {
13334
+ this.ep.assertValidity();
13335
+ }
13336
+ toAffine(invertedZ) {
13337
+ return this.ep.toAffine(invertedZ);
13338
+ }
13339
+ toHex() {
13340
+ return bytesToHex(this.toBytes());
13341
+ }
13342
+ toString() {
13343
+ return this.toHex();
13344
+ }
13345
+ isTorsionFree() {
13346
+ return true;
13347
+ }
13348
+ isSmallOrder() {
13349
+ return false;
13350
+ }
13351
+ add(other) {
13352
+ this.assertSame(other);
13353
+ return this.init(this.ep.add(other.ep));
13201
13354
  }
13355
+ subtract(other) {
13356
+ this.assertSame(other);
13357
+ return this.init(this.ep.subtract(other.ep));
13358
+ }
13359
+ multiply(scalar) {
13360
+ return this.init(this.ep.multiply(scalar));
13361
+ }
13362
+ multiplyUnsafe(scalar) {
13363
+ return this.init(this.ep.multiplyUnsafe(scalar));
13364
+ }
13365
+ double() {
13366
+ return this.init(this.ep.double());
13367
+ }
13368
+ negate() {
13369
+ return this.init(this.ep.negate());
13370
+ }
13371
+ precompute(windowSize, isLazy) {
13372
+ return this.init(this.ep.precompute(windowSize, isLazy));
13373
+ }
13374
+ /** @deprecated use `toBytes` */
13375
+ toRawBytes() {
13376
+ return this.toBytes();
13377
+ }
13378
+ };
13379
+ function eddsa(Point, cHash, eddsaOpts = {}) {
13380
+ if (typeof cHash !== "function")
13381
+ throw new Error('"hash" function param is required');
13382
+ _validateObject(eddsaOpts, {}, {
13383
+ adjustScalarBytes: "function",
13384
+ randomBytes: "function",
13385
+ domain: "function",
13386
+ prehash: "function",
13387
+ mapToCurve: "function"
13388
+ });
13389
+ const { prehash } = eddsaOpts;
13390
+ const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
13391
+ const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
13392
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
13393
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
13394
+ _abool2(phflag, "phflag");
13395
+ if (ctx.length || phflag)
13396
+ throw new Error("Contexts/pre-hash are not supported");
13397
+ return data;
13398
+ });
13202
13399
  function modN_LE(hash) {
13203
- return modN(bytesToNumberLE(hash));
13400
+ return Fn2.create(bytesToNumberLE(hash));
13204
13401
  }
13205
13402
  function getPrivateScalar(key) {
13206
- const len = Fp2.BYTES;
13403
+ const len = lengths.secretKey;
13207
13404
  key = ensureBytes("private key", key, len);
13208
13405
  const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
13209
13406
  const head = adjustScalarBytes2(hashed.slice(0, len));
@@ -13211,97 +13408,190 @@ function twistedEdwards(curveDef) {
13211
13408
  const scalar = modN_LE(head);
13212
13409
  return { head, prefix, scalar };
13213
13410
  }
13214
- function getExtendedPublicKey(key) {
13215
- const { head, prefix, scalar } = getPrivateScalar(key);
13216
- const point = G.multiply(scalar);
13217
- const pointBytes = point.toRawBytes();
13411
+ function getExtendedPublicKey(secretKey) {
13412
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
13413
+ const point = BASE.multiply(scalar);
13414
+ const pointBytes = point.toBytes();
13218
13415
  return { head, prefix, scalar, point, pointBytes };
13219
13416
  }
13220
- function getPublicKey2(privKey) {
13221
- return getExtendedPublicKey(privKey).pointBytes;
13417
+ function getPublicKey2(secretKey) {
13418
+ return getExtendedPublicKey(secretKey).pointBytes;
13222
13419
  }
13223
13420
  function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
13224
- const msg = concatBytes2(...msgs);
13421
+ const msg = concatBytes(...msgs);
13225
13422
  return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
13226
13423
  }
13227
- function sign2(msg, privKey, options = {}) {
13424
+ function sign2(msg, secretKey, options = {}) {
13228
13425
  msg = ensureBytes("message", msg);
13229
13426
  if (prehash)
13230
13427
  msg = prehash(msg);
13231
- const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
13428
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
13232
13429
  const r = hashDomainToScalar(options.context, prefix, msg);
13233
- const R = G.multiply(r).toRawBytes();
13430
+ const R = BASE.multiply(r).toBytes();
13234
13431
  const k = hashDomainToScalar(options.context, R, pointBytes, msg);
13235
- const s = modN(r + k * scalar);
13236
- aInRange("signature.s", s, _0n4, CURVE_ORDER);
13237
- const res = concatBytes2(R, numberToBytesLE(s, Fp2.BYTES));
13238
- return ensureBytes("result", res, Fp2.BYTES * 2);
13432
+ const s = Fn2.create(r + k * scalar);
13433
+ if (!Fn2.isValid(s))
13434
+ throw new Error("sign failed: invalid s");
13435
+ const rs = concatBytes(R, Fn2.toBytes(s));
13436
+ return _abytes2(rs, lengths.signature, "result");
13239
13437
  }
13240
- const verifyOpts = VERIFY_DEFAULT;
13438
+ const verifyOpts = { zip215: true };
13241
13439
  function verify2(sig, msg, publicKey2, options = verifyOpts) {
13242
13440
  const { context, zip215 } = options;
13243
- const len = Fp2.BYTES;
13244
- sig = ensureBytes("signature", sig, 2 * len);
13441
+ const len = lengths.signature;
13442
+ sig = ensureBytes("signature", sig, len);
13245
13443
  msg = ensureBytes("message", msg);
13246
- publicKey2 = ensureBytes("publicKey", publicKey2, len);
13444
+ publicKey2 = ensureBytes("publicKey", publicKey2, lengths.publicKey);
13247
13445
  if (zip215 !== void 0)
13248
- abool("zip215", zip215);
13446
+ _abool2(zip215, "zip215");
13249
13447
  if (prehash)
13250
13448
  msg = prehash(msg);
13251
- const s = bytesToNumberLE(sig.slice(len, 2 * len));
13449
+ const mid = len / 2;
13450
+ const r = sig.subarray(0, mid);
13451
+ const s = bytesToNumberLE(sig.subarray(mid, len));
13252
13452
  let A, R, SB;
13253
13453
  try {
13254
- A = Point.fromHex(publicKey2, zip215);
13255
- R = Point.fromHex(sig.slice(0, len), zip215);
13256
- SB = G.multiplyUnsafe(s);
13454
+ A = Point.fromBytes(publicKey2, zip215);
13455
+ R = Point.fromBytes(r, zip215);
13456
+ SB = BASE.multiplyUnsafe(s);
13257
13457
  } catch (error) {
13258
13458
  return false;
13259
13459
  }
13260
13460
  if (!zip215 && A.isSmallOrder())
13261
13461
  return false;
13262
- const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
13462
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
13263
13463
  const RkA = R.add(A.multiplyUnsafe(k));
13264
- return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
13464
+ return RkA.subtract(SB).clearCofactor().is0();
13465
+ }
13466
+ const _size = Fp2.BYTES;
13467
+ const lengths = {
13468
+ secretKey: _size,
13469
+ publicKey: _size,
13470
+ signature: 2 * _size,
13471
+ seed: _size
13472
+ };
13473
+ function randomSecretKey(seed = randomBytes2(lengths.seed)) {
13474
+ return _abytes2(seed, lengths.seed, "seed");
13475
+ }
13476
+ function keygen(seed) {
13477
+ const secretKey = utils.randomSecretKey(seed);
13478
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
13479
+ }
13480
+ function isValidSecretKey(key) {
13481
+ return isBytes(key) && key.length === Fn2.BYTES;
13482
+ }
13483
+ function isValidPublicKey(key, zip215) {
13484
+ try {
13485
+ return !!Point.fromBytes(key, zip215);
13486
+ } catch (error) {
13487
+ return false;
13488
+ }
13265
13489
  }
13266
- G._setWindowSize(8);
13267
13490
  const utils = {
13268
13491
  getExtendedPublicKey,
13269
- /** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */
13270
- randomPrivateKey: () => randomBytes2(Fp2.BYTES),
13492
+ randomSecretKey,
13493
+ isValidSecretKey,
13494
+ isValidPublicKey,
13271
13495
  /**
13272
- * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
13273
- * values. This slows down first getPublicKey() by milliseconds (see Speed section),
13274
- * but allows to speed-up subsequent getPublicKey() calls up to 20x.
13275
- * @param windowSize 2, 4, 8, 16
13496
+ * Converts ed public key to x public key. Uses formula:
13497
+ * - ed25519:
13498
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
13499
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
13500
+ * - ed448:
13501
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
13502
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
13276
13503
  */
13504
+ toMontgomery(publicKey2) {
13505
+ const { y } = Point.fromBytes(publicKey2);
13506
+ const size = lengths.publicKey;
13507
+ const is25519 = size === 32;
13508
+ if (!is25519 && size !== 57)
13509
+ throw new Error("only defined for 25519 and 448");
13510
+ const u = is25519 ? Fp2.div(_1n4 + y, _1n4 - y) : Fp2.div(y - _1n4, y + _1n4);
13511
+ return Fp2.toBytes(u);
13512
+ },
13513
+ toMontgomerySecret(secretKey) {
13514
+ const size = lengths.secretKey;
13515
+ _abytes2(secretKey, size);
13516
+ const hashed = cHash(secretKey.subarray(0, size));
13517
+ return adjustScalarBytes2(hashed).subarray(0, size);
13518
+ },
13519
+ /** @deprecated */
13520
+ randomPrivateKey: randomSecretKey,
13521
+ /** @deprecated */
13277
13522
  precompute(windowSize = 8, point = Point.BASE) {
13278
- point._setWindowSize(windowSize);
13279
- point.multiply(BigInt(3));
13280
- return point;
13523
+ return point.precompute(windowSize, false);
13281
13524
  }
13282
13525
  };
13283
- return {
13284
- CURVE,
13526
+ return Object.freeze({
13527
+ keygen,
13285
13528
  getPublicKey: getPublicKey2,
13286
13529
  sign: sign2,
13287
13530
  verify: verify2,
13288
- ExtendedPoint: Point,
13289
- utils
13531
+ utils,
13532
+ Point,
13533
+ lengths
13534
+ });
13535
+ }
13536
+ function _eddsa_legacy_opts_to_new(c) {
13537
+ const CURVE = {
13538
+ a: c.a,
13539
+ d: c.d,
13540
+ p: c.Fp.ORDER,
13541
+ n: c.n,
13542
+ h: c.h,
13543
+ Gx: c.Gx,
13544
+ Gy: c.Gy
13545
+ };
13546
+ const Fp2 = c.Fp;
13547
+ const Fn2 = Field(CURVE.n, c.nBitLength, true);
13548
+ const curveOpts = { Fp: Fp2, Fn: Fn2, uvRatio: c.uvRatio };
13549
+ const eddsaOpts = {
13550
+ randomBytes: c.randomBytes,
13551
+ adjustScalarBytes: c.adjustScalarBytes,
13552
+ domain: c.domain,
13553
+ prehash: c.prehash,
13554
+ mapToCurve: c.mapToCurve
13290
13555
  };
13556
+ return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
13557
+ }
13558
+ function _eddsa_new_output_to_legacy(c, eddsa2) {
13559
+ const Point = eddsa2.Point;
13560
+ const legacy = Object.assign({}, eddsa2, {
13561
+ ExtendedPoint: Point,
13562
+ CURVE: c,
13563
+ nBitLength: Point.Fn.BITS,
13564
+ nByteLength: Point.Fn.BYTES
13565
+ });
13566
+ return legacy;
13567
+ }
13568
+ function twistedEdwards(c) {
13569
+ const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
13570
+ const Point = edwards(CURVE, curveOpts);
13571
+ const EDDSA = eddsa(Point, hash, eddsaOpts);
13572
+ return _eddsa_new_output_to_legacy(c, EDDSA);
13291
13573
  }
13292
13574
 
13293
- // node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/ed25519.js
13294
- var ED25519_P = BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");
13295
- var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
13296
- var _0n5 = BigInt(0);
13575
+ // node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js
13576
+ var _0n5 = /* @__PURE__ */ BigInt(0);
13297
13577
  var _1n5 = BigInt(1);
13298
13578
  var _2n3 = BigInt(2);
13299
13579
  var _3n2 = BigInt(3);
13300
13580
  var _5n2 = BigInt(5);
13301
13581
  var _8n3 = BigInt(8);
13582
+ var ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
13583
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
13584
+ p: ed25519_CURVE_p,
13585
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
13586
+ h: _8n3,
13587
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
13588
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
13589
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
13590
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
13591
+ }))();
13302
13592
  function ed25519_pow_2_252_3(x) {
13303
13593
  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
13304
- const P = ED25519_P;
13594
+ const P = ed25519_CURVE_p;
13305
13595
  const x2 = x * x % P;
13306
13596
  const b2 = x2 * x % P;
13307
13597
  const b4 = pow2(b2, _2n3, P) * b2 % P;
@@ -13322,8 +13612,9 @@ function adjustScalarBytes(bytes) {
13322
13612
  bytes[31] |= 64;
13323
13613
  return bytes;
13324
13614
  }
13615
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
13325
13616
  function uvRatio(u, v) {
13326
- const P = ED25519_P;
13617
+ const P = ed25519_CURVE_p;
13327
13618
  const v32 = mod(v * v * v, P);
13328
13619
  const v7 = mod(v32 * v32 * v, P);
13329
13620
  const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
@@ -13342,21 +13633,12 @@ function uvRatio(u, v) {
13342
13633
  x = mod(-x, P);
13343
13634
  return { isValid: useRoot1 || useRoot2, value: x };
13344
13635
  }
13345
- var Fp = /* @__PURE__ */ (() => Field(ED25519_P, void 0, true))();
13636
+ var Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
13637
+ var Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
13346
13638
  var ed25519Defaults = /* @__PURE__ */ (() => ({
13347
- // Removing Fp.create() will still work, and is 10% faster on sign
13348
- a: Fp.create(BigInt(-1)),
13349
- // d is -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))
13350
- d: BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),
13351
- // Finite field 2n**255n - 19n
13639
+ ...ed25519_CURVE,
13352
13640
  Fp,
13353
- // Subgroup order 2n**252n + 27742317777372353535851937790883648493n;
13354
- n: BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),
13355
- h: _8n3,
13356
- Gx: BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),
13357
- Gy: BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),
13358
13641
  hash: sha512,
13359
- randomBytes,
13360
13642
  adjustScalarBytes,
13361
13643
  // dom2
13362
13644
  // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
@@ -13364,6 +13646,154 @@ var ed25519Defaults = /* @__PURE__ */ (() => ({
13364
13646
  uvRatio
13365
13647
  }))();
13366
13648
  var ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
13649
+ var SQRT_M1 = ED25519_SQRT_M1;
13650
+ var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
13651
+ var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
13652
+ var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
13653
+ var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
13654
+ var invertSqrt = (number2) => uvRatio(_1n5, number2);
13655
+ var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
13656
+ var bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
13657
+ function calcElligatorRistrettoMap(r0) {
13658
+ const { d } = ed25519_CURVE;
13659
+ const P = ed25519_CURVE_p;
13660
+ const mod2 = (n) => Fp.create(n);
13661
+ const r = mod2(SQRT_M1 * r0 * r0);
13662
+ const Ns = mod2((r + _1n5) * ONE_MINUS_D_SQ);
13663
+ let c = BigInt(-1);
13664
+ const D = mod2((c - d * r) * mod2(r + d));
13665
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
13666
+ let s_ = mod2(s * r0);
13667
+ if (!isNegativeLE(s_, P))
13668
+ s_ = mod2(-s_);
13669
+ if (!Ns_D_is_sq)
13670
+ s = s_;
13671
+ if (!Ns_D_is_sq)
13672
+ c = r;
13673
+ const Nt = mod2(c * (r - _1n5) * D_MINUS_ONE_SQ - D);
13674
+ const s2 = s * s;
13675
+ const W0 = mod2((s + s) * D);
13676
+ const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
13677
+ const W2 = mod2(_1n5 - s2);
13678
+ const W3 = mod2(_1n5 + s2);
13679
+ return new ed25519.Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
13680
+ }
13681
+ function ristretto255_map(bytes) {
13682
+ abytes(bytes, 64);
13683
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
13684
+ const R1 = calcElligatorRistrettoMap(r1);
13685
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
13686
+ const R2 = calcElligatorRistrettoMap(r2);
13687
+ return new _RistrettoPoint(R1.add(R2));
13688
+ }
13689
+ var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
13690
+ constructor(ep) {
13691
+ super(ep);
13692
+ }
13693
+ static fromAffine(ap) {
13694
+ return new __RistrettoPoint(ed25519.Point.fromAffine(ap));
13695
+ }
13696
+ assertSame(other) {
13697
+ if (!(other instanceof __RistrettoPoint))
13698
+ throw new Error("RistrettoPoint expected");
13699
+ }
13700
+ init(ep) {
13701
+ return new __RistrettoPoint(ep);
13702
+ }
13703
+ /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
13704
+ static hashToCurve(hex) {
13705
+ return ristretto255_map(ensureBytes("ristrettoHash", hex, 64));
13706
+ }
13707
+ static fromBytes(bytes) {
13708
+ abytes(bytes, 32);
13709
+ const { a, d } = ed25519_CURVE;
13710
+ const P = ed25519_CURVE_p;
13711
+ const mod2 = (n) => Fp.create(n);
13712
+ const s = bytes255ToNumberLE(bytes);
13713
+ if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
13714
+ throw new Error("invalid ristretto255 encoding 1");
13715
+ const s2 = mod2(s * s);
13716
+ const u1 = mod2(_1n5 + a * s2);
13717
+ const u2 = mod2(_1n5 - a * s2);
13718
+ const u1_2 = mod2(u1 * u1);
13719
+ const u2_2 = mod2(u2 * u2);
13720
+ const v = mod2(a * d * u1_2 - u2_2);
13721
+ const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
13722
+ const Dx = mod2(I * u2);
13723
+ const Dy = mod2(I * Dx * v);
13724
+ let x = mod2((s + s) * Dx);
13725
+ if (isNegativeLE(x, P))
13726
+ x = mod2(-x);
13727
+ const y = mod2(u1 * Dy);
13728
+ const t = mod2(x * y);
13729
+ if (!isValid || isNegativeLE(t, P) || y === _0n5)
13730
+ throw new Error("invalid ristretto255 encoding 2");
13731
+ return new __RistrettoPoint(new ed25519.Point(x, y, _1n5, t));
13732
+ }
13733
+ /**
13734
+ * Converts ristretto-encoded string to ristretto point.
13735
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
13736
+ * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
13737
+ */
13738
+ static fromHex(hex) {
13739
+ return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex, 32));
13740
+ }
13741
+ static msm(points, scalars) {
13742
+ return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
13743
+ }
13744
+ /**
13745
+ * Encodes ristretto point to Uint8Array.
13746
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
13747
+ */
13748
+ toBytes() {
13749
+ let { X, Y, Z, T } = this.ep;
13750
+ const P = ed25519_CURVE_p;
13751
+ const mod2 = (n) => Fp.create(n);
13752
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
13753
+ const u2 = mod2(X * Y);
13754
+ const u2sq = mod2(u2 * u2);
13755
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
13756
+ const D1 = mod2(invsqrt * u1);
13757
+ const D2 = mod2(invsqrt * u2);
13758
+ const zInv = mod2(D1 * D2 * T);
13759
+ let D;
13760
+ if (isNegativeLE(T * zInv, P)) {
13761
+ let _x = mod2(Y * SQRT_M1);
13762
+ let _y = mod2(X * SQRT_M1);
13763
+ X = _x;
13764
+ Y = _y;
13765
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
13766
+ } else {
13767
+ D = D2;
13768
+ }
13769
+ if (isNegativeLE(X * zInv, P))
13770
+ Y = mod2(-Y);
13771
+ let s = mod2((Z - Y) * D);
13772
+ if (isNegativeLE(s, P))
13773
+ s = mod2(-s);
13774
+ return Fp.toBytes(s);
13775
+ }
13776
+ /**
13777
+ * Compares two Ristretto points.
13778
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
13779
+ */
13780
+ equals(other) {
13781
+ this.assertSame(other);
13782
+ const { X: X1, Y: Y1 } = this.ep;
13783
+ const { X: X2, Y: Y2 } = other.ep;
13784
+ const mod2 = (n) => Fp.create(n);
13785
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
13786
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
13787
+ return one || two;
13788
+ }
13789
+ is0() {
13790
+ return this.equals(__RistrettoPoint.ZERO);
13791
+ }
13792
+ };
13793
+ _RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
13794
+ _RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
13795
+ _RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
13796
+ _RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
13367
13797
 
13368
13798
  // node_modules/.pnpm/@solana+web3.js@1.98.4_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@solana/web3.js/lib/index.esm.js
13369
13799
  var import_bn = __toESM(require_bn());
@@ -15763,7 +16193,7 @@ fetch.isRedirect = function(code) {
15763
16193
  fetch.Promise = global.Promise;
15764
16194
  var lib_default = fetch;
15765
16195
 
15766
- // node_modules/.pnpm/ws@8.18.3_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/wrapper.mjs
16196
+ // node_modules/.pnpm/ws@8.19.0_bufferutil@4.1.0_utf-8-validate@5.0.10/node_modules/ws/wrapper.mjs
15767
16197
  var import_stream2 = __toESM(require_stream(), 1);
15768
16198
  var import_receiver = __toESM(require_receiver(), 1);
15769
16199
  var import_sender = __toESM(require_sender(), 1);
@@ -15771,10 +16201,10 @@ var import_websocket = __toESM(require_websocket(), 1);
15771
16201
  var import_websocket_server = __toESM(require_websocket_server(), 1);
15772
16202
  var wrapper_default = import_websocket.default;
15773
16203
 
15774
- // node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.mjs
16204
+ // node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.mjs
15775
16205
  var import_index = __toESM(require_eventemitter3(), 1);
15776
16206
 
15777
- // node_modules/.pnpm/rpc-websockets@9.3.2/node_modules/rpc-websockets/dist/index.mjs
16207
+ // node_modules/.pnpm/rpc-websockets@9.3.3/node_modules/rpc-websockets/dist/index.mjs
15778
16208
  import url from "url";
15779
16209
  function WebSocket2(address, options) {
15780
16210
  return new wrapper_default(address, options);
@@ -16115,7 +16545,7 @@ var CommonClient = class extends import_index.default {
16115
16545
  var _0n6 = BigInt(0);
16116
16546
  var _1n6 = BigInt(1);
16117
16547
  var _2n4 = BigInt(2);
16118
- var _7n = BigInt(7);
16548
+ var _7n2 = BigInt(7);
16119
16549
  var _256n = BigInt(256);
16120
16550
  var _0x71n = BigInt(113);
16121
16551
  var SHA3_PI = [];
@@ -16127,7 +16557,7 @@ for (let round = 0, R = _1n6, x = 1, y = 0; round < 24; round++) {
16127
16557
  SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
16128
16558
  let t = _0n6;
16129
16559
  for (let j = 0; j < 7; j++) {
16130
- R = (R << _1n6 ^ (R >> _7n) * _0x71n) % _256n;
16560
+ R = (R << _1n6 ^ (R >> _7n2) * _0x71n) % _256n;
16131
16561
  if (R & _2n4)
16132
16562
  t ^= _1n6 << (_1n6 << /* @__PURE__ */ BigInt(j)) - _1n6;
16133
16563
  }
@@ -16360,37 +16790,41 @@ var HMAC = class extends Hash {
16360
16790
  var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
16361
16791
  hmac.create = (hash, key) => new HMAC(hash, key);
16362
16792
 
16363
- // node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/weierstrass.js
16364
- function validateSigVerOpts(opts) {
16365
- if (opts.lowS !== void 0)
16366
- abool("lowS", opts.lowS);
16367
- if (opts.prehash !== void 0)
16368
- abool("prehash", opts.prehash);
16793
+ // node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/weierstrass.js
16794
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n5) / den;
16795
+ function _splitEndoScalar(k, basis, n) {
16796
+ const [[a1, b1], [a2, b2]] = basis;
16797
+ const c1 = divNearest(b2 * k, n);
16798
+ const c2 = divNearest(-b1 * k, n);
16799
+ let k1 = k - c1 * a1 - c2 * a2;
16800
+ let k2 = -c1 * b1 - c2 * b2;
16801
+ const k1neg = k1 < _0n7;
16802
+ const k2neg = k2 < _0n7;
16803
+ if (k1neg)
16804
+ k1 = -k1;
16805
+ if (k2neg)
16806
+ k2 = -k2;
16807
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n7;
16808
+ if (k1 < _0n7 || k1 >= MAX_NUM || k2 < _0n7 || k2 >= MAX_NUM) {
16809
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
16810
+ }
16811
+ return { k1neg, k1, k2neg, k2 };
16369
16812
  }
16370
- function validatePointOpts(curve) {
16371
- const opts = validateBasic(curve);
16372
- validateObject(opts, {
16373
- a: "field",
16374
- b: "field"
16375
- }, {
16376
- allowInfinityPoint: "boolean",
16377
- allowedPrivateKeyLengths: "array",
16378
- clearCofactor: "function",
16379
- fromBytes: "function",
16380
- isTorsionFree: "function",
16381
- toBytes: "function",
16382
- wrapPrivateKey: "boolean"
16383
- });
16384
- const { endo, Fp: Fp2, a } = opts;
16385
- if (endo) {
16386
- if (!Fp2.eql(a, Fp2.ZERO)) {
16387
- throw new Error("invalid endo: CURVE.a must be 0");
16388
- }
16389
- if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
16390
- throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
16391
- }
16392
- }
16393
- return Object.freeze({ ...opts });
16813
+ function validateSigFormat(format) {
16814
+ if (!["compact", "recovered", "der"].includes(format))
16815
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
16816
+ return format;
16817
+ }
16818
+ function validateSigOpts(opts, def) {
16819
+ const optsn = {};
16820
+ for (let optName of Object.keys(def)) {
16821
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
16822
+ }
16823
+ _abool2(optsn.lowS, "lowS");
16824
+ _abool2(optsn.prehash, "prehash");
16825
+ if (optsn.format !== void 0)
16826
+ validateSigFormat(optsn.format);
16827
+ return optsn;
16394
16828
  }
16395
16829
  var DERErr = class extends Error {
16396
16830
  constructor(m = "") {
@@ -16497,33 +16931,106 @@ var DER = {
16497
16931
  return tlv.encode(48, seq2);
16498
16932
  }
16499
16933
  };
16500
- function numToSizedHex(num, size) {
16501
- return bytesToHex(numberToBytesBE(num, size));
16502
- }
16503
16934
  var _0n7 = BigInt(0);
16504
16935
  var _1n7 = BigInt(1);
16505
16936
  var _2n5 = BigInt(2);
16506
16937
  var _3n3 = BigInt(3);
16507
16938
  var _4n2 = BigInt(4);
16508
- function weierstrassPoints(opts) {
16509
- const CURVE = validatePointOpts(opts);
16510
- const { Fp: Fp2 } = CURVE;
16511
- const Fn = Field(CURVE.n, CURVE.nBitLength);
16512
- const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => {
16513
- const a = point.toAffine();
16514
- return concatBytes2(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y));
16939
+ function _normFnElement(Fn2, key) {
16940
+ const { BYTES: expected } = Fn2;
16941
+ let num;
16942
+ if (typeof key === "bigint") {
16943
+ num = key;
16944
+ } else {
16945
+ let bytes = ensureBytes("private key", key);
16946
+ try {
16947
+ num = Fn2.fromBytes(bytes);
16948
+ } catch (error) {
16949
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
16950
+ }
16951
+ }
16952
+ if (!Fn2.isValidNot0(num))
16953
+ throw new Error("invalid private key: out of range [1..N-1]");
16954
+ return num;
16955
+ }
16956
+ function weierstrassN(params, extraOpts = {}) {
16957
+ const validated = _createCurveFields("weierstrass", params, extraOpts);
16958
+ const { Fp: Fp2, Fn: Fn2 } = validated;
16959
+ let CURVE = validated.CURVE;
16960
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
16961
+ _validateObject(extraOpts, {}, {
16962
+ allowInfinityPoint: "boolean",
16963
+ clearCofactor: "function",
16964
+ isTorsionFree: "function",
16965
+ fromBytes: "function",
16966
+ toBytes: "function",
16967
+ endo: "object",
16968
+ wrapPrivateKey: "boolean"
16515
16969
  });
16516
- const fromBytes = CURVE.fromBytes || ((bytes) => {
16970
+ const { endo } = extraOpts;
16971
+ if (endo) {
16972
+ if (!Fp2.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
16973
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
16974
+ }
16975
+ }
16976
+ const lengths = getWLengths(Fp2, Fn2);
16977
+ function assertCompressionIsSupported() {
16978
+ if (!Fp2.isOdd)
16979
+ throw new Error("compression is not supported: Field does not have .isOdd()");
16980
+ }
16981
+ function pointToBytes(_c, point, isCompressed) {
16982
+ const { x, y } = point.toAffine();
16983
+ const bx = Fp2.toBytes(x);
16984
+ _abool2(isCompressed, "isCompressed");
16985
+ if (isCompressed) {
16986
+ assertCompressionIsSupported();
16987
+ const hasEvenY = !Fp2.isOdd(y);
16988
+ return concatBytes(pprefix(hasEvenY), bx);
16989
+ } else {
16990
+ return concatBytes(Uint8Array.of(4), bx, Fp2.toBytes(y));
16991
+ }
16992
+ }
16993
+ function pointFromBytes(bytes) {
16994
+ _abytes2(bytes, void 0, "Point");
16995
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
16996
+ const length = bytes.length;
16997
+ const head = bytes[0];
16517
16998
  const tail = bytes.subarray(1);
16518
- const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
16519
- const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
16520
- return { x, y };
16521
- });
16999
+ if (length === comp && (head === 2 || head === 3)) {
17000
+ const x = Fp2.fromBytes(tail);
17001
+ if (!Fp2.isValid(x))
17002
+ throw new Error("bad point: is not on curve, wrong x");
17003
+ const y2 = weierstrassEquation(x);
17004
+ let y;
17005
+ try {
17006
+ y = Fp2.sqrt(y2);
17007
+ } catch (sqrtError) {
17008
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
17009
+ throw new Error("bad point: is not on curve, sqrt error" + err);
17010
+ }
17011
+ assertCompressionIsSupported();
17012
+ const isYOdd = Fp2.isOdd(y);
17013
+ const isHeadOdd = (head & 1) === 1;
17014
+ if (isHeadOdd !== isYOdd)
17015
+ y = Fp2.neg(y);
17016
+ return { x, y };
17017
+ } else if (length === uncomp && head === 4) {
17018
+ const L = Fp2.BYTES;
17019
+ const x = Fp2.fromBytes(tail.subarray(0, L));
17020
+ const y = Fp2.fromBytes(tail.subarray(L, L * 2));
17021
+ if (!isValidXY(x, y))
17022
+ throw new Error("bad point: is not on curve");
17023
+ return { x, y };
17024
+ } else {
17025
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
17026
+ }
17027
+ }
17028
+ const encodePoint = extraOpts.toBytes || pointToBytes;
17029
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
16522
17030
  function weierstrassEquation(x) {
16523
- const { a, b } = CURVE;
16524
17031
  const x2 = Fp2.sqr(x);
16525
17032
  const x3 = Fp2.mul(x2, x);
16526
- return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b);
17033
+ return Fp2.add(Fp2.add(x3, Fp2.mul(x, CURVE.a)), CURVE.b);
16527
17034
  }
16528
17035
  function isValidXY(x, y) {
16529
17036
  const left = Fp2.sqr(y);
@@ -16536,90 +17043,87 @@ function weierstrassPoints(opts) {
16536
17043
  const _27b2 = Fp2.mul(Fp2.sqr(CURVE.b), BigInt(27));
16537
17044
  if (Fp2.is0(Fp2.add(_4a3, _27b2)))
16538
17045
  throw new Error("bad curve params: a or b");
16539
- function isWithinCurveOrder(num) {
16540
- return inRange(num, _1n7, CURVE.n);
16541
- }
16542
- function normPrivateKeyToScalar(key) {
16543
- const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
16544
- if (lengths && typeof key !== "bigint") {
16545
- if (isBytes2(key))
16546
- key = bytesToHex(key);
16547
- if (typeof key !== "string" || !lengths.includes(key.length))
16548
- throw new Error("invalid private key");
16549
- key = key.padStart(nByteLength * 2, "0");
16550
- }
16551
- let num;
16552
- try {
16553
- num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
16554
- } catch (error) {
16555
- throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
16556
- }
16557
- if (wrapPrivateKey)
16558
- num = mod(num, N);
16559
- aInRange("private key", num, _1n7, N);
16560
- return num;
17046
+ function acoord(title, n, banZero = false) {
17047
+ if (!Fp2.isValid(n) || banZero && Fp2.is0(n))
17048
+ throw new Error(`bad point coordinate ${title}`);
17049
+ return n;
16561
17050
  }
16562
17051
  function aprjpoint(other) {
16563
17052
  if (!(other instanceof Point))
16564
17053
  throw new Error("ProjectivePoint expected");
16565
17054
  }
17055
+ function splitEndoScalarN(k) {
17056
+ if (!endo || !endo.basises)
17057
+ throw new Error("no endo");
17058
+ return _splitEndoScalar(k, endo.basises, Fn2.ORDER);
17059
+ }
16566
17060
  const toAffineMemo = memoized((p, iz) => {
16567
- const { px: x, py: y, pz: z } = p;
16568
- if (Fp2.eql(z, Fp2.ONE))
16569
- return { x, y };
17061
+ const { X, Y, Z } = p;
17062
+ if (Fp2.eql(Z, Fp2.ONE))
17063
+ return { x: X, y: Y };
16570
17064
  const is0 = p.is0();
16571
17065
  if (iz == null)
16572
- iz = is0 ? Fp2.ONE : Fp2.inv(z);
16573
- const ax = Fp2.mul(x, iz);
16574
- const ay = Fp2.mul(y, iz);
16575
- const zz = Fp2.mul(z, iz);
17066
+ iz = is0 ? Fp2.ONE : Fp2.inv(Z);
17067
+ const x = Fp2.mul(X, iz);
17068
+ const y = Fp2.mul(Y, iz);
17069
+ const zz = Fp2.mul(Z, iz);
16576
17070
  if (is0)
16577
17071
  return { x: Fp2.ZERO, y: Fp2.ZERO };
16578
17072
  if (!Fp2.eql(zz, Fp2.ONE))
16579
17073
  throw new Error("invZ was invalid");
16580
- return { x: ax, y: ay };
17074
+ return { x, y };
16581
17075
  });
16582
17076
  const assertValidMemo = memoized((p) => {
16583
17077
  if (p.is0()) {
16584
- if (CURVE.allowInfinityPoint && !Fp2.is0(p.py))
17078
+ if (extraOpts.allowInfinityPoint && !Fp2.is0(p.Y))
16585
17079
  return;
16586
17080
  throw new Error("bad point: ZERO");
16587
17081
  }
16588
17082
  const { x, y } = p.toAffine();
16589
17083
  if (!Fp2.isValid(x) || !Fp2.isValid(y))
16590
- throw new Error("bad point: x or y not FE");
17084
+ throw new Error("bad point: x or y not field elements");
16591
17085
  if (!isValidXY(x, y))
16592
17086
  throw new Error("bad point: equation left != right");
16593
17087
  if (!p.isTorsionFree())
16594
17088
  throw new Error("bad point: not in prime-order subgroup");
16595
17089
  return true;
16596
17090
  });
17091
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
17092
+ k2p = new Point(Fp2.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
17093
+ k1p = negateCt(k1neg, k1p);
17094
+ k2p = negateCt(k2neg, k2p);
17095
+ return k1p.add(k2p);
17096
+ }
16597
17097
  class Point {
16598
- constructor(px, py, pz) {
16599
- if (px == null || !Fp2.isValid(px))
16600
- throw new Error("x required");
16601
- if (py == null || !Fp2.isValid(py) || Fp2.is0(py))
16602
- throw new Error("y required");
16603
- if (pz == null || !Fp2.isValid(pz))
16604
- throw new Error("z required");
16605
- this.px = px;
16606
- this.py = py;
16607
- this.pz = pz;
17098
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
17099
+ constructor(X, Y, Z) {
17100
+ this.X = acoord("x", X);
17101
+ this.Y = acoord("y", Y, true);
17102
+ this.Z = acoord("z", Z);
16608
17103
  Object.freeze(this);
16609
17104
  }
16610
- // Does not validate if the point is on-curve.
16611
- // Use fromHex instead, or call assertValidity() later.
17105
+ static CURVE() {
17106
+ return CURVE;
17107
+ }
17108
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
16612
17109
  static fromAffine(p) {
16613
17110
  const { x, y } = p || {};
16614
17111
  if (!p || !Fp2.isValid(x) || !Fp2.isValid(y))
16615
17112
  throw new Error("invalid affine point");
16616
17113
  if (p instanceof Point)
16617
17114
  throw new Error("projective point not allowed");
16618
- const is0 = (i) => Fp2.eql(i, Fp2.ZERO);
16619
- if (is0(x) && is0(y))
17115
+ if (Fp2.is0(x) && Fp2.is0(y))
16620
17116
  return Point.ZERO;
16621
17117
  return new Point(x, y, Fp2.ONE);
16622
17118
  }
17119
+ static fromBytes(bytes) {
17120
+ const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
17121
+ P.assertValidity();
17122
+ return P;
17123
+ }
17124
+ static fromHex(hex) {
17125
+ return Point.fromBytes(ensureBytes("pointHex", hex));
17126
+ }
16623
17127
  get x() {
16624
17128
  return this.toAffine().x;
16625
17129
  }
@@ -16627,62 +17131,40 @@ function weierstrassPoints(opts) {
16627
17131
  return this.toAffine().y;
16628
17132
  }
16629
17133
  /**
16630
- * Takes a bunch of Projective Points but executes only one
16631
- * inversion on all of them. Inversion is very slow operation,
16632
- * so this improves performance massively.
16633
- * Optimization: converts a list of projective points to a list of identical points with Z=1.
16634
- */
16635
- static normalizeZ(points) {
16636
- const toInv = FpInvertBatch(Fp2, points.map((p) => p.pz));
16637
- return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
16638
- }
16639
- /**
16640
- * Converts hash string or Uint8Array to Point.
16641
- * @param hex short/long ECDSA hex
17134
+ *
17135
+ * @param windowSize
17136
+ * @param isLazy true will defer table computation until the first multiplication
17137
+ * @returns
16642
17138
  */
16643
- static fromHex(hex) {
16644
- const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
16645
- P.assertValidity();
16646
- return P;
16647
- }
16648
- // Multiplies generator point by privateKey.
16649
- static fromPrivateKey(privateKey) {
16650
- return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
16651
- }
16652
- // Multiscalar Multiplication
16653
- static msm(points, scalars) {
16654
- return pippenger(Point, Fn, points, scalars);
16655
- }
16656
- // "Private method", don't use it directly
16657
- _setWindowSize(windowSize) {
16658
- wnaf.setWindowSize(this, windowSize);
17139
+ precompute(windowSize = 8, isLazy = true) {
17140
+ wnaf.createCache(this, windowSize);
17141
+ if (!isLazy)
17142
+ this.multiply(_3n3);
17143
+ return this;
16659
17144
  }
16660
- // A point on curve is valid if it conforms to equation.
17145
+ // TODO: return `this`
17146
+ /** A point on curve is valid if it conforms to equation. */
16661
17147
  assertValidity() {
16662
17148
  assertValidMemo(this);
16663
17149
  }
16664
17150
  hasEvenY() {
16665
17151
  const { y } = this.toAffine();
16666
- if (Fp2.isOdd)
16667
- return !Fp2.isOdd(y);
16668
- throw new Error("Field doesn't support isOdd");
17152
+ if (!Fp2.isOdd)
17153
+ throw new Error("Field doesn't support isOdd");
17154
+ return !Fp2.isOdd(y);
16669
17155
  }
16670
- /**
16671
- * Compare one point to another.
16672
- */
17156
+ /** Compare one point to another. */
16673
17157
  equals(other) {
16674
17158
  aprjpoint(other);
16675
- const { px: X1, py: Y1, pz: Z1 } = this;
16676
- const { px: X2, py: Y2, pz: Z2 } = other;
17159
+ const { X: X1, Y: Y1, Z: Z1 } = this;
17160
+ const { X: X2, Y: Y2, Z: Z2 } = other;
16677
17161
  const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
16678
17162
  const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
16679
17163
  return U1 && U2;
16680
17164
  }
16681
- /**
16682
- * Flips point to one corresponding to (x, -y) in Affine coordinates.
16683
- */
17165
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
16684
17166
  negate() {
16685
- return new Point(this.px, Fp2.neg(this.py), this.pz);
17167
+ return new Point(this.X, Fp2.neg(this.Y), this.Z);
16686
17168
  }
16687
17169
  // Renes-Costello-Batina exception-free doubling formula.
16688
17170
  // There is 30% faster Jacobian formula, but it is not complete.
@@ -16691,7 +17173,7 @@ function weierstrassPoints(opts) {
16691
17173
  double() {
16692
17174
  const { a, b } = CURVE;
16693
17175
  const b3 = Fp2.mul(b, _3n3);
16694
- const { px: X1, py: Y1, pz: Z1 } = this;
17176
+ const { X: X1, Y: Y1, Z: Z1 } = this;
16695
17177
  let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
16696
17178
  let t0 = Fp2.mul(X1, X1);
16697
17179
  let t1 = Fp2.mul(Y1, Y1);
@@ -16732,8 +17214,8 @@ function weierstrassPoints(opts) {
16732
17214
  // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
16733
17215
  add(other) {
16734
17216
  aprjpoint(other);
16735
- const { px: X1, py: Y1, pz: Z1 } = this;
16736
- const { px: X2, py: Y2, pz: Z2 } = other;
17217
+ const { X: X1, Y: Y1, Z: Z1 } = this;
17218
+ const { X: X2, Y: Y2, Z: Z2 } = other;
16737
17219
  let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
16738
17220
  const a = CURVE.a;
16739
17221
  const b3 = Fp2.mul(CURVE.b, _3n3);
@@ -16785,44 +17267,6 @@ function weierstrassPoints(opts) {
16785
17267
  is0() {
16786
17268
  return this.equals(Point.ZERO);
16787
17269
  }
16788
- wNAF(n) {
16789
- return wnaf.wNAFCached(this, n, Point.normalizeZ);
16790
- }
16791
- /**
16792
- * Non-constant-time multiplication. Uses double-and-add algorithm.
16793
- * It's faster, but should only be used when you don't care about
16794
- * an exposed private key e.g. sig verification, which works over *public* keys.
16795
- */
16796
- multiplyUnsafe(sc) {
16797
- const { endo: endo2, n: N } = CURVE;
16798
- aInRange("scalar", sc, _0n7, N);
16799
- const I = Point.ZERO;
16800
- if (sc === _0n7)
16801
- return I;
16802
- if (this.is0() || sc === _1n7)
16803
- return this;
16804
- if (!endo2 || wnaf.hasPrecomputes(this))
16805
- return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
16806
- let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc);
16807
- let k1p = I;
16808
- let k2p = I;
16809
- let d = this;
16810
- while (k1 > _0n7 || k2 > _0n7) {
16811
- if (k1 & _1n7)
16812
- k1p = k1p.add(d);
16813
- if (k2 & _1n7)
16814
- k2p = k2p.add(d);
16815
- d = d.double();
16816
- k1 >>= _1n7;
16817
- k2 >>= _1n7;
16818
- }
16819
- if (k1neg)
16820
- k1p = k1p.negate();
16821
- if (k2neg)
16822
- k2p = k2p.negate();
16823
- k2p = new Point(Fp2.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
16824
- return k1p.add(k2p);
16825
- }
16826
17270
  /**
16827
17271
  * Constant time multiplication.
16828
17272
  * Uses wNAF method. Windowed method may be 10% faster,
@@ -16833,204 +17277,295 @@ function weierstrassPoints(opts) {
16833
17277
  * @returns New point
16834
17278
  */
16835
17279
  multiply(scalar) {
16836
- const { endo: endo2, n: N } = CURVE;
16837
- aInRange("scalar", scalar, _1n7, N);
17280
+ const { endo: endo2 } = extraOpts;
17281
+ if (!Fn2.isValidNot0(scalar))
17282
+ throw new Error("invalid scalar: out of range");
16838
17283
  let point, fake;
17284
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
16839
17285
  if (endo2) {
16840
- const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar);
16841
- let { p: k1p, f: f1p } = this.wNAF(k1);
16842
- let { p: k2p, f: f2p } = this.wNAF(k2);
16843
- k1p = wnaf.constTimeNegate(k1neg, k1p);
16844
- k2p = wnaf.constTimeNegate(k2neg, k2p);
16845
- k2p = new Point(Fp2.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
16846
- point = k1p.add(k2p);
16847
- fake = f1p.add(f2p);
17286
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
17287
+ const { p: k1p, f: k1f } = mul(k1);
17288
+ const { p: k2p, f: k2f } = mul(k2);
17289
+ fake = k1f.add(k2f);
17290
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
16848
17291
  } else {
16849
- const { p, f } = this.wNAF(scalar);
17292
+ const { p, f } = mul(scalar);
16850
17293
  point = p;
16851
17294
  fake = f;
16852
17295
  }
16853
- return Point.normalizeZ([point, fake])[0];
17296
+ return normalizeZ(Point, [point, fake])[0];
16854
17297
  }
16855
17298
  /**
16856
- * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
16857
- * Not using Strauss-Shamir trick: precomputation tables are faster.
16858
- * The trick could be useful if both P and Q are not G (not in our case).
16859
- * @returns non-zero affine point
17299
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
17300
+ * It's faster, but should only be used when you don't care about
17301
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
16860
17302
  */
17303
+ multiplyUnsafe(sc) {
17304
+ const { endo: endo2 } = extraOpts;
17305
+ const p = this;
17306
+ if (!Fn2.isValid(sc))
17307
+ throw new Error("invalid scalar: out of range");
17308
+ if (sc === _0n7 || p.is0())
17309
+ return Point.ZERO;
17310
+ if (sc === _1n7)
17311
+ return p;
17312
+ if (wnaf.hasCache(this))
17313
+ return this.multiply(sc);
17314
+ if (endo2) {
17315
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
17316
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
17317
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
17318
+ } else {
17319
+ return wnaf.unsafe(p, sc);
17320
+ }
17321
+ }
16861
17322
  multiplyAndAddUnsafe(Q, a, b) {
16862
- const G = Point.BASE;
16863
- const mul = (P, a2) => a2 === _0n7 || a2 === _1n7 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
16864
- const sum = mul(this, a).add(mul(Q, b));
17323
+ const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
16865
17324
  return sum.is0() ? void 0 : sum;
16866
17325
  }
16867
- // Converts Projective point to affine (x, y) coordinates.
16868
- // Can accept precomputed Z^-1 - for example, from invertBatch.
16869
- // (x, y, z) (x=x/z, y=y/z)
16870
- toAffine(iz) {
16871
- return toAffineMemo(this, iz);
17326
+ /**
17327
+ * Converts Projective point to affine (x, y) coordinates.
17328
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
17329
+ */
17330
+ toAffine(invertedZ) {
17331
+ return toAffineMemo(this, invertedZ);
16872
17332
  }
17333
+ /**
17334
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
17335
+ * Always torsion-free for cofactor=1 curves.
17336
+ */
16873
17337
  isTorsionFree() {
16874
- const { h: cofactor, isTorsionFree } = CURVE;
17338
+ const { isTorsionFree } = extraOpts;
16875
17339
  if (cofactor === _1n7)
16876
17340
  return true;
16877
17341
  if (isTorsionFree)
16878
17342
  return isTorsionFree(Point, this);
16879
- throw new Error("isTorsionFree() has not been declared for the elliptic curve");
17343
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
16880
17344
  }
16881
17345
  clearCofactor() {
16882
- const { h: cofactor, clearCofactor } = CURVE;
17346
+ const { clearCofactor } = extraOpts;
16883
17347
  if (cofactor === _1n7)
16884
17348
  return this;
16885
17349
  if (clearCofactor)
16886
17350
  return clearCofactor(Point, this);
16887
- return this.multiplyUnsafe(CURVE.h);
17351
+ return this.multiplyUnsafe(cofactor);
16888
17352
  }
16889
- toRawBytes(isCompressed = true) {
16890
- abool("isCompressed", isCompressed);
17353
+ isSmallOrder() {
17354
+ return this.multiplyUnsafe(cofactor).is0();
17355
+ }
17356
+ toBytes(isCompressed = true) {
17357
+ _abool2(isCompressed, "isCompressed");
16891
17358
  this.assertValidity();
16892
- return toBytes2(Point, this, isCompressed);
17359
+ return encodePoint(Point, this, isCompressed);
16893
17360
  }
16894
17361
  toHex(isCompressed = true) {
16895
- abool("isCompressed", isCompressed);
16896
- return bytesToHex(this.toRawBytes(isCompressed));
17362
+ return bytesToHex(this.toBytes(isCompressed));
17363
+ }
17364
+ toString() {
17365
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
17366
+ }
17367
+ // TODO: remove
17368
+ get px() {
17369
+ return this.X;
17370
+ }
17371
+ get py() {
17372
+ return this.X;
17373
+ }
17374
+ get pz() {
17375
+ return this.Z;
17376
+ }
17377
+ toRawBytes(isCompressed = true) {
17378
+ return this.toBytes(isCompressed);
17379
+ }
17380
+ _setWindowSize(windowSize) {
17381
+ this.precompute(windowSize);
17382
+ }
17383
+ static normalizeZ(points) {
17384
+ return normalizeZ(Point, points);
17385
+ }
17386
+ static msm(points, scalars) {
17387
+ return pippenger(Point, Fn2, points, scalars);
17388
+ }
17389
+ static fromPrivateKey(privateKey) {
17390
+ return Point.BASE.multiply(_normFnElement(Fn2, privateKey));
16897
17391
  }
16898
17392
  }
16899
17393
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE);
16900
17394
  Point.ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO);
16901
- const { endo, nBitLength } = CURVE;
16902
- const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);
17395
+ Point.Fp = Fp2;
17396
+ Point.Fn = Fn2;
17397
+ const bits = Fn2.BITS;
17398
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
17399
+ Point.BASE.precompute(8);
17400
+ return Point;
17401
+ }
17402
+ function pprefix(hasEvenY) {
17403
+ return Uint8Array.of(hasEvenY ? 2 : 3);
17404
+ }
17405
+ function getWLengths(Fp2, Fn2) {
16903
17406
  return {
16904
- CURVE,
16905
- ProjectivePoint: Point,
16906
- normPrivateKeyToScalar,
16907
- weierstrassEquation,
16908
- isWithinCurveOrder
17407
+ secretKey: Fn2.BYTES,
17408
+ publicKey: 1 + Fp2.BYTES,
17409
+ publicKeyUncompressed: 1 + 2 * Fp2.BYTES,
17410
+ publicKeyHasPrefix: true,
17411
+ signature: 2 * Fn2.BYTES
17412
+ };
17413
+ }
17414
+ function ecdh(Point, ecdhOpts = {}) {
17415
+ const { Fn: Fn2 } = Point;
17416
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
17417
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn2), { seed: getMinHashLength(Fn2.ORDER) });
17418
+ function isValidSecretKey(secretKey) {
17419
+ try {
17420
+ return !!_normFnElement(Fn2, secretKey);
17421
+ } catch (error) {
17422
+ return false;
17423
+ }
17424
+ }
17425
+ function isValidPublicKey(publicKey2, isCompressed) {
17426
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
17427
+ try {
17428
+ const l = publicKey2.length;
17429
+ if (isCompressed === true && l !== comp)
17430
+ return false;
17431
+ if (isCompressed === false && l !== publicKeyUncompressed)
17432
+ return false;
17433
+ return !!Point.fromBytes(publicKey2);
17434
+ } catch (error) {
17435
+ return false;
17436
+ }
17437
+ }
17438
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
17439
+ return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn2.ORDER);
17440
+ }
17441
+ function getPublicKey2(secretKey, isCompressed = true) {
17442
+ return Point.BASE.multiply(_normFnElement(Fn2, secretKey)).toBytes(isCompressed);
17443
+ }
17444
+ function keygen(seed) {
17445
+ const secretKey = randomSecretKey(seed);
17446
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
17447
+ }
17448
+ function isProbPub(item) {
17449
+ if (typeof item === "bigint")
17450
+ return false;
17451
+ if (item instanceof Point)
17452
+ return true;
17453
+ const { secretKey, publicKey: publicKey2, publicKeyUncompressed } = lengths;
17454
+ if (Fn2.allowedLengths || secretKey === publicKey2)
17455
+ return void 0;
17456
+ const l = ensureBytes("key", item).length;
17457
+ return l === publicKey2 || l === publicKeyUncompressed;
17458
+ }
17459
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
17460
+ if (isProbPub(secretKeyA) === true)
17461
+ throw new Error("first arg must be private key");
17462
+ if (isProbPub(publicKeyB) === false)
17463
+ throw new Error("second arg must be public key");
17464
+ const s = _normFnElement(Fn2, secretKeyA);
17465
+ const b = Point.fromHex(publicKeyB);
17466
+ return b.multiply(s).toBytes(isCompressed);
17467
+ }
17468
+ const utils = {
17469
+ isValidSecretKey,
17470
+ isValidPublicKey,
17471
+ randomSecretKey,
17472
+ // TODO: remove
17473
+ isValidPrivateKey: isValidSecretKey,
17474
+ randomPrivateKey: randomSecretKey,
17475
+ normPrivateKeyToScalar: (key) => _normFnElement(Fn2, key),
17476
+ precompute(windowSize = 8, point = Point.BASE) {
17477
+ return point.precompute(windowSize, false);
17478
+ }
16909
17479
  };
17480
+ return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
16910
17481
  }
16911
- function validateOpts2(curve) {
16912
- const opts = validateBasic(curve);
16913
- validateObject(opts, {
16914
- hash: "hash",
17482
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
17483
+ ahash(hash);
17484
+ _validateObject(ecdsaOpts, {}, {
16915
17485
  hmac: "function",
16916
- randomBytes: "function"
16917
- }, {
17486
+ lowS: "boolean",
17487
+ randomBytes: "function",
16918
17488
  bits2int: "function",
16919
- bits2int_modN: "function",
16920
- lowS: "boolean"
16921
- });
16922
- return Object.freeze({ lowS: true, ...opts });
16923
- }
16924
- function weierstrass(curveDef) {
16925
- const CURVE = validateOpts2(curveDef);
16926
- const { Fp: Fp2, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
16927
- const compressedLen = Fp2.BYTES + 1;
16928
- const uncompressedLen = 2 * Fp2.BYTES + 1;
16929
- function modN(a) {
16930
- return mod(a, CURVE_ORDER);
16931
- }
16932
- function invN(a) {
16933
- return invert(a, CURVE_ORDER);
16934
- }
16935
- const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
16936
- ...CURVE,
16937
- toBytes(_c, point, isCompressed) {
16938
- const a = point.toAffine();
16939
- const x = Fp2.toBytes(a.x);
16940
- const cat = concatBytes2;
16941
- abool("isCompressed", isCompressed);
16942
- if (isCompressed) {
16943
- return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
16944
- } else {
16945
- return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y));
16946
- }
16947
- },
16948
- fromBytes(bytes) {
16949
- const len = bytes.length;
16950
- const head = bytes[0];
16951
- const tail = bytes.subarray(1);
16952
- if (len === compressedLen && (head === 2 || head === 3)) {
16953
- const x = bytesToNumberBE(tail);
16954
- if (!inRange(x, _1n7, Fp2.ORDER))
16955
- throw new Error("Point is not on curve");
16956
- const y2 = weierstrassEquation(x);
16957
- let y;
16958
- try {
16959
- y = Fp2.sqrt(y2);
16960
- } catch (sqrtError) {
16961
- const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
16962
- throw new Error("Point is not on curve" + suffix);
16963
- }
16964
- const isYOdd = (y & _1n7) === _1n7;
16965
- const isHeadOdd = (head & 1) === 1;
16966
- if (isHeadOdd !== isYOdd)
16967
- y = Fp2.neg(y);
16968
- return { x, y };
16969
- } else if (len === uncompressedLen && head === 4) {
16970
- const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
16971
- const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
16972
- return { x, y };
16973
- } else {
16974
- const cl = compressedLen;
16975
- const ul = uncompressedLen;
16976
- throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
16977
- }
16978
- }
17489
+ bits2int_modN: "function"
16979
17490
  });
17491
+ const randomBytes2 = ecdsaOpts.randomBytes || randomBytes;
17492
+ const hmac2 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
17493
+ const { Fp: Fp2, Fn: Fn2 } = Point;
17494
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2;
17495
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
17496
+ const defaultSigOpts = {
17497
+ prehash: false,
17498
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
17499
+ format: void 0,
17500
+ //'compact' as ECDSASigFormat,
17501
+ extraEntropy: false
17502
+ };
17503
+ const defaultSigOpts_format = "compact";
16980
17504
  function isBiggerThanHalfOrder(number2) {
16981
17505
  const HALF = CURVE_ORDER >> _1n7;
16982
17506
  return number2 > HALF;
16983
17507
  }
16984
- function normalizeS(s) {
16985
- return isBiggerThanHalfOrder(s) ? modN(-s) : s;
17508
+ function validateRS(title, num) {
17509
+ if (!Fn2.isValidNot0(num))
17510
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
17511
+ return num;
17512
+ }
17513
+ function validateSigLength(bytes, format) {
17514
+ validateSigFormat(format);
17515
+ const size = lengths.signature;
17516
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
17517
+ return _abytes2(bytes, sizer, `${format} signature`);
16986
17518
  }
16987
- const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
16988
17519
  class Signature {
16989
17520
  constructor(r, s, recovery) {
16990
- aInRange("r", r, _1n7, CURVE_ORDER);
16991
- aInRange("s", s, _1n7, CURVE_ORDER);
16992
- this.r = r;
16993
- this.s = s;
17521
+ this.r = validateRS("r", r);
17522
+ this.s = validateRS("s", s);
16994
17523
  if (recovery != null)
16995
17524
  this.recovery = recovery;
16996
17525
  Object.freeze(this);
16997
17526
  }
16998
- // pair (bytes of r, bytes of s)
16999
- static fromCompact(hex) {
17000
- const l = nByteLength;
17001
- hex = ensureBytes("compactSignature", hex, l * 2);
17002
- return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
17003
- }
17004
- // DER encoded ECDSA signature
17005
- // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
17006
- static fromDER(hex) {
17007
- const { r, s } = DER.toSig(ensureBytes("DER", hex));
17008
- return new Signature(r, s);
17527
+ static fromBytes(bytes, format = defaultSigOpts_format) {
17528
+ validateSigLength(bytes, format);
17529
+ let recid;
17530
+ if (format === "der") {
17531
+ const { r: r2, s: s2 } = DER.toSig(_abytes2(bytes));
17532
+ return new Signature(r2, s2);
17533
+ }
17534
+ if (format === "recovered") {
17535
+ recid = bytes[0];
17536
+ format = "compact";
17537
+ bytes = bytes.subarray(1);
17538
+ }
17539
+ const L = Fn2.BYTES;
17540
+ const r = bytes.subarray(0, L);
17541
+ const s = bytes.subarray(L, L * 2);
17542
+ return new Signature(Fn2.fromBytes(r), Fn2.fromBytes(s), recid);
17009
17543
  }
17010
- /**
17011
- * @todo remove
17012
- * @deprecated
17013
- */
17014
- assertValidity() {
17544
+ static fromHex(hex, format) {
17545
+ return this.fromBytes(hexToBytes(hex), format);
17015
17546
  }
17016
17547
  addRecoveryBit(recovery) {
17017
17548
  return new Signature(this.r, this.s, recovery);
17018
17549
  }
17019
- recoverPublicKey(msgHash) {
17550
+ recoverPublicKey(messageHash) {
17551
+ const FIELD_ORDER = Fp2.ORDER;
17020
17552
  const { r, s, recovery: rec } = this;
17021
- const h = bits2int_modN(ensureBytes("msgHash", msgHash));
17022
17553
  if (rec == null || ![0, 1, 2, 3].includes(rec))
17023
17554
  throw new Error("recovery id invalid");
17024
- const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
17025
- if (radj >= Fp2.ORDER)
17555
+ const hasCofactor = CURVE_ORDER * _2n5 < FIELD_ORDER;
17556
+ if (hasCofactor && rec > 1)
17557
+ throw new Error("recovery id is ambiguous for h>1 curve");
17558
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
17559
+ if (!Fp2.isValid(radj))
17026
17560
  throw new Error("recovery id 2 or 3 invalid");
17027
- const prefix = (rec & 1) === 0 ? "02" : "03";
17028
- const R = Point.fromHex(prefix + numToSizedHex(radj, Fp2.BYTES));
17029
- const ir = invN(radj);
17030
- const u1 = modN(-h * ir);
17031
- const u2 = modN(s * ir);
17032
- const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
17033
- if (!Q)
17561
+ const x = Fp2.toBytes(radj);
17562
+ const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
17563
+ const ir = Fn2.inv(radj);
17564
+ const h = bits2int_modN(ensureBytes("msgHash", messageHash));
17565
+ const u1 = Fn2.create(-h * ir);
17566
+ const u2 = Fn2.create(s * ir);
17567
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
17568
+ if (Q.is0())
17034
17569
  throw new Error("point at infinify");
17035
17570
  Q.assertValidity();
17036
17571
  return Q;
@@ -17039,235 +17574,262 @@ function weierstrass(curveDef) {
17039
17574
  hasHighS() {
17040
17575
  return isBiggerThanHalfOrder(this.s);
17041
17576
  }
17577
+ toBytes(format = defaultSigOpts_format) {
17578
+ validateSigFormat(format);
17579
+ if (format === "der")
17580
+ return hexToBytes(DER.hexFromSig(this));
17581
+ const r = Fn2.toBytes(this.r);
17582
+ const s = Fn2.toBytes(this.s);
17583
+ if (format === "recovered") {
17584
+ if (this.recovery == null)
17585
+ throw new Error("recovery bit must be present");
17586
+ return concatBytes(Uint8Array.of(this.recovery), r, s);
17587
+ }
17588
+ return concatBytes(r, s);
17589
+ }
17590
+ toHex(format) {
17591
+ return bytesToHex(this.toBytes(format));
17592
+ }
17593
+ // TODO: remove
17594
+ assertValidity() {
17595
+ }
17596
+ static fromCompact(hex) {
17597
+ return Signature.fromBytes(ensureBytes("sig", hex), "compact");
17598
+ }
17599
+ static fromDER(hex) {
17600
+ return Signature.fromBytes(ensureBytes("sig", hex), "der");
17601
+ }
17042
17602
  normalizeS() {
17043
- return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
17603
+ return this.hasHighS() ? new Signature(this.r, Fn2.neg(this.s), this.recovery) : this;
17044
17604
  }
17045
- // DER-encoded
17046
17605
  toDERRawBytes() {
17047
- return hexToBytes(this.toDERHex());
17606
+ return this.toBytes("der");
17048
17607
  }
17049
17608
  toDERHex() {
17050
- return DER.hexFromSig(this);
17609
+ return bytesToHex(this.toBytes("der"));
17051
17610
  }
17052
- // padded bytes of r, then padded bytes of s
17053
17611
  toCompactRawBytes() {
17054
- return hexToBytes(this.toCompactHex());
17612
+ return this.toBytes("compact");
17055
17613
  }
17056
17614
  toCompactHex() {
17057
- const l = nByteLength;
17058
- return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);
17059
- }
17060
- }
17061
- const utils = {
17062
- isValidPrivateKey(privateKey) {
17063
- try {
17064
- normPrivateKeyToScalar(privateKey);
17065
- return true;
17066
- } catch (error) {
17067
- return false;
17068
- }
17069
- },
17070
- normPrivateKeyToScalar,
17071
- /**
17072
- * Produces cryptographically secure private key from random of size
17073
- * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
17074
- */
17075
- randomPrivateKey: () => {
17076
- const length = getMinHashLength(CURVE.n);
17077
- return mapHashToField(CURVE.randomBytes(length), CURVE.n);
17078
- },
17079
- /**
17080
- * Creates precompute table for an arbitrary EC point. Makes point "cached".
17081
- * Allows to massively speed-up `point.multiply(scalar)`.
17082
- * @returns cached point
17083
- * @example
17084
- * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
17085
- * fast.multiply(privKey); // much faster ECDH now
17086
- */
17087
- precompute(windowSize = 8, point = Point.BASE) {
17088
- point._setWindowSize(windowSize);
17089
- point.multiply(BigInt(3));
17090
- return point;
17091
- }
17092
- };
17093
- function getPublicKey2(privateKey, isCompressed = true) {
17094
- return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
17095
- }
17096
- function isProbPub(item) {
17097
- if (typeof item === "bigint")
17098
- return false;
17099
- if (item instanceof Point)
17100
- return true;
17101
- const arr = ensureBytes("key", item);
17102
- const len = arr.length;
17103
- const fpl = Fp2.BYTES;
17104
- const compLen = fpl + 1;
17105
- const uncompLen = 2 * fpl + 1;
17106
- if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {
17107
- return void 0;
17108
- } else {
17109
- return len === compLen || len === uncompLen;
17615
+ return bytesToHex(this.toBytes("compact"));
17110
17616
  }
17111
17617
  }
17112
- function getSharedSecret(privateA, publicB, isCompressed = true) {
17113
- if (isProbPub(privateA) === true)
17114
- throw new Error("first arg must be private key");
17115
- if (isProbPub(publicB) === false)
17116
- throw new Error("second arg must be public key");
17117
- const b = Point.fromHex(publicB);
17118
- return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
17119
- }
17120
- const bits2int = CURVE.bits2int || function(bytes) {
17618
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
17121
17619
  if (bytes.length > 8192)
17122
17620
  throw new Error("input is too large");
17123
17621
  const num = bytesToNumberBE(bytes);
17124
- const delta = bytes.length * 8 - nBitLength;
17622
+ const delta = bytes.length * 8 - fnBits;
17125
17623
  return delta > 0 ? num >> BigInt(delta) : num;
17126
17624
  };
17127
- const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
17128
- return modN(bits2int(bytes));
17625
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
17626
+ return Fn2.create(bits2int(bytes));
17129
17627
  };
17130
- const ORDER_MASK = bitMask(nBitLength);
17628
+ const ORDER_MASK = bitMask(fnBits);
17131
17629
  function int2octets(num) {
17132
- aInRange("num < 2^" + nBitLength, num, _0n7, ORDER_MASK);
17133
- return numberToBytesBE(num, nByteLength);
17630
+ aInRange("num < 2^" + fnBits, num, _0n7, ORDER_MASK);
17631
+ return Fn2.toBytes(num);
17632
+ }
17633
+ function validateMsgAndHash(message, prehash) {
17634
+ _abytes2(message, void 0, "message");
17635
+ return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
17134
17636
  }
17135
- function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
17637
+ function prepSig(message, privateKey, opts) {
17136
17638
  if (["recovered", "canonical"].some((k) => k in opts))
17137
17639
  throw new Error("sign() legacy options not supported");
17138
- const { hash, randomBytes: randomBytes2 } = CURVE;
17139
- let { lowS, prehash, extraEntropy: ent } = opts;
17140
- if (lowS == null)
17141
- lowS = true;
17142
- msgHash = ensureBytes("msgHash", msgHash);
17143
- validateSigVerOpts(opts);
17144
- if (prehash)
17145
- msgHash = ensureBytes("prehashed msgHash", hash(msgHash));
17146
- const h1int = bits2int_modN(msgHash);
17147
- const d = normPrivateKeyToScalar(privateKey);
17640
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
17641
+ message = validateMsgAndHash(message, prehash);
17642
+ const h1int = bits2int_modN(message);
17643
+ const d = _normFnElement(Fn2, privateKey);
17148
17644
  const seedArgs = [int2octets(d), int2octets(h1int)];
17149
- if (ent != null && ent !== false) {
17150
- const e = ent === true ? randomBytes2(Fp2.BYTES) : ent;
17645
+ if (extraEntropy != null && extraEntropy !== false) {
17646
+ const e = extraEntropy === true ? randomBytes2(lengths.secretKey) : extraEntropy;
17151
17647
  seedArgs.push(ensureBytes("extraEntropy", e));
17152
17648
  }
17153
- const seed = concatBytes2(...seedArgs);
17649
+ const seed = concatBytes(...seedArgs);
17154
17650
  const m = h1int;
17155
17651
  function k2sig(kBytes) {
17156
17652
  const k = bits2int(kBytes);
17157
- if (!isWithinCurveOrder(k))
17653
+ if (!Fn2.isValidNot0(k))
17158
17654
  return;
17159
- const ik = invN(k);
17655
+ const ik = Fn2.inv(k);
17160
17656
  const q = Point.BASE.multiply(k).toAffine();
17161
- const r = modN(q.x);
17657
+ const r = Fn2.create(q.x);
17162
17658
  if (r === _0n7)
17163
17659
  return;
17164
- const s = modN(ik * modN(m + r * d));
17660
+ const s = Fn2.create(ik * Fn2.create(m + r * d));
17165
17661
  if (s === _0n7)
17166
17662
  return;
17167
17663
  let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n7);
17168
17664
  let normS = s;
17169
17665
  if (lowS && isBiggerThanHalfOrder(s)) {
17170
- normS = normalizeS(s);
17666
+ normS = Fn2.neg(s);
17171
17667
  recovery ^= 1;
17172
17668
  }
17173
17669
  return new Signature(r, normS, recovery);
17174
17670
  }
17175
17671
  return { seed, k2sig };
17176
17672
  }
17177
- const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
17178
- const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
17179
- function sign2(msgHash, privKey, opts = defaultSigOpts) {
17180
- const { seed, k2sig } = prepSig(msgHash, privKey, opts);
17181
- const C = CURVE;
17182
- const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
17183
- return drbg(seed, k2sig);
17184
- }
17185
- Point.BASE._setWindowSize(8);
17186
- function verify2(signature2, msgHash, publicKey2, opts = defaultVerOpts) {
17187
- const sg = signature2;
17188
- msgHash = ensureBytes("msgHash", msgHash);
17189
- publicKey2 = ensureBytes("publicKey", publicKey2);
17190
- const { lowS, prehash, format } = opts;
17191
- validateSigVerOpts(opts);
17192
- if ("strict" in opts)
17193
- throw new Error("options.strict was renamed to lowS");
17194
- if (format !== void 0 && format !== "compact" && format !== "der")
17195
- throw new Error("format must be compact or der");
17196
- const isHex = typeof sg === "string" || isBytes2(sg);
17197
- const isObj = !isHex && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
17673
+ function sign2(message, secretKey, opts = {}) {
17674
+ message = ensureBytes("message", message);
17675
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
17676
+ const drbg = createHmacDrbg(hash.outputLen, Fn2.BYTES, hmac2);
17677
+ const sig = drbg(seed, k2sig);
17678
+ return sig;
17679
+ }
17680
+ function tryParsingSig(sg) {
17681
+ let sig = void 0;
17682
+ const isHex = typeof sg === "string" || isBytes(sg);
17683
+ const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
17198
17684
  if (!isHex && !isObj)
17199
17685
  throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
17200
- let _sig = void 0;
17201
- let P;
17202
- try {
17203
- if (isObj)
17204
- _sig = new Signature(sg.r, sg.s);
17205
- if (isHex) {
17686
+ if (isObj) {
17687
+ sig = new Signature(sg.r, sg.s);
17688
+ } else if (isHex) {
17689
+ try {
17690
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
17691
+ } catch (derError) {
17692
+ if (!(derError instanceof DER.Err))
17693
+ throw derError;
17694
+ }
17695
+ if (!sig) {
17206
17696
  try {
17207
- if (format !== "compact")
17208
- _sig = Signature.fromDER(sg);
17209
- } catch (derError) {
17210
- if (!(derError instanceof DER.Err))
17211
- throw derError;
17697
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
17698
+ } catch (error) {
17699
+ return false;
17212
17700
  }
17213
- if (!_sig && format !== "der")
17214
- _sig = Signature.fromCompact(sg);
17215
17701
  }
17216
- P = Point.fromHex(publicKey2);
17217
- } catch (error) {
17218
- return false;
17219
17702
  }
17220
- if (!_sig)
17703
+ if (!sig)
17221
17704
  return false;
17222
- if (lowS && _sig.hasHighS())
17705
+ return sig;
17706
+ }
17707
+ function verify2(signature2, message, publicKey2, opts = {}) {
17708
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
17709
+ publicKey2 = ensureBytes("publicKey", publicKey2);
17710
+ message = validateMsgAndHash(ensureBytes("message", message), prehash);
17711
+ if ("strict" in opts)
17712
+ throw new Error("options.strict was renamed to lowS");
17713
+ const sig = format === void 0 ? tryParsingSig(signature2) : Signature.fromBytes(ensureBytes("sig", signature2), format);
17714
+ if (sig === false)
17223
17715
  return false;
17224
- if (prehash)
17225
- msgHash = CURVE.hash(msgHash);
17226
- const { r, s } = _sig;
17227
- const h = bits2int_modN(msgHash);
17228
- const is2 = invN(s);
17229
- const u1 = modN(h * is2);
17230
- const u2 = modN(r * is2);
17231
- const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
17232
- if (!R)
17716
+ try {
17717
+ const P = Point.fromBytes(publicKey2);
17718
+ if (lowS && sig.hasHighS())
17719
+ return false;
17720
+ const { r, s } = sig;
17721
+ const h = bits2int_modN(message);
17722
+ const is2 = Fn2.inv(s);
17723
+ const u1 = Fn2.create(h * is2);
17724
+ const u2 = Fn2.create(r * is2);
17725
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
17726
+ if (R.is0())
17727
+ return false;
17728
+ const v = Fn2.create(R.x);
17729
+ return v === r;
17730
+ } catch (e) {
17233
17731
  return false;
17234
- const v = modN(R.x);
17235
- return v === r;
17732
+ }
17236
17733
  }
17237
- return {
17238
- CURVE,
17734
+ function recoverPublicKey(signature2, message, opts = {}) {
17735
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
17736
+ message = validateMsgAndHash(message, prehash);
17737
+ return Signature.fromBytes(signature2, "recovered").recoverPublicKey(message).toBytes();
17738
+ }
17739
+ return Object.freeze({
17740
+ keygen,
17239
17741
  getPublicKey: getPublicKey2,
17240
17742
  getSharedSecret,
17743
+ utils,
17744
+ lengths,
17745
+ Point,
17241
17746
  sign: sign2,
17242
17747
  verify: verify2,
17243
- ProjectivePoint: Point,
17748
+ recoverPublicKey,
17244
17749
  Signature,
17245
- utils
17750
+ hash
17751
+ });
17752
+ }
17753
+ function _weierstrass_legacy_opts_to_new(c) {
17754
+ const CURVE = {
17755
+ a: c.a,
17756
+ b: c.b,
17757
+ p: c.Fp.ORDER,
17758
+ n: c.n,
17759
+ h: c.h,
17760
+ Gx: c.Gx,
17761
+ Gy: c.Gy
17762
+ };
17763
+ const Fp2 = c.Fp;
17764
+ let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
17765
+ const Fn2 = Field(CURVE.n, {
17766
+ BITS: c.nBitLength,
17767
+ allowedLengths,
17768
+ modFromBytes: c.wrapPrivateKey
17769
+ });
17770
+ const curveOpts = {
17771
+ Fp: Fp2,
17772
+ Fn: Fn2,
17773
+ allowInfinityPoint: c.allowInfinityPoint,
17774
+ endo: c.endo,
17775
+ isTorsionFree: c.isTorsionFree,
17776
+ clearCofactor: c.clearCofactor,
17777
+ fromBytes: c.fromBytes,
17778
+ toBytes: c.toBytes
17246
17779
  };
17780
+ return { CURVE, curveOpts };
17247
17781
  }
17248
-
17249
- // node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/_shortw_utils.js
17250
- function getHash(hash) {
17251
- return {
17252
- hash,
17253
- hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),
17254
- randomBytes
17782
+ function _ecdsa_legacy_opts_to_new(c) {
17783
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
17784
+ const ecdsaOpts = {
17785
+ hmac: c.hmac,
17786
+ randomBytes: c.randomBytes,
17787
+ lowS: c.lowS,
17788
+ bits2int: c.bits2int,
17789
+ bits2int_modN: c.bits2int_modN
17255
17790
  };
17791
+ return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
17792
+ }
17793
+ function _ecdsa_new_output_to_legacy(c, _ecdsa) {
17794
+ const Point = _ecdsa.Point;
17795
+ return Object.assign({}, _ecdsa, {
17796
+ ProjectivePoint: Point,
17797
+ CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
17798
+ });
17256
17799
  }
17800
+ function weierstrass(c) {
17801
+ const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
17802
+ const Point = weierstrassN(CURVE, curveOpts);
17803
+ const signs = ecdsa(Point, hash, ecdsaOpts);
17804
+ return _ecdsa_new_output_to_legacy(c, signs);
17805
+ }
17806
+
17807
+ // node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/_shortw_utils.js
17257
17808
  function createCurve(curveDef, defHash) {
17258
- const create2 = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
17809
+ const create2 = (hash) => weierstrass({ ...curveDef, hash });
17259
17810
  return { ...create2(defHash), create: create2 };
17260
17811
  }
17261
17812
 
17262
- // node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/secp256k1.js
17263
- var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
17264
- var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
17265
- var _0n8 = BigInt(0);
17266
- var _1n8 = BigInt(1);
17267
- var _2n6 = BigInt(2);
17268
- var divNearest = (a, b) => (a + b / _2n6) / b;
17813
+ // node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/secp256k1.js
17814
+ var secp256k1_CURVE = {
17815
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
17816
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
17817
+ h: BigInt(1),
17818
+ a: BigInt(0),
17819
+ b: BigInt(7),
17820
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
17821
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
17822
+ };
17823
+ var secp256k1_ENDO = {
17824
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
17825
+ basises: [
17826
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
17827
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
17828
+ ]
17829
+ };
17830
+ var _2n6 = /* @__PURE__ */ BigInt(2);
17269
17831
  function sqrtMod(y) {
17270
- const P = secp256k1P;
17832
+ const P = secp256k1_CURVE.p;
17271
17833
  const _3n4 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
17272
17834
  const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
17273
17835
  const b2 = y * y * y % P;
@@ -17288,44 +17850,8 @@ function sqrtMod(y) {
17288
17850
  throw new Error("Cannot find square root");
17289
17851
  return root;
17290
17852
  }
17291
- var Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod });
17292
- var secp256k1 = createCurve({
17293
- a: _0n8,
17294
- b: BigInt(7),
17295
- Fp: Fpk1,
17296
- n: secp256k1N,
17297
- Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
17298
- Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
17299
- h: BigInt(1),
17300
- lowS: true,
17301
- // Allow only low-S signatures by default in sign() and verify()
17302
- endo: {
17303
- // Endomorphism, see above
17304
- beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
17305
- splitScalar: (k) => {
17306
- const n = secp256k1N;
17307
- const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
17308
- const b1 = -_1n8 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
17309
- const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
17310
- const b2 = a1;
17311
- const POW_2_128 = BigInt("0x100000000000000000000000000000000");
17312
- const c1 = divNearest(b2 * k, n);
17313
- const c2 = divNearest(-b1 * k, n);
17314
- let k1 = mod(k - c1 * a1 - c2 * a2, n);
17315
- let k2 = mod(-c1 * b1 - c2 * b2, n);
17316
- const k1neg = k1 > POW_2_128;
17317
- const k2neg = k2 > POW_2_128;
17318
- if (k1neg)
17319
- k1 = n - k1;
17320
- if (k2neg)
17321
- k2 = n - k2;
17322
- if (k1 > POW_2_128 || k2 > POW_2_128) {
17323
- throw new Error("splitScalar: Endomorphism failed, k=" + k);
17324
- }
17325
- return { k1neg, k1, k2neg, k2 };
17326
- }
17327
- }
17328
- }, sha256);
17853
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
17854
+ var secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
17329
17855
 
17330
17856
  // node_modules/.pnpm/@solana+web3.js@1.98.4_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@solana/web3.js/lib/index.esm.js
17331
17857
  var generatePrivateKey = ed25519.utils.randomPrivateKey;
@@ -26567,7 +27093,7 @@ safe-buffer/index.js:
26567
27093
  @noble/hashes/esm/utils.js:
26568
27094
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
26569
27095
 
26570
- @noble/curves/esm/abstract/utils.js:
27096
+ @noble/curves/esm/utils.js:
26571
27097
  @noble/curves/esm/abstract/modular.js:
26572
27098
  @noble/curves/esm/abstract/curve.js:
26573
27099
  @noble/curves/esm/abstract/edwards.js: