starknet 5.0.2 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -546,11 +546,11 @@ var starknet = (() => {
546
546
  "use strict";
547
547
  Object.defineProperty(exports, "__esModule", { value: true });
548
548
  exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0;
549
- function number2(n) {
549
+ function number3(n) {
550
550
  if (!Number.isSafeInteger(n) || n < 0)
551
551
  throw new Error(`Wrong positive integer: ${n}`);
552
552
  }
553
- exports.number = number2;
553
+ exports.number = number3;
554
554
  function bool2(b) {
555
555
  if (typeof b !== "boolean")
556
556
  throw new Error(`Expected boolean, not ${b}`);
@@ -566,8 +566,8 @@ var starknet = (() => {
566
566
  function hash2(hash3) {
567
567
  if (typeof hash3 !== "function" || typeof hash3.create !== "function")
568
568
  throw new Error("Hash should be wrapped by utils.wrapConstructor");
569
- number2(hash3.outputLen);
570
- number2(hash3.blockLen);
569
+ number3(hash3.outputLen);
570
+ number3(hash3.blockLen);
571
571
  }
572
572
  exports.hash = hash2;
573
573
  function exists2(instance, checkFinished = true) {
@@ -586,7 +586,7 @@ var starknet = (() => {
586
586
  }
587
587
  exports.output = output2;
588
588
  var assert3 = {
589
- number: number2,
589
+ number: number3,
590
590
  bool: bool2,
591
591
  bytes: bytes2,
592
592
  hash: hash2,
@@ -749,16 +749,16 @@ var starknet = (() => {
749
749
  }
750
750
  }
751
751
  exports.asyncLoop = asyncLoop;
752
- function utf8ToBytes2(str) {
752
+ function utf8ToBytes3(str) {
753
753
  if (typeof str !== "string") {
754
754
  throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`);
755
755
  }
756
756
  return new TextEncoder().encode(str);
757
757
  }
758
- exports.utf8ToBytes = utf8ToBytes2;
758
+ exports.utf8ToBytes = utf8ToBytes3;
759
759
  function toBytes2(data) {
760
760
  if (typeof data === "string")
761
- data = utf8ToBytes2(data);
761
+ data = utf8ToBytes3(data);
762
762
  if (!(data instanceof Uint8Array))
763
763
  throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);
764
764
  return data;
@@ -1502,7 +1502,7 @@ var starknet = (() => {
1502
1502
  }
1503
1503
  return arr.reverse();
1504
1504
  }
1505
- return function(str, baseIn, baseOut, sign, callerIsToString) {
1505
+ return function(str, baseIn, baseOut, sign2, callerIsToString) {
1506
1506
  var alphabet, d, e, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE;
1507
1507
  if (i >= 0) {
1508
1508
  k = POW_PRECISION;
@@ -1530,7 +1530,7 @@ var starknet = (() => {
1530
1530
  } else {
1531
1531
  x.c = xc;
1532
1532
  x.e = e;
1533
- x.s = sign;
1533
+ x.s = sign2;
1534
1534
  x = div(x, y, dp, rm, baseOut);
1535
1535
  xc = x.c;
1536
1536
  r = x.r;
@@ -2755,8 +2755,8 @@ var starknet = (() => {
2755
2755
  ch = text.charAt(at);
2756
2756
  at += 1;
2757
2757
  return ch;
2758
- }, number2 = function() {
2759
- var number3, string2 = "";
2758
+ }, number3 = function() {
2759
+ var number4, string2 = "";
2760
2760
  if (ch === "-") {
2761
2761
  string2 = "-";
2762
2762
  next("-");
@@ -2783,8 +2783,8 @@ var starknet = (() => {
2783
2783
  next();
2784
2784
  }
2785
2785
  }
2786
- number3 = +string2;
2787
- if (!isFinite(number3)) {
2786
+ number4 = +string2;
2787
+ if (!isFinite(number4)) {
2788
2788
  error("Bad number");
2789
2789
  } else {
2790
2790
  if (BigNumber == null)
@@ -2792,7 +2792,7 @@ var starknet = (() => {
2792
2792
  if (string2.length > 15)
2793
2793
  return _options.storeAsString ? string2 : _options.useNativeBigInt ? BigInt(string2) : new BigNumber(string2);
2794
2794
  else
2795
- return !_options.alwaysParseAsBig ? number3 : _options.useNativeBigInt ? BigInt(number3) : new BigNumber(number3);
2795
+ return !_options.alwaysParseAsBig ? number4 : _options.useNativeBigInt ? BigInt(number4) : new BigNumber(number4);
2796
2796
  }
2797
2797
  }, string = function() {
2798
2798
  var hex, i, string2 = "", uffff;
@@ -2933,9 +2933,9 @@ var starknet = (() => {
2933
2933
  case '"':
2934
2934
  return string();
2935
2935
  case "-":
2936
- return number2();
2936
+ return number3();
2937
2937
  default:
2938
- return ch >= "0" && ch <= "9" ? number2() : word();
2938
+ return ch >= "0" && ch <= "9" ? number3() : word();
2939
2939
  }
2940
2940
  };
2941
2941
  return function(source, reviver) {
@@ -3080,7 +3080,8 @@ var starknet = (() => {
3080
3080
  isUrl: () => isUrl,
3081
3081
  json: () => json_exports,
3082
3082
  merkle: () => merkle_exports,
3083
- number: () => number_exports,
3083
+ num: () => num_exports,
3084
+ number: () => number2,
3084
3085
  shortString: () => shortString_exports,
3085
3086
  stark: () => stark_exports2,
3086
3087
  transaction: () => transaction_exports,
@@ -3141,11 +3142,12 @@ var starknet = (() => {
3141
3142
  getSelector: () => getSelector,
3142
3143
  getSelectorFromName: () => getSelectorFromName,
3143
3144
  keccakBn: () => keccakBn,
3145
+ poseidon: () => poseidon_exports,
3144
3146
  starknetKeccak: () => starknetKeccak,
3145
3147
  transactionVersion: () => transactionVersion
3146
3148
  });
3147
3149
  var import_keccak = __toESM(require_keccak());
3148
- var import_utils8 = __toESM(require_utils2());
3150
+ var import_utils11 = __toESM(require_utils2());
3149
3151
 
3150
3152
  // src/constants.ts
3151
3153
  var constants_exports = {};
@@ -5302,9 +5304,9 @@ var starknet = (() => {
5302
5304
  ]
5303
5305
  ];
5304
5306
 
5305
- // src/utils/number.ts
5306
- var number_exports = {};
5307
- __export(number_exports, {
5307
+ // src/utils/num.ts
5308
+ var num_exports = {};
5309
+ __export(num_exports, {
5308
5310
  assertInRange: () => assertInRange,
5309
5311
  bigNumberishArrayToDecimalStringArray: () => bigNumberishArrayToDecimalStringArray,
5310
5312
  bigNumberishArrayToHexadecimalStringArray: () => bigNumberishArrayToHexadecimalStringArray,
@@ -5329,7 +5331,7 @@ var starknet = (() => {
5329
5331
  }
5330
5332
  }
5331
5333
 
5332
- // src/utils/number.ts
5334
+ // src/utils/num.ts
5333
5335
  function isHex(hex) {
5334
5336
  return /^0x[0-9a-f]*$/i.test(hex);
5335
5337
  }
@@ -5339,8 +5341,8 @@ var starknet = (() => {
5339
5341
  function isBigInt(value) {
5340
5342
  return typeof value === "bigint";
5341
5343
  }
5342
- function toHex(number2) {
5343
- return addHexPrefix(toBigInt(number2).toString(16));
5344
+ function toHex(number3) {
5345
+ return addHexPrefix(toBigInt(number3).toString(16));
5344
5346
  }
5345
5347
  function hexToDecimalString(hex) {
5346
5348
  return BigInt(addHexPrefix(hex)).toString(10);
@@ -5501,30 +5503,33 @@ var starknet = (() => {
5501
5503
  weierstrass: () => weierstrass_exports
5502
5504
  });
5503
5505
 
5504
- // node_modules/@noble/curves/lib/esm/stark.js
5506
+ // node_modules/@noble/curves/esm/stark.js
5505
5507
  var stark_exports = {};
5506
5508
  __export(stark_exports, {
5507
5509
  CURVE: () => CURVE,
5508
- Point: () => Point,
5510
+ Fp251: () => Fp251,
5511
+ Fp253: () => Fp253,
5509
5512
  ProjectivePoint: () => ProjectivePoint,
5510
5513
  Signature: () => Signature,
5511
- bytesToHexEth: () => bytesToHexEth,
5514
+ _poseidonMDS: () => _poseidonMDS,
5515
+ _starkCurve: () => _starkCurve,
5512
5516
  computeHashOnElements: () => computeHashOnElements,
5513
5517
  ethSigToPrivate: () => ethSigToPrivate,
5514
5518
  getAccountPath: () => getAccountPath,
5515
- getPublicKey: () => getPublicKey0x,
5516
- getSharedSecret: () => getSharedSecret0x,
5519
+ getPublicKey: () => getPublicKey,
5520
+ getSharedSecret: () => getSharedSecret,
5517
5521
  getStarkKey: () => getStarkKey,
5518
5522
  grindKey: () => grindKey,
5519
5523
  hashChain: () => hashChain,
5520
5524
  keccak: () => keccak,
5521
- numberToHexEth: () => numberToHexEth,
5522
5525
  pedersen: () => pedersen,
5523
- sign: () => sign0x,
5524
- starkCurve: () => starkCurve,
5525
- strip0x: () => strip0x,
5526
+ poseidonBasic: () => poseidonBasic,
5527
+ poseidonCreate: () => poseidonCreate,
5528
+ poseidonHash: () => poseidonHash,
5529
+ poseidonSmall: () => poseidonSmall,
5530
+ sign: () => sign,
5526
5531
  utils: () => utils,
5527
- verify: () => verify0x
5532
+ verify: () => verify
5528
5533
  });
5529
5534
 
5530
5535
  // node_modules/@noble/hashes/esm/_assert.js
@@ -6154,16 +6159,7 @@ var starknet = (() => {
6154
6159
  var sha256 = wrapConstructor(() => new SHA256());
6155
6160
  var sha224 = wrapConstructor(() => new SHA224());
6156
6161
 
6157
- // node_modules/@noble/curves/lib/esm/abstract/weierstrass.js
6158
- var weierstrass_exports = {};
6159
- __export(weierstrass_exports, {
6160
- SWUFpSqrtRatio: () => SWUFpSqrtRatio,
6161
- mapToCurveSimpleSWU: () => mapToCurveSimpleSWU,
6162
- weierstrass: () => weierstrass,
6163
- weierstrassPoints: () => weierstrassPoints
6164
- });
6165
-
6166
- // node_modules/@noble/curves/lib/esm/abstract/utils.js
6162
+ // node_modules/@noble/curves/esm/abstract/utils.js
6167
6163
  var utils_exports = {};
6168
6164
  __export(utils_exports, {
6169
6165
  bitGet: () => bitGet,
@@ -6174,51 +6170,29 @@ var starknet = (() => {
6174
6170
  bytesToNumberBE: () => bytesToNumberBE,
6175
6171
  bytesToNumberLE: () => bytesToNumberLE,
6176
6172
  concatBytes: () => concatBytes2,
6173
+ createHmacDrbg: () => createHmacDrbg,
6177
6174
  ensureBytes: () => ensureBytes,
6178
6175
  equalBytes: () => equalBytes,
6179
- hashToPrivateScalar: () => hashToPrivateScalar,
6180
6176
  hexToBytes: () => hexToBytes,
6181
6177
  hexToNumber: () => hexToNumber,
6182
- isPositiveInt: () => isPositiveInt,
6183
- nLength: () => nLength,
6184
6178
  numberToBytesBE: () => numberToBytesBE,
6185
6179
  numberToBytesLE: () => numberToBytesLE,
6186
6180
  numberToHexUnpadded: () => numberToHexUnpadded,
6187
- validateOpts: () => validateOpts
6181
+ numberToVarBytesBE: () => numberToVarBytesBE,
6182
+ utf8ToBytes: () => utf8ToBytes2,
6183
+ validateObject: () => validateObject
6188
6184
  });
6189
6185
  var _0n2 = BigInt(0);
6190
6186
  var _1n2 = BigInt(1);
6191
6187
  var _2n2 = BigInt(2);
6192
- function isPositiveInt(num) {
6193
- return typeof num === "number" && Number.isSafeInteger(num) && num > 0;
6194
- }
6195
- function validateOpts(curve) {
6196
- validateField(curve.Fp);
6197
- for (const i of ["n", "h"]) {
6198
- const val = curve[i];
6199
- if (typeof val !== "bigint")
6200
- throw new Error(`Invalid curve param ${i}=${val} (${typeof val})`);
6201
- }
6202
- if (!curve.Fp.isValid(curve.Gx))
6203
- throw new Error("Invalid generator X coordinate Fp element");
6204
- if (!curve.Fp.isValid(curve.Gy))
6205
- throw new Error("Invalid generator Y coordinate Fp element");
6206
- for (const i of ["nBitLength", "nByteLength"]) {
6207
- const val = curve[i];
6208
- if (val === void 0)
6209
- continue;
6210
- if (!isPositiveInt(val))
6211
- throw new Error(`Invalid curve param ${i}=${val} (${typeof val})`);
6212
- }
6213
- return Object.freeze({ ...nLength(curve.n, curve.nBitLength), ...curve });
6214
- }
6188
+ var u8a = (a) => a instanceof Uint8Array;
6215
6189
  var hexes2 = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0"));
6216
- function bytesToHex(uint8a) {
6217
- if (!(uint8a instanceof Uint8Array))
6218
- throw new Error("Expected Uint8Array");
6190
+ function bytesToHex(bytes2) {
6191
+ if (!u8a(bytes2))
6192
+ throw new Error("Uint8Array expected");
6219
6193
  let hex = "";
6220
- for (let i = 0; i < uint8a.length; i++) {
6221
- hex += hexes2[uint8a[i]];
6194
+ for (let i = 0; i < bytes2.length; i++) {
6195
+ hex += hexes2[bytes2[i]];
6222
6196
  }
6223
6197
  return hex;
6224
6198
  }
@@ -6227,24 +6201,22 @@ var starknet = (() => {
6227
6201
  return hex.length & 1 ? `0${hex}` : hex;
6228
6202
  }
6229
6203
  function hexToNumber(hex) {
6230
- if (typeof hex !== "string") {
6231
- throw new TypeError("hexToNumber: expected string, got " + typeof hex);
6232
- }
6233
- return BigInt(`0x${hex}`);
6204
+ if (typeof hex !== "string")
6205
+ throw new Error("hex string expected, got " + typeof hex);
6206
+ return BigInt(hex === "" ? "0" : `0x${hex}`);
6234
6207
  }
6235
6208
  function hexToBytes(hex) {
6236
- if (typeof hex !== "string") {
6237
- throw new TypeError("hexToBytes: expected string, got " + typeof hex);
6238
- }
6209
+ if (typeof hex !== "string")
6210
+ throw new Error("hex string expected, got " + typeof hex);
6239
6211
  if (hex.length % 2)
6240
- throw new Error("hexToBytes: received invalid unpadded hex " + hex.length);
6212
+ throw new Error("hex string is invalid: unpadded " + hex.length);
6241
6213
  const array = new Uint8Array(hex.length / 2);
6242
6214
  for (let i = 0; i < array.length; i++) {
6243
6215
  const j = i * 2;
6244
6216
  const hexByte = hex.slice(j, j + 2);
6245
6217
  const byte = Number.parseInt(hexByte, 16);
6246
6218
  if (Number.isNaN(byte) || byte < 0)
6247
- throw new Error("Invalid byte sequence");
6219
+ throw new Error("invalid byte sequence");
6248
6220
  array[i] = byte;
6249
6221
  }
6250
6222
  return array;
@@ -6252,46 +6224,42 @@ var starknet = (() => {
6252
6224
  function bytesToNumberBE(bytes2) {
6253
6225
  return hexToNumber(bytesToHex(bytes2));
6254
6226
  }
6255
- function bytesToNumberLE(uint8a) {
6256
- if (!(uint8a instanceof Uint8Array))
6257
- throw new Error("Expected Uint8Array");
6258
- return BigInt("0x" + bytesToHex(Uint8Array.from(uint8a).reverse()));
6227
+ function bytesToNumberLE(bytes2) {
6228
+ if (!u8a(bytes2))
6229
+ throw new Error("Uint8Array expected");
6230
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes2).reverse()));
6259
6231
  }
6260
6232
  var numberToBytesBE = (n, len) => hexToBytes(n.toString(16).padStart(len * 2, "0"));
6261
6233
  var numberToBytesLE = (n, len) => numberToBytesBE(n, len).reverse();
6262
- function ensureBytes(hex, expectedLength) {
6263
- const bytes2 = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);
6264
- if (typeof expectedLength === "number" && bytes2.length !== expectedLength)
6265
- throw new Error(`Expected ${expectedLength} bytes`);
6266
- return bytes2;
6267
- }
6268
- function concatBytes2(...arrays) {
6269
- if (!arrays.every((b) => b instanceof Uint8Array))
6270
- throw new Error("Uint8Array list expected");
6271
- if (arrays.length === 1)
6272
- return arrays[0];
6273
- const length = arrays.reduce((a, arr) => a + arr.length, 0);
6274
- const result = new Uint8Array(length);
6275
- for (let i = 0, pad = 0; i < arrays.length; i++) {
6276
- const arr = arrays[i];
6277
- result.set(arr, pad);
6278
- pad += arr.length;
6234
+ var numberToVarBytesBE = (n) => hexToBytes(numberToHexUnpadded(n));
6235
+ function ensureBytes(title, hex, expectedLength) {
6236
+ let res;
6237
+ if (typeof hex === "string") {
6238
+ try {
6239
+ res = hexToBytes(hex);
6240
+ } catch (e) {
6241
+ throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
6242
+ }
6243
+ } else if (u8a(hex)) {
6244
+ res = Uint8Array.from(hex);
6245
+ } else {
6246
+ throw new Error(`${title} must be hex string or Uint8Array`);
6279
6247
  }
6280
- return result;
6281
- }
6282
- function nLength(n, nBitLength2) {
6283
- const _nBitLength = nBitLength2 !== void 0 ? nBitLength2 : n.toString(2).length;
6284
- const nByteLength = Math.ceil(_nBitLength / 8);
6285
- return { nBitLength: _nBitLength, nByteLength };
6248
+ const len = res.length;
6249
+ if (typeof expectedLength === "number" && len !== expectedLength)
6250
+ throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
6251
+ return res;
6286
6252
  }
6287
- function hashToPrivateScalar(hash2, groupOrder, isLE2 = false) {
6288
- hash2 = ensureBytes(hash2);
6289
- const hashLen = hash2.length;
6290
- const minLen = nLength(groupOrder).nByteLength + 8;
6291
- if (minLen < 24 || hashLen < minLen || hashLen > 1024)
6292
- throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
6293
- const num = isLE2 ? bytesToNumberLE(hash2) : bytesToNumberBE(hash2);
6294
- return mod(num, groupOrder - _1n2) + _1n2;
6253
+ function concatBytes2(...arrs) {
6254
+ const r = new Uint8Array(arrs.reduce((sum, a) => sum + a.length, 0));
6255
+ let pad = 0;
6256
+ arrs.forEach((a) => {
6257
+ if (!u8a(a))
6258
+ throw new Error("Uint8Array expected");
6259
+ r.set(a, pad);
6260
+ pad += a.length;
6261
+ });
6262
+ return r;
6295
6263
  }
6296
6264
  function equalBytes(b1, b2) {
6297
6265
  if (b1.length !== b2.length)
@@ -6301,6 +6269,12 @@ var starknet = (() => {
6301
6269
  return false;
6302
6270
  return true;
6303
6271
  }
6272
+ function utf8ToBytes2(str) {
6273
+ if (typeof str !== "string") {
6274
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
6275
+ }
6276
+ return new TextEncoder().encode(str);
6277
+ }
6304
6278
  function bitLen(n) {
6305
6279
  let len;
6306
6280
  for (len = 0; n > 0n; n >>= _1n2, len += 1)
@@ -6310,8 +6284,86 @@ var starknet = (() => {
6310
6284
  var bitGet = (n, pos) => n >> BigInt(pos) & 1n;
6311
6285
  var bitSet = (n, pos, value) => n | (value ? _1n2 : _0n2) << BigInt(pos);
6312
6286
  var bitMask = (n) => (_2n2 << BigInt(n - 1)) - _1n2;
6287
+ var u8n = (data) => new Uint8Array(data);
6288
+ var u8fr = (arr) => Uint8Array.from(arr);
6289
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
6290
+ if (typeof hashLen !== "number" || hashLen < 2)
6291
+ throw new Error("hashLen must be a number");
6292
+ if (typeof qByteLen !== "number" || qByteLen < 2)
6293
+ throw new Error("qByteLen must be a number");
6294
+ if (typeof hmacFn !== "function")
6295
+ throw new Error("hmacFn must be a function");
6296
+ let v = u8n(hashLen);
6297
+ let k = u8n(hashLen);
6298
+ let i = 0;
6299
+ const reset = () => {
6300
+ v.fill(1);
6301
+ k.fill(0);
6302
+ i = 0;
6303
+ };
6304
+ const h = (...b) => hmacFn(k, v, ...b);
6305
+ const reseed = (seed = u8n()) => {
6306
+ k = h(u8fr([0]), seed);
6307
+ v = h();
6308
+ if (seed.length === 0)
6309
+ return;
6310
+ k = h(u8fr([1]), seed);
6311
+ v = h();
6312
+ };
6313
+ const gen2 = () => {
6314
+ if (i++ >= 1e3)
6315
+ throw new Error("drbg: tried 1000 values");
6316
+ let len = 0;
6317
+ const out = [];
6318
+ while (len < qByteLen) {
6319
+ v = h();
6320
+ const sl = v.slice();
6321
+ out.push(sl);
6322
+ len += v.length;
6323
+ }
6324
+ return concatBytes2(...out);
6325
+ };
6326
+ const genUntil = (seed, pred) => {
6327
+ reset();
6328
+ reseed(seed);
6329
+ let res = void 0;
6330
+ while (!(res = pred(gen2())))
6331
+ reseed();
6332
+ reset();
6333
+ return res;
6334
+ };
6335
+ return genUntil;
6336
+ }
6337
+ var validatorFns = {
6338
+ bigint: (val) => typeof val === "bigint",
6339
+ function: (val) => typeof val === "function",
6340
+ boolean: (val) => typeof val === "boolean",
6341
+ string: (val) => typeof val === "string",
6342
+ isSafeInteger: (val) => Number.isSafeInteger(val),
6343
+ array: (val) => Array.isArray(val),
6344
+ field: (val, object) => object.Fp.isValid(val),
6345
+ hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
6346
+ };
6347
+ function validateObject(object, validators, optValidators = {}) {
6348
+ const checkField = (fieldName, type, isOptional) => {
6349
+ const checkVal = validatorFns[type];
6350
+ if (typeof checkVal !== "function")
6351
+ throw new Error(`Invalid validator "${type}", expected function`);
6352
+ const val = object[fieldName];
6353
+ if (isOptional && val === void 0)
6354
+ return;
6355
+ if (!checkVal(val, object)) {
6356
+ throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
6357
+ }
6358
+ };
6359
+ for (const [fieldName, type] of Object.entries(validators))
6360
+ checkField(fieldName, type, false);
6361
+ for (const [fieldName, type] of Object.entries(optValidators))
6362
+ checkField(fieldName, type, true);
6363
+ return object;
6364
+ }
6313
6365
 
6314
- // node_modules/@noble/curves/lib/esm/abstract/modular.js
6366
+ // node_modules/@noble/curves/esm/abstract/modular.js
6315
6367
  var _0n3 = BigInt(0);
6316
6368
  var _1n3 = BigInt(1);
6317
6369
  var _2n3 = BigInt(2);
@@ -6339,11 +6391,11 @@ var starknet = (() => {
6339
6391
  }
6340
6392
  return res;
6341
6393
  }
6342
- function invert(number2, modulo) {
6343
- if (number2 === _0n3 || modulo <= _0n3) {
6344
- throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`);
6394
+ function invert(number3, modulo) {
6395
+ if (number3 === _0n3 || modulo <= _0n3) {
6396
+ throw new Error(`invert: expected positive integers, got n=${number3} mod=${modulo}`);
6345
6397
  }
6346
- let a = mod(number2, modulo);
6398
+ let a = mod(number3, modulo);
6347
6399
  let b = modulo;
6348
6400
  let x = _0n3, y = _1n3, u = _1n3, v = _0n3;
6349
6401
  while (a !== _0n3) {
@@ -6369,30 +6421,30 @@ var starknet = (() => {
6369
6421
  const p1div4 = (P + _1n3) / _4n;
6370
6422
  return function tonelliFast(Fp2, n) {
6371
6423
  const root = Fp2.pow(n, p1div4);
6372
- if (!Fp2.equals(Fp2.square(root), n))
6424
+ if (!Fp2.eql(Fp2.sqr(root), n))
6373
6425
  throw new Error("Cannot find square root");
6374
6426
  return root;
6375
6427
  };
6376
6428
  }
6377
6429
  const Q1div2 = (Q + _1n3) / _2n3;
6378
6430
  return function tonelliSlow(Fp2, n) {
6379
- if (Fp2.pow(n, legendreC) === Fp2.negate(Fp2.ONE))
6431
+ if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE))
6380
6432
  throw new Error("Cannot find square root");
6381
6433
  let r = S;
6382
6434
  let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q);
6383
6435
  let x = Fp2.pow(n, Q1div2);
6384
6436
  let b = Fp2.pow(n, Q);
6385
- while (!Fp2.equals(b, Fp2.ONE)) {
6386
- if (Fp2.equals(b, Fp2.ZERO))
6437
+ while (!Fp2.eql(b, Fp2.ONE)) {
6438
+ if (Fp2.eql(b, Fp2.ZERO))
6387
6439
  return Fp2.ZERO;
6388
6440
  let m = 1;
6389
- for (let t2 = Fp2.square(b); m < r; m++) {
6390
- if (Fp2.equals(t2, Fp2.ONE))
6441
+ for (let t2 = Fp2.sqr(b); m < r; m++) {
6442
+ if (Fp2.eql(t2, Fp2.ONE))
6391
6443
  break;
6392
- t2 = Fp2.square(t2);
6444
+ t2 = Fp2.sqr(t2);
6393
6445
  }
6394
6446
  const ge = Fp2.pow(g, _1n3 << BigInt(r - m - 1));
6395
- g = Fp2.square(ge);
6447
+ g = Fp2.sqr(ge);
6396
6448
  x = Fp2.mul(x, ge);
6397
6449
  b = Fp2.mul(b, g);
6398
6450
  r = m;
@@ -6405,7 +6457,7 @@ var starknet = (() => {
6405
6457
  const p1div4 = (P + _1n3) / _4n;
6406
6458
  return function sqrt3mod4(Fp2, n) {
6407
6459
  const root = Fp2.pow(n, p1div4);
6408
- if (!Fp2.equals(Fp2.square(root), n))
6460
+ if (!Fp2.eql(Fp2.sqr(root), n))
6409
6461
  throw new Error("Cannot find square root");
6410
6462
  return root;
6411
6463
  };
@@ -6418,7 +6470,7 @@ var starknet = (() => {
6418
6470
  const nv = Fp2.mul(n, v);
6419
6471
  const i = Fp2.mul(Fp2.mul(nv, _2n3), v);
6420
6472
  const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
6421
- if (!Fp2.equals(Fp2.square(root), n))
6473
+ if (!Fp2.eql(Fp2.sqr(root), n))
6422
6474
  throw new Error("Cannot find square root");
6423
6475
  return root;
6424
6476
  };
@@ -6430,12 +6482,12 @@ var starknet = (() => {
6430
6482
  var FIELD_FIELDS = [
6431
6483
  "create",
6432
6484
  "isValid",
6433
- "isZero",
6434
- "negate",
6435
- "invert",
6485
+ "is0",
6486
+ "neg",
6487
+ "inv",
6436
6488
  "sqrt",
6437
- "square",
6438
- "equals",
6489
+ "sqr",
6490
+ "eql",
6439
6491
  "add",
6440
6492
  "sub",
6441
6493
  "mul",
@@ -6444,21 +6496,20 @@ var starknet = (() => {
6444
6496
  "addN",
6445
6497
  "subN",
6446
6498
  "mulN",
6447
- "squareN"
6499
+ "sqrN"
6448
6500
  ];
6449
6501
  function validateField(field) {
6450
- for (const i of ["ORDER", "MASK"]) {
6451
- if (typeof field[i] !== "bigint")
6452
- throw new Error(`Invalid field param ${i}=${field[i]} (${typeof field[i]})`);
6453
- }
6454
- for (const i of ["BYTES", "BITS"]) {
6455
- if (typeof field[i] !== "number")
6456
- throw new Error(`Invalid field param ${i}=${field[i]} (${typeof field[i]})`);
6457
- }
6458
- for (const i of FIELD_FIELDS) {
6459
- if (typeof field[i] !== "function")
6460
- throw new Error(`Invalid field param ${i}=${field[i]} (${typeof field[i]})`);
6461
- }
6502
+ const initial = {
6503
+ ORDER: "bigint",
6504
+ MASK: "bigint",
6505
+ BYTES: "isSafeInteger",
6506
+ BITS: "isSafeInteger"
6507
+ };
6508
+ const opts = FIELD_FIELDS.reduce((map, val) => {
6509
+ map[val] = "function";
6510
+ return map;
6511
+ }, initial);
6512
+ return validateObject(field, opts);
6462
6513
  }
6463
6514
  function FpPow(f, num, power) {
6464
6515
  if (power < _0n3)
@@ -6472,7 +6523,7 @@ var starknet = (() => {
6472
6523
  while (power > _0n3) {
6473
6524
  if (power & _1n3)
6474
6525
  p = f.mul(p, d);
6475
- d = f.square(d);
6526
+ d = f.sqr(d);
6476
6527
  power >>= 1n;
6477
6528
  }
6478
6529
  return p;
@@ -6480,20 +6531,25 @@ var starknet = (() => {
6480
6531
  function FpInvertBatch(f, nums) {
6481
6532
  const tmp = new Array(nums.length);
6482
6533
  const lastMultiplied = nums.reduce((acc, num, i) => {
6483
- if (f.isZero(num))
6534
+ if (f.is0(num))
6484
6535
  return acc;
6485
6536
  tmp[i] = acc;
6486
6537
  return f.mul(acc, num);
6487
6538
  }, f.ONE);
6488
- const inverted = f.invert(lastMultiplied);
6539
+ const inverted = f.inv(lastMultiplied);
6489
6540
  nums.reduceRight((acc, num, i) => {
6490
- if (f.isZero(num))
6541
+ if (f.is0(num))
6491
6542
  return acc;
6492
6543
  tmp[i] = f.mul(acc, tmp[i]);
6493
6544
  return f.mul(acc, num);
6494
6545
  }, inverted);
6495
6546
  return tmp;
6496
6547
  }
6548
+ function nLength(n, nBitLength2) {
6549
+ const _nBitLength = nBitLength2 !== void 0 ? nBitLength2 : n.toString(2).length;
6550
+ const nByteLength = Math.ceil(_nBitLength / 8);
6551
+ return { nBitLength: _nBitLength, nByteLength };
6552
+ }
6497
6553
  function Fp(ORDER, bitLen2, isLE2 = false, redef = {}) {
6498
6554
  if (ORDER <= _0n3)
6499
6555
  throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`);
@@ -6514,21 +6570,21 @@ var starknet = (() => {
6514
6570
  throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
6515
6571
  return _0n3 <= num && num < ORDER;
6516
6572
  },
6517
- isZero: (num) => num === _0n3,
6573
+ is0: (num) => num === _0n3,
6518
6574
  isOdd: (num) => (num & _1n3) === _1n3,
6519
- negate: (num) => mod(-num, ORDER),
6520
- equals: (lhs, rhs) => lhs === rhs,
6521
- square: (num) => mod(num * num, ORDER),
6575
+ neg: (num) => mod(-num, ORDER),
6576
+ eql: (lhs, rhs) => lhs === rhs,
6577
+ sqr: (num) => mod(num * num, ORDER),
6522
6578
  add: (lhs, rhs) => mod(lhs + rhs, ORDER),
6523
6579
  sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
6524
6580
  mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
6525
6581
  pow: (num, power) => FpPow(f, num, power),
6526
6582
  div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
6527
- squareN: (num) => num * num,
6583
+ sqrN: (num) => num * num,
6528
6584
  addN: (lhs, rhs) => lhs + rhs,
6529
6585
  subN: (lhs, rhs) => lhs - rhs,
6530
6586
  mulN: (lhs, rhs) => lhs * rhs,
6531
- invert: (num) => invert(num, ORDER),
6587
+ inv: (num) => invert(num, ORDER),
6532
6588
  sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
6533
6589
  invertBatch: (lst) => FpInvertBatch(f, lst),
6534
6590
  cmov: (a, b, c) => c ? b : a,
@@ -6541,109 +6597,132 @@ var starknet = (() => {
6541
6597
  });
6542
6598
  return Object.freeze(f);
6543
6599
  }
6600
+ function hashToPrivateScalar(hash2, groupOrder, isLE2 = false) {
6601
+ hash2 = ensureBytes("privateHash", hash2);
6602
+ const hashLen = hash2.length;
6603
+ const minLen = nLength(groupOrder).nByteLength + 8;
6604
+ if (minLen < 24 || hashLen < minLen || hashLen > 1024)
6605
+ throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
6606
+ const num = isLE2 ? bytesToNumberLE(hash2) : bytesToNumberBE(hash2);
6607
+ return mod(num, groupOrder - _1n3) + _1n3;
6608
+ }
6544
6609
 
6545
- // node_modules/@noble/curves/lib/esm/abstract/hash-to-curve.js
6546
- function validateHTFOpts(opts) {
6547
- if (typeof opts.DST !== "string")
6548
- throw new Error("Invalid htf/DST");
6549
- if (typeof opts.p !== "bigint")
6550
- throw new Error("Invalid htf/p");
6551
- if (typeof opts.m !== "number")
6552
- throw new Error("Invalid htf/m");
6553
- if (typeof opts.k !== "number")
6554
- throw new Error("Invalid htf/k");
6555
- if (opts.expand !== "xmd" && opts.expand !== "xof" && opts.expand !== void 0)
6556
- throw new Error("Invalid htf/expand");
6557
- if (typeof opts.hash !== "function" || !Number.isSafeInteger(opts.hash.outputLen))
6558
- throw new Error("Invalid htf/hash function");
6559
- }
6560
- function stringToBytes(str) {
6561
- const bytes2 = new Uint8Array(str.length);
6562
- for (let i = 0; i < str.length; i++)
6563
- bytes2[i] = str.charCodeAt(i);
6564
- return bytes2;
6565
- }
6566
- function os2ip(bytes2) {
6567
- let result = 0n;
6568
- for (let i = 0; i < bytes2.length; i++) {
6569
- result <<= 8n;
6570
- result += BigInt(bytes2[i]);
6610
+ // node_modules/@noble/curves/esm/abstract/poseidon.js
6611
+ var poseidon_exports = {};
6612
+ __export(poseidon_exports, {
6613
+ poseidon: () => poseidon,
6614
+ splitConstants: () => splitConstants,
6615
+ validateOpts: () => validateOpts
6616
+ });
6617
+ function validateOpts(opts) {
6618
+ const { Fp: Fp2 } = opts;
6619
+ validateField(Fp2);
6620
+ for (const i of ["t", "roundsFull", "roundsPartial"]) {
6621
+ if (typeof opts[i] !== "number" || !Number.isSafeInteger(opts[i]))
6622
+ throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`);
6623
+ }
6624
+ if (opts.reversePartialPowIdx !== void 0 && typeof opts.reversePartialPowIdx !== "boolean")
6625
+ throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`);
6626
+ let sboxPower = opts.sboxPower;
6627
+ if (sboxPower === void 0)
6628
+ sboxPower = 5;
6629
+ if (typeof sboxPower !== "number" || !Number.isSafeInteger(sboxPower))
6630
+ throw new Error(`Poseidon wrong sboxPower=${sboxPower}`);
6631
+ const _sboxPower = BigInt(sboxPower);
6632
+ let sboxFn = (n) => FpPow(Fp2, n, _sboxPower);
6633
+ if (sboxPower === 3)
6634
+ sboxFn = (n) => Fp2.mul(Fp2.sqrN(n), n);
6635
+ else if (sboxPower === 5)
6636
+ sboxFn = (n) => Fp2.mul(Fp2.sqrN(Fp2.sqrN(n)), n);
6637
+ if (opts.roundsFull % 2 !== 0)
6638
+ throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`);
6639
+ const rounds = opts.roundsFull + opts.roundsPartial;
6640
+ if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds)
6641
+ throw new Error("Poseidon: wrong round constants");
6642
+ const roundConstants = opts.roundConstants.map((rc) => {
6643
+ if (!Array.isArray(rc) || rc.length !== opts.t)
6644
+ throw new Error(`Poseidon wrong round constants: ${rc}`);
6645
+ return rc.map((i) => {
6646
+ if (typeof i !== "bigint" || !Fp2.isValid(i))
6647
+ throw new Error(`Poseidon wrong round constant=${i}`);
6648
+ return Fp2.create(i);
6649
+ });
6650
+ });
6651
+ if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t)
6652
+ throw new Error("Poseidon: wrong MDS matrix");
6653
+ const mds = opts.mds.map((mdsRow) => {
6654
+ if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t)
6655
+ throw new Error(`Poseidon MDS matrix row: ${mdsRow}`);
6656
+ return mdsRow.map((i) => {
6657
+ if (typeof i !== "bigint")
6658
+ throw new Error(`Poseidon MDS matrix value=${i}`);
6659
+ return Fp2.create(i);
6660
+ });
6661
+ });
6662
+ return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds });
6663
+ }
6664
+ function splitConstants(rc, t) {
6665
+ if (typeof t !== "number")
6666
+ throw new Error("poseidonSplitConstants: wrong t");
6667
+ if (!Array.isArray(rc) || rc.length % t)
6668
+ throw new Error("poseidonSplitConstants: wrong rc");
6669
+ const res = [];
6670
+ let tmp = [];
6671
+ for (let i = 0; i < rc.length; i++) {
6672
+ tmp.push(rc[i]);
6673
+ if (tmp.length === t) {
6674
+ res.push(tmp);
6675
+ tmp = [];
6676
+ }
6571
6677
  }
6572
- return result;
6678
+ return res;
6573
6679
  }
6574
- function i2osp(value, length) {
6575
- if (value < 0 || value >= 1 << 8 * length) {
6576
- throw new Error(`bad I2OSP call: value=${value} length=${length}`);
6577
- }
6578
- const res = Array.from({ length }).fill(0);
6579
- for (let i = length - 1; i >= 0; i--) {
6580
- res[i] = value & 255;
6581
- value >>>= 8;
6582
- }
6583
- return new Uint8Array(res);
6584
- }
6585
- function strxor(a, b) {
6586
- const arr = new Uint8Array(a.length);
6587
- for (let i = 0; i < a.length; i++) {
6588
- arr[i] = a[i] ^ b[i];
6589
- }
6590
- return arr;
6591
- }
6592
- function expand_message_xmd(msg, DST, lenInBytes, H) {
6593
- if (DST.length > 255)
6594
- DST = H(concatBytes2(stringToBytes("H2C-OVERSIZE-DST-"), DST));
6595
- const b_in_bytes = H.outputLen;
6596
- const r_in_bytes = H.blockLen;
6597
- const ell = Math.ceil(lenInBytes / b_in_bytes);
6598
- if (ell > 255)
6599
- throw new Error("Invalid xmd length");
6600
- const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
6601
- const Z_pad = i2osp(0, r_in_bytes);
6602
- const l_i_b_str = i2osp(lenInBytes, 2);
6603
- const b = new Array(ell);
6604
- const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
6605
- b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
6606
- for (let i = 1; i <= ell; i++) {
6607
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
6608
- b[i] = H(concatBytes2(...args));
6609
- }
6610
- const pseudo_random_bytes = concatBytes2(...b);
6611
- return pseudo_random_bytes.slice(0, lenInBytes);
6612
- }
6613
- function expand_message_xof(msg, DST, lenInBytes, k, H) {
6614
- if (DST.length > 255) {
6615
- const dkLen = Math.ceil(2 * k / 8);
6616
- DST = H.create({ dkLen }).update(stringToBytes("H2C-OVERSIZE-DST-")).update(DST).digest();
6617
- }
6618
- if (lenInBytes > 65535 || DST.length > 255)
6619
- throw new Error("expand_message_xof: invalid lenInBytes");
6620
- return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
6621
- }
6622
- function hash_to_field(msg, count, options) {
6623
- const log2p = options.p.toString(2).length;
6624
- const L = Math.ceil((log2p + options.k) / 8);
6625
- const len_in_bytes = count * options.m * L;
6626
- const DST = stringToBytes(options.DST);
6627
- let pseudo_random_bytes = msg;
6628
- if (options.expand === "xmd") {
6629
- pseudo_random_bytes = expand_message_xmd(msg, DST, len_in_bytes, options.hash);
6630
- } else if (options.expand === "xof") {
6631
- pseudo_random_bytes = expand_message_xof(msg, DST, len_in_bytes, options.k, options.hash);
6632
- }
6633
- const u = new Array(count);
6634
- for (let i = 0; i < count; i++) {
6635
- const e = new Array(options.m);
6636
- for (let j = 0; j < options.m; j++) {
6637
- const elm_offset = L * (j + i * options.m);
6638
- const tv = pseudo_random_bytes.subarray(elm_offset, elm_offset + L);
6639
- e[j] = mod(os2ip(tv), options.p);
6640
- }
6641
- u[i] = e;
6642
- }
6643
- return u;
6680
+ function poseidon(opts) {
6681
+ const { t, Fp: Fp2, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts);
6682
+ const halfRoundsFull = Math.floor(opts.roundsFull / 2);
6683
+ const partialIdx = reversePartialPowIdx ? t - 1 : 0;
6684
+ const poseidonRound = (values, isFull, idx) => {
6685
+ values = values.map((i, j) => Fp2.add(i, opts.roundConstants[idx][j]));
6686
+ if (isFull)
6687
+ values = values.map((i) => sboxFn(i));
6688
+ else
6689
+ values[partialIdx] = sboxFn(values[partialIdx]);
6690
+ values = opts.mds.map((i) => i.reduce((acc, i2, j) => Fp2.add(acc, Fp2.mulN(i2, values[j])), Fp2.ZERO));
6691
+ return values;
6692
+ };
6693
+ const poseidonHash2 = function poseidonHash3(values) {
6694
+ if (!Array.isArray(values) || values.length !== t)
6695
+ throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`);
6696
+ values = values.map((i) => {
6697
+ if (typeof i !== "bigint")
6698
+ throw new Error(`Poseidon: wrong value=${i} (${typeof i})`);
6699
+ return Fp2.create(i);
6700
+ });
6701
+ let round = 0;
6702
+ for (let i = 0; i < halfRoundsFull; i++)
6703
+ values = poseidonRound(values, true, round++);
6704
+ for (let i = 0; i < opts.roundsPartial; i++)
6705
+ values = poseidonRound(values, false, round++);
6706
+ for (let i = 0; i < halfRoundsFull; i++)
6707
+ values = poseidonRound(values, true, round++);
6708
+ if (round !== rounds)
6709
+ throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`);
6710
+ return values;
6711
+ };
6712
+ poseidonHash2.roundConstants = opts.roundConstants;
6713
+ return poseidonHash2;
6644
6714
  }
6645
6715
 
6646
- // node_modules/@noble/curves/lib/esm/abstract/group.js
6716
+ // node_modules/@noble/curves/esm/abstract/weierstrass.js
6717
+ var weierstrass_exports = {};
6718
+ __export(weierstrass_exports, {
6719
+ SWUFpSqrtRatio: () => SWUFpSqrtRatio,
6720
+ mapToCurveSimpleSWU: () => mapToCurveSimpleSWU,
6721
+ weierstrass: () => weierstrass,
6722
+ weierstrassPoints: () => weierstrassPoints
6723
+ });
6724
+
6725
+ // node_modules/@noble/curves/esm/abstract/curve.js
6647
6726
  var _0n4 = BigInt(0);
6648
6727
  var _1n4 = BigInt(1);
6649
6728
  function wNAF(c, bits) {
@@ -6711,163 +6790,235 @@ var starknet = (() => {
6711
6790
  }
6712
6791
  }
6713
6792
  return { p, f };
6793
+ },
6794
+ wNAFCached(P, precomputesMap, n, transform) {
6795
+ const W = P._WINDOW_SIZE || 1;
6796
+ let comp = precomputesMap.get(P);
6797
+ if (!comp) {
6798
+ comp = this.precomputeWindow(P, W);
6799
+ if (W !== 1) {
6800
+ precomputesMap.set(P, transform(comp));
6801
+ }
6802
+ }
6803
+ return this.wNAF(W, comp, n);
6714
6804
  }
6715
6805
  };
6716
6806
  }
6807
+ function validateBasic(curve2) {
6808
+ validateField(curve2.Fp);
6809
+ validateObject(curve2, {
6810
+ n: "bigint",
6811
+ h: "bigint",
6812
+ Gx: "field",
6813
+ Gy: "field"
6814
+ }, {
6815
+ nBitLength: "isSafeInteger",
6816
+ nByteLength: "isSafeInteger"
6817
+ });
6818
+ return Object.freeze({ ...nLength(curve2.n, curve2.nBitLength), ...curve2 });
6819
+ }
6717
6820
 
6718
- // node_modules/@noble/curves/lib/esm/abstract/weierstrass.js
6719
- var DERError = class extends Error {
6720
- constructor(message) {
6721
- super(message);
6722
- }
6723
- };
6724
- var DER = {
6725
- slice(s) {
6726
- return Number.parseInt(s[0], 16) >= 8 ? "00" + s : s;
6727
- },
6728
- parseInt(data) {
6729
- if (data.length < 2 || data[0] !== 2) {
6730
- throw new DERError(`Invalid signature integer tag: ${bytesToHex(data)}`);
6731
- }
6732
- const len = data[1];
6733
- const res = data.subarray(2, len + 2);
6734
- if (!len || res.length !== len) {
6735
- throw new DERError(`Invalid signature integer: wrong length`);
6736
- }
6737
- if (res[0] === 0 && res[1] <= 127) {
6738
- throw new DERError("Invalid signature integer: trailing length");
6739
- }
6740
- return { data: bytesToNumberBE(res), left: data.subarray(len + 2) };
6741
- },
6742
- parseSig(data) {
6743
- if (data.length < 2 || data[0] != 48) {
6744
- throw new DERError(`Invalid signature tag: ${bytesToHex(data)}`);
6745
- }
6746
- if (data[1] !== data.length - 2) {
6747
- throw new DERError("Invalid signature: incorrect length");
6748
- }
6749
- const { data: r, left: sBytes } = DER.parseInt(data.subarray(2));
6750
- const { data: s, left: rBytesLeft } = DER.parseInt(sBytes);
6751
- if (rBytesLeft.length) {
6752
- throw new DERError(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);
6753
- }
6754
- return { r, s };
6755
- }
6756
- };
6757
- function validatePointOpts(curve) {
6758
- const opts = validateOpts(curve);
6759
- const Fp2 = opts.Fp;
6760
- for (const i of ["a", "b"]) {
6761
- if (!Fp2.isValid(curve[i]))
6762
- throw new Error(`Invalid curve param ${i}=${opts[i]} (${typeof opts[i]})`);
6763
- }
6764
- for (const i of ["isTorsionFree", "clearCofactor", "mapToCurve"]) {
6765
- if (curve[i] === void 0)
6766
- continue;
6767
- if (typeof curve[i] !== "function")
6768
- throw new Error(`Invalid ${i} function`);
6769
- }
6770
- const endo = opts.endo;
6821
+ // node_modules/@noble/curves/esm/abstract/weierstrass.js
6822
+ function validatePointOpts(curve2) {
6823
+ const opts = validateBasic(curve2);
6824
+ validateObject(opts, {
6825
+ a: "field",
6826
+ b: "field",
6827
+ fromBytes: "function",
6828
+ toBytes: "function"
6829
+ }, {
6830
+ allowedPrivateKeyLengths: "array",
6831
+ wrapPrivateKey: "boolean",
6832
+ isTorsionFree: "function",
6833
+ clearCofactor: "function",
6834
+ allowInfinityPoint: "boolean"
6835
+ });
6836
+ const { endo, Fp: Fp2, a } = opts;
6771
6837
  if (endo) {
6772
- if (!Fp2.equals(opts.a, Fp2.ZERO)) {
6838
+ if (!Fp2.eql(a, Fp2.ZERO)) {
6773
6839
  throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
6774
6840
  }
6775
6841
  if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
6776
6842
  throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
6777
6843
  }
6778
6844
  }
6779
- if (typeof opts.fromBytes !== "function")
6780
- throw new Error("Invalid fromBytes function");
6781
- if (typeof opts.toBytes !== "function")
6782
- throw new Error("Invalid fromBytes function");
6783
- if (opts.htfDefaults !== void 0)
6784
- validateHTFOpts(opts.htfDefaults);
6785
6845
  return Object.freeze({ ...opts });
6786
6846
  }
6847
+ var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports;
6848
+ var DER = {
6849
+ Err: class DERErr extends Error {
6850
+ constructor(m = "") {
6851
+ super(m);
6852
+ }
6853
+ },
6854
+ _parseInt(data) {
6855
+ const { Err: E } = DER;
6856
+ if (data.length < 2 || data[0] !== 2)
6857
+ throw new E("Invalid signature integer tag");
6858
+ const len = data[1];
6859
+ const res = data.subarray(2, len + 2);
6860
+ if (!len || res.length !== len)
6861
+ throw new E("Invalid signature integer: wrong length");
6862
+ if (res[0] === 0 && res[1] <= 127)
6863
+ throw new E("Invalid signature integer: trailing length");
6864
+ return { d: b2n(res), l: data.subarray(len + 2) };
6865
+ },
6866
+ toSig(hex) {
6867
+ const { Err: E } = DER;
6868
+ const data = typeof hex === "string" ? h2b(hex) : hex;
6869
+ if (!(data instanceof Uint8Array))
6870
+ throw new Error("ui8a expected");
6871
+ let l = data.length;
6872
+ if (l < 2 || data[0] != 48)
6873
+ throw new E("Invalid signature tag");
6874
+ if (data[1] !== l - 2)
6875
+ throw new E("Invalid signature: incorrect length");
6876
+ const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
6877
+ const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
6878
+ if (rBytesLeft.length)
6879
+ throw new E("Invalid signature: left bytes after parsing");
6880
+ return { r, s };
6881
+ },
6882
+ hexFromSig(sig) {
6883
+ const slice = (s2) => Number.parseInt(s2[0], 16) >= 8 ? "00" + s2 : s2;
6884
+ const h = (num) => {
6885
+ const hex = num.toString(16);
6886
+ return hex.length & 1 ? `0${hex}` : hex;
6887
+ };
6888
+ const s = slice(h(sig.s));
6889
+ const r = slice(h(sig.r));
6890
+ const shl = s.length / 2;
6891
+ const rhl = r.length / 2;
6892
+ const sl = h(shl);
6893
+ const rl = h(rhl);
6894
+ return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
6895
+ }
6896
+ };
6787
6897
  var _0n5 = BigInt(0);
6788
6898
  var _1n5 = BigInt(1);
6789
- var _3n2 = BigInt(3);
6790
6899
  function weierstrassPoints(opts) {
6791
6900
  const CURVE2 = validatePointOpts(opts);
6792
6901
  const { Fp: Fp2 } = CURVE2;
6793
6902
  function weierstrassEquation(x) {
6794
6903
  const { a, b } = CURVE2;
6795
- const x2 = Fp2.square(x);
6904
+ const x2 = Fp2.sqr(x);
6796
6905
  const x3 = Fp2.mul(x2, x);
6797
6906
  return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b);
6798
6907
  }
6799
6908
  function isWithinCurveOrder(num) {
6800
- return _0n5 < num && num < CURVE2.n;
6909
+ return typeof num === "bigint" && _0n5 < num && num < CURVE2.n;
6910
+ }
6911
+ function assertGE(num) {
6912
+ if (!isWithinCurveOrder(num))
6913
+ throw new Error("Expected valid bigint: 0 < bigint < curve.n");
6801
6914
  }
6802
- function normalizePrivateKey2(key) {
6803
- const { normalizePrivateKey: custom, nByteLength: groupLen, wrapPrivateKey, n: order } = CURVE2;
6804
- if (typeof custom === "function")
6805
- key = custom(key);
6915
+ function normPrivateKeyToScalar(key) {
6916
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE2;
6917
+ if (lengths && typeof key !== "bigint") {
6918
+ if (key instanceof Uint8Array)
6919
+ key = bytesToHex(key);
6920
+ if (typeof key !== "string" || !lengths.includes(key.length))
6921
+ throw new Error("Invalid key");
6922
+ key = key.padStart(nByteLength * 2, "0");
6923
+ }
6806
6924
  let num;
6807
- if (typeof key === "bigint") {
6808
- num = key;
6809
- } else if (isPositiveInt(key)) {
6810
- num = BigInt(key);
6811
- } else if (typeof key === "string") {
6812
- if (key.length !== 2 * groupLen)
6813
- throw new Error(`Expected ${groupLen} bytes of private key`);
6814
- num = hexToNumber(key);
6815
- } else if (key instanceof Uint8Array) {
6816
- if (key.length !== groupLen)
6817
- throw new Error(`Expected ${groupLen} bytes of private key`);
6818
- num = bytesToNumberBE(key);
6819
- } else {
6820
- throw new TypeError("Expected valid private key");
6925
+ try {
6926
+ num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
6927
+ } catch (error) {
6928
+ throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
6821
6929
  }
6822
6930
  if (wrapPrivateKey)
6823
- num = mod(num, order);
6824
- if (!isWithinCurveOrder(num))
6825
- throw new Error("Expected private key: 0 < key < n");
6931
+ num = mod(num, n);
6932
+ assertGE(num);
6826
6933
  return num;
6827
6934
  }
6828
- function normalizeScalar(num) {
6829
- if (isPositiveInt(num))
6830
- return BigInt(num);
6831
- if (typeof num === "bigint" && isWithinCurveOrder(num))
6832
- return num;
6833
- throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n");
6834
- }
6835
- class ProjectivePoint2 {
6836
- constructor(x, y, z) {
6837
- this.x = x;
6838
- this.y = y;
6839
- this.z = z;
6935
+ const pointPrecomputes = /* @__PURE__ */ new Map();
6936
+ function assertPrjPoint(other) {
6937
+ if (!(other instanceof Point))
6938
+ throw new Error("ProjectivePoint expected");
6939
+ }
6940
+ class Point {
6941
+ constructor(px, py, pz) {
6942
+ this.px = px;
6943
+ this.py = py;
6944
+ this.pz = pz;
6945
+ if (px == null || !Fp2.isValid(px))
6946
+ throw new Error("x required");
6947
+ if (py == null || !Fp2.isValid(py))
6948
+ throw new Error("y required");
6949
+ if (pz == null || !Fp2.isValid(pz))
6950
+ throw new Error("z required");
6840
6951
  }
6841
6952
  static fromAffine(p) {
6842
- if (!(p instanceof Point2)) {
6843
- throw new TypeError("ProjectivePoint#fromAffine: expected Point");
6844
- }
6845
- if (p.equals(Point2.ZERO))
6846
- return ProjectivePoint2.ZERO;
6847
- return new ProjectivePoint2(p.x, p.y, Fp2.ONE);
6848
- }
6849
- static toAffineBatch(points) {
6850
- const toInv = Fp2.invertBatch(points.map((p) => p.z));
6851
- return points.map((p, i) => p.toAffine(toInv[i]));
6953
+ const { x, y } = p || {};
6954
+ if (!p || !Fp2.isValid(x) || !Fp2.isValid(y))
6955
+ throw new Error("invalid affine point");
6956
+ if (p instanceof Point)
6957
+ throw new Error("projective point not allowed");
6958
+ const is0 = (i) => Fp2.eql(i, Fp2.ZERO);
6959
+ if (is0(x) && is0(y))
6960
+ return Point.ZERO;
6961
+ return new Point(x, y, Fp2.ONE);
6962
+ }
6963
+ get x() {
6964
+ return this.toAffine().x;
6965
+ }
6966
+ get y() {
6967
+ return this.toAffine().y;
6852
6968
  }
6853
6969
  static normalizeZ(points) {
6854
- return ProjectivePoint2.toAffineBatch(points).map(ProjectivePoint2.fromAffine);
6970
+ const toInv = Fp2.invertBatch(points.map((p) => p.pz));
6971
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
6972
+ }
6973
+ static fromHex(hex) {
6974
+ const P = Point.fromAffine(CURVE2.fromBytes(ensureBytes("pointHex", hex)));
6975
+ P.assertValidity();
6976
+ return P;
6977
+ }
6978
+ static fromPrivateKey(privateKey) {
6979
+ return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
6980
+ }
6981
+ _setWindowSize(windowSize) {
6982
+ this._WINDOW_SIZE = windowSize;
6983
+ pointPrecomputes.delete(this);
6984
+ }
6985
+ assertValidity() {
6986
+ if (this.is0()) {
6987
+ if (CURVE2.allowInfinityPoint)
6988
+ return;
6989
+ throw new Error("bad point: ZERO");
6990
+ }
6991
+ const { x, y } = this.toAffine();
6992
+ if (!Fp2.isValid(x) || !Fp2.isValid(y))
6993
+ throw new Error("bad point: x or y not FE");
6994
+ const left = Fp2.sqr(y);
6995
+ const right = weierstrassEquation(x);
6996
+ if (!Fp2.eql(left, right))
6997
+ throw new Error("bad point: equation left != right");
6998
+ if (!this.isTorsionFree())
6999
+ throw new Error("bad point: not in prime-order subgroup");
7000
+ }
7001
+ hasEvenY() {
7002
+ const { y } = this.toAffine();
7003
+ if (Fp2.isOdd)
7004
+ return !Fp2.isOdd(y);
7005
+ throw new Error("Field doesn't support isOdd");
6855
7006
  }
6856
7007
  equals(other) {
6857
7008
  assertPrjPoint(other);
6858
- const { x: X1, y: Y1, z: Z1 } = this;
6859
- const { x: X2, y: Y2, z: Z2 } = other;
6860
- const U1 = Fp2.equals(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
6861
- const U2 = Fp2.equals(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
7009
+ const { px: X1, py: Y1, pz: Z1 } = this;
7010
+ const { px: X2, py: Y2, pz: Z2 } = other;
7011
+ const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
7012
+ const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
6862
7013
  return U1 && U2;
6863
7014
  }
6864
7015
  negate() {
6865
- return new ProjectivePoint2(this.x, Fp2.negate(this.y), this.z);
7016
+ return new Point(this.px, Fp2.neg(this.py), this.pz);
6866
7017
  }
6867
7018
  double() {
6868
7019
  const { a, b } = CURVE2;
6869
7020
  const b3 = Fp2.mul(b, 3n);
6870
- const { x: X1, y: Y1, z: Z1 } = this;
7021
+ const { px: X1, py: Y1, pz: Z1 } = this;
6871
7022
  let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
6872
7023
  let t0 = Fp2.mul(X1, X1);
6873
7024
  let t1 = Fp2.mul(Y1, Y1);
@@ -6900,12 +7051,12 @@ var starknet = (() => {
6900
7051
  Z3 = Fp2.mul(t2, t1);
6901
7052
  Z3 = Fp2.add(Z3, Z3);
6902
7053
  Z3 = Fp2.add(Z3, Z3);
6903
- return new ProjectivePoint2(X3, Y3, Z3);
7054
+ return new Point(X3, Y3, Z3);
6904
7055
  }
6905
7056
  add(other) {
6906
7057
  assertPrjPoint(other);
6907
- const { x: X1, y: Y1, z: Z1 } = this;
6908
- const { x: X2, y: Y2, z: Z2 } = other;
7058
+ const { px: X1, py: Y1, pz: Z1 } = this;
7059
+ const { px: X2, py: Y2, pz: Z2 } = other;
6909
7060
  let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
6910
7061
  const a = CURVE2.a;
6911
7062
  const b3 = Fp2.mul(CURVE2.b, 3n);
@@ -6949,23 +7100,33 @@ var starknet = (() => {
6949
7100
  t0 = Fp2.mul(t3, t1);
6950
7101
  Z3 = Fp2.mul(t5, Z3);
6951
7102
  Z3 = Fp2.add(Z3, t0);
6952
- return new ProjectivePoint2(X3, Y3, Z3);
7103
+ return new Point(X3, Y3, Z3);
6953
7104
  }
6954
7105
  subtract(other) {
6955
7106
  return this.add(other.negate());
6956
7107
  }
6957
- multiplyUnsafe(scalar) {
6958
- const P0 = ProjectivePoint2.ZERO;
6959
- if (typeof scalar === "bigint" && scalar === _0n5)
6960
- return P0;
6961
- let n = normalizeScalar(scalar);
7108
+ is0() {
7109
+ return this.equals(Point.ZERO);
7110
+ }
7111
+ wNAF(n) {
7112
+ return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
7113
+ const toInv = Fp2.invertBatch(comp.map((p) => p.pz));
7114
+ return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
7115
+ });
7116
+ }
7117
+ multiplyUnsafe(n) {
7118
+ const I = Point.ZERO;
7119
+ if (n === _0n5)
7120
+ return I;
7121
+ assertGE(n);
6962
7122
  if (n === _1n5)
6963
7123
  return this;
6964
- if (!CURVE2.endo)
7124
+ const { endo } = CURVE2;
7125
+ if (!endo)
6965
7126
  return wnaf.unsafeLadder(this, n);
6966
- let { k1neg, k1, k2neg, k2 } = CURVE2.endo.splitScalar(n);
6967
- let k1p = P0;
6968
- let k2p = P0;
7127
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
7128
+ let k1p = I;
7129
+ let k2p = I;
6969
7130
  let d = this;
6970
7131
  while (k1 > _0n5 || k2 > _0n5) {
6971
7132
  if (k1 & _1n5)
@@ -6980,63 +7141,56 @@ var starknet = (() => {
6980
7141
  k1p = k1p.negate();
6981
7142
  if (k2neg)
6982
7143
  k2p = k2p.negate();
6983
- k2p = new ProjectivePoint2(Fp2.mul(k2p.x, CURVE2.endo.beta), k2p.y, k2p.z);
7144
+ k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
6984
7145
  return k1p.add(k2p);
6985
7146
  }
6986
- wNAF(n, affinePoint) {
6987
- if (!affinePoint && this.equals(ProjectivePoint2.BASE))
6988
- affinePoint = Point2.BASE;
6989
- const W = affinePoint && affinePoint._WINDOW_SIZE || 1;
6990
- let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
6991
- if (!precomputes) {
6992
- precomputes = wnaf.precomputeWindow(this, W);
6993
- if (affinePoint && W !== 1) {
6994
- precomputes = ProjectivePoint2.normalizeZ(precomputes);
6995
- pointPrecomputes.set(affinePoint, precomputes);
6996
- }
6997
- }
6998
- return wnaf.wNAF(W, precomputes, n);
6999
- }
7000
- multiply(scalar, affinePoint) {
7001
- let n = normalizeScalar(scalar);
7002
- let point;
7003
- let fake;
7004
- if (CURVE2.endo) {
7005
- const { k1neg, k1, k2neg, k2 } = CURVE2.endo.splitScalar(n);
7006
- let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
7007
- let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);
7147
+ multiply(scalar) {
7148
+ assertGE(scalar);
7149
+ let n = scalar;
7150
+ let point, fake;
7151
+ const { endo } = CURVE2;
7152
+ if (endo) {
7153
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
7154
+ let { p: k1p, f: f1p } = this.wNAF(k1);
7155
+ let { p: k2p, f: f2p } = this.wNAF(k2);
7008
7156
  k1p = wnaf.constTimeNegate(k1neg, k1p);
7009
7157
  k2p = wnaf.constTimeNegate(k2neg, k2p);
7010
- k2p = new ProjectivePoint2(Fp2.mul(k2p.x, CURVE2.endo.beta), k2p.y, k2p.z);
7158
+ k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
7011
7159
  point = k1p.add(k2p);
7012
7160
  fake = f1p.add(f2p);
7013
7161
  } else {
7014
- const { p, f } = this.wNAF(n, affinePoint);
7162
+ const { p, f } = this.wNAF(n);
7015
7163
  point = p;
7016
7164
  fake = f;
7017
7165
  }
7018
- return ProjectivePoint2.normalizeZ([point, fake])[0];
7166
+ return Point.normalizeZ([point, fake])[0];
7019
7167
  }
7020
- toAffine(invZ) {
7021
- const { x, y, z } = this;
7022
- const is0 = this.equals(ProjectivePoint2.ZERO);
7023
- if (invZ == null)
7024
- invZ = is0 ? Fp2.ONE : Fp2.invert(z);
7025
- const ax = Fp2.mul(x, invZ);
7026
- const ay = Fp2.mul(y, invZ);
7027
- const zz = Fp2.mul(z, invZ);
7168
+ multiplyAndAddUnsafe(Q, a, b) {
7169
+ const G = Point.BASE;
7170
+ const mul = (P, a2) => a2 === _0n5 || a2 === _1n5 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
7171
+ const sum = mul(this, a).add(mul(Q, b));
7172
+ return sum.is0() ? void 0 : sum;
7173
+ }
7174
+ toAffine(iz) {
7175
+ const { px: x, py: y, pz: z } = this;
7176
+ const is0 = this.is0();
7177
+ if (iz == null)
7178
+ iz = is0 ? Fp2.ONE : Fp2.inv(z);
7179
+ const ax = Fp2.mul(x, iz);
7180
+ const ay = Fp2.mul(y, iz);
7181
+ const zz = Fp2.mul(z, iz);
7028
7182
  if (is0)
7029
- return Point2.ZERO;
7030
- if (!Fp2.equals(zz, Fp2.ONE))
7183
+ return { x: Fp2.ZERO, y: Fp2.ZERO };
7184
+ if (!Fp2.eql(zz, Fp2.ONE))
7031
7185
  throw new Error("invZ was invalid");
7032
- return new Point2(ax, ay);
7186
+ return { x: ax, y: ay };
7033
7187
  }
7034
7188
  isTorsionFree() {
7035
7189
  const { h: cofactor, isTorsionFree } = CURVE2;
7036
7190
  if (cofactor === _1n5)
7037
7191
  return true;
7038
7192
  if (isTorsionFree)
7039
- return isTorsionFree(ProjectivePoint2, this);
7193
+ return isTorsionFree(Point, this);
7040
7194
  throw new Error("isTorsionFree() has not been declared for the elliptic curve");
7041
7195
  }
7042
7196
  clearCofactor() {
@@ -7044,269 +7198,101 @@ var starknet = (() => {
7044
7198
  if (cofactor === _1n5)
7045
7199
  return this;
7046
7200
  if (clearCofactor)
7047
- return clearCofactor(ProjectivePoint2, this);
7201
+ return clearCofactor(Point, this);
7048
7202
  return this.multiplyUnsafe(CURVE2.h);
7049
7203
  }
7050
- }
7051
- ProjectivePoint2.BASE = new ProjectivePoint2(CURVE2.Gx, CURVE2.Gy, Fp2.ONE);
7052
- ProjectivePoint2.ZERO = new ProjectivePoint2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO);
7053
- const _bits = CURVE2.nBitLength;
7054
- const wnaf = wNAF(ProjectivePoint2, CURVE2.endo ? Math.ceil(_bits / 2) : _bits);
7055
- function assertPrjPoint(other) {
7056
- if (!(other instanceof ProjectivePoint2))
7057
- throw new TypeError("ProjectivePoint expected");
7058
- }
7059
- const pointPrecomputes = /* @__PURE__ */ new WeakMap();
7060
- class Point2 {
7061
- constructor(x, y) {
7062
- this.x = x;
7063
- this.y = y;
7064
- }
7065
- _setWindowSize(windowSize) {
7066
- this._WINDOW_SIZE = windowSize;
7067
- pointPrecomputes.delete(this);
7068
- }
7069
- hasEvenY() {
7070
- if (Fp2.isOdd)
7071
- return !Fp2.isOdd(this.y);
7072
- throw new Error("Field doesn't support isOdd");
7073
- }
7074
- static fromHex(hex) {
7075
- const { x, y } = CURVE2.fromBytes(ensureBytes(hex));
7076
- const point = new Point2(x, y);
7077
- point.assertValidity();
7078
- return point;
7079
- }
7080
- static fromPrivateKey(privateKey) {
7081
- return Point2.BASE.multiply(normalizePrivateKey2(privateKey));
7082
- }
7083
- toRawBytes(isCompressed = false) {
7204
+ toRawBytes(isCompressed = true) {
7084
7205
  this.assertValidity();
7085
- return CURVE2.toBytes(Point2, this, isCompressed);
7206
+ return CURVE2.toBytes(Point, this, isCompressed);
7086
7207
  }
7087
- toHex(isCompressed = false) {
7208
+ toHex(isCompressed = true) {
7088
7209
  return bytesToHex(this.toRawBytes(isCompressed));
7089
7210
  }
7090
- assertValidity() {
7091
- if (this.equals(Point2.ZERO)) {
7092
- if (CURVE2.allowInfinityPoint)
7093
- return;
7094
- throw new Error("Point at infinity");
7095
- }
7096
- const msg = "Point is not on elliptic curve";
7097
- const { x, y } = this;
7098
- if (!Fp2.isValid(x) || !Fp2.isValid(y))
7099
- throw new Error(msg);
7100
- const left = Fp2.square(y);
7101
- const right = weierstrassEquation(x);
7102
- if (!Fp2.equals(left, right))
7103
- throw new Error(msg);
7104
- if (!this.isTorsionFree())
7105
- throw new Error("Point must be of prime-order subgroup");
7106
- }
7107
- equals(other) {
7108
- if (!(other instanceof Point2))
7109
- throw new TypeError("Point#equals: expected Point");
7110
- return Fp2.equals(this.x, other.x) && Fp2.equals(this.y, other.y);
7111
- }
7112
- negate() {
7113
- return new Point2(this.x, Fp2.negate(this.y));
7114
- }
7115
- toProj() {
7116
- return ProjectivePoint2.fromAffine(this);
7117
- }
7118
- double() {
7119
- return this.toProj().double().toAffine();
7120
- }
7121
- add(other) {
7122
- return this.toProj().add(ProjectivePoint2.fromAffine(other)).toAffine();
7123
- }
7124
- subtract(other) {
7125
- return this.add(other.negate());
7126
- }
7127
- multiply(scalar) {
7128
- return this.toProj().multiply(scalar, this).toAffine();
7129
- }
7130
- multiplyUnsafe(scalar) {
7131
- return this.toProj().multiplyUnsafe(scalar).toAffine();
7132
- }
7133
- clearCofactor() {
7134
- return this.toProj().clearCofactor().toAffine();
7135
- }
7136
- isTorsionFree() {
7137
- return this.toProj().isTorsionFree();
7138
- }
7139
- multiplyAndAddUnsafe(Q, a, b) {
7140
- const P = this.toProj();
7141
- const aP = a === _0n5 || a === _1n5 || this !== Point2.BASE ? P.multiplyUnsafe(a) : P.multiply(a);
7142
- const bQ = ProjectivePoint2.fromAffine(Q).multiplyUnsafe(b);
7143
- const sum = aP.add(bQ);
7144
- return sum.equals(ProjectivePoint2.ZERO) ? void 0 : sum.toAffine();
7145
- }
7146
- static hashToCurve(msg, options) {
7147
- const { mapToCurve } = CURVE2;
7148
- if (!mapToCurve)
7149
- throw new Error("CURVE.mapToCurve() has not been defined");
7150
- msg = ensureBytes(msg);
7151
- const u = hash_to_field(msg, 2, { ...CURVE2.htfDefaults, ...options });
7152
- const { x: x0, y: y0 } = mapToCurve(u[0]);
7153
- const { x: x1, y: y1 } = mapToCurve(u[1]);
7154
- return new Point2(x0, y0).add(new Point2(x1, y1)).clearCofactor();
7155
- }
7156
- static encodeToCurve(msg, options) {
7157
- const { mapToCurve } = CURVE2;
7158
- if (!mapToCurve)
7159
- throw new Error("CURVE.mapToCurve() has not been defined");
7160
- msg = ensureBytes(msg);
7161
- const u = hash_to_field(msg, 1, { ...CURVE2.htfDefaults, ...options });
7162
- const { x, y } = mapToCurve(u[0]);
7163
- return new Point2(x, y).clearCofactor();
7164
- }
7165
- }
7166
- Point2.BASE = new Point2(CURVE2.Gx, CURVE2.Gy);
7167
- Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ZERO);
7211
+ }
7212
+ Point.BASE = new Point(CURVE2.Gx, CURVE2.Gy, Fp2.ONE);
7213
+ Point.ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO);
7214
+ const _bits = CURVE2.nBitLength;
7215
+ const wnaf = wNAF(Point, CURVE2.endo ? Math.ceil(_bits / 2) : _bits);
7168
7216
  return {
7169
- Point: Point2,
7170
- ProjectivePoint: ProjectivePoint2,
7171
- normalizePrivateKey: normalizePrivateKey2,
7217
+ ProjectivePoint: Point,
7218
+ normPrivateKeyToScalar,
7172
7219
  weierstrassEquation,
7173
7220
  isWithinCurveOrder
7174
7221
  };
7175
7222
  }
7176
- function validateOpts2(curve) {
7177
- const opts = validateOpts(curve);
7178
- if (typeof opts.hash !== "function" || !isPositiveInt(opts.hash.outputLen))
7179
- throw new Error("Invalid hash function");
7180
- if (typeof opts.hmac !== "function")
7181
- throw new Error("Invalid hmac function");
7182
- if (typeof opts.randomBytes !== "function")
7183
- throw new Error("Invalid randomBytes function");
7223
+ function validateOpts2(curve2) {
7224
+ const opts = validateBasic(curve2);
7225
+ validateObject(opts, {
7226
+ hash: "hash",
7227
+ hmac: "function",
7228
+ randomBytes: "function"
7229
+ }, {
7230
+ bits2int: "function",
7231
+ bits2int_modN: "function",
7232
+ lowS: "boolean"
7233
+ });
7184
7234
  return Object.freeze({ lowS: true, ...opts });
7185
7235
  }
7186
- var HmacDrbg = class {
7187
- constructor(hashLen, qByteLen, hmacFn) {
7188
- this.hashLen = hashLen;
7189
- this.qByteLen = qByteLen;
7190
- this.hmacFn = hmacFn;
7191
- if (typeof hashLen !== "number" || hashLen < 2)
7192
- throw new Error("hashLen must be a number");
7193
- if (typeof qByteLen !== "number" || qByteLen < 2)
7194
- throw new Error("qByteLen must be a number");
7195
- if (typeof hmacFn !== "function")
7196
- throw new Error("hmacFn must be a function");
7197
- this.v = new Uint8Array(hashLen).fill(1);
7198
- this.k = new Uint8Array(hashLen).fill(0);
7199
- this.counter = 0;
7200
- }
7201
- hmacSync(...values) {
7202
- return this.hmacFn(this.k, ...values);
7203
- }
7204
- incr() {
7205
- if (this.counter >= 1e3)
7206
- throw new Error("Tried 1,000 k values for sign(), all were invalid");
7207
- this.counter += 1;
7208
- }
7209
- reseedSync(seed = new Uint8Array()) {
7210
- this.k = this.hmacSync(this.v, Uint8Array.from([0]), seed);
7211
- this.v = this.hmacSync(this.v);
7212
- if (seed.length === 0)
7213
- return;
7214
- this.k = this.hmacSync(this.v, Uint8Array.from([1]), seed);
7215
- this.v = this.hmacSync(this.v);
7216
- }
7217
- generateSync() {
7218
- this.incr();
7219
- let len = 0;
7220
- const out = [];
7221
- while (len < this.qByteLen) {
7222
- this.v = this.hmacSync(this.v);
7223
- const sl = this.v.slice();
7224
- out.push(sl);
7225
- len += this.v.length;
7226
- }
7227
- return concatBytes2(...out);
7228
- }
7229
- };
7230
7236
  function weierstrass(curveDef) {
7231
7237
  const CURVE2 = validateOpts2(curveDef);
7232
- const CURVE_ORDER = CURVE2.n;
7238
+ const CURVE_ORDER2 = CURVE2.n;
7233
7239
  const Fp2 = CURVE2.Fp;
7234
7240
  const compressedLen = Fp2.BYTES + 1;
7235
7241
  const uncompressedLen = 2 * Fp2.BYTES + 1;
7236
7242
  function isValidFieldElement(num) {
7237
7243
  return _0n5 < num && num < Fp2.ORDER;
7238
7244
  }
7239
- const { Point: Point2, ProjectivePoint: ProjectivePoint2, normalizePrivateKey: normalizePrivateKey2, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
7245
+ function modN(a) {
7246
+ return mod(a, CURVE_ORDER2);
7247
+ }
7248
+ function invN(a) {
7249
+ return invert(a, CURVE_ORDER2);
7250
+ }
7251
+ const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
7240
7252
  ...CURVE2,
7241
7253
  toBytes(c, point, isCompressed) {
7242
- const x = Fp2.toBytes(point.x);
7254
+ const a = point.toAffine();
7255
+ const x = Fp2.toBytes(a.x);
7243
7256
  const cat = concatBytes2;
7244
7257
  if (isCompressed) {
7245
7258
  return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
7246
7259
  } else {
7247
- return cat(Uint8Array.from([4]), x, Fp2.toBytes(point.y));
7260
+ return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y));
7248
7261
  }
7249
7262
  },
7250
7263
  fromBytes(bytes2) {
7251
7264
  const len = bytes2.length;
7252
- const header = bytes2[0];
7253
- if (len === compressedLen && (header === 2 || header === 3)) {
7254
- const x = bytesToNumberBE(bytes2.subarray(1));
7265
+ const head = bytes2[0];
7266
+ const tail = bytes2.subarray(1);
7267
+ if (len === compressedLen && (head === 2 || head === 3)) {
7268
+ const x = bytesToNumberBE(tail);
7255
7269
  if (!isValidFieldElement(x))
7256
7270
  throw new Error("Point is not on curve");
7257
7271
  const y2 = weierstrassEquation(x);
7258
7272
  let y = Fp2.sqrt(y2);
7259
7273
  const isYOdd = (y & _1n5) === _1n5;
7260
- const isFirstByteOdd = (bytes2[0] & 1) === 1;
7261
- if (isFirstByteOdd !== isYOdd)
7262
- y = Fp2.negate(y);
7274
+ const isHeadOdd = (head & 1) === 1;
7275
+ if (isHeadOdd !== isYOdd)
7276
+ y = Fp2.neg(y);
7263
7277
  return { x, y };
7264
- } else if (len === uncompressedLen && header === 4) {
7265
- const x = Fp2.fromBytes(bytes2.subarray(1, Fp2.BYTES + 1));
7266
- const y = Fp2.fromBytes(bytes2.subarray(Fp2.BYTES + 1, 2 * Fp2.BYTES + 1));
7278
+ } else if (len === uncompressedLen && head === 4) {
7279
+ const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
7280
+ const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
7267
7281
  return { x, y };
7268
7282
  } else {
7269
- throw new Error(`Point.fromHex: received invalid point. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`);
7283
+ throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
7270
7284
  }
7271
7285
  }
7272
7286
  });
7273
- function numToField(num) {
7274
- if (typeof num !== "bigint")
7275
- throw new Error("Expected bigint");
7276
- if (!(_0n5 <= num && num < Fp2.MASK))
7277
- throw new Error(`Expected number < 2^${Fp2.BYTES * 8}`);
7278
- return Fp2.toBytes(num);
7279
- }
7280
- const numToFieldStr = (num) => bytesToHex(numToField(num));
7281
- function normalizePublicKey(publicKey) {
7282
- if (publicKey instanceof Point2) {
7283
- publicKey.assertValidity();
7284
- return publicKey;
7285
- } else if (publicKey instanceof Uint8Array || typeof publicKey === "string") {
7286
- return Point2.fromHex(publicKey);
7287
- } else
7288
- throw new Error(`Unknown type of public key: ${publicKey}`);
7289
- }
7290
- function isBiggerThanHalfOrder(number2) {
7291
- const HALF = CURVE_ORDER >> _1n5;
7292
- return number2 > HALF;
7287
+ const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE2.nByteLength));
7288
+ function isBiggerThanHalfOrder(number3) {
7289
+ const HALF = CURVE_ORDER2 >> _1n5;
7290
+ return number3 > HALF;
7293
7291
  }
7294
7292
  function normalizeS(s) {
7295
- return isBiggerThanHalfOrder(s) ? mod(-s, CURVE_ORDER) : s;
7293
+ return isBiggerThanHalfOrder(s) ? modN(-s) : s;
7296
7294
  }
7297
- function bits2int_2(bytes2) {
7298
- const delta = bytes2.length * 8 - CURVE2.nBitLength;
7299
- const num = bytesToNumberBE(bytes2);
7300
- return delta > 0 ? num >> BigInt(delta) : num;
7301
- }
7302
- function _truncateHash(hash2, truncateOnly = false) {
7303
- const h = bits2int_2(hash2);
7304
- if (truncateOnly)
7305
- return h;
7306
- const { n } = CURVE2;
7307
- return h >= n ? h - n : h;
7308
- }
7309
- const truncateHash = CURVE2.truncateHash || _truncateHash;
7295
+ const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
7310
7296
  class Signature3 {
7311
7297
  constructor(r, s, recovery) {
7312
7298
  this.r = r;
@@ -7315,53 +7301,39 @@ var starknet = (() => {
7315
7301
  this.assertValidity();
7316
7302
  }
7317
7303
  static fromCompact(hex) {
7318
- const arr = hex instanceof Uint8Array;
7319
- const name = "Signature.fromCompact";
7320
- if (typeof hex !== "string" && !arr)
7321
- throw new TypeError(`${name}: Expected string or Uint8Array`);
7322
- const str = arr ? bytesToHex(hex) : hex;
7323
- const gl = CURVE2.nByteLength * 2;
7324
- if (str.length !== 2 * gl)
7325
- throw new Error(`${name}: Expected ${gl / 2}-byte hex`);
7326
- const slice = (from, to) => hexToNumber(str.slice(from, to));
7327
- return new Signature3(slice(0, gl), slice(gl, 2 * gl));
7304
+ const l = CURVE2.nByteLength;
7305
+ hex = ensureBytes("compactSignature", hex, l * 2);
7306
+ return new Signature3(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
7328
7307
  }
7329
7308
  static fromDER(hex) {
7330
- const arr = hex instanceof Uint8Array;
7331
- if (typeof hex !== "string" && !arr)
7332
- throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
7333
- const { r, s } = DER.parseSig(arr ? hex : hexToBytes(hex));
7309
+ const { r, s } = DER.toSig(ensureBytes("DER", hex));
7334
7310
  return new Signature3(r, s);
7335
7311
  }
7336
7312
  assertValidity() {
7337
- const { r, s } = this;
7338
- if (!isWithinCurveOrder(r))
7339
- throw new Error("Invalid Signature: r must be 0 < r < n");
7340
- if (!isWithinCurveOrder(s))
7341
- throw new Error("Invalid Signature: s must be 0 < s < n");
7313
+ if (!isWithinCurveOrder(this.r))
7314
+ throw new Error("r must be 0 < r < CURVE.n");
7315
+ if (!isWithinCurveOrder(this.s))
7316
+ throw new Error("s must be 0 < s < CURVE.n");
7342
7317
  }
7343
- copyWithRecoveryBit(recovery) {
7318
+ addRecoveryBit(recovery) {
7344
7319
  return new Signature3(this.r, this.s, recovery);
7345
7320
  }
7346
7321
  recoverPublicKey(msgHash) {
7347
- const { r, s, recovery } = this;
7348
- if (recovery == null)
7349
- throw new Error("Cannot recover: recovery bit is not present");
7350
- if (![0, 1, 2, 3].includes(recovery))
7351
- throw new Error("Cannot recover: invalid recovery bit");
7352
- const h = truncateHash(ensureBytes(msgHash));
7353
- const { n } = CURVE2;
7354
- const radj = recovery === 2 || recovery === 3 ? r + n : r;
7322
+ const { r, s, recovery: rec } = this;
7323
+ const h = bits2int_modN(ensureBytes("msgHash", msgHash));
7324
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
7325
+ throw new Error("recovery id invalid");
7326
+ const radj = rec === 2 || rec === 3 ? r + CURVE2.n : r;
7355
7327
  if (radj >= Fp2.ORDER)
7356
- throw new Error("Cannot recover: bit 2/3 is invalid with current r");
7357
- const rinv = invert(radj, n);
7358
- const u1 = mod(-h * rinv, n);
7359
- const u2 = mod(s * rinv, n);
7360
- const prefix = recovery & 1 ? "03" : "02";
7361
- const R = Point2.fromHex(prefix + numToFieldStr(radj));
7362
- const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2);
7328
+ throw new Error("recovery id 2 or 3 invalid");
7329
+ const prefix = (rec & 1) === 0 ? "02" : "03";
7330
+ const R = Point.fromHex(prefix + numToNByteStr(radj));
7331
+ const ir = invN(radj);
7332
+ const u1 = modN(-h * ir);
7333
+ const u2 = modN(s * ir);
7334
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
7363
7335
  if (!Q)
7364
- throw new Error("Cannot recover: point at infinify");
7336
+ throw new Error("point at infinify");
7365
7337
  Q.assertValidity();
7366
7338
  return Q;
7367
7339
  }
@@ -7369,56 +7341,44 @@ var starknet = (() => {
7369
7341
  return isBiggerThanHalfOrder(this.s);
7370
7342
  }
7371
7343
  normalizeS() {
7372
- return this.hasHighS() ? new Signature3(this.r, mod(-this.s, CURVE_ORDER), this.recovery) : this;
7344
+ return this.hasHighS() ? new Signature3(this.r, modN(-this.s), this.recovery) : this;
7373
7345
  }
7374
7346
  toDERRawBytes() {
7375
7347
  return hexToBytes(this.toDERHex());
7376
7348
  }
7377
7349
  toDERHex() {
7378
- const { numberToHexUnpadded: toHex2 } = utils_exports;
7379
- const sHex = DER.slice(toHex2(this.s));
7380
- const rHex = DER.slice(toHex2(this.r));
7381
- const sHexL = sHex.length / 2;
7382
- const rHexL = rHex.length / 2;
7383
- const sLen = toHex2(sHexL);
7384
- const rLen = toHex2(rHexL);
7385
- const length = toHex2(rHexL + sHexL + 4);
7386
- return `30${length}02${rLen}${rHex}02${sLen}${sHex}`;
7350
+ return DER.hexFromSig({ r: this.r, s: this.s });
7387
7351
  }
7388
7352
  toCompactRawBytes() {
7389
7353
  return hexToBytes(this.toCompactHex());
7390
7354
  }
7391
7355
  toCompactHex() {
7392
- return numToFieldStr(this.r) + numToFieldStr(this.s);
7356
+ return numToNByteStr(this.r) + numToNByteStr(this.s);
7393
7357
  }
7394
7358
  }
7395
7359
  const utils2 = {
7396
7360
  isValidPrivateKey(privateKey) {
7397
7361
  try {
7398
- normalizePrivateKey2(privateKey);
7362
+ normPrivateKeyToScalar(privateKey);
7399
7363
  return true;
7400
7364
  } catch (error) {
7401
7365
  return false;
7402
7366
  }
7403
7367
  },
7404
- _bigintToBytes: numToField,
7405
- _bigintToString: numToFieldStr,
7406
- _normalizePrivateKey: normalizePrivateKey2,
7407
- _normalizePublicKey: normalizePublicKey,
7408
- _isWithinCurveOrder: isWithinCurveOrder,
7409
- _isValidFieldElement: isValidFieldElement,
7410
- _weierstrassEquation: weierstrassEquation,
7411
- hashToPrivateKey: (hash2) => numToField(hashToPrivateScalar(hash2, CURVE_ORDER)),
7412
- randomPrivateKey: () => utils2.hashToPrivateKey(CURVE2.randomBytes(Fp2.BYTES + 8)),
7413
- precompute(windowSize = 8, point = Point2.BASE) {
7414
- const cached = point === Point2.BASE ? point : new Point2(point.x, point.y);
7415
- cached._setWindowSize(windowSize);
7416
- cached.multiply(_3n2);
7417
- return cached;
7368
+ normPrivateKeyToScalar,
7369
+ randomPrivateKey: () => {
7370
+ const rand = CURVE2.randomBytes(Fp2.BYTES + 8);
7371
+ const num = hashToPrivateScalar(rand, CURVE_ORDER2);
7372
+ return numberToBytesBE(num, CURVE2.nByteLength);
7373
+ },
7374
+ precompute(windowSize = 8, point = Point.BASE) {
7375
+ point._setWindowSize(windowSize);
7376
+ point.multiply(BigInt(3));
7377
+ return point;
7418
7378
  }
7419
7379
  };
7420
- function getPublicKey(privateKey, isCompressed = false) {
7421
- return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed);
7380
+ function getPublicKey2(privateKey, isCompressed = true) {
7381
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
7422
7382
  }
7423
7383
  function isProbPub(item) {
7424
7384
  const arr = item instanceof Uint8Array;
@@ -7428,134 +7388,141 @@ var starknet = (() => {
7428
7388
  return len === compressedLen || len === uncompressedLen;
7429
7389
  if (str)
7430
7390
  return len === 2 * compressedLen || len === 2 * uncompressedLen;
7431
- if (item instanceof Point2)
7391
+ if (item instanceof Point)
7432
7392
  return true;
7433
7393
  return false;
7434
7394
  }
7435
- function getSharedSecret(privateA, publicB, isCompressed = false) {
7395
+ function getSharedSecret2(privateA, publicB, isCompressed = true) {
7436
7396
  if (isProbPub(privateA))
7437
- throw new TypeError("getSharedSecret: first arg must be private key");
7397
+ throw new Error("first arg must be private key");
7438
7398
  if (!isProbPub(publicB))
7439
- throw new TypeError("getSharedSecret: second arg must be public key");
7440
- const b = normalizePublicKey(publicB);
7441
- b.assertValidity();
7442
- return b.multiply(normalizePrivateKey2(privateA)).toRawBytes(isCompressed);
7443
- }
7444
- function bits2int(bytes2) {
7445
- const { nByteLength } = CURVE2;
7446
- if (!(bytes2 instanceof Uint8Array))
7447
- throw new Error("Expected Uint8Array");
7448
- const slice = bytes2.length > nByteLength ? bytes2.slice(0, nByteLength) : bytes2;
7449
- let num = bytesToNumberBE(slice);
7450
- return num;
7451
- }
7452
- function bits2octets(bytes2) {
7453
- const z1 = bits2int(bytes2);
7454
- const z2 = mod(z1, CURVE_ORDER);
7455
- return int2octets(z2 < _0n5 ? z1 : z2);
7399
+ throw new Error("second arg must be public key");
7400
+ const b = Point.fromHex(publicB);
7401
+ return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
7456
7402
  }
7403
+ const bits2int2 = CURVE2.bits2int || function(bytes2) {
7404
+ const num = bytesToNumberBE(bytes2);
7405
+ const delta = bytes2.length * 8 - CURVE2.nBitLength;
7406
+ return delta > 0 ? num >> BigInt(delta) : num;
7407
+ };
7408
+ const bits2int_modN = CURVE2.bits2int_modN || function(bytes2) {
7409
+ return modN(bits2int2(bytes2));
7410
+ };
7411
+ const ORDER_MASK = bitMask(CURVE2.nBitLength);
7457
7412
  function int2octets(num) {
7458
- return numToField(num);
7459
- }
7460
- function initSigArgs(msgHash, privateKey, extraEntropy) {
7461
- if (msgHash == null)
7462
- throw new Error(`sign: expected valid message hash, not "${msgHash}"`);
7463
- const h1 = numToField(truncateHash(ensureBytes(msgHash)));
7464
- const d = normalizePrivateKey2(privateKey);
7465
- const seedArgs = [int2octets(d), bits2octets(h1)];
7466
- if (extraEntropy != null) {
7467
- if (extraEntropy === true)
7468
- extraEntropy = CURVE2.randomBytes(Fp2.BYTES);
7469
- const e = ensureBytes(extraEntropy);
7470
- if (e.length !== Fp2.BYTES)
7471
- throw new Error(`sign: Expected ${Fp2.BYTES} bytes of extra data`);
7472
- seedArgs.push(e);
7413
+ if (typeof num !== "bigint")
7414
+ throw new Error("bigint expected");
7415
+ if (!(_0n5 <= num && num < ORDER_MASK))
7416
+ throw new Error(`bigint expected < 2^${CURVE2.nBitLength}`);
7417
+ return numberToBytesBE(num, CURVE2.nByteLength);
7418
+ }
7419
+ function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
7420
+ if (["recovered", "canonical"].some((k) => k in opts))
7421
+ throw new Error("sign() legacy options not supported");
7422
+ const { hash: hash2, randomBytes: randomBytes2 } = CURVE2;
7423
+ let { lowS, prehash, extraEntropy: ent } = opts;
7424
+ if (lowS == null)
7425
+ lowS = true;
7426
+ msgHash = ensureBytes("msgHash", msgHash);
7427
+ if (prehash)
7428
+ msgHash = ensureBytes("prehashed msgHash", hash2(msgHash));
7429
+ const h1int = bits2int_modN(msgHash);
7430
+ const d = normPrivateKeyToScalar(privateKey);
7431
+ const seedArgs = [int2octets(d), int2octets(h1int)];
7432
+ if (ent != null) {
7433
+ const e = ent === true ? randomBytes2(Fp2.BYTES) : ent;
7434
+ seedArgs.push(ensureBytes("extraEntropy", e, Fp2.BYTES));
7473
7435
  }
7474
7436
  const seed = concatBytes2(...seedArgs);
7475
- const m = bits2int(h1);
7476
- return { seed, m, d };
7437
+ const m = h1int;
7438
+ function k2sig(kBytes) {
7439
+ const k = bits2int2(kBytes);
7440
+ if (!isWithinCurveOrder(k))
7441
+ return;
7442
+ const ik = invN(k);
7443
+ const q = Point.BASE.multiply(k).toAffine();
7444
+ const r = modN(q.x);
7445
+ if (r === _0n5)
7446
+ return;
7447
+ const b = bytesToNumberBE(utils2.randomPrivateKey());
7448
+ const bi = invN(b);
7449
+ const bdr = modN(b * d * r);
7450
+ const bm = modN(b * m);
7451
+ const mrx = modN(bi * modN(bdr + bm));
7452
+ const s = modN(ik * mrx);
7453
+ if (s === _0n5)
7454
+ return;
7455
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n5);
7456
+ let normS = s;
7457
+ if (lowS && isBiggerThanHalfOrder(s)) {
7458
+ normS = normalizeS(s);
7459
+ recovery ^= 1;
7460
+ }
7461
+ return new Signature3(r, normS, recovery);
7462
+ }
7463
+ return { seed, k2sig };
7477
7464
  }
7478
- function kmdToSig(kBytes, m, d, lowS = true) {
7479
- const { n } = CURVE2;
7480
- const k = truncateHash(kBytes, true);
7481
- if (!isWithinCurveOrder(k))
7482
- return;
7483
- const kinv = invert(k, n);
7484
- const q = Point2.BASE.multiply(k);
7485
- const r = mod(q.x, n);
7486
- if (r === _0n5)
7487
- return;
7488
- const s = mod(kinv * mod(m + mod(d * r, n), n), n);
7489
- if (s === _0n5)
7490
- return;
7491
- let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n5);
7492
- let normS = s;
7493
- if (lowS && isBiggerThanHalfOrder(s)) {
7494
- normS = normalizeS(s);
7495
- recovery ^= 1;
7496
- }
7497
- return new Signature3(r, normS, recovery);
7498
- }
7499
- const defaultSigOpts = { lowS: CURVE2.lowS };
7500
- function sign(msgHash, privKey, opts = defaultSigOpts) {
7501
- const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);
7502
- const drbg = new HmacDrbg(CURVE2.hash.outputLen, CURVE2.nByteLength, CURVE2.hmac);
7503
- drbg.reseedSync(seed);
7504
- let sig;
7505
- while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.lowS)))
7506
- drbg.reseedSync();
7507
- return sig;
7508
- }
7509
- function signUnhashed(msg, privKey, opts = defaultSigOpts) {
7510
- return sign(CURVE2.hash(ensureBytes(msg)), privKey, opts);
7511
- }
7512
- Point2.BASE._setWindowSize(8);
7513
- function verify(signature, msgHash, publicKey, opts = { lowS: CURVE2.lowS }) {
7465
+ const defaultSigOpts = { lowS: CURVE2.lowS, prehash: false };
7466
+ const defaultVerOpts = { lowS: CURVE2.lowS, prehash: false };
7467
+ function sign2(msgHash, privKey, opts = defaultSigOpts) {
7468
+ const { seed, k2sig } = prepSig(msgHash, privKey, opts);
7469
+ const drbg = createHmacDrbg(CURVE2.hash.outputLen, CURVE2.nByteLength, CURVE2.hmac);
7470
+ return drbg(seed, k2sig);
7471
+ }
7472
+ Point.BASE._setWindowSize(8);
7473
+ function verify2(signature, msgHash, publicKey, opts = defaultVerOpts) {
7474
+ var _a;
7475
+ const sg = signature;
7476
+ msgHash = ensureBytes("msgHash", msgHash);
7477
+ publicKey = ensureBytes("publicKey", publicKey);
7478
+ if ("strict" in opts)
7479
+ throw new Error("options.strict was renamed to lowS");
7480
+ const { lowS, prehash } = opts;
7481
+ let _sig = void 0;
7482
+ let P;
7514
7483
  try {
7515
- if (signature instanceof Signature3) {
7516
- signature.assertValidity();
7517
- } else {
7484
+ if (typeof sg === "string" || sg instanceof Uint8Array) {
7518
7485
  try {
7519
- signature = Signature3.fromDER(signature);
7486
+ _sig = Signature3.fromDER(sg);
7520
7487
  } catch (derError) {
7521
- if (!(derError instanceof DERError))
7488
+ if (!(derError instanceof DER.Err))
7522
7489
  throw derError;
7523
- signature = Signature3.fromCompact(signature);
7490
+ _sig = Signature3.fromCompact(sg);
7524
7491
  }
7492
+ } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") {
7493
+ const { r: r2, s: s2 } = sg;
7494
+ _sig = new Signature3(r2, s2);
7495
+ } else {
7496
+ throw new Error("PARSE");
7525
7497
  }
7526
- msgHash = ensureBytes(msgHash);
7498
+ P = Point.fromHex(publicKey);
7527
7499
  } catch (error) {
7500
+ if (error.message === "PARSE")
7501
+ throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
7528
7502
  return false;
7529
7503
  }
7530
- if (opts.lowS && signature.hasHighS())
7504
+ if (lowS && _sig.hasHighS())
7531
7505
  return false;
7532
- let P;
7533
- try {
7534
- P = normalizePublicKey(publicKey);
7535
- } catch (error) {
7536
- return false;
7537
- }
7538
- const { n } = CURVE2;
7539
- const { r, s } = signature;
7540
- const h = truncateHash(msgHash);
7541
- const sinv = invert(s, n);
7542
- const u1 = mod(h * sinv, n);
7543
- const u2 = mod(r * sinv, n);
7544
- const R = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2);
7506
+ if (prehash)
7507
+ msgHash = CURVE2.hash(msgHash);
7508
+ const { r, s } = _sig;
7509
+ const h = bits2int_modN(msgHash);
7510
+ const is = invN(s);
7511
+ const u1 = modN(h * is);
7512
+ const u2 = modN(r * is);
7513
+ const R = (_a = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)) == null ? void 0 : _a.toAffine();
7545
7514
  if (!R)
7546
7515
  return false;
7547
- const v = mod(R.x, n);
7516
+ const v = modN(R.x);
7548
7517
  return v === r;
7549
7518
  }
7550
7519
  return {
7551
7520
  CURVE: CURVE2,
7552
- getPublicKey,
7553
- getSharedSecret,
7554
- sign,
7555
- signUnhashed,
7556
- verify,
7557
- Point: Point2,
7558
- ProjectivePoint: ProjectivePoint2,
7521
+ getPublicKey: getPublicKey2,
7522
+ getSharedSecret: getSharedSecret2,
7523
+ sign: sign2,
7524
+ verify: verify2,
7525
+ ProjectivePoint: Point,
7559
7526
  Signature: Signature3,
7560
7527
  utils: utils2
7561
7528
  };
@@ -7575,7 +7542,7 @@ var starknet = (() => {
7575
7542
  let sqrtRatio = (u, v) => {
7576
7543
  let tv1 = c6;
7577
7544
  let tv2 = Fp2.pow(v, c4);
7578
- let tv3 = Fp2.square(tv2);
7545
+ let tv3 = Fp2.sqr(tv2);
7579
7546
  tv3 = Fp2.mul(tv3, v);
7580
7547
  let tv5 = Fp2.mul(u, tv3);
7581
7548
  tv5 = Fp2.pow(tv5, c3);
@@ -7584,7 +7551,7 @@ var starknet = (() => {
7584
7551
  tv3 = Fp2.mul(tv5, u);
7585
7552
  let tv4 = Fp2.mul(tv3, tv2);
7586
7553
  tv5 = Fp2.pow(tv4, c5);
7587
- let isQR = Fp2.equals(tv5, Fp2.ONE);
7554
+ let isQR = Fp2.eql(tv5, Fp2.ONE);
7588
7555
  tv2 = Fp2.mul(tv3, c7);
7589
7556
  tv5 = Fp2.mul(tv4, tv1);
7590
7557
  tv3 = Fp2.cmov(tv2, tv3, isQR);
@@ -7592,7 +7559,7 @@ var starknet = (() => {
7592
7559
  for (let i = c1; i > 1; i--) {
7593
7560
  let tv52 = 2n ** (i - 2n);
7594
7561
  let tvv5 = Fp2.pow(tv4, tv52);
7595
- const e1 = Fp2.equals(tvv5, Fp2.ONE);
7562
+ const e1 = Fp2.eql(tvv5, Fp2.ONE);
7596
7563
  tv2 = Fp2.mul(tv3, tv1);
7597
7564
  tv1 = Fp2.mul(tv1, tv1);
7598
7565
  tvv5 = Fp2.mul(tv4, tv1);
@@ -7603,16 +7570,16 @@ var starknet = (() => {
7603
7570
  };
7604
7571
  if (Fp2.ORDER % 4n === 3n) {
7605
7572
  const c12 = (Fp2.ORDER - 3n) / 4n;
7606
- const c22 = Fp2.sqrt(Fp2.negate(Z));
7573
+ const c22 = Fp2.sqrt(Fp2.neg(Z));
7607
7574
  sqrtRatio = (u, v) => {
7608
- let tv1 = Fp2.square(v);
7575
+ let tv1 = Fp2.sqr(v);
7609
7576
  const tv2 = Fp2.mul(u, v);
7610
7577
  tv1 = Fp2.mul(tv1, tv2);
7611
7578
  let y1 = Fp2.pow(tv1, c12);
7612
7579
  y1 = Fp2.mul(y1, tv2);
7613
7580
  const y2 = Fp2.mul(y1, c22);
7614
- const tv3 = Fp2.mul(Fp2.square(y1), v);
7615
- const isQR = Fp2.equals(tv3, u);
7581
+ const tv3 = Fp2.mul(Fp2.sqr(y1), v);
7582
+ const isQR = Fp2.eql(tv3, u);
7616
7583
  let y = Fp2.cmov(y2, y1, isQR);
7617
7584
  return { isValid: isQR, value: y };
7618
7585
  };
@@ -7628,16 +7595,16 @@ var starknet = (() => {
7628
7595
  throw new Error("Fp.isOdd is not implemented!");
7629
7596
  return (u) => {
7630
7597
  let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
7631
- tv1 = Fp2.square(u);
7598
+ tv1 = Fp2.sqr(u);
7632
7599
  tv1 = Fp2.mul(tv1, opts.Z);
7633
- tv2 = Fp2.square(tv1);
7600
+ tv2 = Fp2.sqr(tv1);
7634
7601
  tv2 = Fp2.add(tv2, tv1);
7635
7602
  tv3 = Fp2.add(tv2, Fp2.ONE);
7636
7603
  tv3 = Fp2.mul(tv3, opts.B);
7637
- tv4 = Fp2.cmov(opts.Z, Fp2.negate(tv2), !Fp2.equals(tv2, Fp2.ZERO));
7604
+ tv4 = Fp2.cmov(opts.Z, Fp2.neg(tv2), !Fp2.eql(tv2, Fp2.ZERO));
7638
7605
  tv4 = Fp2.mul(tv4, opts.A);
7639
- tv2 = Fp2.square(tv3);
7640
- tv6 = Fp2.square(tv4);
7606
+ tv2 = Fp2.sqr(tv3);
7607
+ tv6 = Fp2.sqr(tv4);
7641
7608
  tv5 = Fp2.mul(tv6, opts.A);
7642
7609
  tv2 = Fp2.add(tv2, tv5);
7643
7610
  tv2 = Fp2.mul(tv2, tv3);
@@ -7651,7 +7618,7 @@ var starknet = (() => {
7651
7618
  x = Fp2.cmov(x, tv3, isValid);
7652
7619
  y = Fp2.cmov(y, value, isValid);
7653
7620
  const e1 = Fp2.isOdd(u) === Fp2.isOdd(y);
7654
- y = Fp2.cmov(Fp2.negate(y), y, e1);
7621
+ y = Fp2.cmov(Fp2.neg(y), y, e1);
7655
7622
  x = Fp2.div(x, tv4);
7656
7623
  return { x, y };
7657
7624
  };
@@ -7722,7 +7689,7 @@ var starknet = (() => {
7722
7689
  var hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest();
7723
7690
  hmac.create = (hash2, key) => new HMAC(hash2, key);
7724
7691
 
7725
- // node_modules/@noble/curves/lib/esm/_shortw_utils.js
7692
+ // node_modules/@noble/curves/esm/_shortw_utils.js
7726
7693
  function getHash(hash2) {
7727
7694
  return {
7728
7695
  hash: hash2,
@@ -7731,118 +7698,92 @@ var starknet = (() => {
7731
7698
  };
7732
7699
  }
7733
7700
 
7734
- // node_modules/@noble/curves/lib/esm/stark.js
7735
- var CURVE_N = BigInt("3618502788666131213697322783095070105526743751716087489154079457884512865583");
7701
+ // node_modules/@noble/curves/esm/stark.js
7702
+ var CURVE_ORDER = BigInt("3618502788666131213697322783095070105526743751716087489154079457884512865583");
7736
7703
  var nBitLength = 252;
7737
- var starkCurve = weierstrass({
7704
+ function bits2int(bytes2) {
7705
+ while (bytes2[0] === 0)
7706
+ bytes2 = bytes2.subarray(1);
7707
+ const delta = bytes2.length * 8 - nBitLength;
7708
+ const num = bytesToNumberBE(bytes2);
7709
+ return delta > 0 ? num >> BigInt(delta) : num;
7710
+ }
7711
+ function hex0xToBytes(hex) {
7712
+ if (typeof hex === "string") {
7713
+ hex = strip0x(hex);
7714
+ if (hex.length & 1)
7715
+ hex = "0" + hex;
7716
+ }
7717
+ return hexToBytes(hex);
7718
+ }
7719
+ var curve = weierstrass({
7738
7720
  a: BigInt(1),
7739
7721
  b: BigInt("3141592653589793238462643383279502884197169399375105820974944592307816406665"),
7740
7722
  Fp: Fp(BigInt("0x800000000000011000000000000000000000000000000000000000000000001")),
7741
- n: CURVE_N,
7723
+ n: CURVE_ORDER,
7742
7724
  nBitLength,
7743
7725
  Gx: BigInt("874739451078007766457464989774322083649278607533249481151382481072868806602"),
7744
7726
  Gy: BigInt("152666792071518830868575557812948353041420400780739481342941381225525861407"),
7745
7727
  h: BigInt(1),
7746
7728
  lowS: false,
7747
7729
  ...getHash(sha256),
7748
- truncateHash: (hash2, truncateOnly = false) => {
7749
- if (!truncateOnly) {
7750
- let hashS = bytesToNumber0x(hash2).toString(16);
7751
- if (hashS.length === 63) {
7752
- hashS += "0";
7753
- hash2 = hexToBytes0x(hashS);
7754
- }
7755
- }
7756
- while (hash2[0] === 0)
7757
- hash2 = hash2.subarray(1);
7758
- const byteLength = hash2.length;
7759
- const delta = byteLength * 8 - nBitLength;
7760
- let h = hash2.length ? bytesToNumber0x(hash2) : 0n;
7761
- if (delta > 0)
7762
- h = h >> BigInt(delta);
7763
- if (!truncateOnly && h >= CURVE_N)
7764
- h -= CURVE_N;
7765
- return h;
7730
+ bits2int,
7731
+ bits2int_modN: (bytes2) => {
7732
+ const hex = bytesToNumberBE(bytes2).toString(16);
7733
+ if (hex.length === 63)
7734
+ bytes2 = hex0xToBytes(hex + "0");
7735
+ return mod(bits2int(bytes2), CURVE_ORDER);
7766
7736
  }
7767
7737
  });
7768
- function hexToBytes0x(hex) {
7769
- if (typeof hex !== "string") {
7770
- throw new TypeError("hexToBytes: expected string, got " + typeof hex);
7771
- }
7772
- hex = strip0x(hex);
7773
- if (hex.length & 1)
7774
- hex = "0" + hex;
7775
- if (hex.length % 2)
7776
- throw new Error("hexToBytes: received invalid unpadded hex " + hex.length);
7777
- const array = new Uint8Array(hex.length / 2);
7778
- for (let i = 0; i < array.length; i++) {
7779
- const j = i * 2;
7780
- const hexByte = hex.slice(j, j + 2);
7781
- const byte = Number.parseInt(hexByte, 16);
7782
- if (Number.isNaN(byte) || byte < 0)
7783
- throw new Error("Invalid byte sequence");
7784
- array[i] = byte;
7785
- }
7786
- return array;
7787
- }
7788
- function hexToNumber0x(hex) {
7789
- if (typeof hex !== "string") {
7790
- throw new TypeError("hexToNumber: expected string, got " + typeof hex);
7791
- }
7792
- return BigInt(`0x${strip0x(hex)}`);
7738
+ var _starkCurve = curve;
7739
+ function ensureBytes2(hex) {
7740
+ return ensureBytes("", typeof hex === "string" ? hex0xToBytes(hex) : hex);
7793
7741
  }
7794
- function bytesToNumber0x(bytes2) {
7795
- return hexToNumber0x(bytesToHex(bytes2));
7742
+ function normPrivKey(privKey) {
7743
+ return bytesToHex(ensureBytes2(privKey)).padStart(64, "0");
7796
7744
  }
7797
- function ensureBytes0x(hex) {
7798
- return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes0x(hex);
7745
+ function getPublicKey(privKey, isCompressed = false) {
7746
+ return curve.getPublicKey(normPrivKey(privKey), isCompressed);
7799
7747
  }
7800
- function normalizePrivateKey(privKey) {
7801
- return bytesToHex(ensureBytes0x(privKey)).padStart(32 * 2, "0");
7748
+ function getSharedSecret(privKeyA, pubKeyB) {
7749
+ return curve.getSharedSecret(normPrivKey(privKeyA), pubKeyB);
7802
7750
  }
7803
- function getPublicKey0x(privKey, isCompressed) {
7804
- return starkCurve.getPublicKey(normalizePrivateKey(privKey), isCompressed);
7751
+ function sign(msgHash, privKey, opts) {
7752
+ return curve.sign(ensureBytes2(msgHash), normPrivKey(privKey), opts);
7805
7753
  }
7806
- function getSharedSecret0x(privKeyA, pubKeyB) {
7807
- return starkCurve.getSharedSecret(normalizePrivateKey(privKeyA), pubKeyB);
7754
+ function verify(signature, msgHash, pubKey) {
7755
+ const sig = signature instanceof Signature ? signature : ensureBytes2(signature);
7756
+ return curve.verify(sig, ensureBytes2(msgHash), ensureBytes2(pubKey));
7808
7757
  }
7809
- function sign0x(msgHash, privKey, opts) {
7810
- if (typeof privKey === "string")
7811
- privKey = strip0x(privKey).padStart(64, "0");
7812
- return starkCurve.sign(ensureBytes0x(msgHash), normalizePrivateKey(privKey), opts);
7758
+ var { CURVE, ProjectivePoint, Signature, utils } = curve;
7759
+ function extractX(bytes2) {
7760
+ const hex = bytesToHex(bytes2.subarray(1));
7761
+ const stripped = hex.replace(/^0+/gm, "");
7762
+ return `0x${stripped}`;
7813
7763
  }
7814
- function verify0x(signature, msgHash, pubKey) {
7815
- const sig = signature instanceof Signature ? signature : ensureBytes0x(signature);
7816
- return starkCurve.verify(sig, ensureBytes0x(msgHash), ensureBytes0x(pubKey));
7764
+ function strip0x(hex) {
7765
+ return hex.replace(/^0x/i, "");
7817
7766
  }
7818
- var { CURVE, Point, ProjectivePoint, Signature } = starkCurve;
7819
- var utils = starkCurve.utils;
7820
- var stripLeadingZeros = (s) => s.replace(/^0+/gm, "");
7821
- var bytesToHexEth = (uint8a) => `0x${stripLeadingZeros(bytesToHex(uint8a))}`;
7822
- var strip0x = (hex) => hex.replace(/^0x/i, "");
7823
- var numberToHexEth = (num) => `0x${num.toString(16)}`;
7824
- function hashKeyWithIndex(key, index) {
7825
- let indexHex = numberToHexUnpadded(index);
7826
- if (indexHex.length & 1)
7827
- indexHex = "0" + indexHex;
7828
- return bytesToNumber0x(sha256(concatBytes2(key, hexToBytes0x(indexHex))));
7767
+ function numberTo0x16(num) {
7768
+ return `0x${num.toString(16)}`;
7829
7769
  }
7830
7770
  function grindKey(seed) {
7831
- const _seed = ensureBytes0x(seed);
7771
+ const _seed = ensureBytes2(seed);
7832
7772
  const sha256mask = 2n ** 256n;
7833
- const Fn = Fp(CURVE.n);
7834
- const limit = sha256mask - Fn.create(sha256mask);
7773
+ const limit = sha256mask - mod(sha256mask, CURVE_ORDER);
7835
7774
  for (let i = 0; ; i++) {
7836
- const key = hashKeyWithIndex(_seed, i);
7775
+ const key = sha256Num(concatBytes2(_seed, numberToVarBytesBE(BigInt(i))));
7837
7776
  if (key < limit)
7838
- return Fn.create(key).toString(16);
7777
+ return mod(key, CURVE_ORDER).toString(16);
7778
+ if (i === 1e5)
7779
+ throw new Error("grindKey is broken: tried 100k vals");
7839
7780
  }
7840
7781
  }
7841
7782
  function getStarkKey(privateKey) {
7842
- return bytesToHexEth(getPublicKey0x(privateKey, true).slice(1));
7783
+ return extractX(getPublicKey(privateKey, true));
7843
7784
  }
7844
7785
  function ethSigToPrivate(signature) {
7845
- signature = strip0x(signature.replace(/^0x/, ""));
7786
+ signature = strip0x(signature);
7846
7787
  if (signature.length !== 130)
7847
7788
  throw new Error("Wrong ethereum signature");
7848
7789
  return grindKey(signature.substring(0, 64));
@@ -7850,19 +7791,18 @@ var starknet = (() => {
7850
7791
  var MASK_31 = 2n ** 31n - 1n;
7851
7792
  var int31 = (n) => Number(n & MASK_31);
7852
7793
  function getAccountPath(layer, application, ethereumAddress, index) {
7853
- const layerNum = int31(bytesToNumber0x(sha256(layer)));
7854
- const applicationNum = int31(bytesToNumber0x(sha256(application)));
7855
- const eth = hexToNumber0x(ethereumAddress);
7794
+ const layerNum = int31(sha256Num(layer));
7795
+ const applicationNum = int31(sha256Num(application));
7796
+ const eth = hexToNumber(strip0x(ethereumAddress));
7856
7797
  return `m/2645'/${layerNum}'/${applicationNum}'/${int31(eth)}'/${int31(eth >> 31n)}'/${index}`;
7857
7798
  }
7858
- var PEDERSEN_POINTS_AFFINE = [
7859
- new Point(2089986280348253421170679821480865132823066470938446095505822317253594081284n, 1713931329540660377023406109199410414810705867260802078187082345529207694986n),
7860
- new Point(996781205833008774514500082376783249102396023663454813447423147977397232763n, 1668503676786377725805489344771023921079126552019160156920634619255970485781n),
7861
- new Point(2251563274489750535117886426533222435294046428347329203627021249169616184184n, 1798716007562728905295480679789526322175868328062420237419143593021674992973n),
7862
- new Point(2138414695194151160943305727036575959195309218611738193261179310511854807447n, 113410276730064486255102093846540133784865286929052426931474106396135072156n),
7863
- new Point(2379962749567351885752724891227938183011949129833673362440656643086021394946n, 776496453633298175483985398648758586525933812536653089401905292063708816422n)
7799
+ var PEDERSEN_POINTS = [
7800
+ new ProjectivePoint(2089986280348253421170679821480865132823066470938446095505822317253594081284n, 1713931329540660377023406109199410414810705867260802078187082345529207694986n, 1n),
7801
+ new ProjectivePoint(996781205833008774514500082376783249102396023663454813447423147977397232763n, 1668503676786377725805489344771023921079126552019160156920634619255970485781n, 1n),
7802
+ new ProjectivePoint(2251563274489750535117886426533222435294046428347329203627021249169616184184n, 1798716007562728905295480679789526322175868328062420237419143593021674992973n, 1n),
7803
+ new ProjectivePoint(2138414695194151160943305727036575959195309218611738193261179310511854807447n, 113410276730064486255102093846540133784865286929052426931474106396135072156n, 1n),
7804
+ new ProjectivePoint(2379962749567351885752724891227938183011949129833673362440656643086021394946n, 776496453633298175483985398648758586525933812536653089401905292063708816422n, 1n)
7864
7805
  ];
7865
- var PEDERSEN_POINTS = PEDERSEN_POINTS_AFFINE.map(ProjectivePoint.fromAffine);
7866
7806
  function pedersenPrecompute(p1, p2) {
7867
7807
  const out = [];
7868
7808
  let p = p1;
@@ -7881,15 +7821,16 @@ var starknet = (() => {
7881
7821
  var PEDERSEN_POINTS2 = pedersenPrecompute(PEDERSEN_POINTS[3], PEDERSEN_POINTS[4]);
7882
7822
  function pedersenArg(arg) {
7883
7823
  let value;
7884
- if (typeof arg === "bigint")
7824
+ if (typeof arg === "bigint") {
7885
7825
  value = arg;
7886
- else if (typeof arg === "number") {
7826
+ } else if (typeof arg === "number") {
7887
7827
  if (!Number.isSafeInteger(arg))
7888
7828
  throw new Error(`Invalid pedersenArg: ${arg}`);
7889
7829
  value = BigInt(arg);
7890
- } else
7891
- value = bytesToNumber0x(ensureBytes0x(arg));
7892
- if (!(0n <= value && value < starkCurve.CURVE.Fp.ORDER))
7830
+ } else {
7831
+ value = bytesToNumberBE(ensureBytes2(arg));
7832
+ }
7833
+ if (!(0n <= value && value < curve.CURVE.Fp.ORDER))
7893
7834
  throw new Error(`PedersenArg should be 0 <= value < CURVE.P: ${value}`);
7894
7835
  return value;
7895
7836
  }
@@ -7897,7 +7838,7 @@ var starknet = (() => {
7897
7838
  let x = pedersenArg(value);
7898
7839
  for (let j = 0; j < 252; j++) {
7899
7840
  const pt = constants2[j];
7900
- if (pt.x === point.x)
7841
+ if (pt.px === point.px)
7901
7842
  throw new Error("Same point");
7902
7843
  if ((x & 1n) !== 0n)
7903
7844
  point = point.add(pt);
@@ -7909,18 +7850,73 @@ var starknet = (() => {
7909
7850
  let point = PEDERSEN_POINTS[0];
7910
7851
  point = pedersenSingle(point, x, PEDERSEN_POINTS1);
7911
7852
  point = pedersenSingle(point, y, PEDERSEN_POINTS2);
7912
- return bytesToHexEth(point.toAffine().toRawBytes(true).slice(1));
7853
+ return extractX(point.toRawBytes(true));
7913
7854
  }
7914
7855
  function hashChain(data, fn = pedersen) {
7915
7856
  if (!Array.isArray(data) || data.length < 1)
7916
7857
  throw new Error("data should be array of at least 1 element");
7917
7858
  if (data.length === 1)
7918
- return numberToHexEth(pedersenArg(data[0]));
7859
+ return numberTo0x16(pedersenArg(data[0]));
7919
7860
  return Array.from(data).reverse().reduce((acc, i) => fn(i, acc));
7920
7861
  }
7921
7862
  var computeHashOnElements = (data, fn = pedersen) => [0, ...data, data.length].reduce((x, y) => fn(x, y));
7922
- var MASK_2502 = 2n ** 250n - 1n;
7923
- var keccak = (data) => bytesToNumber0x(keccak_256(data)) & MASK_2502;
7863
+ var MASK_2502 = bitMask(250);
7864
+ var keccak = (data) => bytesToNumberBE(keccak_256(data)) & MASK_2502;
7865
+ var sha256Num = (data) => bytesToNumberBE(sha256(data));
7866
+ var Fp253 = Fp(BigInt("14474011154664525231415395255581126252639794253786371766033694892385558855681"));
7867
+ var Fp251 = Fp(BigInt("3618502788666131213697322783095070105623107215331596699973092056135872020481"));
7868
+ function poseidonRoundConstant(Fp2, name, idx) {
7869
+ const val = Fp2.fromBytes(sha256(utf8ToBytes(`${name}${idx}`)));
7870
+ return Fp2.create(val);
7871
+ }
7872
+ function _poseidonMDS(Fp2, name, m, attempt = 0) {
7873
+ const x_values = [];
7874
+ const y_values = [];
7875
+ for (let i = 0; i < m; i++) {
7876
+ x_values.push(poseidonRoundConstant(Fp2, `${name}x`, attempt * m + i));
7877
+ y_values.push(poseidonRoundConstant(Fp2, `${name}y`, attempt * m + i));
7878
+ }
7879
+ if ((/* @__PURE__ */ new Set([...x_values, ...y_values])).size !== 2 * m)
7880
+ throw new Error("X and Y values are not distinct");
7881
+ return x_values.map((x) => y_values.map((y) => Fp2.inv(Fp2.sub(x, y))));
7882
+ }
7883
+ var MDS_SMALL = [
7884
+ [3, 1, 1],
7885
+ [1, -1, 1],
7886
+ [1, 1, -2]
7887
+ ].map((i) => i.map(BigInt));
7888
+ function poseidonBasic(opts, mds) {
7889
+ validateField(opts.Fp);
7890
+ if (!Number.isSafeInteger(opts.rate) || !Number.isSafeInteger(opts.capacity))
7891
+ throw new Error(`Wrong poseidon opts: ${opts}`);
7892
+ const m = opts.rate + opts.capacity;
7893
+ const rounds = opts.roundsFull + opts.roundsPartial;
7894
+ const roundConstants = [];
7895
+ for (let i = 0; i < rounds; i++) {
7896
+ const row = [];
7897
+ for (let j = 0; j < m; j++)
7898
+ row.push(poseidonRoundConstant(opts.Fp, "Hades", m * i + j));
7899
+ roundConstants.push(row);
7900
+ }
7901
+ return poseidon({
7902
+ ...opts,
7903
+ t: m,
7904
+ sboxPower: 3,
7905
+ reversePartialPowIdx: true,
7906
+ mds,
7907
+ roundConstants
7908
+ });
7909
+ }
7910
+ function poseidonCreate(opts, mdsAttempt = 0) {
7911
+ const m = opts.rate + opts.capacity;
7912
+ if (!Number.isSafeInteger(mdsAttempt))
7913
+ throw new Error(`Wrong mdsAttempt=${mdsAttempt}`);
7914
+ return poseidonBasic(opts, _poseidonMDS(opts.Fp, "HadesMDS", m, mdsAttempt));
7915
+ }
7916
+ var poseidonSmall = poseidonBasic({ Fp: Fp251, rate: 2, capacity: 1, roundsFull: 8, roundsPartial: 83 }, MDS_SMALL);
7917
+ function poseidonHash(x, y, fn = poseidonSmall) {
7918
+ return fn([x, y, 2n])[0];
7919
+ }
7924
7920
 
7925
7921
  // src/utils/json.ts
7926
7922
  var json_exports = {};
@@ -7950,7 +7946,7 @@ var starknet = (() => {
7950
7946
  function keccakBn(value) {
7951
7947
  const hexWithoutPrefix = removeHexPrefix(toHex(BigInt(value)));
7952
7948
  const evenHex = hexWithoutPrefix.length % 2 === 0 ? hexWithoutPrefix : `0${hexWithoutPrefix}`;
7953
- return addHexPrefix(buf2hex((0, import_keccak.keccak256)((0, import_utils8.hexToBytes)(evenHex))));
7949
+ return addHexPrefix(buf2hex((0, import_keccak.keccak256)((0, import_utils11.hexToBytes)(evenHex))));
7954
7950
  }
7955
7951
  function keccakHex(value) {
7956
7952
  return addHexPrefix(buf2hex((0, import_keccak.keccak256)(utf8ToArray(value))));
@@ -15413,6 +15409,9 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
15413
15409
  function validateChecksumAddress(address) {
15414
15410
  return getChecksumAddress(address) === address;
15415
15411
  }
15412
+
15413
+ // src/index.ts
15414
+ var number2 = num_exports;
15416
15415
  return __toCommonJS(src_exports);
15417
15416
  })();
15418
15417
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */