@0xpolygonid/js-sdk 1.17.6 → 1.17.8

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.
@@ -2339,9 +2339,9 @@ const sha512$1 = /* @__PURE__ */ wrapConstructor$1(() => new SHA512$1());
2339
2339
  // This is OK: `abstract` directory does not use noble-hashes.
2340
2340
  // User may opt-in into using different hashing library. This way, noble-hashes
2341
2341
  // won't be included into their bundle.
2342
- const _0n$a = BigInt(0);
2343
- const _1n$d = BigInt(1);
2344
- const _2n$9 = BigInt(2);
2342
+ const _0n$a = /* @__PURE__ */ BigInt(0);
2343
+ const _1n$d = /* @__PURE__ */ BigInt(1);
2344
+ const _2n$9 = /* @__PURE__ */ BigInt(2);
2345
2345
  function isBytes$1(a) {
2346
2346
  return (a instanceof Uint8Array ||
2347
2347
  (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
@@ -2350,6 +2350,10 @@ function abytes(item) {
2350
2350
  if (!isBytes$1(item))
2351
2351
  throw new Error('Uint8Array expected');
2352
2352
  }
2353
+ function abool(title, value) {
2354
+ if (typeof value !== 'boolean')
2355
+ throw new Error(`${title} must be valid boolean, got "${value}".`);
2356
+ }
2353
2357
  // Array where index 0xf0 (240) is mapped to string 'f0'
2354
2358
  const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
2355
2359
  /**
@@ -2492,6 +2496,25 @@ function utf8ToBytes$2(str) {
2492
2496
  throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
2493
2497
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
2494
2498
  }
2499
+ // Is positive bigint
2500
+ const isPosBig = (n) => typeof n === 'bigint' && _0n$a <= n;
2501
+ function inRange(n, min, max) {
2502
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
2503
+ }
2504
+ /**
2505
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
2506
+ * @example
2507
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
2508
+ */
2509
+ function aInRange(title, n, min, max) {
2510
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
2511
+ // consider P=256n, min=0n, max=P
2512
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
2513
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
2514
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
2515
+ if (!inRange(n, min, max))
2516
+ throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
2517
+ }
2495
2518
  // Bit operations
2496
2519
  /**
2497
2520
  * Calculates amount of bits in a bigint.
@@ -2622,9 +2645,32 @@ function validateObject$1(object, validators, optValidators = {}) {
2622
2645
  // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
2623
2646
  // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
2624
2647
  // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
2648
+ /**
2649
+ * throws not implemented error
2650
+ */
2651
+ const notImplemented = () => {
2652
+ throw new Error('not implemented');
2653
+ };
2654
+ /**
2655
+ * Memoizes (caches) computation result.
2656
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
2657
+ */
2658
+ function memoized(fn) {
2659
+ const map = new WeakMap();
2660
+ return (arg, ...args) => {
2661
+ const val = map.get(arg);
2662
+ if (val !== undefined)
2663
+ return val;
2664
+ const computed = fn(arg, ...args);
2665
+ map.set(arg, computed);
2666
+ return computed;
2667
+ };
2668
+ }
2625
2669
 
2626
2670
  var ut$1 = /*#__PURE__*/Object.freeze({
2627
2671
  __proto__: null,
2672
+ aInRange: aInRange,
2673
+ abool: abool,
2628
2674
  abytes: abytes,
2629
2675
  bitGet: bitGet$1,
2630
2676
  bitLen: bitLen$1,
@@ -2639,7 +2685,10 @@ var ut$1 = /*#__PURE__*/Object.freeze({
2639
2685
  equalBytes: equalBytes$1,
2640
2686
  hexToBytes: hexToBytes$2,
2641
2687
  hexToNumber: hexToNumber$1,
2688
+ inRange: inRange,
2642
2689
  isBytes: isBytes$1,
2690
+ memoized: memoized,
2691
+ notImplemented: notImplemented,
2643
2692
  numberToBytesBE: numberToBytesBE$1,
2644
2693
  numberToBytesLE: numberToBytesLE$1,
2645
2694
  numberToHexUnpadded: numberToHexUnpadded$1,
@@ -2653,7 +2702,7 @@ var ut$1 = /*#__PURE__*/Object.freeze({
2653
2702
  // prettier-ignore
2654
2703
  const _0n$9 = BigInt(0), _1n$c = BigInt(1), _2n$8 = BigInt(2), _3n$3 = BigInt(3);
2655
2704
  // prettier-ignore
2656
- const _4n$1 = BigInt(4), _5n$2 = BigInt(5), _8n$2 = BigInt(8);
2705
+ const _4n$1 = BigInt(4), _5n$2 = BigInt(5), _8n$3 = BigInt(8);
2657
2706
  // prettier-ignore
2658
2707
  BigInt(9); BigInt(16);
2659
2708
  // Calculates a modulo b
@@ -2799,8 +2848,8 @@ function FpSqrt$1(P) {
2799
2848
  };
2800
2849
  }
2801
2850
  // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
2802
- if (P % _8n$2 === _5n$2) {
2803
- const c1 = (P - _5n$2) / _8n$2;
2851
+ if (P % _8n$3 === _5n$2) {
2852
+ const c1 = (P - _5n$2) / _8n$3;
2804
2853
  return function sqrt5mod8(Fp, n) {
2805
2854
  const n2 = Fp.mul(n, _2n$8);
2806
2855
  const v = Fp.pow(n2, c1);
@@ -2898,6 +2947,9 @@ function nLength$1(n, nBitLength) {
2898
2947
  * * a) denormalized operations like mulN instead of mul
2899
2948
  * * b) same object shape: never add or remove keys
2900
2949
  * * c) Object.freeze
2950
+ * NOTE: operations don't check 'isValid' for all elements for performance reasons,
2951
+ * it is caller responsibility to check this.
2952
+ * This is low-level code, please make sure you know what you doing.
2901
2953
  * @param ORDER prime positive bigint
2902
2954
  * @param bitLen how many bits the field consumes
2903
2955
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -2953,12 +3005,6 @@ function Field$1(ORDER, bitLen, isLE = false, redef = {}) {
2953
3005
  });
2954
3006
  return Object.freeze(f);
2955
3007
  }
2956
- function FpSqrtEven(Fp, elm) {
2957
- if (!Fp.isOdd)
2958
- throw new Error(`Field doesn't have isOdd`);
2959
- const root = Fp.sqrt(elm);
2960
- return Fp.isOdd(root) ? Fp.neg(root) : root;
2961
- }
2962
3008
  /**
2963
3009
  * Returns total number of bytes consumed by the field element.
2964
3010
  * For example, 32 bytes for usual 256-bit weierstrass curve.
@@ -3012,6 +3058,10 @@ function mapHashToField$1(key, fieldOrder, isLE = false) {
3012
3058
  // Abelian group utilities
3013
3059
  const _0n$8 = BigInt(0);
3014
3060
  const _1n$b = BigInt(1);
3061
+ // Since points in different groups cannot be equal (different object constructor),
3062
+ // we can have single place to store precomputes
3063
+ const pointPrecomputes = new WeakMap();
3064
+ const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
3015
3065
  // Elliptic curve multiplication of Point by scalar. Fragile.
3016
3066
  // Scalars should always be less than curve order: this should be checked inside of a curve itself.
3017
3067
  // Creates precomputation tables for fast multiplication:
@@ -3028,7 +3078,12 @@ function wNAF$1(c, bits) {
3028
3078
  const neg = item.negate();
3029
3079
  return condition ? neg : item;
3030
3080
  };
3081
+ const validateW = (W) => {
3082
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
3083
+ throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
3084
+ };
3031
3085
  const opts = (W) => {
3086
+ validateW(W);
3032
3087
  const windows = Math.ceil(bits / W) + 1; // +1, because
3033
3088
  const windowSize = 2 ** (W - 1); // -1 because we skip zero
3034
3089
  return { windows, windowSize };
@@ -3128,19 +3183,25 @@ function wNAF$1(c, bits) {
3128
3183
  // which makes it less const-time: around 1 bigint multiply.
3129
3184
  return { p, f };
3130
3185
  },
3131
- wNAFCached(P, precomputesMap, n, transform) {
3132
- // @ts-ignore
3133
- const W = P._WINDOW_SIZE || 1;
3186
+ wNAFCached(P, n, transform) {
3187
+ const W = pointWindowSizes.get(P) || 1;
3134
3188
  // Calculate precomputes on a first run, reuse them after
3135
- let comp = precomputesMap.get(P);
3189
+ let comp = pointPrecomputes.get(P);
3136
3190
  if (!comp) {
3137
3191
  comp = this.precomputeWindow(P, W);
3138
- if (W !== 1) {
3139
- precomputesMap.set(P, transform(comp));
3140
- }
3192
+ if (W !== 1)
3193
+ pointPrecomputes.set(P, transform(comp));
3141
3194
  }
3142
3195
  return this.wNAF(W, comp, n);
3143
3196
  },
3197
+ // We calculate precomputes for elliptic curve point multiplication
3198
+ // using windowed method. This specifies window size and
3199
+ // stores precomputed values. Usually only base point would be precomputed.
3200
+ setWindowSize(P, W) {
3201
+ validateW(W);
3202
+ pointWindowSizes.set(P, W);
3203
+ pointPrecomputes.delete(P);
3204
+ },
3144
3205
  };
3145
3206
  }
3146
3207
  function validateBasic$1(curve) {
@@ -3166,7 +3227,7 @@ function validateBasic$1(curve) {
3166
3227
  // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
3167
3228
  // Be friendly to bad ECMAScript parsers by not using bigint literals
3168
3229
  // prettier-ignore
3169
- const _0n$7 = BigInt(0), _1n$a = BigInt(1), _2n$7 = BigInt(2), _8n$1 = BigInt(8);
3230
+ const _0n$7 = BigInt(0), _1n$a = BigInt(1), _2n$7 = BigInt(2), _8n$2 = BigInt(8);
3170
3231
  // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
3171
3232
  const VERIFY_DEFAULT = { zip215: true };
3172
3233
  function validateOpts$2(curve) {
@@ -3185,7 +3246,13 @@ function validateOpts$2(curve) {
3185
3246
  // Set defaults
3186
3247
  return Object.freeze({ ...opts });
3187
3248
  }
3188
- // It is not generic twisted curve for now, but ed25519/ed448 generic implementation
3249
+ /**
3250
+ * Creates Twisted Edwards curve with EdDSA signatures.
3251
+ * @example
3252
+ * import { Field } from '@noble/curves/abstract/modular';
3253
+ * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h
3254
+ * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })
3255
+ */
3189
3256
  function twistedEdwards(curveDef) {
3190
3257
  const CURVE = validateOpts$2(curveDef);
3191
3258
  const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
@@ -3204,28 +3271,59 @@ function twistedEdwards(curveDef) {
3204
3271
  const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP
3205
3272
  const domain = CURVE.domain ||
3206
3273
  ((data, ctx, phflag) => {
3274
+ abool('phflag', phflag);
3207
3275
  if (ctx.length || phflag)
3208
3276
  throw new Error('Contexts/pre-hash are not supported');
3209
3277
  return data;
3210
3278
  }); // NOOP
3211
- const inBig = (n) => typeof n === 'bigint' && _0n$7 < n; // n in [1..]
3212
- const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]
3213
- const in0MaskRange = (n) => n === _0n$7 || inRange(n, MASK); // n in [0..MASK-1]
3214
- function assertInRange(n, max) {
3215
- // n in [1..max-1]
3216
- if (inRange(n, max))
3217
- return n;
3218
- throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);
3219
- }
3220
- function assertGE0(n) {
3221
- // n in [0..CURVE_ORDER-1]
3222
- return n === _0n$7 ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group
3279
+ // 0 <= n < MASK
3280
+ // Coordinates larger than Fp.ORDER are allowed for zip215
3281
+ function aCoordinate(title, n) {
3282
+ aInRange('coordinate ' + title, n, _0n$7, MASK);
3223
3283
  }
3224
- const pointPrecomputes = new Map();
3225
- function isPoint(other) {
3284
+ function assertPoint(other) {
3226
3285
  if (!(other instanceof Point))
3227
3286
  throw new Error('ExtendedPoint expected');
3228
3287
  }
3288
+ // Converts Extended point to default (x, y) coordinates.
3289
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
3290
+ const toAffineMemo = memoized((p, iz) => {
3291
+ const { ex: x, ey: y, ez: z } = p;
3292
+ const is0 = p.is0();
3293
+ if (iz == null)
3294
+ iz = is0 ? _8n$2 : Fp.inv(z); // 8 was chosen arbitrarily
3295
+ const ax = modP(x * iz);
3296
+ const ay = modP(y * iz);
3297
+ const zz = modP(z * iz);
3298
+ if (is0)
3299
+ return { x: _0n$7, y: _1n$a };
3300
+ if (zz !== _1n$a)
3301
+ throw new Error('invZ was invalid');
3302
+ return { x: ax, y: ay };
3303
+ });
3304
+ const assertValidMemo = memoized((p) => {
3305
+ const { a, d } = CURVE;
3306
+ if (p.is0())
3307
+ throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
3308
+ // Equation in affine coordinates: ax² + y² = 1 + dx²y²
3309
+ // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
3310
+ const { ex: X, ey: Y, ez: Z, et: T } = p;
3311
+ const X2 = modP(X * X); // X²
3312
+ const Y2 = modP(Y * Y); // Y²
3313
+ const Z2 = modP(Z * Z); // Z²
3314
+ const Z4 = modP(Z2 * Z2); // Z⁴
3315
+ const aX2 = modP(X2 * a); // aX²
3316
+ const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
3317
+ const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
3318
+ if (left !== right)
3319
+ throw new Error('bad point: equation left != right (1)');
3320
+ // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
3321
+ const XY = modP(X * Y);
3322
+ const ZT = modP(Z * T);
3323
+ if (XY !== ZT)
3324
+ throw new Error('bad point: equation left != right (2)');
3325
+ return true;
3326
+ });
3229
3327
  // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).
3230
3328
  // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
3231
3329
  class Point {
@@ -3234,14 +3332,11 @@ function twistedEdwards(curveDef) {
3234
3332
  this.ey = ey;
3235
3333
  this.ez = ez;
3236
3334
  this.et = et;
3237
- if (!in0MaskRange(ex))
3238
- throw new Error('x required');
3239
- if (!in0MaskRange(ey))
3240
- throw new Error('y required');
3241
- if (!in0MaskRange(ez))
3242
- throw new Error('z required');
3243
- if (!in0MaskRange(et))
3244
- throw new Error('t required');
3335
+ aCoordinate('x', ex);
3336
+ aCoordinate('y', ey);
3337
+ aCoordinate('z', ez);
3338
+ aCoordinate('t', et);
3339
+ Object.freeze(this);
3245
3340
  }
3246
3341
  get x() {
3247
3342
  return this.toAffine().x;
@@ -3253,8 +3348,8 @@ function twistedEdwards(curveDef) {
3253
3348
  if (p instanceof Point)
3254
3349
  throw new Error('extended point not allowed');
3255
3350
  const { x, y } = p || {};
3256
- if (!in0MaskRange(x) || !in0MaskRange(y))
3257
- throw new Error('invalid affine point');
3351
+ aCoordinate('x', x);
3352
+ aCoordinate('y', y);
3258
3353
  return new Point(x, y, _1n$a, modP(x * y));
3259
3354
  }
3260
3355
  static normalizeZ(points) {
@@ -3263,36 +3358,16 @@ function twistedEdwards(curveDef) {
3263
3358
  }
3264
3359
  // "Private method", don't use it directly
3265
3360
  _setWindowSize(windowSize) {
3266
- this._WINDOW_SIZE = windowSize;
3267
- pointPrecomputes.delete(this);
3361
+ wnaf.setWindowSize(this, windowSize);
3268
3362
  }
3269
3363
  // Not required for fromHex(), which always creates valid points.
3270
3364
  // Could be useful for fromAffine().
3271
3365
  assertValidity() {
3272
- const { a, d } = CURVE;
3273
- if (this.is0())
3274
- throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
3275
- // Equation in affine coordinates: ax² + y² = 1 + dx²y²
3276
- // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
3277
- const { ex: X, ey: Y, ez: Z, et: T } = this;
3278
- const X2 = modP(X * X); // X²
3279
- const Y2 = modP(Y * Y); // Y²
3280
- const Z2 = modP(Z * Z); // Z²
3281
- const Z4 = modP(Z2 * Z2); // Z⁴
3282
- const aX2 = modP(X2 * a); // aX²
3283
- const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
3284
- const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
3285
- if (left !== right)
3286
- throw new Error('bad point: equation left != right (1)');
3287
- // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
3288
- const XY = modP(X * Y);
3289
- const ZT = modP(Z * T);
3290
- if (XY !== ZT)
3291
- throw new Error('bad point: equation left != right (2)');
3366
+ assertValidMemo(this);
3292
3367
  }
3293
3368
  // Compare one point to another.
3294
3369
  equals(other) {
3295
- isPoint(other);
3370
+ assertPoint(other);
3296
3371
  const { ex: X1, ey: Y1, ez: Z1 } = this;
3297
3372
  const { ex: X2, ey: Y2, ez: Z2 } = other;
3298
3373
  const X1Z2 = modP(X1 * Z2);
@@ -3333,7 +3408,7 @@ function twistedEdwards(curveDef) {
3333
3408
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
3334
3409
  // Cost: 9M + 1*a + 1*d + 7add.
3335
3410
  add(other) {
3336
- isPoint(other);
3411
+ assertPoint(other);
3337
3412
  const { a, d } = CURVE;
3338
3413
  const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
3339
3414
  const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
@@ -3376,11 +3451,13 @@ function twistedEdwards(curveDef) {
3376
3451
  return this.add(other.negate());
3377
3452
  }
3378
3453
  wNAF(n) {
3379
- return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);
3454
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
3380
3455
  }
3381
3456
  // Constant-time multiplication.
3382
3457
  multiply(scalar) {
3383
- const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));
3458
+ const n = scalar;
3459
+ aInRange('scalar', n, _1n$a, CURVE_ORDER); // 1 <= scalar < L
3460
+ const { p, f } = this.wNAF(n);
3384
3461
  return Point.normalizeZ([p, f])[0];
3385
3462
  }
3386
3463
  // Non-constant-time multiplication. Uses double-and-add algorithm.
@@ -3388,7 +3465,8 @@ function twistedEdwards(curveDef) {
3388
3465
  // an exposed private key e.g. sig verification.
3389
3466
  // Does NOT allow scalars higher than CURVE.n.
3390
3467
  multiplyUnsafe(scalar) {
3391
- let n = assertGE0(scalar); // 0 <= scalar < CURVE.n
3468
+ const n = scalar;
3469
+ aInRange('scalar', n, _0n$7, CURVE_ORDER); // 0 <= scalar < L
3392
3470
  if (n === _0n$7)
3393
3471
  return I;
3394
3472
  if (this.equals(I) || n === _1n$a)
@@ -3412,18 +3490,7 @@ function twistedEdwards(curveDef) {
3412
3490
  // Converts Extended point to default (x, y) coordinates.
3413
3491
  // Can accept precomputed Z^-1 - for example, from invertBatch.
3414
3492
  toAffine(iz) {
3415
- const { ex: x, ey: y, ez: z } = this;
3416
- const is0 = this.is0();
3417
- if (iz == null)
3418
- iz = is0 ? _8n$1 : Fp.inv(z); // 8 was chosen arbitrarily
3419
- const ax = modP(x * iz);
3420
- const ay = modP(y * iz);
3421
- const zz = modP(z * iz);
3422
- if (is0)
3423
- return { x: _0n$7, y: _1n$a };
3424
- if (zz !== _1n$a)
3425
- throw new Error('invZ was invalid');
3426
- return { x: ax, y: ay };
3493
+ return toAffineMemo(this, iz);
3427
3494
  }
3428
3495
  clearCofactor() {
3429
3496
  const { h: cofactor } = CURVE;
@@ -3437,18 +3504,16 @@ function twistedEdwards(curveDef) {
3437
3504
  const { d, a } = CURVE;
3438
3505
  const len = Fp.BYTES;
3439
3506
  hex = ensureBytes$1('pointHex', hex, len); // copy hex to a new array
3507
+ abool('zip215', zip215);
3440
3508
  const normed = hex.slice(); // copy again, we'll manipulate it
3441
3509
  const lastByte = hex[len - 1]; // select last byte
3442
3510
  normed[len - 1] = lastByte & ~0x80; // clear last bit
3443
3511
  const y = bytesToNumberLE$1(normed);
3444
- if (y === _0n$7) ;
3445
- else {
3446
- // RFC8032 prohibits >= p, but ZIP215 doesn't
3447
- if (zip215)
3448
- assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)
3449
- else
3450
- assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)
3451
- }
3512
+ // RFC8032 prohibits >= p, but ZIP215 doesn't
3513
+ // zip215=true: 0 <= y < MASK (2^256 for ed25519)
3514
+ // zip215=false: 0 <= y < P (2^255-19 for ed25519)
3515
+ const max = zip215 ? MASK : Fp.ORDER;
3516
+ aInRange('pointHex.y', y, _0n$7, max);
3452
3517
  // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
3453
3518
  // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
3454
3519
  const y2 = modP(y * y); // denominator is always non-0 mod p.
@@ -3523,7 +3588,7 @@ function twistedEdwards(curveDef) {
3523
3588
  const R = G.multiply(r).toRawBytes(); // R = rG
3524
3589
  const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
3525
3590
  const s = modN(r + k * scalar); // S = (r + k * s) mod L
3526
- assertGE0(s); // 0 <= s < l
3591
+ aInRange('signature.s', s, _0n$7, CURVE_ORDER); // 0 <= s < l
3527
3592
  const res = concatBytes$2(R, numberToBytesLE$1(s, Fp.BYTES));
3528
3593
  return ensureBytes$1('result', res, nByteLength * 2); // 64-byte signature
3529
3594
  }
@@ -3533,6 +3598,8 @@ function twistedEdwards(curveDef) {
3533
3598
  const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
3534
3599
  sig = ensureBytes$1('signature', sig, 2 * len); // An extended group equation is checked.
3535
3600
  msg = ensureBytes$1('message', msg);
3601
+ if (zip215 !== undefined)
3602
+ abool('zip215', zip215);
3536
3603
  if (prehash)
3537
3604
  msg = prehash(msg); // for ed25519ph, etc
3538
3605
  const s = bytesToNumberLE$1(sig.slice(len, 2 * len));
@@ -3590,12 +3657,14 @@ function twistedEdwards(curveDef) {
3590
3657
  */
3591
3658
  const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
3592
3659
  // √(-1) aka √(a) aka 2^((p-1)/4)
3593
- const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
3660
+ const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
3594
3661
  // prettier-ignore
3595
- BigInt(0); const _1n$9 = BigInt(1), _2n$6 = BigInt(2), _5n$1 = BigInt(5);
3662
+ BigInt(0); const _1n$9 = BigInt(1), _2n$6 = BigInt(2); BigInt(3);
3596
3663
  // prettier-ignore
3597
- const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
3664
+ const _5n$1 = BigInt(5), _8n$1 = BigInt(8);
3598
3665
  function ed25519_pow_2_252_3(x) {
3666
+ // prettier-ignore
3667
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
3599
3668
  const P = ED25519_P;
3600
3669
  const x2 = (x * x) % P;
3601
3670
  const b2 = (x2 * x) % P; // x^3, 11
@@ -3644,8 +3713,8 @@ function uvRatio(u, v) {
3644
3713
  x = mod$1(-x, P);
3645
3714
  return { isValid: useRoot1 || useRoot2, value: x };
3646
3715
  }
3647
- const Fp$3 = Field$1(ED25519_P, undefined, true);
3648
- const ed25519Defaults = {
3716
+ const Fp$3 = /* @__PURE__ */ (() => Field$1(ED25519_P, undefined, true))();
3717
+ const ed25519Defaults = /* @__PURE__ */ (() => ({
3649
3718
  // Param: a
3650
3719
  a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
3651
3720
  // d is equal to -121665/121666 over finite field.
@@ -3657,7 +3726,7 @@ const ed25519Defaults = {
3657
3726
  // 2n**252n + 27742317777372353535851937790883648493n;
3658
3727
  n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
3659
3728
  // Cofactor
3660
- h: BigInt(8),
3729
+ h: _8n$1,
3661
3730
  // Base point (x, y) aka generator point
3662
3731
  Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
3663
3732
  Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
@@ -3668,26 +3737,11 @@ const ed25519Defaults = {
3668
3737
  // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
3669
3738
  // Constant-time, u/√v
3670
3739
  uvRatio,
3671
- };
3672
- const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);
3673
- // Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)
3674
- // NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since
3675
- // SageMath returns different root first and everything falls apart
3676
- const ELL2_C1 = (Fp$3.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic
3677
- Fp$3.pow(_2n$6, ELL2_C1); // 2. c2 = 2^c1
3678
- Fp$3.sqrt(Fp$3.neg(Fp$3.ONE)); // 3. c3 = sqrt(-1)
3679
- (Fp$3.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic
3680
- BigInt(486662);
3681
- FpSqrtEven(Fp$3, Fp$3.neg(BigInt(486664))); // sgn0(c1) MUST equal 0
3682
- // √(ad - 1)
3683
- BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
3684
- // 1 / √(a-d)
3685
- BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
3686
- // 1-d²
3687
- BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
3688
- // (d-1)²
3689
- BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
3690
- BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
3740
+ }))();
3741
+ /**
3742
+ * ed25519 curve with EdDSA signatures.
3743
+ */
3744
+ const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
3691
3745
 
3692
3746
  /**
3693
3747
  * Provider for Ed25519 keys
@@ -3880,8 +3934,89 @@ let SHA256$1 = class SHA256 extends HashMD {
3880
3934
  */
3881
3935
  const sha256$3 = /* @__PURE__ */ wrapConstructor$1(() => new SHA256$1());
3882
3936
 
3937
+ // HMAC (RFC 2104)
3938
+ let HMAC$1 = class HMAC extends Hash$1 {
3939
+ constructor(hash, _key) {
3940
+ super();
3941
+ this.finished = false;
3942
+ this.destroyed = false;
3943
+ hash$1(hash);
3944
+ const key = toBytes$1(_key);
3945
+ this.iHash = hash.create();
3946
+ if (typeof this.iHash.update !== 'function')
3947
+ throw new Error('Expected instance of class which extends utils.Hash');
3948
+ this.blockLen = this.iHash.blockLen;
3949
+ this.outputLen = this.iHash.outputLen;
3950
+ const blockLen = this.blockLen;
3951
+ const pad = new Uint8Array(blockLen);
3952
+ // blockLen can be bigger than outputLen
3953
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
3954
+ for (let i = 0; i < pad.length; i++)
3955
+ pad[i] ^= 0x36;
3956
+ this.iHash.update(pad);
3957
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
3958
+ this.oHash = hash.create();
3959
+ // Undo internal XOR && apply outer XOR
3960
+ for (let i = 0; i < pad.length; i++)
3961
+ pad[i] ^= 0x36 ^ 0x5c;
3962
+ this.oHash.update(pad);
3963
+ pad.fill(0);
3964
+ }
3965
+ update(buf) {
3966
+ exists$1(this);
3967
+ this.iHash.update(buf);
3968
+ return this;
3969
+ }
3970
+ digestInto(out) {
3971
+ exists$1(this);
3972
+ bytes$1(out, this.outputLen);
3973
+ this.finished = true;
3974
+ this.iHash.digestInto(out);
3975
+ this.oHash.update(out);
3976
+ this.oHash.digestInto(out);
3977
+ this.destroy();
3978
+ }
3979
+ digest() {
3980
+ const out = new Uint8Array(this.oHash.outputLen);
3981
+ this.digestInto(out);
3982
+ return out;
3983
+ }
3984
+ _cloneInto(to) {
3985
+ // Create new instance without calling constructor since key already in state and we don't know it.
3986
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
3987
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
3988
+ to = to;
3989
+ to.finished = finished;
3990
+ to.destroyed = destroyed;
3991
+ to.blockLen = blockLen;
3992
+ to.outputLen = outputLen;
3993
+ to.oHash = oHash._cloneInto(to.oHash);
3994
+ to.iHash = iHash._cloneInto(to.iHash);
3995
+ return to;
3996
+ }
3997
+ destroy() {
3998
+ this.destroyed = true;
3999
+ this.oHash.destroy();
4000
+ this.iHash.destroy();
4001
+ }
4002
+ };
4003
+ /**
4004
+ * HMAC: RFC2104 message authentication code.
4005
+ * @param hash - function that would be used e.g. sha256
4006
+ * @param key - message key
4007
+ * @param message - message data
4008
+ */
4009
+ const hmac$1 = (hash, key, message) => new HMAC$1(hash, key).update(message).digest();
4010
+ hmac$1.create = (hash, key) => new HMAC$1(hash, key);
4011
+
3883
4012
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3884
4013
  // Short Weierstrass curve. The formula is: y² = x³ + ax + b
4014
+ function validateSigVerOpts(opts) {
4015
+ if (opts.lowS !== undefined)
4016
+ abool('lowS', opts.lowS);
4017
+ if (opts.prehash !== undefined)
4018
+ abool('prehash', opts.prehash);
4019
+ }
3885
4020
  function validatePointOpts$1(curve) {
3886
4021
  const opts = validateBasic$1(curve);
3887
4022
  validateObject$1(opts, {
@@ -4006,16 +4141,12 @@ function weierstrassPoints$1(opts) {
4006
4141
  throw new Error('bad generator point: equation left != right');
4007
4142
  // Valid group elements reside in range 1..n-1
4008
4143
  function isWithinCurveOrder(num) {
4009
- return typeof num === 'bigint' && _0n$6 < num && num < CURVE.n;
4010
- }
4011
- function assertGE(num) {
4012
- if (!isWithinCurveOrder(num))
4013
- throw new Error('Expected valid bigint: 0 < bigint < curve.n');
4144
+ return inRange(num, _1n$8, CURVE.n);
4014
4145
  }
4015
4146
  // Validates if priv key is valid and converts it to bigint.
4016
4147
  // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
4017
4148
  function normPrivateKeyToScalar(key) {
4018
- const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
4149
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
4019
4150
  if (lengths && typeof key !== 'bigint') {
4020
4151
  if (isBytes$1(key))
4021
4152
  key = bytesToHex$2(key);
@@ -4035,15 +4166,61 @@ function weierstrassPoints$1(opts) {
4035
4166
  throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
4036
4167
  }
4037
4168
  if (wrapPrivateKey)
4038
- num = mod$1(num, n); // disabled by default, enabled for BLS
4039
- assertGE(num); // num in range [1..N-1]
4169
+ num = mod$1(num, N); // disabled by default, enabled for BLS
4170
+ aInRange('private key', num, _1n$8, N); // num in range [1..N-1]
4040
4171
  return num;
4041
4172
  }
4042
- const pointPrecomputes = new Map();
4043
4173
  function assertPrjPoint(other) {
4044
4174
  if (!(other instanceof Point))
4045
4175
  throw new Error('ProjectivePoint expected');
4046
4176
  }
4177
+ // Memoized toAffine / validity check. They are heavy. Points are immutable.
4178
+ // Converts Projective point to affine (x, y) coordinates.
4179
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
4180
+ // (x, y, z) ∋ (x=x/z, y=y/z)
4181
+ const toAffineMemo = memoized((p, iz) => {
4182
+ const { px: x, py: y, pz: z } = p;
4183
+ // Fast-path for normalized points
4184
+ if (Fp.eql(z, Fp.ONE))
4185
+ return { x, y };
4186
+ const is0 = p.is0();
4187
+ // If invZ was 0, we return zero point. However we still want to execute
4188
+ // all operations, so we replace invZ with a random number, 1.
4189
+ if (iz == null)
4190
+ iz = is0 ? Fp.ONE : Fp.inv(z);
4191
+ const ax = Fp.mul(x, iz);
4192
+ const ay = Fp.mul(y, iz);
4193
+ const zz = Fp.mul(z, iz);
4194
+ if (is0)
4195
+ return { x: Fp.ZERO, y: Fp.ZERO };
4196
+ if (!Fp.eql(zz, Fp.ONE))
4197
+ throw new Error('invZ was invalid');
4198
+ return { x: ax, y: ay };
4199
+ });
4200
+ // NOTE: on exception this will crash 'cached' and no value will be set.
4201
+ // Otherwise true will be return
4202
+ const assertValidMemo = memoized((p) => {
4203
+ if (p.is0()) {
4204
+ // (0, 1, 0) aka ZERO is invalid in most contexts.
4205
+ // In BLS, ZERO can be serialized, so we allow it.
4206
+ // (0, 0, 0) is wrong representation of ZERO and is always invalid.
4207
+ if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
4208
+ return;
4209
+ throw new Error('bad point: ZERO');
4210
+ }
4211
+ // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
4212
+ const { x, y } = p.toAffine();
4213
+ // Check if x, y are valid field elements
4214
+ if (!Fp.isValid(x) || !Fp.isValid(y))
4215
+ throw new Error('bad point: x or y not FE');
4216
+ const left = Fp.sqr(y); // y²
4217
+ const right = weierstrassEquation(x); // x³ + ax + b
4218
+ if (!Fp.eql(left, right))
4219
+ throw new Error('bad point: equation left != right');
4220
+ if (!p.isTorsionFree())
4221
+ throw new Error('bad point: not in prime-order subgroup');
4222
+ return true;
4223
+ });
4047
4224
  /**
4048
4225
  * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
4049
4226
  * Default Point works in 2d / affine coordinates: (x, y)
@@ -4060,6 +4237,7 @@ function weierstrassPoints$1(opts) {
4060
4237
  throw new Error('y required');
4061
4238
  if (pz == null || !Fp.isValid(pz))
4062
4239
  throw new Error('z required');
4240
+ Object.freeze(this);
4063
4241
  }
4064
4242
  // Does not validate if the point is on-curve.
4065
4243
  // Use fromHex instead, or call assertValidity() later.
@@ -4106,30 +4284,11 @@ function weierstrassPoints$1(opts) {
4106
4284
  }
4107
4285
  // "Private method", don't use it directly
4108
4286
  _setWindowSize(windowSize) {
4109
- this._WINDOW_SIZE = windowSize;
4110
- pointPrecomputes.delete(this);
4287
+ wnaf.setWindowSize(this, windowSize);
4111
4288
  }
4112
4289
  // A point on curve is valid if it conforms to equation.
4113
4290
  assertValidity() {
4114
- if (this.is0()) {
4115
- // (0, 1, 0) aka ZERO is invalid in most contexts.
4116
- // In BLS, ZERO can be serialized, so we allow it.
4117
- // (0, 0, 0) is wrong representation of ZERO and is always invalid.
4118
- if (CURVE.allowInfinityPoint && !Fp.is0(this.py))
4119
- return;
4120
- throw new Error('bad point: ZERO');
4121
- }
4122
- // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
4123
- const { x, y } = this.toAffine();
4124
- // Check if x, y are valid field elements
4125
- if (!Fp.isValid(x) || !Fp.isValid(y))
4126
- throw new Error('bad point: x or y not FE');
4127
- const left = Fp.sqr(y); // y²
4128
- const right = weierstrassEquation(x); // x³ + ax + b
4129
- if (!Fp.eql(left, right))
4130
- throw new Error('bad point: equation left != right');
4131
- if (!this.isTorsionFree())
4132
- throw new Error('bad point: not in prime-order subgroup');
4291
+ assertValidMemo(this);
4133
4292
  }
4134
4293
  hasEvenY() {
4135
4294
  const { y } = this.toAffine();
@@ -4256,28 +4415,25 @@ function weierstrassPoints$1(opts) {
4256
4415
  return this.equals(Point.ZERO);
4257
4416
  }
4258
4417
  wNAF(n) {
4259
- return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
4260
- const toInv = Fp.invertBatch(comp.map((p) => p.pz));
4261
- return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
4262
- });
4418
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
4263
4419
  }
4264
4420
  /**
4265
4421
  * Non-constant-time multiplication. Uses double-and-add algorithm.
4266
4422
  * It's faster, but should only be used when you don't care about
4267
4423
  * an exposed private key e.g. sig verification, which works over *public* keys.
4268
4424
  */
4269
- multiplyUnsafe(n) {
4425
+ multiplyUnsafe(sc) {
4426
+ aInRange('scalar', sc, _0n$6, CURVE.n);
4270
4427
  const I = Point.ZERO;
4271
- if (n === _0n$6)
4428
+ if (sc === _0n$6)
4272
4429
  return I;
4273
- assertGE(n); // Will throw on 0
4274
- if (n === _1n$8)
4430
+ if (sc === _1n$8)
4275
4431
  return this;
4276
4432
  const { endo } = CURVE;
4277
4433
  if (!endo)
4278
- return wnaf.unsafeLadder(this, n);
4434
+ return wnaf.unsafeLadder(this, sc);
4279
4435
  // Apply endomorphism
4280
- let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
4436
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
4281
4437
  let k1p = I;
4282
4438
  let k2p = I;
4283
4439
  let d = this;
@@ -4307,12 +4463,11 @@ function weierstrassPoints$1(opts) {
4307
4463
  * @returns New point
4308
4464
  */
4309
4465
  multiply(scalar) {
4310
- assertGE(scalar);
4311
- let n = scalar;
4466
+ const { endo, n: N } = CURVE;
4467
+ aInRange('scalar', scalar, _1n$8, N);
4312
4468
  let point, fake; // Fake point is used to const-time mult
4313
- const { endo } = CURVE;
4314
4469
  if (endo) {
4315
- const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
4470
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
4316
4471
  let { p: k1p, f: f1p } = this.wNAF(k1);
4317
4472
  let { p: k2p, f: f2p } = this.wNAF(k2);
4318
4473
  k1p = wnaf.constTimeNegate(k1neg, k1p);
@@ -4322,7 +4477,7 @@ function weierstrassPoints$1(opts) {
4322
4477
  fake = f1p.add(f2p);
4323
4478
  }
4324
4479
  else {
4325
- const { p, f } = this.wNAF(n);
4480
+ const { p, f } = this.wNAF(scalar);
4326
4481
  point = p;
4327
4482
  fake = f;
4328
4483
  }
@@ -4346,20 +4501,7 @@ function weierstrassPoints$1(opts) {
4346
4501
  // Can accept precomputed Z^-1 - for example, from invertBatch.
4347
4502
  // (x, y, z) ∋ (x=x/z, y=y/z)
4348
4503
  toAffine(iz) {
4349
- const { px: x, py: y, pz: z } = this;
4350
- const is0 = this.is0();
4351
- // If invZ was 0, we return zero point. However we still want to execute
4352
- // all operations, so we replace invZ with a random number, 1.
4353
- if (iz == null)
4354
- iz = is0 ? Fp.ONE : Fp.inv(z);
4355
- const ax = Fp.mul(x, iz);
4356
- const ay = Fp.mul(y, iz);
4357
- const zz = Fp.mul(z, iz);
4358
- if (is0)
4359
- return { x: Fp.ZERO, y: Fp.ZERO };
4360
- if (!Fp.eql(zz, Fp.ONE))
4361
- throw new Error('invZ was invalid');
4362
- return { x: ax, y: ay };
4504
+ return toAffineMemo(this, iz);
4363
4505
  }
4364
4506
  isTorsionFree() {
4365
4507
  const { h: cofactor, isTorsionFree } = CURVE;
@@ -4378,10 +4520,12 @@ function weierstrassPoints$1(opts) {
4378
4520
  return this.multiplyUnsafe(CURVE.h);
4379
4521
  }
4380
4522
  toRawBytes(isCompressed = true) {
4523
+ abool('isCompressed', isCompressed);
4381
4524
  this.assertValidity();
4382
4525
  return toBytes(Point, this, isCompressed);
4383
4526
  }
4384
4527
  toHex(isCompressed = true) {
4528
+ abool('isCompressed', isCompressed);
4385
4529
  return bytesToHex$2(this.toRawBytes(isCompressed));
4386
4530
  }
4387
4531
  }
@@ -4411,14 +4555,18 @@ function validateOpts$1(curve) {
4411
4555
  });
4412
4556
  return Object.freeze({ lowS: true, ...opts });
4413
4557
  }
4558
+ /**
4559
+ * Creates short weierstrass curve and ECDSA signature methods for it.
4560
+ * @example
4561
+ * import { Field } from '@noble/curves/abstract/modular';
4562
+ * // Before that, define BigInt-s: a, b, p, n, Gx, Gy
4563
+ * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })
4564
+ */
4414
4565
  function weierstrass$1(curveDef) {
4415
4566
  const CURVE = validateOpts$1(curveDef);
4416
4567
  const { Fp, n: CURVE_ORDER } = CURVE;
4417
4568
  const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
4418
4569
  const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
4419
- function isValidFieldElement(num) {
4420
- return _0n$6 < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
4421
- }
4422
4570
  function modN(a) {
4423
4571
  return mod$1(a, CURVE_ORDER);
4424
4572
  }
@@ -4431,6 +4579,7 @@ function weierstrass$1(curveDef) {
4431
4579
  const a = point.toAffine();
4432
4580
  const x = Fp.toBytes(a.x);
4433
4581
  const cat = concatBytes$2;
4582
+ abool('isCompressed', isCompressed);
4434
4583
  if (isCompressed) {
4435
4584
  return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
4436
4585
  }
@@ -4445,7 +4594,7 @@ function weierstrass$1(curveDef) {
4445
4594
  // this.assertValidity() is done inside of fromHex
4446
4595
  if (len === compressedLen && (head === 0x02 || head === 0x03)) {
4447
4596
  const x = bytesToNumberBE$1(tail);
4448
- if (!isValidFieldElement(x))
4597
+ if (!inRange(x, _1n$8, Fp.ORDER))
4449
4598
  throw new Error('Point is not on curve');
4450
4599
  const y2 = weierstrassEquation(x); // y² = x³ + ax + b
4451
4600
  let y;
@@ -4506,11 +4655,8 @@ function weierstrass$1(curveDef) {
4506
4655
  return new Signature(r, s);
4507
4656
  }
4508
4657
  assertValidity() {
4509
- // can use assertGE here
4510
- if (!isWithinCurveOrder(this.r))
4511
- throw new Error('r must be 0 < r < CURVE.n');
4512
- if (!isWithinCurveOrder(this.s))
4513
- throw new Error('s must be 0 < s < CURVE.n');
4658
+ aInRange('r', this.r, _1n$8, CURVE_ORDER); // r in [1..N]
4659
+ aInRange('s', this.s, _1n$8, CURVE_ORDER); // s in [1..N]
4514
4660
  }
4515
4661
  addRecoveryBit(recovery) {
4516
4662
  return new Signature(this.r, this.s, recovery);
@@ -4653,10 +4799,7 @@ function weierstrass$1(curveDef) {
4653
4799
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
4654
4800
  */
4655
4801
  function int2octets(num) {
4656
- if (typeof num !== 'bigint')
4657
- throw new Error('bigint expected');
4658
- if (!(_0n$6 <= num && num < ORDER_MASK))
4659
- throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
4802
+ aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$6, ORDER_MASK);
4660
4803
  // works with order, can have different size than numToField!
4661
4804
  return numberToBytesBE$1(num, CURVE.nByteLength);
4662
4805
  }
@@ -4673,6 +4816,7 @@ function weierstrass$1(curveDef) {
4673
4816
  if (lowS == null)
4674
4817
  lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
4675
4818
  msgHash = ensureBytes$1('msgHash', msgHash);
4819
+ validateSigVerOpts(opts);
4676
4820
  if (prehash)
4677
4821
  msgHash = ensureBytes$1('prehashed msgHash', hash(msgHash));
4678
4822
  // We can't later call bits2octets, since nested bits2int is broken for curves
@@ -4759,6 +4903,7 @@ function weierstrass$1(curveDef) {
4759
4903
  publicKey = ensureBytes$1('publicKey', publicKey);
4760
4904
  if ('strict' in opts)
4761
4905
  throw new Error('options.strict was renamed to lowS');
4906
+ validateSigVerOpts(opts);
4762
4907
  const { lowS, prehash } = opts;
4763
4908
  let _sig = undefined;
4764
4909
  let P;
@@ -4816,81 +4961,6 @@ function weierstrass$1(curveDef) {
4816
4961
  };
4817
4962
  }
4818
4963
 
4819
- // HMAC (RFC 2104)
4820
- let HMAC$1 = class HMAC extends Hash$1 {
4821
- constructor(hash, _key) {
4822
- super();
4823
- this.finished = false;
4824
- this.destroyed = false;
4825
- hash$1(hash);
4826
- const key = toBytes$1(_key);
4827
- this.iHash = hash.create();
4828
- if (typeof this.iHash.update !== 'function')
4829
- throw new Error('Expected instance of class which extends utils.Hash');
4830
- this.blockLen = this.iHash.blockLen;
4831
- this.outputLen = this.iHash.outputLen;
4832
- const blockLen = this.blockLen;
4833
- const pad = new Uint8Array(blockLen);
4834
- // blockLen can be bigger than outputLen
4835
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
4836
- for (let i = 0; i < pad.length; i++)
4837
- pad[i] ^= 0x36;
4838
- this.iHash.update(pad);
4839
- // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
4840
- this.oHash = hash.create();
4841
- // Undo internal XOR && apply outer XOR
4842
- for (let i = 0; i < pad.length; i++)
4843
- pad[i] ^= 0x36 ^ 0x5c;
4844
- this.oHash.update(pad);
4845
- pad.fill(0);
4846
- }
4847
- update(buf) {
4848
- exists$1(this);
4849
- this.iHash.update(buf);
4850
- return this;
4851
- }
4852
- digestInto(out) {
4853
- exists$1(this);
4854
- bytes$1(out, this.outputLen);
4855
- this.finished = true;
4856
- this.iHash.digestInto(out);
4857
- this.oHash.update(out);
4858
- this.oHash.digestInto(out);
4859
- this.destroy();
4860
- }
4861
- digest() {
4862
- const out = new Uint8Array(this.oHash.outputLen);
4863
- this.digestInto(out);
4864
- return out;
4865
- }
4866
- _cloneInto(to) {
4867
- // Create new instance without calling constructor since key already in state and we don't know it.
4868
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
4869
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
4870
- to = to;
4871
- to.finished = finished;
4872
- to.destroyed = destroyed;
4873
- to.blockLen = blockLen;
4874
- to.outputLen = outputLen;
4875
- to.oHash = oHash._cloneInto(to.oHash);
4876
- to.iHash = iHash._cloneInto(to.iHash);
4877
- return to;
4878
- }
4879
- destroy() {
4880
- this.destroyed = true;
4881
- this.oHash.destroy();
4882
- this.iHash.destroy();
4883
- }
4884
- };
4885
- /**
4886
- * HMAC: RFC2104 message authentication code.
4887
- * @param hash - function that would be used e.g. sha256
4888
- * @param key - message key
4889
- * @param message - message data
4890
- */
4891
- const hmac$1 = (hash, key, message) => new HMAC$1(hash, key).update(message).digest();
4892
- hmac$1.create = (hash, key) => new HMAC$1(hash, key);
4893
-
4894
4964
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
4895
4965
  // connects noble-curves to noble-hashes
4896
4966
  function getHash$1(hash) {
@@ -4940,6 +5010,9 @@ function sqrtMod$1(y) {
4940
5010
  return root;
4941
5011
  }
4942
5012
  const Fp$2 = Field$1(secp256k1P$1, undefined, undefined, { sqrt: sqrtMod$1 });
5013
+ /**
5014
+ * secp256k1 short weierstrass curve and ECDSA signatures over it.
5015
+ */
4943
5016
  const secp256k1$1 = createCurve$1({
4944
5017
  a: BigInt(0), // equation params: a, b
4945
5018
  b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
@@ -6995,11 +7068,6 @@ function hexToBytes$1(s, minLength) {
6995
7068
  input = `0${input}`;
6996
7069
  }
6997
7070
 
6998
- if (minLength) {
6999
- const paddedLength = Math.max(input.length, minLength * 2);
7000
- input = input.padStart(paddedLength, '00');
7001
- }
7002
-
7003
7071
  return u8a$2.fromString(input.toLowerCase(), 'base16');
7004
7072
  }
7005
7073
  function decodeBase64url(s) {
@@ -7629,11 +7697,11 @@ class Iden3SparseMerkleTreeProof {
7629
7697
  const notEmpties = ne instanceof Uint8Array ? ne : new Uint8Array(Object.values(ne));
7630
7698
  const siblingsHashes = obj?.mtp?.siblings.map((h) => Hash$2.fromString(JSON.stringify(h)));
7631
7699
  const allSiblings = Proof.buildAllSiblings(obj?.mtp?.depth, notEmpties, siblingsHashes);
7632
- let nodeAux = undefined;
7633
- if (obj.mtp.nodeAux) {
7700
+ let nodeAux = obj.mtp.nodeAux || obj.mtp.node_aux;
7701
+ if (nodeAux) {
7634
7702
  nodeAux = {
7635
- key: Hash$2.fromString(JSON.stringify(obj.mtp.nodeAux.key)),
7636
- value: Hash$2.fromString(JSON.stringify(obj.mtp.nodeAux.value))
7703
+ key: Hash$2.fromString(JSON.stringify(nodeAux.key)),
7704
+ value: Hash$2.fromString(JSON.stringify(nodeAux.value))
7637
7705
  };
7638
7706
  }
7639
7707
  mtp = new Proof({ existence: obj?.mtp.existence, nodeAux: nodeAux, siblings: allSiblings });
@@ -19655,7 +19723,7 @@ class W3CCredential {
19655
19723
  }
19656
19724
  static fromJSON(obj) {
19657
19725
  const w = new W3CCredential();
19658
- Object.assign(w, obj);
19726
+ Object.assign(w, structuredClone(obj));
19659
19727
  w.proof = Array.isArray(w.proof)
19660
19728
  ? w.proof.map(W3CCredential.proofFromJSON)
19661
19729
  : W3CCredential.proofFromJSON(w.proof);
@@ -20496,16 +20564,6 @@ function v4(options, buf, offset) {
20496
20564
  rnds[6] = rnds[6] & 0x0f | 0x40;
20497
20565
  rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
20498
20566
 
20499
- if (buf) {
20500
- offset = offset || 0;
20501
-
20502
- for (let i = 0; i < 16; ++i) {
20503
- buf[offset + i] = rnds[i];
20504
- }
20505
-
20506
- return buf;
20507
- }
20508
-
20509
20567
  return unsafeStringify(rnds);
20510
20568
  }
20511
20569
 
@@ -30040,7 +30098,7 @@ const cacheLoader = (opts) => {
30040
30098
  /**
30041
30099
  * The current version of Ethers.
30042
30100
  */
30043
- const version = "6.13.1";
30101
+ const version = "6.13.2";
30044
30102
 
30045
30103
  /**
30046
30104
  * Property helper functions.
@@ -30265,7 +30323,7 @@ function assertArgumentCount(count, expectedCount, message) {
30265
30323
  expectedCount: expectedCount
30266
30324
  });
30267
30325
  }
30268
- const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => {
30326
+ ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => {
30269
30327
  try {
30270
30328
  // General test for normalize
30271
30329
  /* c8 ignore start */
@@ -30287,14 +30345,6 @@ const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => {
30287
30345
  catch (error) { }
30288
30346
  return accum;
30289
30347
  }, []);
30290
- /**
30291
- * Throws if the normalization %%form%% is not supported.
30292
- */
30293
- function assertNormalize(form) {
30294
- assert(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", {
30295
- operation: "String.prototype.normalize", info: { form }
30296
- });
30297
- }
30298
30348
  /**
30299
30349
  * Many classes use file-scoped values to guard the constructor,
30300
30350
  * making it effectively private. This facilitates that pattern
@@ -30939,10 +30989,6 @@ function getUtf8CodePoints(_bytes, onError) {
30939
30989
  */
30940
30990
  function toUtf8Bytes(str, form) {
30941
30991
  assertArgument(typeof (str) === "string", "invalid string value", "str", str);
30942
- if (form != null) {
30943
- assertNormalize(form);
30944
- str = str.normalize(form);
30945
- }
30946
30992
  let result = [];
30947
30993
  for (let i = 0; i < str.length; i++) {
30948
30994
  const c = str.charCodeAt(i);
@@ -37990,7 +38036,6 @@ function consume_emoji_reversed(cps, eaten) {
37990
38036
  let {V} = node;
37991
38037
  if (V) { // this is a valid emoji (so far)
37992
38038
  emoji = V;
37993
- if (eaten) eaten.push(...cps.slice(pos).reverse()); // (optional) copy input, used for ens_tokenize()
37994
38039
  cps.length = pos; // truncate
37995
38040
  }
37996
38041
  }
@@ -38057,7 +38102,7 @@ function namehash(name) {
38057
38102
  * as the wildcard resolution.
38058
38103
  */
38059
38104
  function dnsEncode(name, _maxLength) {
38060
- const length = (_maxLength != null) ? _maxLength : 63;
38105
+ const length = _maxLength ;
38061
38106
  assertArgument(length <= 255, "DNS encoded label cannot exceed 255", "length", length);
38062
38107
  return hexlify(concat(ensNameSplit(name).map((comp) => {
38063
38108
  assertArgument(comp.length <= length, `label ${JSON.stringify(name)} exceeds ${length} bytes`, "name", name);
@@ -48052,7 +48097,7 @@ class JsonRpcSigner extends AbstractSigner {
48052
48097
  // If the network changed: calling again will also fail
48053
48098
  // If unsupported: likely destroyed
48054
48099
  if (isError(error, "CANCELLED") || isError(error, "BAD_DATA") ||
48055
- isError(error, "NETWORK_ERROR" )) {
48100
+ isError(error, "NETWORK_ERROR")) {
48056
48101
  if (error.info == null) {
48057
48102
  error.info = {};
48058
48103
  }
@@ -53030,18 +53075,12 @@ class OnChainRevocationStorage {
53030
53075
  let nodeAux = undefined;
53031
53076
  const siblings = mtp.siblings?.map((s) => s.toString());
53032
53077
  if (mtp.auxExistence) {
53033
- const auxIndex = BigInt(mtp.auxIndex.toString());
53034
- const auxValue = BigInt(mtp.auxValue.toString());
53035
53078
  nodeAux = {
53036
- key: auxIndex.toString(),
53037
- value: auxValue.toString()
53079
+ key: mtp.auxIndex.toString(),
53080
+ value: mtp.auxValue.toString()
53038
53081
  };
53039
53082
  }
53040
- return Proof.fromJSON({
53041
- existence: mtp.existence,
53042
- nodeAux,
53043
- siblings
53044
- });
53083
+ return Proof.fromJSON({ existence: mtp.existence, node_aux: nodeAux, siblings });
53045
53084
  }
53046
53085
  }
53047
53086
 
@@ -54130,13 +54169,8 @@ class IssuerResolver {
54130
54169
  * @returns {RevocationStatus} RevocationStatus
54131
54170
  */
54132
54171
  const toRevocationStatus = ({ issuer, mtp }) => {
54133
- const p = Proof.fromJSON({
54134
- nodeAux: mtp.node_aux,
54135
- existence: mtp.existence,
54136
- siblings: mtp.siblings
54137
- });
54138
54172
  return {
54139
- mtp: p,
54173
+ mtp: Proof.fromJSON(mtp),
54140
54174
  issuer
54141
54175
  };
54142
54176
  };