@t2000/cli 5.16.0 → 5.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,8 @@ import "./chunk-SVEVGZKZ.js";
5
5
  import { createRequire } from "module";
6
6
  import url, { fileURLToPath } from "url";
7
7
  import { dirname, join as join$1, resolve } from "path";
8
- import crypto2 from "crypto";
8
+ import * as nc from "crypto";
9
+ import nc__default from "crypto";
9
10
  import stream3, { Readable } from "stream";
10
11
  import util3 from "util";
11
12
  import http from "http";
@@ -35,8 +36,8 @@ var __require = /* @__PURE__ */ ((x) => typeof require$1 !== "undefined" ? requi
35
36
  var __esm = (fn, res) => function __init() {
36
37
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
37
38
  };
38
- var __commonJS = (cb, mod3) => function __require3() {
39
- return mod3 || (0, cb[__getOwnPropNames(cb)[0]])((mod3 = { exports: {} }).exports, mod3), mod3.exports;
39
+ var __commonJS = (cb, mod4) => function __require3() {
40
+ return mod4 || (0, cb[__getOwnPropNames(cb)[0]])((mod4 = { exports: {} }).exports, mod4), mod4.exports;
40
41
  };
41
42
  var __export = (target, all3) => {
42
43
  for (var name in all3)
@@ -50,13 +51,13 @@ var __copyProps = (to, from, except, desc) => {
50
51
  }
51
52
  return to;
52
53
  };
53
- var __toESM = (mod3, isNodeMode, target) => (target = mod3 != null ? __create(__getProtoOf(mod3)) : {}, __copyProps(
54
+ var __toESM = (mod4, isNodeMode, target) => (target = mod4 != null ? __create(__getProtoOf(mod4)) : {}, __copyProps(
54
55
  // If the importer is in node compatibility mode or this is not an ESM
55
56
  // file that has been converted to a CommonJS file using a Babel-
56
57
  // compatible transform (i.e. "__esModule" has not been set), then set
57
58
  // "default" to the CommonJS "module.exports" for node compatibility.
58
- __defProp(target, "default", { value: mod3, enumerable: true }),
59
- mod3
59
+ __defProp(target, "default", { value: mod4, enumerable: true }),
60
+ mod4
60
61
  ));
61
62
  var util;
62
63
  var objectUtil;
@@ -11600,7 +11601,7 @@ function dynamicSizeBcsType({ serialize, ...options }) {
11600
11601
  });
11601
11602
  return type;
11602
11603
  }
11603
- function stringLikeBcsType({ toBytes, fromBytes, ...options }) {
11604
+ function stringLikeBcsType({ toBytes: toBytes2, fromBytes, ...options }) {
11604
11605
  return new BcsType({
11605
11606
  ...options,
11606
11607
  read: (reader) => {
@@ -11608,12 +11609,12 @@ function stringLikeBcsType({ toBytes, fromBytes, ...options }) {
11608
11609
  return fromBytes(reader.readBytes(length));
11609
11610
  },
11610
11611
  write: (hex, writer) => {
11611
- const bytes = toBytes(hex);
11612
+ const bytes = toBytes2(hex);
11612
11613
  writer.writeULEB(bytes.length);
11613
11614
  for (let i = 0; i < bytes.length; i++) writer.write8(bytes[i]);
11614
11615
  },
11615
11616
  serialize: (value) => {
11616
- const bytes = toBytes(value);
11617
+ const bytes = toBytes2(value);
11617
11618
  const size = ulebEncode(bytes.length);
11618
11619
  const result = new Uint8Array(size.length + bytes.length);
11619
11620
  result.set(size, 0);
@@ -14925,7 +14926,7 @@ function serializeV1TransactionData(transactionData) {
14925
14926
  };
14926
14927
  if (command.Publish) return {
14927
14928
  kind: "Publish",
14928
- modules: command.Publish.modules.map((mod3) => Array.from(fromBase64(mod3))),
14929
+ modules: command.Publish.modules.map((mod4) => Array.from(fromBase64(mod4))),
14929
14930
  dependencies: command.Publish.dependencies
14930
14931
  };
14931
14932
  if (command.SplitCoins) return {
@@ -14940,7 +14941,7 @@ function serializeV1TransactionData(transactionData) {
14940
14941
  };
14941
14942
  if (command.Upgrade) return {
14942
14943
  kind: "Upgrade",
14943
- modules: command.Upgrade.modules.map((mod3) => Array.from(fromBase64(mod3))),
14944
+ modules: command.Upgrade.modules.map((mod4) => Array.from(fromBase64(mod4))),
14944
14945
  dependencies: command.Upgrade.dependencies,
14945
14946
  packageId: command.Upgrade.package,
14946
14947
  ticket: convertTransactionArgument(command.Upgrade.ticket, inputs)
@@ -15020,10 +15021,10 @@ function transactionDataFromV1(data) {
15020
15021
  sources: transaction.sources.map((arg) => parseV1TransactionArgument(arg))
15021
15022
  } };
15022
15023
  case "MoveCall": {
15023
- const [pkg, mod3, fn] = transaction.target.split("::");
15024
+ const [pkg, mod4, fn] = transaction.target.split("::");
15024
15025
  return { MoveCall: {
15025
15026
  package: pkg,
15026
- module: mod3,
15027
+ module: mod4,
15027
15028
  function: fn,
15028
15029
  typeArguments: transaction.typeArguments,
15029
15030
  arguments: transaction.arguments.map((arg) => parseV1TransactionArgument(arg))
@@ -15031,7 +15032,7 @@ function transactionDataFromV1(data) {
15031
15032
  }
15032
15033
  case "Publish":
15033
15034
  return { Publish: {
15034
- modules: transaction.modules.map((mod3) => toBase64(Uint8Array.from(mod3))),
15035
+ modules: transaction.modules.map((mod4) => toBase64(Uint8Array.from(mod4))),
15035
15036
  dependencies: transaction.dependencies
15036
15037
  } };
15037
15038
  case "SplitCoins":
@@ -15046,7 +15047,7 @@ function transactionDataFromV1(data) {
15046
15047
  } };
15047
15048
  case "Upgrade":
15048
15049
  return { Upgrade: {
15049
- modules: transaction.modules.map((mod3) => toBase64(Uint8Array.from(mod3))),
15050
+ modules: transaction.modules.map((mod4) => toBase64(Uint8Array.from(mod4))),
15050
15051
  dependencies: transaction.dependencies,
15051
15052
  package: transaction.packageId,
15052
15053
  ticket: parseV1TransactionArgument(transaction.ticket)
@@ -15432,7 +15433,7 @@ var init_Commands = __esm({
15432
15433
  init_dist3();
15433
15434
  TransactionCommands = {
15434
15435
  MoveCall(input) {
15435
- const [pkg, mod3 = "", fn = ""] = "target" in input ? input.target.split("::") : [
15436
+ const [pkg, mod4 = "", fn = ""] = "target" in input ? input.target.split("::") : [
15436
15437
  input.package,
15437
15438
  input.module,
15438
15439
  input.function
@@ -15441,7 +15442,7 @@ var init_Commands = __esm({
15441
15442
  $kind: "MoveCall",
15442
15443
  MoveCall: {
15443
15444
  package: pkg,
15444
- module: mod3,
15445
+ module: mod4,
15445
15446
  function: fn,
15446
15447
  typeArguments: input.typeArguments ?? [],
15447
15448
  arguments: input.arguments ?? []
@@ -42682,10 +42683,10 @@ var require_abort = __commonJS({
42682
42683
  "../../node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/abort.js"(exports$1, module) {
42683
42684
  module.exports = abort;
42684
42685
  function abort(state) {
42685
- Object.keys(state.jobs).forEach(clean2.bind(state));
42686
+ Object.keys(state.jobs).forEach(clean3.bind(state));
42686
42687
  state.jobs = {};
42687
42688
  }
42688
- function clean2(key) {
42689
+ function clean3(key) {
42689
42690
  if (typeof this.jobs[key] == "function") {
42690
42691
  this.jobs[key]();
42691
42692
  }
@@ -43591,7 +43592,7 @@ var require_form_data = __commonJS({
43591
43592
  var parseUrl2 = __require("url").parse;
43592
43593
  var fs = __require("fs");
43593
43594
  var Stream = __require("stream").Stream;
43594
- var crypto3 = __require("crypto");
43595
+ var crypto4 = __require("crypto");
43595
43596
  var mime = require_mime_types();
43596
43597
  var asynckit = require_asynckit();
43597
43598
  var setToStringTag = require_es_set_tostringtag();
@@ -43797,7 +43798,7 @@ var require_form_data = __commonJS({
43797
43798
  return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
43798
43799
  };
43799
43800
  FormData3.prototype._generateBoundary = function() {
43800
- this._boundary = "--------------------------" + crypto3.randomBytes(12).toString("hex");
43801
+ this._boundary = "--------------------------" + crypto4.randomBytes(12).toString("hex");
43801
43802
  };
43802
43803
  FormData3.prototype.getLengthSync = function() {
43803
43804
  var knownLength = this._overheadLength + this._valueLength;
@@ -44214,7 +44215,7 @@ var init_node = __esm({
44214
44215
  let str = "";
44215
44216
  const { length } = alphabet2;
44216
44217
  const randomValues = new Uint32Array(size);
44217
- crypto2.randomFillSync(randomValues);
44218
+ nc__default.randomFillSync(randomValues);
44218
44219
  for (let i = 0; i < size; i++) {
44219
44220
  str += alphabet2[randomValues[i] % length];
44220
44221
  }
@@ -50698,7 +50699,7 @@ function maxOrMin(Ctor, args, n) {
50698
50699
  return x;
50699
50700
  }
50700
50701
  function naturalExponential(x, sd) {
50701
- var denominator, guard, j, pow22, sum2, t, wpr, rep = 0, i = 0, k = 0, Ctor = x.constructor, rm = Ctor.rounding, pr = Ctor.precision;
50702
+ var denominator, guard, j, pow23, sum2, t, wpr, rep = 0, i = 0, k = 0, Ctor = x.constructor, rm = Ctor.rounding, pr = Ctor.precision;
50702
50703
  if (!x.d || !x.d[0] || x.e > 17) {
50703
50704
  return new Ctor(x.d ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 : x.s ? x.s < 0 ? 0 : x : 0 / 0);
50704
50705
  }
@@ -50715,19 +50716,19 @@ function naturalExponential(x, sd) {
50715
50716
  }
50716
50717
  guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
50717
50718
  wpr += guard;
50718
- denominator = pow22 = sum2 = new Ctor(1);
50719
+ denominator = pow23 = sum2 = new Ctor(1);
50719
50720
  Ctor.precision = wpr;
50720
50721
  for (; ; ) {
50721
- pow22 = finalise(pow22.times(x), wpr, 1);
50722
+ pow23 = finalise(pow23.times(x), wpr, 1);
50722
50723
  denominator = denominator.times(++i);
50723
- t = sum2.plus(divide(pow22, denominator, wpr, 1));
50724
+ t = sum2.plus(divide(pow23, denominator, wpr, 1));
50724
50725
  if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum2.d).slice(0, wpr)) {
50725
50726
  j = k;
50726
50727
  while (j--) sum2 = finalise(sum2.times(sum2), wpr, 1);
50727
50728
  if (sd == null) {
50728
50729
  if (rep < 3 && checkRoundingDigits(sum2.d, wpr - guard, rm, rep)) {
50729
50730
  Ctor.precision = wpr += 10;
50730
- denominator = pow22 = t = new Ctor(1);
50731
+ denominator = pow23 = t = new Ctor(1);
50731
50732
  i = 0;
50732
50733
  rep++;
50733
50734
  } else {
@@ -52106,12 +52107,12 @@ var init_dist7 = __esm({
52106
52107
  }
52107
52108
  }
52108
52109
  if (mod22 !== 0) {
52109
- var pow22 = 1;
52110
+ var pow23 = 1;
52110
52111
  word = parseBase(number4, i, number4.length, base);
52111
52112
  for (i = 0; i < mod22; i++) {
52112
- pow22 *= base;
52113
+ pow23 *= base;
52113
52114
  }
52114
- this.imuln(pow22);
52115
+ this.imuln(pow23);
52115
52116
  if (this.words[0] + word < 67108864) {
52116
52117
  this.words[0] += word;
52117
52118
  } else {
@@ -53446,7 +53447,7 @@ var init_dist7 = __esm({
53446
53447
  BN7.prototype.isqr = function isqr() {
53447
53448
  return this.imul(this.clone());
53448
53449
  };
53449
- BN7.prototype.pow = function pow22(num) {
53450
+ BN7.prototype.pow = function pow23(num) {
53450
53451
  var w2 = toBitArray(num);
53451
53452
  if (w2.length === 0) return new BN7(1);
53452
53453
  var res = this;
@@ -54440,11 +54441,11 @@ var init_dist7 = __esm({
54440
54441
  };
54441
54442
  Red.prototype.sqrt = function sqrt2(a) {
54442
54443
  if (a.isZero()) return a.clone();
54443
- var mod3 = this.m.andln(3);
54444
- assert3(mod3 % 2 === 1);
54445
- if (mod3 === 3) {
54446
- var pow22 = this.m.add(new BN7(1)).iushrn(2);
54447
- return this.pow(a, pow22);
54444
+ var mod32 = this.m.andln(3);
54445
+ assert3(mod32 % 2 === 1);
54446
+ if (mod32 === 3) {
54447
+ var pow23 = this.m.add(new BN7(1)).iushrn(2);
54448
+ return this.pow(a, pow23);
54448
54449
  }
54449
54450
  var q = this.m.subn(1);
54450
54451
  var s = 0;
@@ -54488,7 +54489,7 @@ var init_dist7 = __esm({
54488
54489
  return this.imod(inv);
54489
54490
  }
54490
54491
  };
54491
- Red.prototype.pow = function pow22(a, num) {
54492
+ Red.prototype.pow = function pow23(a, num) {
54492
54493
  if (num.isZero()) return new BN7(1).toRed(this);
54493
54494
  if (num.cmpn(1) === 0) return a.clone();
54494
54495
  var windowSize = 4;
@@ -59281,8 +59282,8 @@ var require_bn2 = __commonJS({
59281
59282
  limbLen--;
59282
59283
  limbPow = limbPow / base | 0;
59283
59284
  var total = number4.length - start;
59284
- var mod3 = total % limbLen;
59285
- var end = Math.min(total, total - mod3) + start;
59285
+ var mod4 = total % limbLen;
59286
+ var end = Math.min(total, total - mod4) + start;
59286
59287
  var word = 0;
59287
59288
  for (var i = start; i < end; i += limbLen) {
59288
59289
  word = parseBase(number4, i, i + limbLen, base);
@@ -59293,10 +59294,10 @@ var require_bn2 = __commonJS({
59293
59294
  this._iaddn(word);
59294
59295
  }
59295
59296
  }
59296
- if (mod3 !== 0) {
59297
+ if (mod4 !== 0) {
59297
59298
  var pow3 = 1;
59298
59299
  word = parseBase(number4, i, number4.length, base);
59299
- for (i = 0; i < mod3; i++) {
59300
+ for (i = 0; i < mod4; i++) {
59300
59301
  pow3 *= base;
59301
59302
  }
59302
59303
  this.imuln(pow3);
@@ -60937,21 +60938,21 @@ var require_bn2 = __commonJS({
60937
60938
  mod: new BN2(0)
60938
60939
  };
60939
60940
  }
60940
- var div2, mod3, res;
60941
+ var div2, mod4, res;
60941
60942
  if (this.negative !== 0 && num.negative === 0) {
60942
60943
  res = this.neg().divmod(num, mode);
60943
60944
  if (mode !== "mod") {
60944
60945
  div2 = res.div.neg();
60945
60946
  }
60946
60947
  if (mode !== "div") {
60947
- mod3 = res.mod.neg();
60948
- if (positive && mod3.negative !== 0) {
60949
- mod3.iadd(num);
60948
+ mod4 = res.mod.neg();
60949
+ if (positive && mod4.negative !== 0) {
60950
+ mod4.iadd(num);
60950
60951
  }
60951
60952
  }
60952
60953
  return {
60953
60954
  div: div2,
60954
- mod: mod3
60955
+ mod: mod4
60955
60956
  };
60956
60957
  }
60957
60958
  if (this.negative === 0 && num.negative !== 0) {
@@ -60967,14 +60968,14 @@ var require_bn2 = __commonJS({
60967
60968
  if ((this.negative & num.negative) !== 0) {
60968
60969
  res = this.neg().divmod(num.neg(), mode);
60969
60970
  if (mode !== "div") {
60970
- mod3 = res.mod.neg();
60971
- if (positive && mod3.negative !== 0) {
60972
- mod3.isub(num);
60971
+ mod4 = res.mod.neg();
60972
+ if (positive && mod4.negative !== 0) {
60973
+ mod4.isub(num);
60973
60974
  }
60974
60975
  }
60975
60976
  return {
60976
60977
  div: res.div,
60977
- mod: mod3
60978
+ mod: mod4
60978
60979
  };
60979
60980
  }
60980
60981
  if (num.length > this.length || this.cmp(num) < 0) {
@@ -61006,7 +61007,7 @@ var require_bn2 = __commonJS({
61006
61007
  BN2.prototype.div = function div2(num) {
61007
61008
  return this.divmod(num, "div", false).div;
61008
61009
  };
61009
- BN2.prototype.mod = function mod3(num) {
61010
+ BN2.prototype.mod = function mod4(num) {
61010
61011
  return this.divmod(num, "mod", false).mod;
61011
61012
  };
61012
61013
  BN2.prototype.umod = function umod(num) {
@@ -61015,10 +61016,10 @@ var require_bn2 = __commonJS({
61015
61016
  BN2.prototype.divRound = function divRound(num) {
61016
61017
  var dm = this.divmod(num);
61017
61018
  if (dm.mod.isZero()) return dm.div;
61018
- var mod3 = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
61019
+ var mod4 = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
61019
61020
  var half = num.ushrn(1);
61020
61021
  var r2 = num.andln(1);
61021
- var cmp = mod3.cmp(half);
61022
+ var cmp = mod4.cmp(half);
61022
61023
  if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
61023
61024
  return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
61024
61025
  };
@@ -61632,9 +61633,9 @@ var require_bn2 = __commonJS({
61632
61633
  };
61633
61634
  Red.prototype.sqrt = function sqrt2(a) {
61634
61635
  if (a.isZero()) return a.clone();
61635
- var mod3 = this.m.andln(3);
61636
- assert3(mod3 % 2 === 1);
61637
- if (mod3 === 3) {
61636
+ var mod32 = this.m.andln(3);
61637
+ assert3(mod32 % 2 === 1);
61638
+ if (mod32 === 3) {
61638
61639
  var pow3 = this.m.add(new BN2(1)).iushrn(2);
61639
61640
  return this.pow(a, pow3);
61640
61641
  }
@@ -77038,7 +77039,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
77038
77039
  });
77039
77040
  const { prehash } = eddsaOpts;
77040
77041
  const { BASE: BASE2, Fp, Fn } = Point;
77041
- const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
77042
+ const randomBytes3 = eddsaOpts.randomBytes || randomBytes;
77042
77043
  const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
77043
77044
  const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
77044
77045
  abool(phflag, "phflag");
@@ -77120,7 +77121,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
77120
77121
  signature: 2 * _size2,
77121
77122
  seed: _size2
77122
77123
  };
77123
- function randomSecretKey(seed = randomBytes2(lengths.seed)) {
77124
+ function randomSecretKey(seed = randomBytes3(lengths.seed)) {
77124
77125
  return abytes(seed, lengths.seed, "seed");
77125
77126
  }
77126
77127
  function isValidSecretKey(key) {
@@ -77664,6 +77665,2288 @@ var Ed25519Keypair = class Ed25519Keypair2 extends Keypair {
77664
77665
  return Ed25519Keypair2.fromSecretKey(key);
77665
77666
  }
77666
77667
  };
77668
+ var crypto3 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
77669
+ function isBytes3(a) {
77670
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
77671
+ }
77672
+ function anumber3(n) {
77673
+ if (!Number.isSafeInteger(n) || n < 0)
77674
+ throw new Error("positive integer expected, got " + n);
77675
+ }
77676
+ function abytes2(b, ...lengths) {
77677
+ if (!isBytes3(b))
77678
+ throw new Error("Uint8Array expected");
77679
+ if (lengths.length > 0 && !lengths.includes(b.length))
77680
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
77681
+ }
77682
+ function ahash2(h) {
77683
+ if (typeof h !== "function" || typeof h.create !== "function")
77684
+ throw new Error("Hash should be wrapped by utils.createHasher");
77685
+ anumber3(h.outputLen);
77686
+ anumber3(h.blockLen);
77687
+ }
77688
+ function aexists2(instance, checkFinished = true) {
77689
+ if (instance.destroyed)
77690
+ throw new Error("Hash instance has been destroyed");
77691
+ if (checkFinished && instance.finished)
77692
+ throw new Error("Hash#digest() has already been called");
77693
+ }
77694
+ function aoutput2(out, instance) {
77695
+ abytes2(out);
77696
+ const min2 = instance.outputLen;
77697
+ if (out.length < min2) {
77698
+ throw new Error("digestInto() expects output buffer of length at least " + min2);
77699
+ }
77700
+ }
77701
+ function clean2(...arrays) {
77702
+ for (let i = 0; i < arrays.length; i++) {
77703
+ arrays[i].fill(0);
77704
+ }
77705
+ }
77706
+ function createView2(arr) {
77707
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
77708
+ }
77709
+ function rotr2(word, shift) {
77710
+ return word << 32 - shift | word >>> shift;
77711
+ }
77712
+ var hasHexBuiltin2 = /* @__PURE__ */ (() => (
77713
+ // @ts-ignore
77714
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
77715
+ ))();
77716
+ var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
77717
+ function bytesToHex2(bytes) {
77718
+ abytes2(bytes);
77719
+ if (hasHexBuiltin2)
77720
+ return bytes.toHex();
77721
+ let hex = "";
77722
+ for (let i = 0; i < bytes.length; i++) {
77723
+ hex += hexes2[bytes[i]];
77724
+ }
77725
+ return hex;
77726
+ }
77727
+ var asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
77728
+ function asciiToBase162(ch) {
77729
+ if (ch >= asciis2._0 && ch <= asciis2._9)
77730
+ return ch - asciis2._0;
77731
+ if (ch >= asciis2.A && ch <= asciis2.F)
77732
+ return ch - (asciis2.A - 10);
77733
+ if (ch >= asciis2.a && ch <= asciis2.f)
77734
+ return ch - (asciis2.a - 10);
77735
+ return;
77736
+ }
77737
+ function hexToBytes2(hex) {
77738
+ if (typeof hex !== "string")
77739
+ throw new Error("hex string expected, got " + typeof hex);
77740
+ if (hasHexBuiltin2)
77741
+ return Uint8Array.fromHex(hex);
77742
+ const hl = hex.length;
77743
+ const al = hl / 2;
77744
+ if (hl % 2)
77745
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
77746
+ const array3 = new Uint8Array(al);
77747
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
77748
+ const n1 = asciiToBase162(hex.charCodeAt(hi));
77749
+ const n2 = asciiToBase162(hex.charCodeAt(hi + 1));
77750
+ if (n1 === void 0 || n2 === void 0) {
77751
+ const char = hex[hi] + hex[hi + 1];
77752
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
77753
+ }
77754
+ array3[ai] = n1 * 16 + n2;
77755
+ }
77756
+ return array3;
77757
+ }
77758
+ function utf8ToBytes2(str) {
77759
+ if (typeof str !== "string")
77760
+ throw new Error("string expected");
77761
+ return new Uint8Array(new TextEncoder().encode(str));
77762
+ }
77763
+ function toBytes(data) {
77764
+ if (typeof data === "string")
77765
+ data = utf8ToBytes2(data);
77766
+ abytes2(data);
77767
+ return data;
77768
+ }
77769
+ function concatBytes3(...arrays) {
77770
+ let sum2 = 0;
77771
+ for (let i = 0; i < arrays.length; i++) {
77772
+ const a = arrays[i];
77773
+ abytes2(a);
77774
+ sum2 += a.length;
77775
+ }
77776
+ const res = new Uint8Array(sum2);
77777
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
77778
+ const a = arrays[i];
77779
+ res.set(a, pad);
77780
+ pad += a.length;
77781
+ }
77782
+ return res;
77783
+ }
77784
+ var Hash = class {
77785
+ };
77786
+ function createHasher2(hashCons) {
77787
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
77788
+ const tmp = hashCons();
77789
+ hashC.outputLen = tmp.outputLen;
77790
+ hashC.blockLen = tmp.blockLen;
77791
+ hashC.create = () => hashCons();
77792
+ return hashC;
77793
+ }
77794
+ function randomBytes2(bytesLength = 32) {
77795
+ if (crypto3 && typeof crypto3.getRandomValues === "function") {
77796
+ return crypto3.getRandomValues(new Uint8Array(bytesLength));
77797
+ }
77798
+ if (crypto3 && typeof crypto3.randomBytes === "function") {
77799
+ return Uint8Array.from(crypto3.randomBytes(bytesLength));
77800
+ }
77801
+ throw new Error("crypto.getRandomValues must be defined");
77802
+ }
77803
+ function setBigUint64(view, byteOffset, value, isLE2) {
77804
+ if (typeof view.setBigUint64 === "function")
77805
+ return view.setBigUint64(byteOffset, value, isLE2);
77806
+ const _32n2 = BigInt(32);
77807
+ const _u32_max = BigInt(4294967295);
77808
+ const wh = Number(value >> _32n2 & _u32_max);
77809
+ const wl = Number(value & _u32_max);
77810
+ const h = isLE2 ? 4 : 0;
77811
+ const l2 = isLE2 ? 0 : 4;
77812
+ view.setUint32(byteOffset + h, wh, isLE2);
77813
+ view.setUint32(byteOffset + l2, wl, isLE2);
77814
+ }
77815
+ function Chi2(a, b, c) {
77816
+ return a & b ^ ~a & c;
77817
+ }
77818
+ function Maj2(a, b, c) {
77819
+ return a & b ^ a & c ^ b & c;
77820
+ }
77821
+ var HashMD2 = class extends Hash {
77822
+ constructor(blockLen, outputLen, padOffset, isLE2) {
77823
+ super();
77824
+ this.finished = false;
77825
+ this.length = 0;
77826
+ this.pos = 0;
77827
+ this.destroyed = false;
77828
+ this.blockLen = blockLen;
77829
+ this.outputLen = outputLen;
77830
+ this.padOffset = padOffset;
77831
+ this.isLE = isLE2;
77832
+ this.buffer = new Uint8Array(blockLen);
77833
+ this.view = createView2(this.buffer);
77834
+ }
77835
+ update(data) {
77836
+ aexists2(this);
77837
+ data = toBytes(data);
77838
+ abytes2(data);
77839
+ const { view, buffer, blockLen } = this;
77840
+ const len = data.length;
77841
+ for (let pos = 0; pos < len; ) {
77842
+ const take = Math.min(blockLen - this.pos, len - pos);
77843
+ if (take === blockLen) {
77844
+ const dataView = createView2(data);
77845
+ for (; blockLen <= len - pos; pos += blockLen)
77846
+ this.process(dataView, pos);
77847
+ continue;
77848
+ }
77849
+ buffer.set(data.subarray(pos, pos + take), this.pos);
77850
+ this.pos += take;
77851
+ pos += take;
77852
+ if (this.pos === blockLen) {
77853
+ this.process(view, 0);
77854
+ this.pos = 0;
77855
+ }
77856
+ }
77857
+ this.length += data.length;
77858
+ this.roundClean();
77859
+ return this;
77860
+ }
77861
+ digestInto(out) {
77862
+ aexists2(this);
77863
+ aoutput2(out, this);
77864
+ this.finished = true;
77865
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
77866
+ let { pos } = this;
77867
+ buffer[pos++] = 128;
77868
+ clean2(this.buffer.subarray(pos));
77869
+ if (this.padOffset > blockLen - pos) {
77870
+ this.process(view, 0);
77871
+ pos = 0;
77872
+ }
77873
+ for (let i = pos; i < blockLen; i++)
77874
+ buffer[i] = 0;
77875
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
77876
+ this.process(view, 0);
77877
+ const oview = createView2(out);
77878
+ const len = this.outputLen;
77879
+ if (len % 4)
77880
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
77881
+ const outLen = len / 4;
77882
+ const state = this.get();
77883
+ if (outLen > state.length)
77884
+ throw new Error("_sha2: outputLen bigger than state");
77885
+ for (let i = 0; i < outLen; i++)
77886
+ oview.setUint32(4 * i, state[i], isLE2);
77887
+ }
77888
+ digest() {
77889
+ const { buffer, outputLen } = this;
77890
+ this.digestInto(buffer);
77891
+ const res = buffer.slice(0, outputLen);
77892
+ this.destroy();
77893
+ return res;
77894
+ }
77895
+ _cloneInto(to) {
77896
+ to || (to = new this.constructor());
77897
+ to.set(...this.get());
77898
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
77899
+ to.destroyed = destroyed;
77900
+ to.finished = finished;
77901
+ to.length = length;
77902
+ to.pos = pos;
77903
+ if (length % blockLen)
77904
+ to.buffer.set(buffer);
77905
+ return to;
77906
+ }
77907
+ clone() {
77908
+ return this._cloneInto();
77909
+ }
77910
+ };
77911
+ var SHA256_IV2 = /* @__PURE__ */ Uint32Array.from([
77912
+ 1779033703,
77913
+ 3144134277,
77914
+ 1013904242,
77915
+ 2773480762,
77916
+ 1359893119,
77917
+ 2600822924,
77918
+ 528734635,
77919
+ 1541459225
77920
+ ]);
77921
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
77922
+ 1116352408,
77923
+ 1899447441,
77924
+ 3049323471,
77925
+ 3921009573,
77926
+ 961987163,
77927
+ 1508970993,
77928
+ 2453635748,
77929
+ 2870763221,
77930
+ 3624381080,
77931
+ 310598401,
77932
+ 607225278,
77933
+ 1426881987,
77934
+ 1925078388,
77935
+ 2162078206,
77936
+ 2614888103,
77937
+ 3248222580,
77938
+ 3835390401,
77939
+ 4022224774,
77940
+ 264347078,
77941
+ 604807628,
77942
+ 770255983,
77943
+ 1249150122,
77944
+ 1555081692,
77945
+ 1996064986,
77946
+ 2554220882,
77947
+ 2821834349,
77948
+ 2952996808,
77949
+ 3210313671,
77950
+ 3336571891,
77951
+ 3584528711,
77952
+ 113926993,
77953
+ 338241895,
77954
+ 666307205,
77955
+ 773529912,
77956
+ 1294757372,
77957
+ 1396182291,
77958
+ 1695183700,
77959
+ 1986661051,
77960
+ 2177026350,
77961
+ 2456956037,
77962
+ 2730485921,
77963
+ 2820302411,
77964
+ 3259730800,
77965
+ 3345764771,
77966
+ 3516065817,
77967
+ 3600352804,
77968
+ 4094571909,
77969
+ 275423344,
77970
+ 430227734,
77971
+ 506948616,
77972
+ 659060556,
77973
+ 883997877,
77974
+ 958139571,
77975
+ 1322822218,
77976
+ 1537002063,
77977
+ 1747873779,
77978
+ 1955562222,
77979
+ 2024104815,
77980
+ 2227730452,
77981
+ 2361852424,
77982
+ 2428436474,
77983
+ 2756734187,
77984
+ 3204031479,
77985
+ 3329325298
77986
+ ]);
77987
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
77988
+ var SHA256 = class extends HashMD2 {
77989
+ constructor(outputLen = 32) {
77990
+ super(64, outputLen, 8, false);
77991
+ this.A = SHA256_IV2[0] | 0;
77992
+ this.B = SHA256_IV2[1] | 0;
77993
+ this.C = SHA256_IV2[2] | 0;
77994
+ this.D = SHA256_IV2[3] | 0;
77995
+ this.E = SHA256_IV2[4] | 0;
77996
+ this.F = SHA256_IV2[5] | 0;
77997
+ this.G = SHA256_IV2[6] | 0;
77998
+ this.H = SHA256_IV2[7] | 0;
77999
+ }
78000
+ get() {
78001
+ const { A, B: B2, C: C2, D: D2, E, F: F2, G: G2, H: H2 } = this;
78002
+ return [A, B2, C2, D2, E, F2, G2, H2];
78003
+ }
78004
+ // prettier-ignore
78005
+ set(A, B2, C2, D2, E, F2, G2, H2) {
78006
+ this.A = A | 0;
78007
+ this.B = B2 | 0;
78008
+ this.C = C2 | 0;
78009
+ this.D = D2 | 0;
78010
+ this.E = E | 0;
78011
+ this.F = F2 | 0;
78012
+ this.G = G2 | 0;
78013
+ this.H = H2 | 0;
78014
+ }
78015
+ process(view, offset) {
78016
+ for (let i = 0; i < 16; i++, offset += 4)
78017
+ SHA256_W[i] = view.getUint32(offset, false);
78018
+ for (let i = 16; i < 64; i++) {
78019
+ const W15 = SHA256_W[i - 15];
78020
+ const W2 = SHA256_W[i - 2];
78021
+ const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3;
78022
+ const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10;
78023
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
78024
+ }
78025
+ let { A, B: B2, C: C2, D: D2, E, F: F2, G: G2, H: H2 } = this;
78026
+ for (let i = 0; i < 64; i++) {
78027
+ const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25);
78028
+ const T1 = H2 + sigma1 + Chi2(E, F2, G2) + SHA256_K[i] + SHA256_W[i] | 0;
78029
+ const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22);
78030
+ const T2 = sigma0 + Maj2(A, B2, C2) | 0;
78031
+ H2 = G2;
78032
+ G2 = F2;
78033
+ F2 = E;
78034
+ E = D2 + T1 | 0;
78035
+ D2 = C2;
78036
+ C2 = B2;
78037
+ B2 = A;
78038
+ A = T1 + T2 | 0;
78039
+ }
78040
+ A = A + this.A | 0;
78041
+ B2 = B2 + this.B | 0;
78042
+ C2 = C2 + this.C | 0;
78043
+ D2 = D2 + this.D | 0;
78044
+ E = E + this.E | 0;
78045
+ F2 = F2 + this.F | 0;
78046
+ G2 = G2 + this.G | 0;
78047
+ H2 = H2 + this.H | 0;
78048
+ this.set(A, B2, C2, D2, E, F2, G2, H2);
78049
+ }
78050
+ roundClean() {
78051
+ clean2(SHA256_W);
78052
+ }
78053
+ destroy() {
78054
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
78055
+ clean2(this.buffer);
78056
+ }
78057
+ };
78058
+ var sha2562 = /* @__PURE__ */ createHasher2(() => new SHA256());
78059
+ var HMAC = class extends Hash {
78060
+ constructor(hash, _key) {
78061
+ super();
78062
+ this.finished = false;
78063
+ this.destroyed = false;
78064
+ ahash2(hash);
78065
+ const key = toBytes(_key);
78066
+ this.iHash = hash.create();
78067
+ if (typeof this.iHash.update !== "function")
78068
+ throw new Error("Expected instance of class which extends utils.Hash");
78069
+ this.blockLen = this.iHash.blockLen;
78070
+ this.outputLen = this.iHash.outputLen;
78071
+ const blockLen = this.blockLen;
78072
+ const pad = new Uint8Array(blockLen);
78073
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
78074
+ for (let i = 0; i < pad.length; i++)
78075
+ pad[i] ^= 54;
78076
+ this.iHash.update(pad);
78077
+ this.oHash = hash.create();
78078
+ for (let i = 0; i < pad.length; i++)
78079
+ pad[i] ^= 54 ^ 92;
78080
+ this.oHash.update(pad);
78081
+ clean2(pad);
78082
+ }
78083
+ update(buf) {
78084
+ aexists2(this);
78085
+ this.iHash.update(buf);
78086
+ return this;
78087
+ }
78088
+ digestInto(out) {
78089
+ aexists2(this);
78090
+ abytes2(out, this.outputLen);
78091
+ this.finished = true;
78092
+ this.iHash.digestInto(out);
78093
+ this.oHash.update(out);
78094
+ this.oHash.digestInto(out);
78095
+ this.destroy();
78096
+ }
78097
+ digest() {
78098
+ const out = new Uint8Array(this.oHash.outputLen);
78099
+ this.digestInto(out);
78100
+ return out;
78101
+ }
78102
+ _cloneInto(to) {
78103
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
78104
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
78105
+ to = to;
78106
+ to.finished = finished;
78107
+ to.destroyed = destroyed;
78108
+ to.blockLen = blockLen;
78109
+ to.outputLen = outputLen;
78110
+ to.oHash = oHash._cloneInto(to.oHash);
78111
+ to.iHash = iHash._cloneInto(to.iHash);
78112
+ return to;
78113
+ }
78114
+ clone() {
78115
+ return this._cloneInto();
78116
+ }
78117
+ destroy() {
78118
+ this.destroyed = true;
78119
+ this.oHash.destroy();
78120
+ this.iHash.destroy();
78121
+ }
78122
+ };
78123
+ var hmac2 = (hash, key, message) => new HMAC(hash, key).update(message).digest();
78124
+ hmac2.create = (hash, key) => new HMAC(hash, key);
78125
+ var _0n5 = /* @__PURE__ */ BigInt(0);
78126
+ var _1n6 = /* @__PURE__ */ BigInt(1);
78127
+ function _abool2(value, title = "") {
78128
+ if (typeof value !== "boolean") {
78129
+ const prefix = title && `"${title}"`;
78130
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
78131
+ }
78132
+ return value;
78133
+ }
78134
+ function _abytes2(value, length, title = "") {
78135
+ const bytes = isBytes3(value);
78136
+ const len = value?.length;
78137
+ const needsLen = length !== void 0;
78138
+ if (!bytes || needsLen && len !== length) {
78139
+ const prefix = title && `"${title}" `;
78140
+ const ofLen = needsLen ? ` of length ${length}` : "";
78141
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
78142
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
78143
+ }
78144
+ return value;
78145
+ }
78146
+ function numberToHexUnpadded(num) {
78147
+ const hex = num.toString(16);
78148
+ return hex.length & 1 ? "0" + hex : hex;
78149
+ }
78150
+ function hexToNumber2(hex) {
78151
+ if (typeof hex !== "string")
78152
+ throw new Error("hex string expected, got " + typeof hex);
78153
+ return hex === "" ? _0n5 : BigInt("0x" + hex);
78154
+ }
78155
+ function bytesToNumberBE2(bytes) {
78156
+ return hexToNumber2(bytesToHex2(bytes));
78157
+ }
78158
+ function bytesToNumberLE2(bytes) {
78159
+ abytes2(bytes);
78160
+ return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse()));
78161
+ }
78162
+ function numberToBytesBE2(n, len) {
78163
+ return hexToBytes2(n.toString(16).padStart(len * 2, "0"));
78164
+ }
78165
+ function numberToBytesLE2(n, len) {
78166
+ return numberToBytesBE2(n, len).reverse();
78167
+ }
78168
+ function ensureBytes(title, hex, expectedLength) {
78169
+ let res;
78170
+ if (typeof hex === "string") {
78171
+ try {
78172
+ res = hexToBytes2(hex);
78173
+ } catch (e) {
78174
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
78175
+ }
78176
+ } else if (isBytes3(hex)) {
78177
+ res = Uint8Array.from(hex);
78178
+ } else {
78179
+ throw new Error(title + " must be hex string or Uint8Array");
78180
+ }
78181
+ res.length;
78182
+ return res;
78183
+ }
78184
+ var isPosBig2 = (n) => typeof n === "bigint" && _0n5 <= n;
78185
+ function inRange2(n, min2, max2) {
78186
+ return isPosBig2(n) && isPosBig2(min2) && isPosBig2(max2) && min2 <= n && n < max2;
78187
+ }
78188
+ function aInRange2(title, n, min2, max2) {
78189
+ if (!inRange2(n, min2, max2))
78190
+ throw new Error("expected valid " + title + ": " + min2 + " <= n < " + max2 + ", got " + n);
78191
+ }
78192
+ function bitLen2(n) {
78193
+ let len;
78194
+ for (len = 0; n > _0n5; n >>= _1n6, len += 1)
78195
+ ;
78196
+ return len;
78197
+ }
78198
+ var bitMask2 = (n) => (_1n6 << BigInt(n)) - _1n6;
78199
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
78200
+ if (typeof hashLen !== "number" || hashLen < 2)
78201
+ throw new Error("hashLen must be a number");
78202
+ if (typeof qByteLen !== "number" || qByteLen < 2)
78203
+ throw new Error("qByteLen must be a number");
78204
+ if (typeof hmacFn !== "function")
78205
+ throw new Error("hmacFn must be a function");
78206
+ const u8n = (len) => new Uint8Array(len);
78207
+ const u8of = (byte) => Uint8Array.of(byte);
78208
+ let v = u8n(hashLen);
78209
+ let k = u8n(hashLen);
78210
+ let i = 0;
78211
+ const reset = () => {
78212
+ v.fill(1);
78213
+ k.fill(0);
78214
+ i = 0;
78215
+ };
78216
+ const h = (...b) => hmacFn(k, v, ...b);
78217
+ const reseed = (seed = u8n(0)) => {
78218
+ k = h(u8of(0), seed);
78219
+ v = h();
78220
+ if (seed.length === 0)
78221
+ return;
78222
+ k = h(u8of(1), seed);
78223
+ v = h();
78224
+ };
78225
+ const gen = () => {
78226
+ if (i++ >= 1e3)
78227
+ throw new Error("drbg: tried 1000 values");
78228
+ let len = 0;
78229
+ const out = [];
78230
+ while (len < qByteLen) {
78231
+ v = h();
78232
+ const sl = v.slice();
78233
+ out.push(sl);
78234
+ len += v.length;
78235
+ }
78236
+ return concatBytes3(...out);
78237
+ };
78238
+ const genUntil = (seed, pred) => {
78239
+ reset();
78240
+ reseed(seed);
78241
+ let res = void 0;
78242
+ while (!(res = pred(gen())))
78243
+ reseed();
78244
+ reset();
78245
+ return res;
78246
+ };
78247
+ return genUntil;
78248
+ }
78249
+ function _validateObject(object4, fields, optFields = {}) {
78250
+ if (!object4 || typeof object4 !== "object")
78251
+ throw new Error("expected valid options object");
78252
+ function checkField(fieldName, expectedType, isOpt) {
78253
+ const val = object4[fieldName];
78254
+ if (isOpt && val === void 0)
78255
+ return;
78256
+ const current = typeof val;
78257
+ if (current !== expectedType || val === null)
78258
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
78259
+ }
78260
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
78261
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
78262
+ }
78263
+ function memoized2(fn) {
78264
+ const map2 = /* @__PURE__ */ new WeakMap();
78265
+ return (arg, ...args) => {
78266
+ const val = map2.get(arg);
78267
+ if (val !== void 0)
78268
+ return val;
78269
+ const computed = fn(arg, ...args);
78270
+ map2.set(arg, computed);
78271
+ return computed;
78272
+ };
78273
+ }
78274
+ var _0n6 = BigInt(0);
78275
+ var _1n7 = BigInt(1);
78276
+ var _2n4 = /* @__PURE__ */ BigInt(2);
78277
+ var _3n2 = /* @__PURE__ */ BigInt(3);
78278
+ var _4n2 = /* @__PURE__ */ BigInt(4);
78279
+ var _5n3 = /* @__PURE__ */ BigInt(5);
78280
+ var _7n2 = /* @__PURE__ */ BigInt(7);
78281
+ var _8n4 = /* @__PURE__ */ BigInt(8);
78282
+ var _9n2 = /* @__PURE__ */ BigInt(9);
78283
+ var _16n2 = /* @__PURE__ */ BigInt(16);
78284
+ function mod3(a, b) {
78285
+ const result = a % b;
78286
+ return result >= _0n6 ? result : b + result;
78287
+ }
78288
+ function pow22(x, power, modulo) {
78289
+ let res = x;
78290
+ while (power-- > _0n6) {
78291
+ res *= res;
78292
+ res %= modulo;
78293
+ }
78294
+ return res;
78295
+ }
78296
+ function invert2(number4, modulo) {
78297
+ if (number4 === _0n6)
78298
+ throw new Error("invert: expected non-zero number");
78299
+ if (modulo <= _0n6)
78300
+ throw new Error("invert: expected positive modulus, got " + modulo);
78301
+ let a = mod3(number4, modulo);
78302
+ let b = modulo;
78303
+ let x = _0n6, u2 = _1n7;
78304
+ while (a !== _0n6) {
78305
+ const q = b / a;
78306
+ const r = b % a;
78307
+ const m = x - u2 * q;
78308
+ b = a, a = r, x = u2, u2 = m;
78309
+ }
78310
+ const gcd2 = b;
78311
+ if (gcd2 !== _1n7)
78312
+ throw new Error("invert: does not exist");
78313
+ return mod3(x, modulo);
78314
+ }
78315
+ function assertIsSquare2(Fp, root, n) {
78316
+ if (!Fp.eql(Fp.sqr(root), n))
78317
+ throw new Error("Cannot find square root");
78318
+ }
78319
+ function sqrt3mod42(Fp, n) {
78320
+ const p1div4 = (Fp.ORDER + _1n7) / _4n2;
78321
+ const root = Fp.pow(n, p1div4);
78322
+ assertIsSquare2(Fp, root, n);
78323
+ return root;
78324
+ }
78325
+ function sqrt5mod82(Fp, n) {
78326
+ const p5div8 = (Fp.ORDER - _5n3) / _8n4;
78327
+ const n2 = Fp.mul(n, _2n4);
78328
+ const v = Fp.pow(n2, p5div8);
78329
+ const nv = Fp.mul(n, v);
78330
+ const i = Fp.mul(Fp.mul(nv, _2n4), v);
78331
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
78332
+ assertIsSquare2(Fp, root, n);
78333
+ return root;
78334
+ }
78335
+ function sqrt9mod162(P3) {
78336
+ const Fp_ = Field2(P3);
78337
+ const tn = tonelliShanks2(P3);
78338
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
78339
+ const c2 = tn(Fp_, c1);
78340
+ const c3 = tn(Fp_, Fp_.neg(c1));
78341
+ const c4 = (P3 + _7n2) / _16n2;
78342
+ return (Fp, n) => {
78343
+ let tv1 = Fp.pow(n, c4);
78344
+ let tv2 = Fp.mul(tv1, c1);
78345
+ const tv3 = Fp.mul(tv1, c2);
78346
+ const tv4 = Fp.mul(tv1, c3);
78347
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
78348
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
78349
+ tv1 = Fp.cmov(tv1, tv2, e1);
78350
+ tv2 = Fp.cmov(tv4, tv3, e2);
78351
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
78352
+ const root = Fp.cmov(tv1, tv2, e3);
78353
+ assertIsSquare2(Fp, root, n);
78354
+ return root;
78355
+ };
78356
+ }
78357
+ function tonelliShanks2(P3) {
78358
+ if (P3 < _3n2)
78359
+ throw new Error("sqrt is not defined for small field");
78360
+ let Q = P3 - _1n7;
78361
+ let S2 = 0;
78362
+ while (Q % _2n4 === _0n6) {
78363
+ Q /= _2n4;
78364
+ S2++;
78365
+ }
78366
+ let Z2 = _2n4;
78367
+ const _Fp = Field2(P3);
78368
+ while (FpLegendre2(_Fp, Z2) === 1) {
78369
+ if (Z2++ > 1e3)
78370
+ throw new Error("Cannot find square root: probably non-prime P");
78371
+ }
78372
+ if (S2 === 1)
78373
+ return sqrt3mod42;
78374
+ let cc = _Fp.pow(Z2, Q);
78375
+ const Q1div2 = (Q + _1n7) / _2n4;
78376
+ return function tonelliSlow(Fp, n) {
78377
+ if (Fp.is0(n))
78378
+ return n;
78379
+ if (FpLegendre2(Fp, n) !== 1)
78380
+ throw new Error("Cannot find square root");
78381
+ let M2 = S2;
78382
+ let c = Fp.mul(Fp.ONE, cc);
78383
+ let t = Fp.pow(n, Q);
78384
+ let R2 = Fp.pow(n, Q1div2);
78385
+ while (!Fp.eql(t, Fp.ONE)) {
78386
+ if (Fp.is0(t))
78387
+ return Fp.ZERO;
78388
+ let i = 1;
78389
+ let t_tmp = Fp.sqr(t);
78390
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
78391
+ i++;
78392
+ t_tmp = Fp.sqr(t_tmp);
78393
+ if (i === M2)
78394
+ throw new Error("Cannot find square root");
78395
+ }
78396
+ const exponent = _1n7 << BigInt(M2 - i - 1);
78397
+ const b = Fp.pow(c, exponent);
78398
+ M2 = i;
78399
+ c = Fp.sqr(b);
78400
+ t = Fp.mul(t, c);
78401
+ R2 = Fp.mul(R2, b);
78402
+ }
78403
+ return R2;
78404
+ };
78405
+ }
78406
+ function FpSqrt2(P3) {
78407
+ if (P3 % _4n2 === _3n2)
78408
+ return sqrt3mod42;
78409
+ if (P3 % _8n4 === _5n3)
78410
+ return sqrt5mod82;
78411
+ if (P3 % _16n2 === _9n2)
78412
+ return sqrt9mod162(P3);
78413
+ return tonelliShanks2(P3);
78414
+ }
78415
+ var FIELD_FIELDS2 = [
78416
+ "create",
78417
+ "isValid",
78418
+ "is0",
78419
+ "neg",
78420
+ "inv",
78421
+ "sqrt",
78422
+ "sqr",
78423
+ "eql",
78424
+ "add",
78425
+ "sub",
78426
+ "mul",
78427
+ "pow",
78428
+ "div",
78429
+ "addN",
78430
+ "subN",
78431
+ "mulN",
78432
+ "sqrN"
78433
+ ];
78434
+ function validateField2(field) {
78435
+ const initial = {
78436
+ ORDER: "bigint",
78437
+ MASK: "bigint",
78438
+ BYTES: "number",
78439
+ BITS: "number"
78440
+ };
78441
+ const opts = FIELD_FIELDS2.reduce((map2, val) => {
78442
+ map2[val] = "function";
78443
+ return map2;
78444
+ }, initial);
78445
+ _validateObject(field, opts);
78446
+ return field;
78447
+ }
78448
+ function FpPow2(Fp, num, power) {
78449
+ if (power < _0n6)
78450
+ throw new Error("invalid exponent, negatives unsupported");
78451
+ if (power === _0n6)
78452
+ return Fp.ONE;
78453
+ if (power === _1n7)
78454
+ return num;
78455
+ let p = Fp.ONE;
78456
+ let d = num;
78457
+ while (power > _0n6) {
78458
+ if (power & _1n7)
78459
+ p = Fp.mul(p, d);
78460
+ d = Fp.sqr(d);
78461
+ power >>= _1n7;
78462
+ }
78463
+ return p;
78464
+ }
78465
+ function FpInvertBatch2(Fp, nums, passZero = false) {
78466
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
78467
+ const multipliedAcc = nums.reduce((acc, num, i) => {
78468
+ if (Fp.is0(num))
78469
+ return acc;
78470
+ inverted[i] = acc;
78471
+ return Fp.mul(acc, num);
78472
+ }, Fp.ONE);
78473
+ const invertedAcc = Fp.inv(multipliedAcc);
78474
+ nums.reduceRight((acc, num, i) => {
78475
+ if (Fp.is0(num))
78476
+ return acc;
78477
+ inverted[i] = Fp.mul(acc, inverted[i]);
78478
+ return Fp.mul(acc, num);
78479
+ }, invertedAcc);
78480
+ return inverted;
78481
+ }
78482
+ function FpLegendre2(Fp, n) {
78483
+ const p1mod2 = (Fp.ORDER - _1n7) / _2n4;
78484
+ const powered = Fp.pow(n, p1mod2);
78485
+ const yes = Fp.eql(powered, Fp.ONE);
78486
+ const zero = Fp.eql(powered, Fp.ZERO);
78487
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
78488
+ if (!yes && !zero && !no)
78489
+ throw new Error("invalid Legendre symbol result");
78490
+ return yes ? 1 : zero ? 0 : -1;
78491
+ }
78492
+ function nLength2(n, nBitLength) {
78493
+ if (nBitLength !== void 0)
78494
+ anumber3(nBitLength);
78495
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
78496
+ const nByteLength = Math.ceil(_nBitLength / 8);
78497
+ return { nBitLength: _nBitLength, nByteLength };
78498
+ }
78499
+ function Field2(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) {
78500
+ if (ORDER <= _0n6)
78501
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
78502
+ let _nbitLength = void 0;
78503
+ let _sqrt = void 0;
78504
+ let modFromBytes = false;
78505
+ let allowedLengths = void 0;
78506
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
78507
+ if (opts.sqrt || isLE2)
78508
+ throw new Error("cannot specify opts in two arguments");
78509
+ const _opts = bitLenOrOpts;
78510
+ if (_opts.BITS)
78511
+ _nbitLength = _opts.BITS;
78512
+ if (_opts.sqrt)
78513
+ _sqrt = _opts.sqrt;
78514
+ if (typeof _opts.isLE === "boolean")
78515
+ isLE2 = _opts.isLE;
78516
+ if (typeof _opts.modFromBytes === "boolean")
78517
+ modFromBytes = _opts.modFromBytes;
78518
+ allowedLengths = _opts.allowedLengths;
78519
+ } else {
78520
+ if (typeof bitLenOrOpts === "number")
78521
+ _nbitLength = bitLenOrOpts;
78522
+ if (opts.sqrt)
78523
+ _sqrt = opts.sqrt;
78524
+ }
78525
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength2(ORDER, _nbitLength);
78526
+ if (BYTES > 2048)
78527
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
78528
+ let sqrtP;
78529
+ const f = Object.freeze({
78530
+ ORDER,
78531
+ isLE: isLE2,
78532
+ BITS,
78533
+ BYTES,
78534
+ MASK: bitMask2(BITS),
78535
+ ZERO: _0n6,
78536
+ ONE: _1n7,
78537
+ allowedLengths,
78538
+ create: (num) => mod3(num, ORDER),
78539
+ isValid: (num) => {
78540
+ if (typeof num !== "bigint")
78541
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
78542
+ return _0n6 <= num && num < ORDER;
78543
+ },
78544
+ is0: (num) => num === _0n6,
78545
+ // is valid and invertible
78546
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
78547
+ isOdd: (num) => (num & _1n7) === _1n7,
78548
+ neg: (num) => mod3(-num, ORDER),
78549
+ eql: (lhs, rhs) => lhs === rhs,
78550
+ sqr: (num) => mod3(num * num, ORDER),
78551
+ add: (lhs, rhs) => mod3(lhs + rhs, ORDER),
78552
+ sub: (lhs, rhs) => mod3(lhs - rhs, ORDER),
78553
+ mul: (lhs, rhs) => mod3(lhs * rhs, ORDER),
78554
+ pow: (num, power) => FpPow2(f, num, power),
78555
+ div: (lhs, rhs) => mod3(lhs * invert2(rhs, ORDER), ORDER),
78556
+ // Same as above, but doesn't normalize
78557
+ sqrN: (num) => num * num,
78558
+ addN: (lhs, rhs) => lhs + rhs,
78559
+ subN: (lhs, rhs) => lhs - rhs,
78560
+ mulN: (lhs, rhs) => lhs * rhs,
78561
+ inv: (num) => invert2(num, ORDER),
78562
+ sqrt: _sqrt || ((n) => {
78563
+ if (!sqrtP)
78564
+ sqrtP = FpSqrt2(ORDER);
78565
+ return sqrtP(f, n);
78566
+ }),
78567
+ toBytes: (num) => isLE2 ? numberToBytesLE2(num, BYTES) : numberToBytesBE2(num, BYTES),
78568
+ fromBytes: (bytes, skipValidation = true) => {
78569
+ if (allowedLengths) {
78570
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
78571
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
78572
+ }
78573
+ const padded = new Uint8Array(BYTES);
78574
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
78575
+ bytes = padded;
78576
+ }
78577
+ if (bytes.length !== BYTES)
78578
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
78579
+ let scalar = isLE2 ? bytesToNumberLE2(bytes) : bytesToNumberBE2(bytes);
78580
+ if (modFromBytes)
78581
+ scalar = mod3(scalar, ORDER);
78582
+ if (!skipValidation) {
78583
+ if (!f.isValid(scalar))
78584
+ throw new Error("invalid field element: outside of range 0..ORDER");
78585
+ }
78586
+ return scalar;
78587
+ },
78588
+ // TODO: we don't need it here, move out to separate fn
78589
+ invertBatch: (lst) => FpInvertBatch2(f, lst),
78590
+ // We can't move this out because Fp6, Fp12 implement it
78591
+ // and it's unclear what to return in there.
78592
+ cmov: (a, b, c) => c ? b : a
78593
+ });
78594
+ return Object.freeze(f);
78595
+ }
78596
+ function getFieldBytesLength(fieldOrder) {
78597
+ if (typeof fieldOrder !== "bigint")
78598
+ throw new Error("field order must be bigint");
78599
+ const bitLength = fieldOrder.toString(2).length;
78600
+ return Math.ceil(bitLength / 8);
78601
+ }
78602
+ function getMinHashLength(fieldOrder) {
78603
+ const length = getFieldBytesLength(fieldOrder);
78604
+ return length + Math.ceil(length / 2);
78605
+ }
78606
+ function mapHashToField(key, fieldOrder, isLE2 = false) {
78607
+ const len = key.length;
78608
+ const fieldLen = getFieldBytesLength(fieldOrder);
78609
+ const minLen = getMinHashLength(fieldOrder);
78610
+ if (len < 16 || len < minLen || len > 1024)
78611
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
78612
+ const num = isLE2 ? bytesToNumberLE2(key) : bytesToNumberBE2(key);
78613
+ const reduced = mod3(num, fieldOrder - _1n7) + _1n7;
78614
+ return isLE2 ? numberToBytesLE2(reduced, fieldLen) : numberToBytesBE2(reduced, fieldLen);
78615
+ }
78616
+ var _0n7 = BigInt(0);
78617
+ var _1n8 = BigInt(1);
78618
+ function negateCt2(condition, item) {
78619
+ const neg = item.negate();
78620
+ return condition ? neg : item;
78621
+ }
78622
+ function normalizeZ2(c, points) {
78623
+ const invertedZs = FpInvertBatch2(c.Fp, points.map((p) => p.Z));
78624
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
78625
+ }
78626
+ function validateW2(W, bits) {
78627
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
78628
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
78629
+ }
78630
+ function calcWOpts2(W, scalarBits) {
78631
+ validateW2(W, scalarBits);
78632
+ const windows = Math.ceil(scalarBits / W) + 1;
78633
+ const windowSize = 2 ** (W - 1);
78634
+ const maxNumber = 2 ** W;
78635
+ const mask = bitMask2(W);
78636
+ const shiftBy = BigInt(W);
78637
+ return { windows, windowSize, mask, maxNumber, shiftBy };
78638
+ }
78639
+ function calcOffsets2(n, window2, wOpts) {
78640
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
78641
+ let wbits = Number(n & mask);
78642
+ let nextN = n >> shiftBy;
78643
+ if (wbits > windowSize) {
78644
+ wbits -= maxNumber;
78645
+ nextN += _1n8;
78646
+ }
78647
+ const offsetStart = window2 * windowSize;
78648
+ const offset = offsetStart + Math.abs(wbits) - 1;
78649
+ const isZero = wbits === 0;
78650
+ const isNeg = wbits < 0;
78651
+ const isNegF = window2 % 2 !== 0;
78652
+ const offsetF = offsetStart;
78653
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
78654
+ }
78655
+ function validateMSMPoints(points, c) {
78656
+ if (!Array.isArray(points))
78657
+ throw new Error("array expected");
78658
+ points.forEach((p, i) => {
78659
+ if (!(p instanceof c))
78660
+ throw new Error("invalid point at index " + i);
78661
+ });
78662
+ }
78663
+ function validateMSMScalars(scalars, field) {
78664
+ if (!Array.isArray(scalars))
78665
+ throw new Error("array of scalars expected");
78666
+ scalars.forEach((s, i) => {
78667
+ if (!field.isValid(s))
78668
+ throw new Error("invalid scalar at index " + i);
78669
+ });
78670
+ }
78671
+ var pointPrecomputes2 = /* @__PURE__ */ new WeakMap();
78672
+ var pointWindowSizes2 = /* @__PURE__ */ new WeakMap();
78673
+ function getW2(P3) {
78674
+ return pointWindowSizes2.get(P3) || 1;
78675
+ }
78676
+ function assert02(n) {
78677
+ if (n !== _0n7)
78678
+ throw new Error("invalid wNAF");
78679
+ }
78680
+ var wNAF2 = class {
78681
+ // Parametrized with a given Point class (not individual point)
78682
+ constructor(Point, bits) {
78683
+ this.BASE = Point.BASE;
78684
+ this.ZERO = Point.ZERO;
78685
+ this.Fn = Point.Fn;
78686
+ this.bits = bits;
78687
+ }
78688
+ // non-const time multiplication ladder
78689
+ _unsafeLadder(elm, n, p = this.ZERO) {
78690
+ let d = elm;
78691
+ while (n > _0n7) {
78692
+ if (n & _1n8)
78693
+ p = p.add(d);
78694
+ d = d.double();
78695
+ n >>= _1n8;
78696
+ }
78697
+ return p;
78698
+ }
78699
+ /**
78700
+ * Creates a wNAF precomputation window. Used for caching.
78701
+ * Default window size is set by `utils.precompute()` and is equal to 8.
78702
+ * Number of precomputed points depends on the curve size:
78703
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
78704
+ * - 𝑊 is the window size
78705
+ * - 𝑛 is the bitlength of the curve order.
78706
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
78707
+ * @param point Point instance
78708
+ * @param W window size
78709
+ * @returns precomputed point tables flattened to a single array
78710
+ */
78711
+ precomputeWindow(point, W) {
78712
+ const { windows, windowSize } = calcWOpts2(W, this.bits);
78713
+ const points = [];
78714
+ let p = point;
78715
+ let base = p;
78716
+ for (let window2 = 0; window2 < windows; window2++) {
78717
+ base = p;
78718
+ points.push(base);
78719
+ for (let i = 1; i < windowSize; i++) {
78720
+ base = base.add(p);
78721
+ points.push(base);
78722
+ }
78723
+ p = base.double();
78724
+ }
78725
+ return points;
78726
+ }
78727
+ /**
78728
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
78729
+ * More compact implementation:
78730
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
78731
+ * @returns real and fake (for const-time) points
78732
+ */
78733
+ wNAF(W, precomputes, n) {
78734
+ if (!this.Fn.isValid(n))
78735
+ throw new Error("invalid scalar");
78736
+ let p = this.ZERO;
78737
+ let f = this.BASE;
78738
+ const wo = calcWOpts2(W, this.bits);
78739
+ for (let window2 = 0; window2 < wo.windows; window2++) {
78740
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets2(n, window2, wo);
78741
+ n = nextN;
78742
+ if (isZero) {
78743
+ f = f.add(negateCt2(isNegF, precomputes[offsetF]));
78744
+ } else {
78745
+ p = p.add(negateCt2(isNeg, precomputes[offset]));
78746
+ }
78747
+ }
78748
+ assert02(n);
78749
+ return { p, f };
78750
+ }
78751
+ /**
78752
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
78753
+ * @param acc accumulator point to add result of multiplication
78754
+ * @returns point
78755
+ */
78756
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
78757
+ const wo = calcWOpts2(W, this.bits);
78758
+ for (let window2 = 0; window2 < wo.windows; window2++) {
78759
+ if (n === _0n7)
78760
+ break;
78761
+ const { nextN, offset, isZero, isNeg } = calcOffsets2(n, window2, wo);
78762
+ n = nextN;
78763
+ if (isZero) {
78764
+ continue;
78765
+ } else {
78766
+ const item = precomputes[offset];
78767
+ acc = acc.add(isNeg ? item.negate() : item);
78768
+ }
78769
+ }
78770
+ assert02(n);
78771
+ return acc;
78772
+ }
78773
+ getPrecomputes(W, point, transform3) {
78774
+ let comp = pointPrecomputes2.get(point);
78775
+ if (!comp) {
78776
+ comp = this.precomputeWindow(point, W);
78777
+ if (W !== 1) {
78778
+ if (typeof transform3 === "function")
78779
+ comp = transform3(comp);
78780
+ pointPrecomputes2.set(point, comp);
78781
+ }
78782
+ }
78783
+ return comp;
78784
+ }
78785
+ cached(point, scalar, transform3) {
78786
+ const W = getW2(point);
78787
+ return this.wNAF(W, this.getPrecomputes(W, point, transform3), scalar);
78788
+ }
78789
+ unsafe(point, scalar, transform3, prev) {
78790
+ const W = getW2(point);
78791
+ if (W === 1)
78792
+ return this._unsafeLadder(point, scalar, prev);
78793
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform3), scalar, prev);
78794
+ }
78795
+ // We calculate precomputes for elliptic curve point multiplication
78796
+ // using windowed method. This specifies window size and
78797
+ // stores precomputed values. Usually only base point would be precomputed.
78798
+ createCache(P3, W) {
78799
+ validateW2(W, this.bits);
78800
+ pointWindowSizes2.set(P3, W);
78801
+ pointPrecomputes2.delete(P3);
78802
+ }
78803
+ hasCache(elm) {
78804
+ return getW2(elm) !== 1;
78805
+ }
78806
+ };
78807
+ function mulEndoUnsafe(Point, point, k1, k2) {
78808
+ let acc = point;
78809
+ let p1 = Point.ZERO;
78810
+ let p2 = Point.ZERO;
78811
+ while (k1 > _0n7 || k2 > _0n7) {
78812
+ if (k1 & _1n8)
78813
+ p1 = p1.add(acc);
78814
+ if (k2 & _1n8)
78815
+ p2 = p2.add(acc);
78816
+ acc = acc.double();
78817
+ k1 >>= _1n8;
78818
+ k2 >>= _1n8;
78819
+ }
78820
+ return { p1, p2 };
78821
+ }
78822
+ function pippenger(c, fieldN, points, scalars) {
78823
+ validateMSMPoints(points, c);
78824
+ validateMSMScalars(scalars, fieldN);
78825
+ const plength = points.length;
78826
+ const slength = scalars.length;
78827
+ if (plength !== slength)
78828
+ throw new Error("arrays of points and scalars must have equal length");
78829
+ const zero = c.ZERO;
78830
+ const wbits = bitLen2(BigInt(plength));
78831
+ let windowSize = 1;
78832
+ if (wbits > 12)
78833
+ windowSize = wbits - 3;
78834
+ else if (wbits > 4)
78835
+ windowSize = wbits - 2;
78836
+ else if (wbits > 0)
78837
+ windowSize = 2;
78838
+ const MASK = bitMask2(windowSize);
78839
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
78840
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
78841
+ let sum2 = zero;
78842
+ for (let i = lastBits; i >= 0; i -= windowSize) {
78843
+ buckets.fill(zero);
78844
+ for (let j = 0; j < slength; j++) {
78845
+ const scalar = scalars[j];
78846
+ const wbits2 = Number(scalar >> BigInt(i) & MASK);
78847
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
78848
+ }
78849
+ let resI = zero;
78850
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
78851
+ sumI = sumI.add(buckets[j]);
78852
+ resI = resI.add(sumI);
78853
+ }
78854
+ sum2 = sum2.add(resI);
78855
+ if (i !== 0)
78856
+ for (let j = 0; j < windowSize; j++)
78857
+ sum2 = sum2.double();
78858
+ }
78859
+ return sum2;
78860
+ }
78861
+ function createField2(order, field, isLE2) {
78862
+ if (field) {
78863
+ if (field.ORDER !== order)
78864
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
78865
+ validateField2(field);
78866
+ return field;
78867
+ } else {
78868
+ return Field2(order, { isLE: isLE2 });
78869
+ }
78870
+ }
78871
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
78872
+ if (FpFnLE === void 0)
78873
+ FpFnLE = type === "edwards";
78874
+ if (!CURVE || typeof CURVE !== "object")
78875
+ throw new Error(`expected valid ${type} CURVE object`);
78876
+ for (const p of ["p", "n", "h"]) {
78877
+ const val = CURVE[p];
78878
+ if (!(typeof val === "bigint" && val > _0n7))
78879
+ throw new Error(`CURVE.${p} must be positive bigint`);
78880
+ }
78881
+ const Fp = createField2(CURVE.p, curveOpts.Fp, FpFnLE);
78882
+ const Fn = createField2(CURVE.n, curveOpts.Fn, FpFnLE);
78883
+ const _b = "b";
78884
+ const params = ["Gx", "Gy", "a", _b];
78885
+ for (const p of params) {
78886
+ if (!Fp.isValid(CURVE[p]))
78887
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
78888
+ }
78889
+ CURVE = Object.freeze(Object.assign({}, CURVE));
78890
+ return { CURVE, Fp, Fn };
78891
+ }
78892
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n5) / den;
78893
+ function _splitEndoScalar(k, basis, n) {
78894
+ const [[a1, b1], [a2, b2]] = basis;
78895
+ const c1 = divNearest(b2 * k, n);
78896
+ const c2 = divNearest(-b1 * k, n);
78897
+ let k1 = k - c1 * a1 - c2 * a2;
78898
+ let k2 = -c1 * b1 - c2 * b2;
78899
+ const k1neg = k1 < _0n8;
78900
+ const k2neg = k2 < _0n8;
78901
+ if (k1neg)
78902
+ k1 = -k1;
78903
+ if (k2neg)
78904
+ k2 = -k2;
78905
+ const MAX_NUM = bitMask2(Math.ceil(bitLen2(n) / 2)) + _1n9;
78906
+ if (k1 < _0n8 || k1 >= MAX_NUM || k2 < _0n8 || k2 >= MAX_NUM) {
78907
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
78908
+ }
78909
+ return { k1neg, k1, k2neg, k2 };
78910
+ }
78911
+ function validateSigFormat(format) {
78912
+ if (!["compact", "recovered", "der"].includes(format))
78913
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
78914
+ return format;
78915
+ }
78916
+ function validateSigOpts(opts, def) {
78917
+ const optsn = {};
78918
+ for (let optName of Object.keys(def)) {
78919
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
78920
+ }
78921
+ _abool2(optsn.lowS, "lowS");
78922
+ _abool2(optsn.prehash, "prehash");
78923
+ if (optsn.format !== void 0)
78924
+ validateSigFormat(optsn.format);
78925
+ return optsn;
78926
+ }
78927
+ var DERErr = class extends Error {
78928
+ constructor(m = "") {
78929
+ super(m);
78930
+ }
78931
+ };
78932
+ var DER = {
78933
+ // asn.1 DER encoding utils
78934
+ Err: DERErr,
78935
+ // Basic building block is TLV (Tag-Length-Value)
78936
+ _tlv: {
78937
+ encode: (tag2, data) => {
78938
+ const { Err: E } = DER;
78939
+ if (tag2 < 0 || tag2 > 256)
78940
+ throw new E("tlv.encode: wrong tag");
78941
+ if (data.length & 1)
78942
+ throw new E("tlv.encode: unpadded data");
78943
+ const dataLen = data.length / 2;
78944
+ const len = numberToHexUnpadded(dataLen);
78945
+ if (len.length / 2 & 128)
78946
+ throw new E("tlv.encode: long form length too big");
78947
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
78948
+ const t = numberToHexUnpadded(tag2);
78949
+ return t + lenLen + len + data;
78950
+ },
78951
+ // v - value, l - left bytes (unparsed)
78952
+ decode(tag2, data) {
78953
+ const { Err: E } = DER;
78954
+ let pos = 0;
78955
+ if (tag2 < 0 || tag2 > 256)
78956
+ throw new E("tlv.encode: wrong tag");
78957
+ if (data.length < 2 || data[pos++] !== tag2)
78958
+ throw new E("tlv.decode: wrong tlv");
78959
+ const first = data[pos++];
78960
+ const isLong = !!(first & 128);
78961
+ let length = 0;
78962
+ if (!isLong)
78963
+ length = first;
78964
+ else {
78965
+ const lenLen = first & 127;
78966
+ if (!lenLen)
78967
+ throw new E("tlv.decode(long): indefinite length not supported");
78968
+ if (lenLen > 4)
78969
+ throw new E("tlv.decode(long): byte length is too big");
78970
+ const lengthBytes = data.subarray(pos, pos + lenLen);
78971
+ if (lengthBytes.length !== lenLen)
78972
+ throw new E("tlv.decode: length bytes not complete");
78973
+ if (lengthBytes[0] === 0)
78974
+ throw new E("tlv.decode(long): zero leftmost byte");
78975
+ for (const b of lengthBytes)
78976
+ length = length << 8 | b;
78977
+ pos += lenLen;
78978
+ if (length < 128)
78979
+ throw new E("tlv.decode(long): not minimal encoding");
78980
+ }
78981
+ const v = data.subarray(pos, pos + length);
78982
+ if (v.length !== length)
78983
+ throw new E("tlv.decode: wrong value length");
78984
+ return { v, l: data.subarray(pos + length) };
78985
+ }
78986
+ },
78987
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
78988
+ // since we always use positive integers here. It must always be empty:
78989
+ // - add zero byte if exists
78990
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
78991
+ _int: {
78992
+ encode(num) {
78993
+ const { Err: E } = DER;
78994
+ if (num < _0n8)
78995
+ throw new E("integer: negative integers are not allowed");
78996
+ let hex = numberToHexUnpadded(num);
78997
+ if (Number.parseInt(hex[0], 16) & 8)
78998
+ hex = "00" + hex;
78999
+ if (hex.length & 1)
79000
+ throw new E("unexpected DER parsing assertion: unpadded hex");
79001
+ return hex;
79002
+ },
79003
+ decode(data) {
79004
+ const { Err: E } = DER;
79005
+ if (data[0] & 128)
79006
+ throw new E("invalid signature integer: negative");
79007
+ if (data[0] === 0 && !(data[1] & 128))
79008
+ throw new E("invalid signature integer: unnecessary leading zero");
79009
+ return bytesToNumberBE2(data);
79010
+ }
79011
+ },
79012
+ toSig(hex) {
79013
+ const { Err: E, _int: int2, _tlv: tlv } = DER;
79014
+ const data = ensureBytes("signature", hex);
79015
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
79016
+ if (seqLeftBytes.length)
79017
+ throw new E("invalid signature: left bytes after parsing");
79018
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
79019
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
79020
+ if (sLeftBytes.length)
79021
+ throw new E("invalid signature: left bytes after parsing");
79022
+ return { r: int2.decode(rBytes), s: int2.decode(sBytes) };
79023
+ },
79024
+ hexFromSig(sig) {
79025
+ const { _tlv: tlv, _int: int2 } = DER;
79026
+ const rs = tlv.encode(2, int2.encode(sig.r));
79027
+ const ss = tlv.encode(2, int2.encode(sig.s));
79028
+ const seq = rs + ss;
79029
+ return tlv.encode(48, seq);
79030
+ }
79031
+ };
79032
+ var _0n8 = BigInt(0);
79033
+ var _1n9 = BigInt(1);
79034
+ var _2n5 = BigInt(2);
79035
+ var _3n3 = BigInt(3);
79036
+ var _4n3 = BigInt(4);
79037
+ function _normFnElement(Fn, key) {
79038
+ const { BYTES: expected } = Fn;
79039
+ let num;
79040
+ if (typeof key === "bigint") {
79041
+ num = key;
79042
+ } else {
79043
+ let bytes = ensureBytes("private key", key);
79044
+ try {
79045
+ num = Fn.fromBytes(bytes);
79046
+ } catch (error2) {
79047
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
79048
+ }
79049
+ }
79050
+ if (!Fn.isValidNot0(num))
79051
+ throw new Error("invalid private key: out of range [1..N-1]");
79052
+ return num;
79053
+ }
79054
+ function weierstrassN(params, extraOpts = {}) {
79055
+ const validated = _createCurveFields("weierstrass", params, extraOpts);
79056
+ const { Fp, Fn } = validated;
79057
+ let CURVE = validated.CURVE;
79058
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
79059
+ _validateObject(extraOpts, {}, {
79060
+ allowInfinityPoint: "boolean",
79061
+ clearCofactor: "function",
79062
+ isTorsionFree: "function",
79063
+ fromBytes: "function",
79064
+ toBytes: "function",
79065
+ endo: "object",
79066
+ wrapPrivateKey: "boolean"
79067
+ });
79068
+ const { endo } = extraOpts;
79069
+ if (endo) {
79070
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
79071
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
79072
+ }
79073
+ }
79074
+ const lengths = getWLengths(Fp, Fn);
79075
+ function assertCompressionIsSupported() {
79076
+ if (!Fp.isOdd)
79077
+ throw new Error("compression is not supported: Field does not have .isOdd()");
79078
+ }
79079
+ function pointToBytes(_c, point, isCompressed) {
79080
+ const { x, y: y2 } = point.toAffine();
79081
+ const bx = Fp.toBytes(x);
79082
+ _abool2(isCompressed, "isCompressed");
79083
+ if (isCompressed) {
79084
+ assertCompressionIsSupported();
79085
+ const hasEvenY = !Fp.isOdd(y2);
79086
+ return concatBytes3(pprefix(hasEvenY), bx);
79087
+ } else {
79088
+ return concatBytes3(Uint8Array.of(4), bx, Fp.toBytes(y2));
79089
+ }
79090
+ }
79091
+ function pointFromBytes(bytes) {
79092
+ _abytes2(bytes, void 0, "Point");
79093
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
79094
+ const length = bytes.length;
79095
+ const head = bytes[0];
79096
+ const tail = bytes.subarray(1);
79097
+ if (length === comp && (head === 2 || head === 3)) {
79098
+ const x = Fp.fromBytes(tail);
79099
+ if (!Fp.isValid(x))
79100
+ throw new Error("bad point: is not on curve, wrong x");
79101
+ const y2 = weierstrassEquation(x);
79102
+ let y3;
79103
+ try {
79104
+ y3 = Fp.sqrt(y2);
79105
+ } catch (sqrtError) {
79106
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
79107
+ throw new Error("bad point: is not on curve, sqrt error" + err);
79108
+ }
79109
+ assertCompressionIsSupported();
79110
+ const isYOdd = Fp.isOdd(y3);
79111
+ const isHeadOdd = (head & 1) === 1;
79112
+ if (isHeadOdd !== isYOdd)
79113
+ y3 = Fp.neg(y3);
79114
+ return { x, y: y3 };
79115
+ } else if (length === uncomp && head === 4) {
79116
+ const L = Fp.BYTES;
79117
+ const x = Fp.fromBytes(tail.subarray(0, L));
79118
+ const y2 = Fp.fromBytes(tail.subarray(L, L * 2));
79119
+ if (!isValidXY(x, y2))
79120
+ throw new Error("bad point: is not on curve");
79121
+ return { x, y: y2 };
79122
+ } else {
79123
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
79124
+ }
79125
+ }
79126
+ const encodePoint = extraOpts.toBytes || pointToBytes;
79127
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
79128
+ function weierstrassEquation(x) {
79129
+ const x2 = Fp.sqr(x);
79130
+ const x3 = Fp.mul(x2, x);
79131
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
79132
+ }
79133
+ function isValidXY(x, y2) {
79134
+ const left = Fp.sqr(y2);
79135
+ const right = weierstrassEquation(x);
79136
+ return Fp.eql(left, right);
79137
+ }
79138
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
79139
+ throw new Error("bad curve params: generator point");
79140
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n3), _4n3);
79141
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
79142
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
79143
+ throw new Error("bad curve params: a or b");
79144
+ function acoord(title, n, banZero = false) {
79145
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
79146
+ throw new Error(`bad point coordinate ${title}`);
79147
+ return n;
79148
+ }
79149
+ function aprjpoint(other) {
79150
+ if (!(other instanceof Point))
79151
+ throw new Error("ProjectivePoint expected");
79152
+ }
79153
+ function splitEndoScalarN(k) {
79154
+ if (!endo || !endo.basises)
79155
+ throw new Error("no endo");
79156
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
79157
+ }
79158
+ const toAffineMemo = memoized2((p, iz) => {
79159
+ const { X, Y, Z: Z2 } = p;
79160
+ if (Fp.eql(Z2, Fp.ONE))
79161
+ return { x: X, y: Y };
79162
+ const is0 = p.is0();
79163
+ if (iz == null)
79164
+ iz = is0 ? Fp.ONE : Fp.inv(Z2);
79165
+ const x = Fp.mul(X, iz);
79166
+ const y2 = Fp.mul(Y, iz);
79167
+ const zz = Fp.mul(Z2, iz);
79168
+ if (is0)
79169
+ return { x: Fp.ZERO, y: Fp.ZERO };
79170
+ if (!Fp.eql(zz, Fp.ONE))
79171
+ throw new Error("invZ was invalid");
79172
+ return { x, y: y2 };
79173
+ });
79174
+ const assertValidMemo = memoized2((p) => {
79175
+ if (p.is0()) {
79176
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
79177
+ return;
79178
+ throw new Error("bad point: ZERO");
79179
+ }
79180
+ const { x, y: y2 } = p.toAffine();
79181
+ if (!Fp.isValid(x) || !Fp.isValid(y2))
79182
+ throw new Error("bad point: x or y not field elements");
79183
+ if (!isValidXY(x, y2))
79184
+ throw new Error("bad point: equation left != right");
79185
+ if (!p.isTorsionFree())
79186
+ throw new Error("bad point: not in prime-order subgroup");
79187
+ return true;
79188
+ });
79189
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
79190
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
79191
+ k1p = negateCt2(k1neg, k1p);
79192
+ k2p = negateCt2(k2neg, k2p);
79193
+ return k1p.add(k2p);
79194
+ }
79195
+ class Point {
79196
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
79197
+ constructor(X, Y, Z2) {
79198
+ this.X = acoord("x", X);
79199
+ this.Y = acoord("y", Y, true);
79200
+ this.Z = acoord("z", Z2);
79201
+ Object.freeze(this);
79202
+ }
79203
+ static CURVE() {
79204
+ return CURVE;
79205
+ }
79206
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
79207
+ static fromAffine(p) {
79208
+ const { x, y: y2 } = p || {};
79209
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y2))
79210
+ throw new Error("invalid affine point");
79211
+ if (p instanceof Point)
79212
+ throw new Error("projective point not allowed");
79213
+ if (Fp.is0(x) && Fp.is0(y2))
79214
+ return Point.ZERO;
79215
+ return new Point(x, y2, Fp.ONE);
79216
+ }
79217
+ static fromBytes(bytes) {
79218
+ const P3 = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
79219
+ P3.assertValidity();
79220
+ return P3;
79221
+ }
79222
+ static fromHex(hex) {
79223
+ return Point.fromBytes(ensureBytes("pointHex", hex));
79224
+ }
79225
+ get x() {
79226
+ return this.toAffine().x;
79227
+ }
79228
+ get y() {
79229
+ return this.toAffine().y;
79230
+ }
79231
+ /**
79232
+ *
79233
+ * @param windowSize
79234
+ * @param isLazy true will defer table computation until the first multiplication
79235
+ * @returns
79236
+ */
79237
+ precompute(windowSize = 8, isLazy = true) {
79238
+ wnaf.createCache(this, windowSize);
79239
+ if (!isLazy)
79240
+ this.multiply(_3n3);
79241
+ return this;
79242
+ }
79243
+ // TODO: return `this`
79244
+ /** A point on curve is valid if it conforms to equation. */
79245
+ assertValidity() {
79246
+ assertValidMemo(this);
79247
+ }
79248
+ hasEvenY() {
79249
+ const { y: y2 } = this.toAffine();
79250
+ if (!Fp.isOdd)
79251
+ throw new Error("Field doesn't support isOdd");
79252
+ return !Fp.isOdd(y2);
79253
+ }
79254
+ /** Compare one point to another. */
79255
+ equals(other) {
79256
+ aprjpoint(other);
79257
+ const { X: X1, Y: Y1, Z: Z1 } = this;
79258
+ const { X: X2, Y: Y2, Z: Z2 } = other;
79259
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
79260
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
79261
+ return U1 && U2;
79262
+ }
79263
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
79264
+ negate() {
79265
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
79266
+ }
79267
+ // Renes-Costello-Batina exception-free doubling formula.
79268
+ // There is 30% faster Jacobian formula, but it is not complete.
79269
+ // https://eprint.iacr.org/2015/1060, algorithm 3
79270
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
79271
+ double() {
79272
+ const { a, b } = CURVE;
79273
+ const b3 = Fp.mul(b, _3n3);
79274
+ const { X: X1, Y: Y1, Z: Z1 } = this;
79275
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
79276
+ let t0 = Fp.mul(X1, X1);
79277
+ let t1 = Fp.mul(Y1, Y1);
79278
+ let t2 = Fp.mul(Z1, Z1);
79279
+ let t3 = Fp.mul(X1, Y1);
79280
+ t3 = Fp.add(t3, t3);
79281
+ Z3 = Fp.mul(X1, Z1);
79282
+ Z3 = Fp.add(Z3, Z3);
79283
+ X3 = Fp.mul(a, Z3);
79284
+ Y3 = Fp.mul(b3, t2);
79285
+ Y3 = Fp.add(X3, Y3);
79286
+ X3 = Fp.sub(t1, Y3);
79287
+ Y3 = Fp.add(t1, Y3);
79288
+ Y3 = Fp.mul(X3, Y3);
79289
+ X3 = Fp.mul(t3, X3);
79290
+ Z3 = Fp.mul(b3, Z3);
79291
+ t2 = Fp.mul(a, t2);
79292
+ t3 = Fp.sub(t0, t2);
79293
+ t3 = Fp.mul(a, t3);
79294
+ t3 = Fp.add(t3, Z3);
79295
+ Z3 = Fp.add(t0, t0);
79296
+ t0 = Fp.add(Z3, t0);
79297
+ t0 = Fp.add(t0, t2);
79298
+ t0 = Fp.mul(t0, t3);
79299
+ Y3 = Fp.add(Y3, t0);
79300
+ t2 = Fp.mul(Y1, Z1);
79301
+ t2 = Fp.add(t2, t2);
79302
+ t0 = Fp.mul(t2, t3);
79303
+ X3 = Fp.sub(X3, t0);
79304
+ Z3 = Fp.mul(t2, t1);
79305
+ Z3 = Fp.add(Z3, Z3);
79306
+ Z3 = Fp.add(Z3, Z3);
79307
+ return new Point(X3, Y3, Z3);
79308
+ }
79309
+ // Renes-Costello-Batina exception-free addition formula.
79310
+ // There is 30% faster Jacobian formula, but it is not complete.
79311
+ // https://eprint.iacr.org/2015/1060, algorithm 1
79312
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
79313
+ add(other) {
79314
+ aprjpoint(other);
79315
+ const { X: X1, Y: Y1, Z: Z1 } = this;
79316
+ const { X: X2, Y: Y2, Z: Z2 } = other;
79317
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
79318
+ const a = CURVE.a;
79319
+ const b3 = Fp.mul(CURVE.b, _3n3);
79320
+ let t0 = Fp.mul(X1, X2);
79321
+ let t1 = Fp.mul(Y1, Y2);
79322
+ let t2 = Fp.mul(Z1, Z2);
79323
+ let t3 = Fp.add(X1, Y1);
79324
+ let t4 = Fp.add(X2, Y2);
79325
+ t3 = Fp.mul(t3, t4);
79326
+ t4 = Fp.add(t0, t1);
79327
+ t3 = Fp.sub(t3, t4);
79328
+ t4 = Fp.add(X1, Z1);
79329
+ let t5 = Fp.add(X2, Z2);
79330
+ t4 = Fp.mul(t4, t5);
79331
+ t5 = Fp.add(t0, t2);
79332
+ t4 = Fp.sub(t4, t5);
79333
+ t5 = Fp.add(Y1, Z1);
79334
+ X3 = Fp.add(Y2, Z2);
79335
+ t5 = Fp.mul(t5, X3);
79336
+ X3 = Fp.add(t1, t2);
79337
+ t5 = Fp.sub(t5, X3);
79338
+ Z3 = Fp.mul(a, t4);
79339
+ X3 = Fp.mul(b3, t2);
79340
+ Z3 = Fp.add(X3, Z3);
79341
+ X3 = Fp.sub(t1, Z3);
79342
+ Z3 = Fp.add(t1, Z3);
79343
+ Y3 = Fp.mul(X3, Z3);
79344
+ t1 = Fp.add(t0, t0);
79345
+ t1 = Fp.add(t1, t0);
79346
+ t2 = Fp.mul(a, t2);
79347
+ t4 = Fp.mul(b3, t4);
79348
+ t1 = Fp.add(t1, t2);
79349
+ t2 = Fp.sub(t0, t2);
79350
+ t2 = Fp.mul(a, t2);
79351
+ t4 = Fp.add(t4, t2);
79352
+ t0 = Fp.mul(t1, t4);
79353
+ Y3 = Fp.add(Y3, t0);
79354
+ t0 = Fp.mul(t5, t4);
79355
+ X3 = Fp.mul(t3, X3);
79356
+ X3 = Fp.sub(X3, t0);
79357
+ t0 = Fp.mul(t3, t1);
79358
+ Z3 = Fp.mul(t5, Z3);
79359
+ Z3 = Fp.add(Z3, t0);
79360
+ return new Point(X3, Y3, Z3);
79361
+ }
79362
+ subtract(other) {
79363
+ return this.add(other.negate());
79364
+ }
79365
+ is0() {
79366
+ return this.equals(Point.ZERO);
79367
+ }
79368
+ /**
79369
+ * Constant time multiplication.
79370
+ * Uses wNAF method. Windowed method may be 10% faster,
79371
+ * but takes 2x longer to generate and consumes 2x memory.
79372
+ * Uses precomputes when available.
79373
+ * Uses endomorphism for Koblitz curves.
79374
+ * @param scalar by which the point would be multiplied
79375
+ * @returns New point
79376
+ */
79377
+ multiply(scalar) {
79378
+ const { endo: endo2 } = extraOpts;
79379
+ if (!Fn.isValidNot0(scalar))
79380
+ throw new Error("invalid scalar: out of range");
79381
+ let point, fake;
79382
+ const mul2 = (n) => wnaf.cached(this, n, (p) => normalizeZ2(Point, p));
79383
+ if (endo2) {
79384
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
79385
+ const { p: k1p, f: k1f } = mul2(k1);
79386
+ const { p: k2p, f: k2f } = mul2(k2);
79387
+ fake = k1f.add(k2f);
79388
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
79389
+ } else {
79390
+ const { p, f } = mul2(scalar);
79391
+ point = p;
79392
+ fake = f;
79393
+ }
79394
+ return normalizeZ2(Point, [point, fake])[0];
79395
+ }
79396
+ /**
79397
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
79398
+ * It's faster, but should only be used when you don't care about
79399
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
79400
+ */
79401
+ multiplyUnsafe(sc) {
79402
+ const { endo: endo2 } = extraOpts;
79403
+ const p = this;
79404
+ if (!Fn.isValid(sc))
79405
+ throw new Error("invalid scalar: out of range");
79406
+ if (sc === _0n8 || p.is0())
79407
+ return Point.ZERO;
79408
+ if (sc === _1n9)
79409
+ return p;
79410
+ if (wnaf.hasCache(this))
79411
+ return this.multiply(sc);
79412
+ if (endo2) {
79413
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
79414
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
79415
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
79416
+ } else {
79417
+ return wnaf.unsafe(p, sc);
79418
+ }
79419
+ }
79420
+ multiplyAndAddUnsafe(Q, a, b) {
79421
+ const sum2 = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
79422
+ return sum2.is0() ? void 0 : sum2;
79423
+ }
79424
+ /**
79425
+ * Converts Projective point to affine (x, y) coordinates.
79426
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
79427
+ */
79428
+ toAffine(invertedZ) {
79429
+ return toAffineMemo(this, invertedZ);
79430
+ }
79431
+ /**
79432
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
79433
+ * Always torsion-free for cofactor=1 curves.
79434
+ */
79435
+ isTorsionFree() {
79436
+ const { isTorsionFree } = extraOpts;
79437
+ if (cofactor === _1n9)
79438
+ return true;
79439
+ if (isTorsionFree)
79440
+ return isTorsionFree(Point, this);
79441
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
79442
+ }
79443
+ clearCofactor() {
79444
+ const { clearCofactor } = extraOpts;
79445
+ if (cofactor === _1n9)
79446
+ return this;
79447
+ if (clearCofactor)
79448
+ return clearCofactor(Point, this);
79449
+ return this.multiplyUnsafe(cofactor);
79450
+ }
79451
+ isSmallOrder() {
79452
+ return this.multiplyUnsafe(cofactor).is0();
79453
+ }
79454
+ toBytes(isCompressed = true) {
79455
+ _abool2(isCompressed, "isCompressed");
79456
+ this.assertValidity();
79457
+ return encodePoint(Point, this, isCompressed);
79458
+ }
79459
+ toHex(isCompressed = true) {
79460
+ return bytesToHex2(this.toBytes(isCompressed));
79461
+ }
79462
+ toString() {
79463
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
79464
+ }
79465
+ // TODO: remove
79466
+ get px() {
79467
+ return this.X;
79468
+ }
79469
+ get py() {
79470
+ return this.X;
79471
+ }
79472
+ get pz() {
79473
+ return this.Z;
79474
+ }
79475
+ toRawBytes(isCompressed = true) {
79476
+ return this.toBytes(isCompressed);
79477
+ }
79478
+ _setWindowSize(windowSize) {
79479
+ this.precompute(windowSize);
79480
+ }
79481
+ static normalizeZ(points) {
79482
+ return normalizeZ2(Point, points);
79483
+ }
79484
+ static msm(points, scalars) {
79485
+ return pippenger(Point, Fn, points, scalars);
79486
+ }
79487
+ static fromPrivateKey(privateKey) {
79488
+ return Point.BASE.multiply(_normFnElement(Fn, privateKey));
79489
+ }
79490
+ }
79491
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
79492
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
79493
+ Point.Fp = Fp;
79494
+ Point.Fn = Fn;
79495
+ const bits = Fn.BITS;
79496
+ const wnaf = new wNAF2(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
79497
+ Point.BASE.precompute(8);
79498
+ return Point;
79499
+ }
79500
+ function pprefix(hasEvenY) {
79501
+ return Uint8Array.of(hasEvenY ? 2 : 3);
79502
+ }
79503
+ function getWLengths(Fp, Fn) {
79504
+ return {
79505
+ secretKey: Fn.BYTES,
79506
+ publicKey: 1 + Fp.BYTES,
79507
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
79508
+ publicKeyHasPrefix: true,
79509
+ signature: 2 * Fn.BYTES
79510
+ };
79511
+ }
79512
+ function ecdh(Point, ecdhOpts = {}) {
79513
+ const { Fn } = Point;
79514
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
79515
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
79516
+ function isValidSecretKey(secretKey) {
79517
+ try {
79518
+ return !!_normFnElement(Fn, secretKey);
79519
+ } catch (error2) {
79520
+ return false;
79521
+ }
79522
+ }
79523
+ function isValidPublicKey(publicKey, isCompressed) {
79524
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
79525
+ try {
79526
+ const l2 = publicKey.length;
79527
+ if (isCompressed === true && l2 !== comp)
79528
+ return false;
79529
+ if (isCompressed === false && l2 !== publicKeyUncompressed)
79530
+ return false;
79531
+ return !!Point.fromBytes(publicKey);
79532
+ } catch (error2) {
79533
+ return false;
79534
+ }
79535
+ }
79536
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
79537
+ return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
79538
+ }
79539
+ function getPublicKey(secretKey, isCompressed = true) {
79540
+ return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
79541
+ }
79542
+ function keygen(seed) {
79543
+ const secretKey = randomSecretKey(seed);
79544
+ return { secretKey, publicKey: getPublicKey(secretKey) };
79545
+ }
79546
+ function isProbPub(item) {
79547
+ if (typeof item === "bigint")
79548
+ return false;
79549
+ if (item instanceof Point)
79550
+ return true;
79551
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
79552
+ if (Fn.allowedLengths || secretKey === publicKey)
79553
+ return void 0;
79554
+ const l2 = ensureBytes("key", item).length;
79555
+ return l2 === publicKey || l2 === publicKeyUncompressed;
79556
+ }
79557
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
79558
+ if (isProbPub(secretKeyA) === true)
79559
+ throw new Error("first arg must be private key");
79560
+ if (isProbPub(publicKeyB) === false)
79561
+ throw new Error("second arg must be public key");
79562
+ const s = _normFnElement(Fn, secretKeyA);
79563
+ const b = Point.fromHex(publicKeyB);
79564
+ return b.multiply(s).toBytes(isCompressed);
79565
+ }
79566
+ const utils = {
79567
+ isValidSecretKey,
79568
+ isValidPublicKey,
79569
+ randomSecretKey,
79570
+ // TODO: remove
79571
+ isValidPrivateKey: isValidSecretKey,
79572
+ randomPrivateKey: randomSecretKey,
79573
+ normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
79574
+ precompute(windowSize = 8, point = Point.BASE) {
79575
+ return point.precompute(windowSize, false);
79576
+ }
79577
+ };
79578
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
79579
+ }
79580
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
79581
+ ahash2(hash);
79582
+ _validateObject(ecdsaOpts, {}, {
79583
+ hmac: "function",
79584
+ lowS: "boolean",
79585
+ randomBytes: "function",
79586
+ bits2int: "function",
79587
+ bits2int_modN: "function"
79588
+ });
79589
+ const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
79590
+ const hmac3 = ecdsaOpts.hmac || ((key, ...msgs) => hmac2(hash, key, concatBytes3(...msgs)));
79591
+ const { Fp, Fn } = Point;
79592
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
79593
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
79594
+ const defaultSigOpts = {
79595
+ prehash: false,
79596
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
79597
+ format: void 0,
79598
+ //'compact' as ECDSASigFormat,
79599
+ extraEntropy: false
79600
+ };
79601
+ const defaultSigOpts_format = "compact";
79602
+ function isBiggerThanHalfOrder(number4) {
79603
+ const HALF = CURVE_ORDER >> _1n9;
79604
+ return number4 > HALF;
79605
+ }
79606
+ function validateRS(title, num) {
79607
+ if (!Fn.isValidNot0(num))
79608
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
79609
+ return num;
79610
+ }
79611
+ function validateSigLength(bytes, format) {
79612
+ validateSigFormat(format);
79613
+ const size = lengths.signature;
79614
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
79615
+ return _abytes2(bytes, sizer, `${format} signature`);
79616
+ }
79617
+ class Signature {
79618
+ constructor(r, s, recovery) {
79619
+ this.r = validateRS("r", r);
79620
+ this.s = validateRS("s", s);
79621
+ if (recovery != null)
79622
+ this.recovery = recovery;
79623
+ Object.freeze(this);
79624
+ }
79625
+ static fromBytes(bytes, format = defaultSigOpts_format) {
79626
+ validateSigLength(bytes, format);
79627
+ let recid;
79628
+ if (format === "der") {
79629
+ const { r: r2, s: s2 } = DER.toSig(_abytes2(bytes));
79630
+ return new Signature(r2, s2);
79631
+ }
79632
+ if (format === "recovered") {
79633
+ recid = bytes[0];
79634
+ format = "compact";
79635
+ bytes = bytes.subarray(1);
79636
+ }
79637
+ const L = Fn.BYTES;
79638
+ const r = bytes.subarray(0, L);
79639
+ const s = bytes.subarray(L, L * 2);
79640
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
79641
+ }
79642
+ static fromHex(hex, format) {
79643
+ return this.fromBytes(hexToBytes2(hex), format);
79644
+ }
79645
+ addRecoveryBit(recovery) {
79646
+ return new Signature(this.r, this.s, recovery);
79647
+ }
79648
+ recoverPublicKey(messageHash) {
79649
+ const FIELD_ORDER = Fp.ORDER;
79650
+ const { r, s, recovery: rec } = this;
79651
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
79652
+ throw new Error("recovery id invalid");
79653
+ const hasCofactor = CURVE_ORDER * _2n5 < FIELD_ORDER;
79654
+ if (hasCofactor && rec > 1)
79655
+ throw new Error("recovery id is ambiguous for h>1 curve");
79656
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
79657
+ if (!Fp.isValid(radj))
79658
+ throw new Error("recovery id 2 or 3 invalid");
79659
+ const x = Fp.toBytes(radj);
79660
+ const R2 = Point.fromBytes(concatBytes3(pprefix((rec & 1) === 0), x));
79661
+ const ir = Fn.inv(radj);
79662
+ const h = bits2int_modN(ensureBytes("msgHash", messageHash));
79663
+ const u1 = Fn.create(-h * ir);
79664
+ const u2 = Fn.create(s * ir);
79665
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R2.multiplyUnsafe(u2));
79666
+ if (Q.is0())
79667
+ throw new Error("point at infinify");
79668
+ Q.assertValidity();
79669
+ return Q;
79670
+ }
79671
+ // Signatures should be low-s, to prevent malleability.
79672
+ hasHighS() {
79673
+ return isBiggerThanHalfOrder(this.s);
79674
+ }
79675
+ toBytes(format = defaultSigOpts_format) {
79676
+ validateSigFormat(format);
79677
+ if (format === "der")
79678
+ return hexToBytes2(DER.hexFromSig(this));
79679
+ const r = Fn.toBytes(this.r);
79680
+ const s = Fn.toBytes(this.s);
79681
+ if (format === "recovered") {
79682
+ if (this.recovery == null)
79683
+ throw new Error("recovery bit must be present");
79684
+ return concatBytes3(Uint8Array.of(this.recovery), r, s);
79685
+ }
79686
+ return concatBytes3(r, s);
79687
+ }
79688
+ toHex(format) {
79689
+ return bytesToHex2(this.toBytes(format));
79690
+ }
79691
+ // TODO: remove
79692
+ assertValidity() {
79693
+ }
79694
+ static fromCompact(hex) {
79695
+ return Signature.fromBytes(ensureBytes("sig", hex), "compact");
79696
+ }
79697
+ static fromDER(hex) {
79698
+ return Signature.fromBytes(ensureBytes("sig", hex), "der");
79699
+ }
79700
+ normalizeS() {
79701
+ return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
79702
+ }
79703
+ toDERRawBytes() {
79704
+ return this.toBytes("der");
79705
+ }
79706
+ toDERHex() {
79707
+ return bytesToHex2(this.toBytes("der"));
79708
+ }
79709
+ toCompactRawBytes() {
79710
+ return this.toBytes("compact");
79711
+ }
79712
+ toCompactHex() {
79713
+ return bytesToHex2(this.toBytes("compact"));
79714
+ }
79715
+ }
79716
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
79717
+ if (bytes.length > 8192)
79718
+ throw new Error("input is too large");
79719
+ const num = bytesToNumberBE2(bytes);
79720
+ const delta = bytes.length * 8 - fnBits;
79721
+ return delta > 0 ? num >> BigInt(delta) : num;
79722
+ };
79723
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
79724
+ return Fn.create(bits2int(bytes));
79725
+ };
79726
+ const ORDER_MASK = bitMask2(fnBits);
79727
+ function int2octets(num) {
79728
+ aInRange2("num < 2^" + fnBits, num, _0n8, ORDER_MASK);
79729
+ return Fn.toBytes(num);
79730
+ }
79731
+ function validateMsgAndHash(message, prehash) {
79732
+ _abytes2(message, void 0, "message");
79733
+ return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
79734
+ }
79735
+ function prepSig(message, privateKey, opts) {
79736
+ if (["recovered", "canonical"].some((k) => k in opts))
79737
+ throw new Error("sign() legacy options not supported");
79738
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
79739
+ message = validateMsgAndHash(message, prehash);
79740
+ const h1int = bits2int_modN(message);
79741
+ const d = _normFnElement(Fn, privateKey);
79742
+ const seedArgs = [int2octets(d), int2octets(h1int)];
79743
+ if (extraEntropy != null && extraEntropy !== false) {
79744
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
79745
+ seedArgs.push(ensureBytes("extraEntropy", e));
79746
+ }
79747
+ const seed = concatBytes3(...seedArgs);
79748
+ const m = h1int;
79749
+ function k2sig(kBytes) {
79750
+ const k = bits2int(kBytes);
79751
+ if (!Fn.isValidNot0(k))
79752
+ return;
79753
+ const ik = Fn.inv(k);
79754
+ const q = Point.BASE.multiply(k).toAffine();
79755
+ const r = Fn.create(q.x);
79756
+ if (r === _0n8)
79757
+ return;
79758
+ const s = Fn.create(ik * Fn.create(m + r * d));
79759
+ if (s === _0n8)
79760
+ return;
79761
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n9);
79762
+ let normS = s;
79763
+ if (lowS && isBiggerThanHalfOrder(s)) {
79764
+ normS = Fn.neg(s);
79765
+ recovery ^= 1;
79766
+ }
79767
+ return new Signature(r, normS, recovery);
79768
+ }
79769
+ return { seed, k2sig };
79770
+ }
79771
+ function sign2(message, secretKey, opts = {}) {
79772
+ message = ensureBytes("message", message);
79773
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
79774
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac3);
79775
+ const sig = drbg(seed, k2sig);
79776
+ return sig;
79777
+ }
79778
+ function tryParsingSig(sg) {
79779
+ let sig = void 0;
79780
+ const isHex3 = typeof sg === "string" || isBytes3(sg);
79781
+ const isObj = !isHex3 && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
79782
+ if (!isHex3 && !isObj)
79783
+ throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
79784
+ if (isObj) {
79785
+ sig = new Signature(sg.r, sg.s);
79786
+ } else if (isHex3) {
79787
+ try {
79788
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
79789
+ } catch (derError) {
79790
+ if (!(derError instanceof DER.Err))
79791
+ throw derError;
79792
+ }
79793
+ if (!sig) {
79794
+ try {
79795
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
79796
+ } catch (error2) {
79797
+ return false;
79798
+ }
79799
+ }
79800
+ }
79801
+ if (!sig)
79802
+ return false;
79803
+ return sig;
79804
+ }
79805
+ function verify(signature, message, publicKey, opts = {}) {
79806
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
79807
+ publicKey = ensureBytes("publicKey", publicKey);
79808
+ message = validateMsgAndHash(ensureBytes("message", message), prehash);
79809
+ if ("strict" in opts)
79810
+ throw new Error("options.strict was renamed to lowS");
79811
+ const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
79812
+ if (sig === false)
79813
+ return false;
79814
+ try {
79815
+ const P3 = Point.fromBytes(publicKey);
79816
+ if (lowS && sig.hasHighS())
79817
+ return false;
79818
+ const { r, s } = sig;
79819
+ const h = bits2int_modN(message);
79820
+ const is2 = Fn.inv(s);
79821
+ const u1 = Fn.create(h * is2);
79822
+ const u2 = Fn.create(r * is2);
79823
+ const R2 = Point.BASE.multiplyUnsafe(u1).add(P3.multiplyUnsafe(u2));
79824
+ if (R2.is0())
79825
+ return false;
79826
+ const v = Fn.create(R2.x);
79827
+ return v === r;
79828
+ } catch (e) {
79829
+ return false;
79830
+ }
79831
+ }
79832
+ function recoverPublicKey(signature, message, opts = {}) {
79833
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
79834
+ message = validateMsgAndHash(message, prehash);
79835
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
79836
+ }
79837
+ return Object.freeze({
79838
+ keygen,
79839
+ getPublicKey,
79840
+ getSharedSecret,
79841
+ utils,
79842
+ lengths,
79843
+ Point,
79844
+ sign: sign2,
79845
+ verify,
79846
+ recoverPublicKey,
79847
+ Signature,
79848
+ hash
79849
+ });
79850
+ }
79851
+ function _weierstrass_legacy_opts_to_new(c) {
79852
+ const CURVE = {
79853
+ a: c.a,
79854
+ b: c.b,
79855
+ p: c.Fp.ORDER,
79856
+ n: c.n,
79857
+ h: c.h,
79858
+ Gx: c.Gx,
79859
+ Gy: c.Gy
79860
+ };
79861
+ const Fp = c.Fp;
79862
+ let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l2) => Math.ceil(l2 / 2)))) : void 0;
79863
+ const Fn = Field2(CURVE.n, {
79864
+ BITS: c.nBitLength,
79865
+ allowedLengths,
79866
+ modFromBytes: c.wrapPrivateKey
79867
+ });
79868
+ const curveOpts = {
79869
+ Fp,
79870
+ Fn,
79871
+ allowInfinityPoint: c.allowInfinityPoint,
79872
+ endo: c.endo,
79873
+ isTorsionFree: c.isTorsionFree,
79874
+ clearCofactor: c.clearCofactor,
79875
+ fromBytes: c.fromBytes,
79876
+ toBytes: c.toBytes
79877
+ };
79878
+ return { CURVE, curveOpts };
79879
+ }
79880
+ function _ecdsa_legacy_opts_to_new(c) {
79881
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
79882
+ const ecdsaOpts = {
79883
+ hmac: c.hmac,
79884
+ randomBytes: c.randomBytes,
79885
+ lowS: c.lowS,
79886
+ bits2int: c.bits2int,
79887
+ bits2int_modN: c.bits2int_modN
79888
+ };
79889
+ return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
79890
+ }
79891
+ function _ecdsa_new_output_to_legacy(c, _ecdsa) {
79892
+ const Point = _ecdsa.Point;
79893
+ return Object.assign({}, _ecdsa, {
79894
+ ProjectivePoint: Point,
79895
+ CURVE: Object.assign({}, c, nLength2(Point.Fn.ORDER, Point.Fn.BITS))
79896
+ });
79897
+ }
79898
+ function weierstrass(c) {
79899
+ const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
79900
+ const Point = weierstrassN(CURVE, curveOpts);
79901
+ const signs = ecdsa(Point, hash, ecdsaOpts);
79902
+ return _ecdsa_new_output_to_legacy(c, signs);
79903
+ }
79904
+ function createCurve(curveDef, defHash) {
79905
+ const create = (hash) => weierstrass({ ...curveDef, hash });
79906
+ return { ...create(defHash), create };
79907
+ }
79908
+ var secp256k1_CURVE = {
79909
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
79910
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
79911
+ h: BigInt(1),
79912
+ a: BigInt(0),
79913
+ b: BigInt(7),
79914
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
79915
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
79916
+ };
79917
+ var secp256k1_ENDO = {
79918
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
79919
+ basises: [
79920
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
79921
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
79922
+ ]
79923
+ };
79924
+ var _2n6 = /* @__PURE__ */ BigInt(2);
79925
+ function sqrtMod(y2) {
79926
+ const P3 = secp256k1_CURVE.p;
79927
+ const _3n4 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
79928
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
79929
+ const b2 = y2 * y2 * y2 % P3;
79930
+ const b3 = b2 * b2 * y2 % P3;
79931
+ const b6 = pow22(b3, _3n4, P3) * b3 % P3;
79932
+ const b9 = pow22(b6, _3n4, P3) * b3 % P3;
79933
+ const b11 = pow22(b9, _2n6, P3) * b2 % P3;
79934
+ const b22 = pow22(b11, _11n, P3) * b11 % P3;
79935
+ const b44 = pow22(b22, _22n, P3) * b22 % P3;
79936
+ const b88 = pow22(b44, _44n, P3) * b44 % P3;
79937
+ const b176 = pow22(b88, _88n, P3) * b88 % P3;
79938
+ const b220 = pow22(b176, _44n, P3) * b44 % P3;
79939
+ const b223 = pow22(b220, _3n4, P3) * b3 % P3;
79940
+ const t1 = pow22(b223, _23n, P3) * b22 % P3;
79941
+ const t2 = pow22(t1, _6n, P3) * b2 % P3;
79942
+ const root = pow22(t2, _2n6, P3);
79943
+ if (!Fpk1.eql(Fpk1.sqr(root), y2))
79944
+ throw new Error("Cannot find square root");
79945
+ return root;
79946
+ }
79947
+ var Fpk1 = Field2(secp256k1_CURVE.p, { sqrt: sqrtMod });
79948
+ var secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha2562);
79949
+ var sha2563 = sha2562;
77667
79950
  var __defProp4 = Object.defineProperty;
77668
79951
  var __getOwnPropNames3 = Object.getOwnPropertyNames;
77669
79952
  var __esm2 = (fn, res) => function __init() {
@@ -78831,10 +81114,10 @@ async function finalize(response, opts) {
78831
81114
  return { status: response.status, body: body2, paid: opts.paid };
78832
81115
  }
78833
81116
  async function makeGrpcBuildClient(client) {
78834
- const { SuiGrpcClient: SuiGrpcClient2 } = await Promise.resolve().then(() => (init_grpc(), grpc_exports));
81117
+ const { SuiGrpcClient: SuiGrpcClient3 } = await Promise.resolve().then(() => (init_grpc(), grpc_exports));
78835
81118
  const network = client.network === "testnet" ? "testnet" : "mainnet";
78836
81119
  const baseUrl = network === "testnet" ? "https://fullnode.testnet.sui.io" : "https://fullnode.mainnet.sui.io";
78837
- return new SuiGrpcClient2({ baseUrl, network });
81120
+ return new SuiGrpcClient3({ baseUrl, network });
78838
81121
  }
78839
81122
  function atomicToHuman(raw, decimals) {
78840
81123
  return Number(raw) / 10 ** decimals;
@@ -79254,10 +81537,10 @@ function recordFromGqlNode(node, address) {
79254
81537
  commandTypes.push("MoveCall");
79255
81538
  const fn = cmd.function;
79256
81539
  const pkg = fn?.module?.package?.address;
79257
- const mod3 = fn?.module?.name;
81540
+ const mod4 = fn?.module?.name;
79258
81541
  const name = fn?.name;
79259
- if (pkg && mod3 && name) {
79260
- moveCallTargets.push(`${pkg}::${mod3}::${name}`);
81542
+ if (pkg && mod4 && name) {
81543
+ moveCallTargets.push(`${pkg}::${mod4}::${name}`);
79261
81544
  }
79262
81545
  } else if (cmd.__typename === "TransferObjectsCommand") {
79263
81546
  commandTypes.push("TransferObjects");
@@ -79481,6 +81764,207 @@ async function listModels(opts) {
79481
81764
  privacy: m.privacy ?? m.privacy_tier
79482
81765
  }));
79483
81766
  }
81767
+ var RECEIPT_ANCHORED_SUFFIX = "::anchor::ReceiptAnchored";
81768
+ function fullnodeUrl(network) {
81769
+ return network === "testnet" ? "https://fullnode.testnet.sui.io" : "https://fullnode.mainnet.sui.io";
81770
+ }
81771
+ function jcs(value) {
81772
+ if (value === null) {
81773
+ return "null";
81774
+ }
81775
+ if (typeof value === "boolean") {
81776
+ return value ? "true" : "false";
81777
+ }
81778
+ if (typeof value === "number") {
81779
+ if (!Number.isInteger(value)) {
81780
+ throw new Error("JCS: non-integer number");
81781
+ }
81782
+ return String(value);
81783
+ }
81784
+ if (typeof value === "string") {
81785
+ return JSON.stringify(value);
81786
+ }
81787
+ if (Array.isArray(value)) {
81788
+ return `[${value.map(jcs).join(",")}]`;
81789
+ }
81790
+ const keys = Object.keys(value).sort();
81791
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${jcs(value[k])}`).join(",")}}`;
81792
+ }
81793
+ function verifyReceiptSignature(receipt, signingKeyHex) {
81794
+ try {
81795
+ const sig = receipt.signature;
81796
+ if (sig?.algo !== "ecdsa-secp256k1" || !sig.value) {
81797
+ return false;
81798
+ }
81799
+ const canonical = {
81800
+ api_version: receipt.api_version ?? "",
81801
+ receipt_id: receipt.receipt_id ?? "",
81802
+ chat_id: receipt.chat_id ?? null,
81803
+ workload_id: receipt.workload_id ?? "",
81804
+ workload_keyset_digest: receipt.workload_keyset_digest ?? "",
81805
+ endpoint: receipt.endpoint ?? "",
81806
+ method: receipt.method ?? "",
81807
+ served_at: receipt.served_at ?? 0,
81808
+ event_log: receipt.event_log ?? [],
81809
+ signature: { algo: sig.algo, key_id: sig.key_id ?? "" }
81810
+ };
81811
+ const prehash = sha2563(new TextEncoder().encode(jcs(canonical)));
81812
+ const sigBytes = hexToBytes2(sig.value);
81813
+ if (sigBytes.length !== 65) {
81814
+ return false;
81815
+ }
81816
+ let v = sigBytes[64];
81817
+ if (v >= 27 && v <= 30) {
81818
+ v -= 27;
81819
+ }
81820
+ if (v > 3) {
81821
+ return false;
81822
+ }
81823
+ const recovered = secp256k1.Signature.fromCompact(sigBytes.slice(0, 64)).addRecoveryBit(v).recoverPublicKey(prehash).toHex(false);
81824
+ const endorsed = bytesToHex2(hexToBytes2(signingKeyHex.replace(/^0x/, "")));
81825
+ return recovered.toLowerCase() === endorsed.toLowerCase();
81826
+ } catch {
81827
+ return false;
81828
+ }
81829
+ }
81830
+ async function verifyReceipt(receiptId, opts = {}) {
81831
+ const base = opts.apiBase ?? DEFAULT_API_BASE;
81832
+ const network = opts.network ?? "mainnet";
81833
+ const checks = [];
81834
+ let receipt = null;
81835
+ try {
81836
+ const res = await fetch(`${base}/aci/receipts/${encodeURIComponent(receiptId)}`);
81837
+ if (res.ok) {
81838
+ receipt = await res.json();
81839
+ }
81840
+ } catch {
81841
+ }
81842
+ if (!receipt?.event_log) {
81843
+ checks.push({
81844
+ name: "Receipt",
81845
+ status: "fail",
81846
+ detail: "receipt not found or malformed",
81847
+ trust: "receipt-asserted"
81848
+ });
81849
+ return { receiptId, verified: false, anchorVerified: false, checks };
81850
+ }
81851
+ const wireHash = receipt.event_log.find((e) => e.type === "response.returned")?.wire_hash;
81852
+ const workloadId = receipt.workload_id;
81853
+ checks.push({
81854
+ name: "Receipt",
81855
+ status: wireHash && workloadId ? "pass" : "fail",
81856
+ detail: wireHash ? `well-formed (${receipt.event_log.length} log entries, workload ${workloadId})` : "missing response wire_hash / workload_id",
81857
+ trust: "receipt-asserted"
81858
+ });
81859
+ const upstreamEv = receipt.event_log.find((e) => e.type === "upstream.verified");
81860
+ const upstreamOk = upstreamEv?.result === "verified";
81861
+ checks.push({
81862
+ name: "Confidential upstream",
81863
+ status: upstreamEv ? upstreamOk ? "pass" : "fail" : "skip",
81864
+ detail: upstreamEv ? `${upstreamEv.provider ?? upstreamEv.upstream_name ?? "upstream"}: ${upstreamEv.result ?? "unknown"}${upstreamEv.tcb_status ? ` (TCB ${upstreamEv.tcb_status})` : ""}` : "no upstream.verified event (routed/non-confidential?)",
81865
+ trust: "receipt-asserted"
81866
+ });
81867
+ let anchorVerified = false;
81868
+ let anchor;
81869
+ let digest;
81870
+ try {
81871
+ const res = await fetch(`${base}/aci/anchor/${encodeURIComponent(receiptId)}`);
81872
+ if (res.ok) {
81873
+ const j = await res.json();
81874
+ digest = j.txDigest;
81875
+ }
81876
+ } catch {
81877
+ }
81878
+ if (!digest) {
81879
+ checks.push({
81880
+ name: "Sui anchor",
81881
+ status: "fail",
81882
+ detail: `no anchor on record \u2014 POST ${base}/aci/anchor/${receiptId} to create one`,
81883
+ trust: "trustless"
81884
+ });
81885
+ } else {
81886
+ try {
81887
+ const client = new SuiGrpcClient({ baseUrl: fullnodeUrl(network), network });
81888
+ const tx = await client.core.getTransaction({
81889
+ digest,
81890
+ include: { events: true }
81891
+ });
81892
+ const txn = tx.$kind === "Transaction" ? tx.Transaction : tx.FailedTransaction;
81893
+ const ev = (txn.events ?? []).find(
81894
+ (e) => e.eventType.endsWith(RECEIPT_ANCHORED_SUFFIX)
81895
+ );
81896
+ const data = ev?.json ?? {};
81897
+ const onChainReceipt = String(data.receipt_id ?? "");
81898
+ const onChainWire = String(data.wire_hash ?? "");
81899
+ const onChainWorkload = String(data.workload_id ?? "");
81900
+ const matches = onChainReceipt === receiptId && onChainWire === wireHash && onChainWorkload === workloadId;
81901
+ anchorVerified = matches;
81902
+ anchor = {
81903
+ txDigest: digest,
81904
+ anchoredAtMs: data.anchored_at_ms ? String(data.anchored_at_ms) : void 0,
81905
+ anchoredBy: data.anchored_by ? String(data.anchored_by) : void 0,
81906
+ explorer: `https://suiscan.xyz/${network}/tx/${digest}`
81907
+ };
81908
+ checks.push({
81909
+ name: "Sui anchor",
81910
+ status: matches ? "pass" : "fail",
81911
+ detail: matches ? `on-chain ReceiptAnchored matches (wire_hash + workload_id), tx ${digest}` : `on-chain event does NOT match the receipt (wire ${onChainWire || "absent"})`,
81912
+ trust: "trustless"
81913
+ });
81914
+ } catch (e) {
81915
+ checks.push({
81916
+ name: "Sui anchor",
81917
+ status: "fail",
81918
+ detail: `could not read anchor tx ${digest}: ${e instanceof Error ? e.message : "error"}`,
81919
+ trust: "trustless"
81920
+ });
81921
+ }
81922
+ }
81923
+ let signatureForged = false;
81924
+ let sigStatus = "skip";
81925
+ let sigDetail = "no signature on receipt";
81926
+ if (receipt.signature?.value) {
81927
+ try {
81928
+ const model = opts.model ?? "phala/glm-5.2";
81929
+ const res = await fetch(
81930
+ `${base}/aci/attestation?model=${encodeURIComponent(model)}`
81931
+ );
81932
+ const att = res.ok ? await res.json() : null;
81933
+ if (!att?.signingKey) {
81934
+ sigDetail = "could not fetch the attested keyset to check the signature";
81935
+ } else if (att.workloadId && att.workloadId !== workloadId) {
81936
+ sigDetail = `attested keyset is for a different workload \u2014 pass --model for ${workloadId}`;
81937
+ } else {
81938
+ const ok = verifyReceiptSignature(receipt, att.signingKey);
81939
+ sigStatus = ok ? "pass" : "fail";
81940
+ signatureForged = !ok;
81941
+ sigDetail = ok ? `signed by the attested receipt key (${receipt.signature.key_id ?? "key"})` : "signature does NOT recover the attested receipt key \u2014 forged/altered";
81942
+ }
81943
+ } catch {
81944
+ sigDetail = "signature check errored";
81945
+ }
81946
+ }
81947
+ checks.push({
81948
+ name: "Receipt signature",
81949
+ status: sigStatus,
81950
+ detail: sigDetail,
81951
+ trust: sigStatus === "skip" ? "roadmap" : "trustless"
81952
+ });
81953
+ return {
81954
+ receiptId,
81955
+ verified: Boolean(wireHash && workloadId) && anchorVerified && !signatureForged,
81956
+ anchorVerified,
81957
+ checks,
81958
+ wireHash,
81959
+ workloadId,
81960
+ upstream: upstreamEv ? {
81961
+ provider: upstreamEv.provider ?? upstreamEv.upstream_name,
81962
+ result: upstreamEv.result,
81963
+ tcbStatus: upstreamEv.tcb_status
81964
+ } : void 0,
81965
+ anchor
81966
+ };
81967
+ }
79484
81968
  var DEFAULT_CONFIG_DIR = join$1(homedir(), ".t2000");
79485
81969
  function resolveConfigPath(configDir) {
79486
81970
  return join$1(configDir ?? DEFAULT_CONFIG_DIR, "config.json");
@@ -79762,6 +82246,11 @@ var T2000 = class _T2000 extends import_index2.default {
79762
82246
  async models(opts) {
79763
82247
  return listModels(opts);
79764
82248
  }
82249
+ /** Verify a confidential response by receipt id — checks the signed receipt
82250
+ * + its trustless on-chain Sui anchor. Fails closed on any mismatch. */
82251
+ async verify(receiptId, opts) {
82252
+ return verifyReceipt(receiptId, opts);
82253
+ }
79765
82254
  // -- Swap --
79766
82255
  async swap(params) {
79767
82256
  this.limits.assert({
@@ -80489,6 +82978,23 @@ function registerChatTools(server) {
80489
82978
  }
80490
82979
  }
80491
82980
  );
82981
+ server.tool(
82982
+ "t2000_verify",
82983
+ "Verify a confidential response by its receipt id (the `receiptId` from a confidential t2000_chat). Checks the signed receipt + its trustless on-chain Sui anchor (reads the ReceiptAnchored event straight from a fullnode) and returns a per-check result that's `verified:false` on any forgery/mismatch. No key required.",
82984
+ {
82985
+ receiptId: external_exports.string().describe("A confidential receipt id (rcpt-\u2026)")
82986
+ },
82987
+ async ({ receiptId }) => {
82988
+ try {
82989
+ const result = await verifyReceipt(receiptId);
82990
+ return {
82991
+ content: [{ type: "text", text: JSON.stringify(result) }]
82992
+ };
82993
+ } catch (err) {
82994
+ return errorResult(err);
82995
+ }
82996
+ }
82997
+ );
80492
82998
  }
80493
82999
  var cachedSkills = null;
80494
83000
  function getBakedSkills() {
@@ -80556,7 +83062,7 @@ Through this wallet you can reach essentially any major external API, billed to
80556
83062
  CRITICAL: When the user asks to use any external or paid API, names a provider (e.g. "via fal.ai", "with ElevenLabs"), or requests a capability one of the services above provides, DO NOT say you cannot reach that service, that it isn't on an allowlist, or that there's no connector \u2014 and do NOT fall back to writing a script for the user to run. You CAN do it directly through this wallet. Use t2000_services to discover the endpoint and request shape, then t2000_pay to execute, then show the user the result (display image/audio URLs returned in the response).
80557
83063
 
80558
83064
  Spending is the user's own USDC and every t2000_pay call is bounded by maxPrice. For larger or multi-step spends, state the estimated cost first and proceed once the user is happy. Use t2000_balance to check funds. The v4 wallet is payments-only; savings / lending live on audric.ai.`;
80559
- var PKG_VERSION = "5.16.0";
83065
+ var PKG_VERSION = "5.18.0";
80560
83066
  console.log = (...args) => console.error("[log]", ...args);
80561
83067
  console.warn = (...args) => console.error("[warn]", ...args);
80562
83068
  async function startMcpServer(opts) {
@@ -80582,6 +83088,7 @@ export {
80582
83088
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
80583
83089
 
80584
83090
  @noble/hashes/utils.js:
83091
+ @noble/hashes/esm/utils.js:
80585
83092
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
80586
83093
 
80587
83094
  mime-db/index.js:
@@ -80618,9 +83125,15 @@ mime-types/index.js:
80618
83125
  @noble/curves/abstract/curve.js:
80619
83126
  @noble/curves/abstract/edwards.js:
80620
83127
  @noble/curves/ed25519.js:
83128
+ @noble/curves/esm/utils.js:
83129
+ @noble/curves/esm/abstract/modular.js:
83130
+ @noble/curves/esm/abstract/curve.js:
83131
+ @noble/curves/esm/abstract/weierstrass.js:
83132
+ @noble/curves/esm/_shortw_utils.js:
83133
+ @noble/curves/esm/secp256k1.js:
80621
83134
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
80622
83135
 
80623
83136
  @scure/bip39/index.js:
80624
83137
  (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)
80625
83138
  */
80626
- //# sourceMappingURL=dist-UPUBYGXT.js.map
83139
+ //# sourceMappingURL=dist-QHCQQBPF.js.map