@waku/enr 0.0.28-9f1d8ca.0 → 0.0.28-c41b319.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bundle/index.js CHANGED
@@ -655,7 +655,7 @@ new TextDecoder();
655
655
 
656
656
  /* eslint-disable */
657
657
  var encode_1 = encode$3;
658
- var MSB$1 = 0x80, REST$1 = 0x7F, MSBALL = ~REST$1, INT = Math.pow(2, 31);
658
+ var MSB$1 = 0x80, MSBALL = -128, INT = Math.pow(2, 31);
659
659
  /**
660
660
  * @param {number} num
661
661
  * @param {number[]} out
@@ -679,7 +679,7 @@ function encode$3(num, out, offset) {
679
679
  return out;
680
680
  }
681
681
  var decode$4 = read$1;
682
- var MSB$1$1 = 0x80, REST$1$1 = 0x7F;
682
+ var MSB$1$1 = 0x80, REST$1 = 0x7F;
683
683
  /**
684
684
  * @param {string | any[]} buf
685
685
  * @param {number} offset
@@ -694,8 +694,8 @@ function read$1(buf, offset) {
694
694
  }
695
695
  b = buf[counter++];
696
696
  res += shift < 28
697
- ? (b & REST$1$1) << shift
698
- : (b & REST$1$1) * Math.pow(2, shift);
697
+ ? (b & REST$1) << shift
698
+ : (b & REST$1) * Math.pow(2, shift);
699
699
  shift += 7;
700
700
  } while (b >= MSB$1$1);
701
701
  // @ts-ignore
@@ -1586,10 +1586,10 @@ class JacobianPoint {
1586
1586
  const cond1 = window % 2 !== 0;
1587
1587
  const cond2 = wbits < 0;
1588
1588
  if (wbits === 0) {
1589
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
1589
+ f = f.add(constTimeNegate$1(cond1, precomputes[offset1]));
1590
1590
  }
1591
1591
  else {
1592
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
1592
+ p = p.add(constTimeNegate$1(cond2, precomputes[offset2]));
1593
1593
  }
1594
1594
  }
1595
1595
  return { p, f };
@@ -1602,8 +1602,8 @@ class JacobianPoint {
1602
1602
  const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
1603
1603
  let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
1604
1604
  let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);
1605
- k1p = constTimeNegate(k1neg, k1p);
1606
- k2p = constTimeNegate(k2neg, k2p);
1605
+ k1p = constTimeNegate$1(k1neg, k1p);
1606
+ k2p = constTimeNegate$1(k2neg, k2p);
1607
1607
  k2p = new JacobianPoint(mod$1(k2p.x * endo.beta), k2p.y, k2p.z);
1608
1608
  point = k1p.add(k2p);
1609
1609
  fake = f1p.add(f2p);
@@ -1635,7 +1635,7 @@ class JacobianPoint {
1635
1635
  }
1636
1636
  JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n$7);
1637
1637
  JacobianPoint.ZERO = new JacobianPoint(_0n$5, _1n$7, _0n$5);
1638
- function constTimeNegate(condition, item) {
1638
+ function constTimeNegate$1(condition, item) {
1639
1639
  const neg = item.negate();
1640
1640
  return condition ? neg : item;
1641
1641
  }
@@ -3092,43 +3092,55 @@ function verifySignature(signature, message, publicKey) {
3092
3092
  }
3093
3093
  }
3094
3094
 
3095
- function number(n) {
3095
+ /**
3096
+ * Internal assertion helpers.
3097
+ * @module
3098
+ */
3099
+ /** Asserts something is positive integer. */
3100
+ function anumber(n) {
3096
3101
  if (!Number.isSafeInteger(n) || n < 0)
3097
- throw new Error(`positive integer expected, not ${n}`);
3102
+ throw new Error('positive integer expected, got ' + n);
3098
3103
  }
3099
- // copied from utils
3104
+ /** Is number an Uint8Array? Copied from utils for perf. */
3100
3105
  function isBytes$2(a) {
3101
- return (a instanceof Uint8Array ||
3102
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
3106
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
3103
3107
  }
3104
- function bytes(b, ...lengths) {
3108
+ /** Asserts something is Uint8Array. */
3109
+ function abytes$1(b, ...lengths) {
3105
3110
  if (!isBytes$2(b))
3106
3111
  throw new Error('Uint8Array expected');
3107
3112
  if (lengths.length > 0 && !lengths.includes(b.length))
3108
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
3113
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
3109
3114
  }
3110
- function hash(h) {
3115
+ /** Asserts something is hash */
3116
+ function ahash(h) {
3111
3117
  if (typeof h !== 'function' || typeof h.create !== 'function')
3112
3118
  throw new Error('Hash should be wrapped by utils.wrapConstructor');
3113
- number(h.outputLen);
3114
- number(h.blockLen);
3119
+ anumber(h.outputLen);
3120
+ anumber(h.blockLen);
3115
3121
  }
3116
- function exists(instance, checkFinished = true) {
3122
+ /** Asserts a hash instance has not been destroyed / finished */
3123
+ function aexists(instance, checkFinished = true) {
3117
3124
  if (instance.destroyed)
3118
3125
  throw new Error('Hash instance has been destroyed');
3119
3126
  if (checkFinished && instance.finished)
3120
3127
  throw new Error('Hash#digest() has already been called');
3121
3128
  }
3122
- function output(out, instance) {
3123
- bytes(out);
3129
+ /** Asserts output is properly-sized byte array */
3130
+ function aoutput(out, instance) {
3131
+ abytes$1(out);
3124
3132
  const min = instance.outputLen;
3125
3133
  if (out.length < min) {
3126
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
3134
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
3127
3135
  }
3128
3136
  }
3129
3137
 
3130
3138
  const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
3131
3139
 
3140
+ /**
3141
+ * Utilities for hex, bytes, CSPRNG.
3142
+ * @module
3143
+ */
3132
3144
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3133
3145
  // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
3134
3146
  // node.js versions earlier than v19 don't declare it in global scope.
@@ -3137,16 +3149,20 @@ const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? glob
3137
3149
  // Makes the utils un-importable in browsers without a bundler.
3138
3150
  // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
3139
3151
  // Cast array to view
3140
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3141
- // The rotate right (circular right shift) operation for uint32
3142
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
3143
- new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
3152
+ function createView(arr) {
3153
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3154
+ }
3155
+ /** The rotate right (circular right shift) operation for uint32 */
3156
+ function rotr(word, shift) {
3157
+ return (word << (32 - shift)) | (word >>> shift);
3158
+ }
3144
3159
  /**
3160
+ * Convert JS string to byte array.
3145
3161
  * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
3146
3162
  */
3147
3163
  function utf8ToBytes$1(str) {
3148
3164
  if (typeof str !== 'string')
3149
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
3165
+ throw new Error('utf8ToBytes expected string, got ' + typeof str);
3150
3166
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
3151
3167
  }
3152
3168
  /**
@@ -3157,7 +3173,7 @@ function utf8ToBytes$1(str) {
3157
3173
  function toBytes$1(data) {
3158
3174
  if (typeof data === 'string')
3159
3175
  data = utf8ToBytes$1(data);
3160
- bytes(data);
3176
+ abytes$1(data);
3161
3177
  return data;
3162
3178
  }
3163
3179
  /**
@@ -3167,7 +3183,7 @@ function concatBytes$1(...arrays) {
3167
3183
  let sum = 0;
3168
3184
  for (let i = 0; i < arrays.length; i++) {
3169
3185
  const a = arrays[i];
3170
- bytes(a);
3186
+ abytes$1(a);
3171
3187
  sum += a.length;
3172
3188
  }
3173
3189
  const res = new Uint8Array(sum);
@@ -3178,13 +3194,14 @@ function concatBytes$1(...arrays) {
3178
3194
  }
3179
3195
  return res;
3180
3196
  }
3181
- // For runtime check if class implements interface
3197
+ /** For runtime check if class implements interface */
3182
3198
  class Hash {
3183
3199
  // Safe version that clones internal state
3184
3200
  clone() {
3185
3201
  return this._cloneInto();
3186
3202
  }
3187
3203
  }
3204
+ /** Wraps hash function, creating an interface on top of it */
3188
3205
  function wrapConstructor(hashCons) {
3189
3206
  const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
3190
3207
  const tmp = hashCons();
@@ -3193,9 +3210,7 @@ function wrapConstructor(hashCons) {
3193
3210
  hashC.create = () => hashCons();
3194
3211
  return hashC;
3195
3212
  }
3196
- /**
3197
- * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
3198
- */
3213
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
3199
3214
  function randomBytes(bytesLength = 32) {
3200
3215
  if (crypto$1 && typeof crypto$1.getRandomValues === 'function') {
3201
3216
  return crypto$1.getRandomValues(new Uint8Array(bytesLength));
@@ -3208,8 +3223,10 @@ function randomBytes(bytesLength = 32) {
3208
3223
  }
3209
3224
 
3210
3225
  /**
3211
- * Polyfill for Safari 14
3226
+ * Internal Merkle-Damgard hash utils.
3227
+ * @module
3212
3228
  */
3229
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
3213
3230
  function setBigUint64(view, byteOffset, value, isLE) {
3214
3231
  if (typeof view.setBigUint64 === 'function')
3215
3232
  return view.setBigUint64(byteOffset, value, isLE);
@@ -3222,14 +3239,14 @@ function setBigUint64(view, byteOffset, value, isLE) {
3222
3239
  view.setUint32(byteOffset + h, wh, isLE);
3223
3240
  view.setUint32(byteOffset + l, wl, isLE);
3224
3241
  }
3225
- /**
3226
- * Choice: a ? b : c
3227
- */
3228
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
3229
- /**
3230
- * Majority function, true if any two inputs is true
3231
- */
3232
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
3242
+ /** Choice: a ? b : c */
3243
+ function Chi(a, b, c) {
3244
+ return (a & b) ^ (~a & c);
3245
+ }
3246
+ /** Majority function, true if any two inputs is true. */
3247
+ function Maj(a, b, c) {
3248
+ return (a & b) ^ (a & c) ^ (b & c);
3249
+ }
3233
3250
  /**
3234
3251
  * Merkle-Damgard hash construction base class.
3235
3252
  * Could be used to create MD5, RIPEMD, SHA1, SHA2.
@@ -3249,7 +3266,7 @@ class HashMD extends Hash {
3249
3266
  this.view = createView(this.buffer);
3250
3267
  }
3251
3268
  update(data) {
3252
- exists(this);
3269
+ aexists(this);
3253
3270
  const { view, buffer, blockLen } = this;
3254
3271
  data = toBytes$1(data);
3255
3272
  const len = data.length;
@@ -3275,8 +3292,8 @@ class HashMD extends Hash {
3275
3292
  return this;
3276
3293
  }
3277
3294
  digestInto(out) {
3278
- exists(this);
3279
- output(out, this);
3295
+ aexists(this);
3296
+ aoutput(out, this);
3280
3297
  this.finished = true;
3281
3298
  // Padding
3282
3299
  // We can avoid allocation of buffer for padding completely if it
@@ -3333,10 +3350,16 @@ class HashMD extends Hash {
3333
3350
  }
3334
3351
  }
3335
3352
 
3336
- // SHA2-256 need to try 2^128 hashes to execute birthday attack.
3337
- // BTC network is doing 2^67 hashes/sec as per early 2023.
3338
- // Round constants:
3339
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
3353
+ /**
3354
+ * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
3355
+ *
3356
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
3357
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
3358
+ *
3359
+ * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
3360
+ * @module
3361
+ */
3362
+ /** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */
3340
3363
  // prettier-ignore
3341
3364
  const SHA256_K = /* @__PURE__ */ new Uint32Array([
3342
3365
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
@@ -3348,14 +3371,15 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([
3348
3371
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
3349
3372
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
3350
3373
  ]);
3351
- // Initial state:
3352
- // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
3374
+ /** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */
3353
3375
  // prettier-ignore
3354
3376
  const SHA256_IV = /* @__PURE__ */ new Uint32Array([
3355
3377
  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
3356
3378
  ]);
3357
- // Temporary buffer, not used to store anything between runs
3358
- // Named this way because it matches specification.
3379
+ /**
3380
+ * Temporary buffer, not used to store anything between runs.
3381
+ * Named this way because it matches specification.
3382
+ */
3359
3383
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
3360
3384
  class SHA256 extends HashMD {
3361
3385
  constructor() {
@@ -3432,10 +3456,7 @@ class SHA256 extends HashMD {
3432
3456
  this.buffer.fill(0);
3433
3457
  }
3434
3458
  }
3435
- /**
3436
- * SHA2-256 hash function
3437
- * @param message - data that would be hashed
3438
- */
3459
+ /** SHA2-256 hash function */
3439
3460
  const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
3440
3461
 
3441
3462
  var Protocols;
@@ -3552,6 +3573,10 @@ var EConnectionStateEvents;
3552
3573
  EConnectionStateEvents["CONNECTION_STATUS"] = "waku:connection";
3553
3574
  })(EConnectionStateEvents || (EConnectionStateEvents = {}));
3554
3575
 
3576
+ var HealthStatusChangeEvents;
3577
+ (function (HealthStatusChangeEvents) {
3578
+ HealthStatusChangeEvents["StatusChange"] = "health:change";
3579
+ })(HealthStatusChangeEvents || (HealthStatusChangeEvents = {}));
3555
3580
  var HealthStatus;
3556
3581
  (function (HealthStatus) {
3557
3582
  HealthStatus["Unhealthy"] = "Unhealthy";
@@ -3930,24 +3955,62 @@ function setup(env) {
3930
3955
  createDebug.names = [];
3931
3956
  createDebug.skips = [];
3932
3957
 
3933
- let i;
3934
- const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
3935
- const len = split.length;
3958
+ const split = (typeof namespaces === 'string' ? namespaces : '')
3959
+ .trim()
3960
+ .replace(' ', ',')
3961
+ .split(',')
3962
+ .filter(Boolean);
3936
3963
 
3937
- for (i = 0; i < len; i++) {
3938
- if (!split[i]) {
3939
- // ignore empty strings
3940
- continue;
3964
+ for (const ns of split) {
3965
+ if (ns[0] === '-') {
3966
+ createDebug.skips.push(ns.slice(1));
3967
+ } else {
3968
+ createDebug.names.push(ns);
3941
3969
  }
3970
+ }
3971
+ }
3942
3972
 
3943
- namespaces = split[i].replace(/\*/g, '.*?');
3944
-
3945
- if (namespaces[0] === '-') {
3946
- createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
3973
+ /**
3974
+ * Checks if the given string matches a namespace template, honoring
3975
+ * asterisks as wildcards.
3976
+ *
3977
+ * @param {String} search
3978
+ * @param {String} template
3979
+ * @return {Boolean}
3980
+ */
3981
+ function matchesTemplate(search, template) {
3982
+ let searchIndex = 0;
3983
+ let templateIndex = 0;
3984
+ let starIndex = -1;
3985
+ let matchIndex = 0;
3986
+
3987
+ while (searchIndex < search.length) {
3988
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
3989
+ // Match character or proceed with wildcard
3990
+ if (template[templateIndex] === '*') {
3991
+ starIndex = templateIndex;
3992
+ matchIndex = searchIndex;
3993
+ templateIndex++; // Skip the '*'
3994
+ } else {
3995
+ searchIndex++;
3996
+ templateIndex++;
3997
+ }
3998
+ } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
3999
+ // Backtrack to the last '*' and try to match more characters
4000
+ templateIndex = starIndex + 1;
4001
+ matchIndex++;
4002
+ searchIndex = matchIndex;
3947
4003
  } else {
3948
- createDebug.names.push(new RegExp('^' + namespaces + '$'));
4004
+ return false; // No match
3949
4005
  }
3950
4006
  }
4007
+
4008
+ // Handle trailing '*' in template
4009
+ while (templateIndex < template.length && template[templateIndex] === '*') {
4010
+ templateIndex++;
4011
+ }
4012
+
4013
+ return templateIndex === template.length;
3951
4014
  }
3952
4015
 
3953
4016
  /**
@@ -3958,8 +4021,8 @@ function setup(env) {
3958
4021
  */
3959
4022
  function disable() {
3960
4023
  const namespaces = [
3961
- ...createDebug.names.map(toNamespace),
3962
- ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
4024
+ ...createDebug.names,
4025
+ ...createDebug.skips.map(namespace => '-' + namespace)
3963
4026
  ].join(',');
3964
4027
  createDebug.enable('');
3965
4028
  return namespaces;
@@ -3973,21 +4036,14 @@ function setup(env) {
3973
4036
  * @api public
3974
4037
  */
3975
4038
  function enabled(name) {
3976
- if (name[name.length - 1] === '*') {
3977
- return true;
3978
- }
3979
-
3980
- let i;
3981
- let len;
3982
-
3983
- for (i = 0, len = createDebug.skips.length; i < len; i++) {
3984
- if (createDebug.skips[i].test(name)) {
4039
+ for (const skip of createDebug.skips) {
4040
+ if (matchesTemplate(name, skip)) {
3985
4041
  return false;
3986
4042
  }
3987
4043
  }
3988
4044
 
3989
- for (i = 0, len = createDebug.names.length; i < len; i++) {
3990
- if (createDebug.names[i].test(name)) {
4045
+ for (const ns of createDebug.names) {
4046
+ if (matchesTemplate(name, ns)) {
3991
4047
  return true;
3992
4048
  }
3993
4049
  }
@@ -3995,19 +4051,6 @@ function setup(env) {
3995
4051
  return false;
3996
4052
  }
3997
4053
 
3998
- /**
3999
- * Convert regexp to namespace
4000
- *
4001
- * @param {RegExp} regxep
4002
- * @return {String} namespace
4003
- * @api private
4004
- */
4005
- function toNamespace(regexp) {
4006
- return regexp.toString()
4007
- .substring(2, regexp.toString().length - 2)
4008
- .replace(/\.\*\?$/, '*');
4009
- }
4010
-
4011
4054
  /**
4012
4055
  * Coerce `val`.
4013
4056
  *
@@ -4169,6 +4212,7 @@ var common = setup;
4169
4212
 
4170
4213
  // Is webkit? http://stackoverflow.com/a/16459606/376773
4171
4214
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
4215
+ // eslint-disable-next-line no-return-assign
4172
4216
  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
4173
4217
  // Is firebug? http://stackoverflow.com/a/398120/376773
4174
4218
  (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
@@ -4833,7 +4877,7 @@ function parseIPv6(input) {
4833
4877
  return parser.new(input).parseWith(() => parser.readIPv6Addr());
4834
4878
  }
4835
4879
  /** Parse `input` into IPv4 or IPv6 bytes. */
4836
- function parseIP(input) {
4880
+ function parseIP(input, mapIPv4ToIPv6 = false) {
4837
4881
  // strip zone index if it is present
4838
4882
  if (input.includes("%")) {
4839
4883
  input = input.split("%")[0];
@@ -4841,7 +4885,14 @@ function parseIP(input) {
4841
4885
  if (input.length > MAX_IPV6_LENGTH) {
4842
4886
  return undefined;
4843
4887
  }
4844
- return parser.new(input).parseWith(() => parser.readIPAddr());
4888
+ const addr = parser.new(input).parseWith(() => parser.readIPAddr());
4889
+ if (!addr) {
4890
+ return undefined;
4891
+ }
4892
+ if (mapIPv4ToIPv6 && addr.length === 4) {
4893
+ return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, addr[0], addr[1], addr[2], addr[3]]);
4894
+ }
4895
+ return addr;
4845
4896
  }
4846
4897
 
4847
4898
  /** Check if `input` is IPv4. */
@@ -5029,17 +5080,13 @@ function getProtocol(proto) {
5029
5080
  throw new Error(`invalid protocol id type: ${typeof proto}`);
5030
5081
  }
5031
5082
 
5032
- /**
5033
- * @packageDocumentation
5034
- *
5035
- * Provides methods for converting
5036
- */
5037
5083
  getProtocol('ip4');
5038
5084
  getProtocol('ip6');
5039
5085
  getProtocol('ipcidr');
5040
5086
  /**
5041
5087
  * Convert [code,Uint8Array] to string
5042
5088
  */
5089
+ // eslint-disable-next-line complexity
5043
5090
  function convertToString(proto, buf) {
5044
5091
  const protocol = getProtocol(proto);
5045
5092
  switch (protocol.code) {
@@ -5048,6 +5095,8 @@ function convertToString(proto, buf) {
5048
5095
  return bytes2ip(buf);
5049
5096
  case 42: // ipv6zone
5050
5097
  return bytes2str(buf);
5098
+ case 43: // ipcidr
5099
+ return toString$1(buf, 'base10');
5051
5100
  case 6: // tcp
5052
5101
  case 273: // udp
5053
5102
  case 33: // dccp
@@ -5075,6 +5124,7 @@ function convertToString(proto, buf) {
5075
5124
  return toString$1(buf, 'base16'); // no clue. convert to hex
5076
5125
  }
5077
5126
  }
5127
+ // eslint-disable-next-line complexity
5078
5128
  function convertToBytes(proto, str) {
5079
5129
  const protocol = getProtocol(proto);
5080
5130
  switch (protocol.code) {
@@ -5084,6 +5134,8 @@ function convertToBytes(proto, str) {
5084
5134
  return ip2bytes(str);
5085
5135
  case 42: // ipv6zone
5086
5136
  return str2bytes(str);
5137
+ case 43: // ipcidr
5138
+ return fromString(str, 'base10');
5087
5139
  case 6: // tcp
5088
5140
  case 273: // udp
5089
5141
  case 33: // dccp
@@ -5378,19 +5430,6 @@ function ParseError(str) {
5378
5430
  return new Error('Error parsing address: ' + str);
5379
5431
  }
5380
5432
 
5381
- /**
5382
- * @packageDocumentation
5383
- *
5384
- * An implementation of a Multiaddr in JavaScript
5385
- *
5386
- * @example
5387
- *
5388
- * ```js
5389
- * import { multiaddr } from '@multiformats/multiaddr'
5390
- *
5391
- * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')
5392
- * ```
5393
- */
5394
5433
  const inspect$1 = Symbol.for('nodejs.util.inspect.custom');
5395
5434
  const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');
5396
5435
  const DNS_CODES = [
@@ -5502,10 +5541,20 @@ class Multiaddr {
5502
5541
  return this.#tuples.map(([code]) => getProtocol(code).name);
5503
5542
  }
5504
5543
  tuples() {
5505
- return this.#tuples;
5544
+ return this.#tuples.map(([code, value]) => {
5545
+ if (value == null) {
5546
+ return [code];
5547
+ }
5548
+ return [code, value];
5549
+ });
5506
5550
  }
5507
5551
  stringTuples() {
5508
- return this.#stringTuples;
5552
+ return this.#stringTuples.map(([code, value]) => {
5553
+ if (value == null) {
5554
+ return [code];
5555
+ }
5556
+ return [code, value];
5557
+ });
5509
5558
  }
5510
5559
  encapsulate(addr) {
5511
5560
  addr = new Multiaddr(addr);
@@ -5635,10 +5684,8 @@ class Multiaddr {
5635
5684
  *
5636
5685
  * ```TypeScript
5637
5686
  * import { multiaddr } from '@multiformats/multiaddr'
5638
- * const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
5639
- * // Multiaddr(/ip4/127.0.0.1/udp/1234)
5640
5687
  *
5641
- * const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
5688
+ * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')
5642
5689
  * // Multiaddr(/ip4/127.0.0.1/udp/1234)
5643
5690
  *
5644
5691
  * addr.bytes
@@ -5677,9 +5724,9 @@ class Multiaddr {
5677
5724
  *
5678
5725
  * ```TypeScript
5679
5726
  * import { multiaddr, resolvers } from '@multiformats/multiaddr'
5680
- * import { dnsaddr } from '@multiformats/multiaddr/resolvers'
5727
+ * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'
5681
5728
  *
5682
- * resolvers.set('dnsaddr', dnsaddr)
5729
+ * resolvers.set('dnsaddr', dnsaddrResolver)
5683
5730
  *
5684
5731
  * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
5685
5732
  *
@@ -5688,7 +5735,7 @@ class Multiaddr {
5688
5735
  * signal: AbortSignal.timeout(5000)
5689
5736
  * })
5690
5737
  *
5691
- * console.info(await ma.resolve(resolved)
5738
+ * console.info(resolved)
5692
5739
  * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]
5693
5740
  * ```
5694
5741
  *
@@ -5702,7 +5749,9 @@ class Multiaddr {
5702
5749
  * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'
5703
5750
  *
5704
5751
  * const resolver = dns({
5705
- * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')
5752
+ * resolvers: {
5753
+ * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')
5754
+ * }
5706
5755
  * })
5707
5756
  *
5708
5757
  * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
@@ -5788,6 +5837,12 @@ function locationMultiaddrFromEnrFields(enr, protocol) {
5788
5837
  return multiaddrFromFields(isIpv6 ? "ip6" : "ip4", protoName, ipVal, protoVal);
5789
5838
  }
5790
5839
 
5840
+ /**
5841
+ * All PeerId implementations must use this symbol as the name of a property
5842
+ * with a boolean `true` value
5843
+ */
5844
+ const peerIdSymbol = Symbol.for('@libp2p/peer-id');
5845
+
5791
5846
  /**
5792
5847
  * When this error is thrown it means an operation was aborted,
5793
5848
  * usually in response to the `abort` event being emitted by an
@@ -5813,10 +5868,24 @@ class InvalidPublicKeyError extends Error {
5813
5868
  this.name = 'InvalidPublicKeyError';
5814
5869
  }
5815
5870
  }
5871
+ /**
5872
+ * Thrown when and attempt to operate on an unsupported key was made
5873
+ */
5874
+ class UnsupportedKeyTypeError extends Error {
5875
+ static name = 'UnsupportedKeyTypeError';
5876
+ constructor(message = 'Unsupported key type') {
5877
+ super(message);
5878
+ this.name = 'UnsupportedKeyTypeError';
5879
+ }
5880
+ }
5816
5881
 
5882
+ /**
5883
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
5884
+ * @todo re-check https://issues.chromium.org/issues/42212588
5885
+ * @module
5886
+ */
5817
5887
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
5818
5888
  const _32n = /* @__PURE__ */ BigInt(32);
5819
- // We are not using BigUint64Array, because they are extremely slow as per 2022
5820
5889
  function fromBig(n, le = false) {
5821
5890
  if (le)
5822
5891
  return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
@@ -5873,6 +5942,13 @@ const u64 = {
5873
5942
  add, add3L, add3H, add4L, add4H, add5H, add5L,
5874
5943
  };
5875
5944
 
5945
+ /**
5946
+ * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.
5947
+ *
5948
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
5949
+ * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
5950
+ * @module
5951
+ */
5876
5952
  // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
5877
5953
  // prettier-ignore
5878
5954
  const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
@@ -6027,8 +6103,13 @@ class SHA512 extends HashMD {
6027
6103
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
6028
6104
  }
6029
6105
  }
6106
+ /** SHA2-512 hash function. */
6030
6107
  const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
6031
6108
 
6109
+ /**
6110
+ * Hex, bytes and number utilities.
6111
+ * @module
6112
+ */
6032
6113
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6033
6114
  // 100 lines of code in the file are duplicated from noble-hashes (utils).
6034
6115
  // This is OK: `abstract` directory does not use noble-hashes.
@@ -6038,8 +6119,7 @@ const _0n$4 = /* @__PURE__ */ BigInt(0);
6038
6119
  const _1n$6 = /* @__PURE__ */ BigInt(1);
6039
6120
  const _2n$4 = /* @__PURE__ */ BigInt(2);
6040
6121
  function isBytes$1(a) {
6041
- return (a instanceof Uint8Array ||
6042
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
6122
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
6043
6123
  }
6044
6124
  function abytes(item) {
6045
6125
  if (!isBytes$1(item))
@@ -6047,7 +6127,7 @@ function abytes(item) {
6047
6127
  }
6048
6128
  function abool(title, value) {
6049
6129
  if (typeof value !== 'boolean')
6050
- throw new Error(`${title} must be valid boolean, got "${value}".`);
6130
+ throw new Error(title + ' boolean expected, got ' + value);
6051
6131
  }
6052
6132
  // Array where index 0xf0 (240) is mapped to string 'f0'
6053
6133
  const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
@@ -6065,23 +6145,22 @@ function bytesToHex(bytes) {
6065
6145
  }
6066
6146
  function numberToHexUnpadded(num) {
6067
6147
  const hex = num.toString(16);
6068
- return hex.length & 1 ? `0${hex}` : hex;
6148
+ return hex.length & 1 ? '0' + hex : hex;
6069
6149
  }
6070
6150
  function hexToNumber(hex) {
6071
6151
  if (typeof hex !== 'string')
6072
6152
  throw new Error('hex string expected, got ' + typeof hex);
6073
- // Big Endian
6074
- return BigInt(hex === '' ? '0' : `0x${hex}`);
6153
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
6075
6154
  }
6076
6155
  // We use optimized technique to convert hex string to byte array
6077
- const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
6078
- function asciiToBase16(char) {
6079
- if (char >= asciis._0 && char <= asciis._9)
6080
- return char - asciis._0;
6081
- if (char >= asciis._A && char <= asciis._F)
6082
- return char - (asciis._A - 10);
6083
- if (char >= asciis._a && char <= asciis._f)
6084
- return char - (asciis._a - 10);
6156
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
6157
+ function asciiToBase16(ch) {
6158
+ if (ch >= asciis._0 && ch <= asciis._9)
6159
+ return ch - asciis._0; // '2' => 50-48
6160
+ if (ch >= asciis.A && ch <= asciis.F)
6161
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
6162
+ if (ch >= asciis.a && ch <= asciis.f)
6163
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
6085
6164
  return;
6086
6165
  }
6087
6166
  /**
@@ -6093,7 +6172,7 @@ function hexToBytes(hex) {
6093
6172
  const hl = hex.length;
6094
6173
  const al = hl / 2;
6095
6174
  if (hl % 2)
6096
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
6175
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
6097
6176
  const array = new Uint8Array(al);
6098
6177
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
6099
6178
  const n1 = asciiToBase16(hex.charCodeAt(hi));
@@ -6102,7 +6181,7 @@ function hexToBytes(hex) {
6102
6181
  const char = hex[hi] + hex[hi + 1];
6103
6182
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
6104
6183
  }
6105
- array[ai] = n1 * 16 + n2;
6184
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
6106
6185
  }
6107
6186
  return array;
6108
6187
  }
@@ -6140,7 +6219,7 @@ function ensureBytes(title, hex, expectedLength) {
6140
6219
  res = hexToBytes(hex);
6141
6220
  }
6142
6221
  catch (e) {
6143
- throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
6222
+ throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
6144
6223
  }
6145
6224
  }
6146
6225
  else if (isBytes$1(hex)) {
@@ -6149,11 +6228,11 @@ function ensureBytes(title, hex, expectedLength) {
6149
6228
  res = Uint8Array.from(hex);
6150
6229
  }
6151
6230
  else {
6152
- throw new Error(`${title} must be hex string or Uint8Array`);
6231
+ throw new Error(title + ' must be hex string or Uint8Array');
6153
6232
  }
6154
6233
  const len = res.length;
6155
6234
  if (typeof expectedLength === 'number' && len !== expectedLength)
6156
- throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
6235
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
6157
6236
  return res;
6158
6237
  }
6159
6238
  /**
@@ -6188,7 +6267,7 @@ function equalBytes(a, b) {
6188
6267
  */
6189
6268
  function utf8ToBytes(str) {
6190
6269
  if (typeof str !== 'string')
6191
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
6270
+ throw new Error('string expected');
6192
6271
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
6193
6272
  }
6194
6273
  // Is positive bigint
@@ -6208,7 +6287,7 @@ function aInRange(title, n, min, max) {
6208
6287
  // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
6209
6288
  // - our way is the cleanest: `inRange('x', x, 0n, P)
6210
6289
  if (!inRange(n, min, max))
6211
- throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
6290
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
6212
6291
  }
6213
6292
  // Bit operations
6214
6293
  /**
@@ -6318,12 +6397,12 @@ function validateObject(object, validators, optValidators = {}) {
6318
6397
  const checkField = (fieldName, type, isOptional) => {
6319
6398
  const checkVal = validatorFns[type];
6320
6399
  if (typeof checkVal !== 'function')
6321
- throw new Error(`Invalid validator "${type}", expected function`);
6400
+ throw new Error('invalid validator function');
6322
6401
  const val = object[fieldName];
6323
6402
  if (isOptional && val === undefined)
6324
6403
  return;
6325
6404
  if (!checkVal(val, object)) {
6326
- throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
6405
+ throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
6327
6406
  }
6328
6407
  };
6329
6408
  for (const [fieldName, type] of Object.entries(validators))
@@ -6392,14 +6471,17 @@ var ut = /*#__PURE__*/Object.freeze({
6392
6471
  validateObject: validateObject
6393
6472
  });
6394
6473
 
6474
+ /**
6475
+ * Utils for modular division and finite fields.
6476
+ * A finite field over 11 is integer number operations `mod 11`.
6477
+ * There is no division: it is replaced by modular multiplicative inverse.
6478
+ * @module
6479
+ */
6395
6480
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6396
- // Utilities for modular arithmetics and finite fields
6397
- // prettier-ignore
6398
- const _0n$3 = BigInt(0), _1n$5 = BigInt(1), _2n$3 = BigInt(2), _3n$1 = BigInt(3);
6399
6481
  // prettier-ignore
6400
- const _4n = BigInt(4), _5n$1 = BigInt(5), _8n$2 = BigInt(8);
6482
+ const _0n$3 = BigInt(0), _1n$5 = BigInt(1), _2n$3 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
6401
6483
  // prettier-ignore
6402
- BigInt(9); BigInt(16);
6484
+ const _4n = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5), _8n$2 = /* @__PURE__ */ BigInt(8);
6403
6485
  // Calculates a modulo b
6404
6486
  function mod(a, b) {
6405
6487
  const result = a % b;
@@ -6408,13 +6490,15 @@ function mod(a, b) {
6408
6490
  /**
6409
6491
  * Efficiently raise num to power and do modular division.
6410
6492
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
6493
+ * @todo use field version && remove
6411
6494
  * @example
6412
6495
  * pow(2n, 6n, 11n) // 64n % 11n == 9n
6413
6496
  */
6414
- // TODO: use field version && remove
6415
6497
  function pow(num, power, modulo) {
6416
- if (modulo <= _0n$3 || power < _0n$3)
6417
- throw new Error('Expected power/modulo > 0');
6498
+ if (power < _0n$3)
6499
+ throw new Error('invalid exponent, negatives unsupported');
6500
+ if (modulo <= _0n$3)
6501
+ throw new Error('invalid modulus');
6418
6502
  if (modulo === _1n$5)
6419
6503
  return _0n$3;
6420
6504
  let res = _1n$5;
@@ -6426,7 +6510,7 @@ function pow(num, power, modulo) {
6426
6510
  }
6427
6511
  return res;
6428
6512
  }
6429
- // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
6513
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
6430
6514
  function pow2(x, power, modulo) {
6431
6515
  let res = x;
6432
6516
  while (power-- > _0n$3) {
@@ -6435,12 +6519,15 @@ function pow2(x, power, modulo) {
6435
6519
  }
6436
6520
  return res;
6437
6521
  }
6438
- // Inverses number over modulo
6522
+ /**
6523
+ * Inverses number over modulo.
6524
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
6525
+ */
6439
6526
  function invert(number, modulo) {
6440
- if (number === _0n$3 || modulo <= _0n$3) {
6441
- throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
6442
- }
6443
- // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
6527
+ if (number === _0n$3)
6528
+ throw new Error('invert: expected non-zero number');
6529
+ if (modulo <= _0n$3)
6530
+ throw new Error('invert: expected positive modulus, got ' + modulo);
6444
6531
  // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
6445
6532
  let a = mod(number, modulo);
6446
6533
  let b = modulo;
@@ -6480,8 +6567,11 @@ function tonelliShanks(P) {
6480
6567
  for (Q = P - _1n$5, S = 0; Q % _2n$3 === _0n$3; Q /= _2n$3, S++)
6481
6568
  ;
6482
6569
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
6483
- for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$5; Z++)
6484
- ;
6570
+ for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$5; Z++) {
6571
+ // Crash instead of infinity loop, we cannot reasonable count until P.
6572
+ if (Z > 1000)
6573
+ throw new Error('Cannot find square root: likely non-prime P');
6574
+ }
6485
6575
  // Fast-path
6486
6576
  if (S === 1) {
6487
6577
  const p1div4 = (P + _1n$5) / _4n;
@@ -6523,9 +6613,18 @@ function tonelliShanks(P) {
6523
6613
  return x;
6524
6614
  };
6525
6615
  }
6616
+ /**
6617
+ * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:
6618
+ *
6619
+ * 1. P ≡ 3 (mod 4)
6620
+ * 2. P ≡ 5 (mod 8)
6621
+ * 3. P ≡ 9 (mod 16)
6622
+ * 4. Tonelli-Shanks algorithm
6623
+ *
6624
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
6625
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
6626
+ */
6526
6627
  function FpSqrt(P) {
6527
- // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
6528
- // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
6529
6628
  // P ≡ 3 (mod 4)
6530
6629
  // √n = n^((P+1)/4)
6531
6630
  if (P % _4n === _3n$1) {
@@ -6589,7 +6688,7 @@ function FpPow(f, num, power) {
6589
6688
  // Should have same speed as pow for bigints
6590
6689
  // TODO: benchmark!
6591
6690
  if (power < _0n$3)
6592
- throw new Error('Expected power > 0');
6691
+ throw new Error('invalid exponent, negatives unsupported');
6593
6692
  if (power === _0n$3)
6594
6693
  return f.ONE;
6595
6694
  if (power === _1n$5)
@@ -6636,15 +6735,15 @@ function nLength(n, nBitLength) {
6636
6735
  return { nBitLength: _nBitLength, nByteLength };
6637
6736
  }
6638
6737
  /**
6639
- * Initializes a finite field over prime. **Non-primes are not supported.**
6640
- * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
6738
+ * Initializes a finite field over prime.
6641
6739
  * Major performance optimizations:
6642
6740
  * * a) denormalized operations like mulN instead of mul
6643
6741
  * * b) same object shape: never add or remove keys
6644
6742
  * * c) Object.freeze
6645
- * NOTE: operations don't check 'isValid' for all elements for performance reasons,
6743
+ * Fragile: always run a benchmark on a change.
6744
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
6646
6745
  * it is caller responsibility to check this.
6647
- * This is low-level code, please make sure you know what you doing.
6746
+ * This is low-level code, please make sure you know what you're doing.
6648
6747
  * @param ORDER prime positive bigint
6649
6748
  * @param bitLen how many bits the field consumes
6650
6749
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -6652,13 +6751,14 @@ function nLength(n, nBitLength) {
6652
6751
  */
6653
6752
  function Field(ORDER, bitLen, isLE = false, redef = {}) {
6654
6753
  if (ORDER <= _0n$3)
6655
- throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
6754
+ throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
6656
6755
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
6657
6756
  if (BYTES > 2048)
6658
- throw new Error('Field lengths over 2048 bytes are not supported');
6659
- const sqrtP = FpSqrt(ORDER);
6757
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
6758
+ let sqrtP; // cached sqrtP
6660
6759
  const f = Object.freeze({
6661
6760
  ORDER,
6761
+ isLE,
6662
6762
  BITS,
6663
6763
  BYTES,
6664
6764
  MASK: bitMask(BITS),
@@ -6667,7 +6767,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6667
6767
  create: (num) => mod(num, ORDER),
6668
6768
  isValid: (num) => {
6669
6769
  if (typeof num !== 'bigint')
6670
- throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
6770
+ throw new Error('invalid field element: expected bigint, got ' + typeof num);
6671
6771
  return _0n$3 <= num && num < ORDER; // 0 is valid element, but it's not invertible
6672
6772
  },
6673
6773
  is0: (num) => num === _0n$3,
@@ -6686,7 +6786,12 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6686
6786
  subN: (lhs, rhs) => lhs - rhs,
6687
6787
  mulN: (lhs, rhs) => lhs * rhs,
6688
6788
  inv: (num) => invert(num, ORDER),
6689
- sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
6789
+ sqrt: redef.sqrt ||
6790
+ ((n) => {
6791
+ if (!sqrtP)
6792
+ sqrtP = FpSqrt(ORDER);
6793
+ return sqrtP(f, n);
6794
+ }),
6690
6795
  invertBatch: (lst) => FpInvertBatch(f, lst),
6691
6796
  // TODO: do we really need constant cmov?
6692
6797
  // We don't have const-time bigints anyway, so probably will be not very useful
@@ -6694,7 +6799,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6694
6799
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
6695
6800
  fromBytes: (bytes) => {
6696
6801
  if (bytes.length !== BYTES)
6697
- throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
6802
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
6698
6803
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
6699
6804
  },
6700
6805
  });
@@ -6742,52 +6847,80 @@ function mapHashToField(key, fieldOrder, isLE = false) {
6742
6847
  const minLen = getMinHashLength(fieldOrder);
6743
6848
  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
6744
6849
  if (len < 16 || len < minLen || len > 1024)
6745
- throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
6746
- const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
6850
+ throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
6851
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
6747
6852
  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
6748
6853
  const reduced = mod(num, fieldOrder - _1n$5) + _1n$5;
6749
6854
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
6750
6855
  }
6751
6856
 
6857
+ /**
6858
+ * Methods for elliptic curve multiplication by scalars.
6859
+ * Contains wNAF, pippenger
6860
+ * @module
6861
+ */
6752
6862
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6753
- // Abelian group utilities
6754
6863
  const _0n$2 = BigInt(0);
6755
6864
  const _1n$4 = BigInt(1);
6865
+ function constTimeNegate(condition, item) {
6866
+ const neg = item.negate();
6867
+ return condition ? neg : item;
6868
+ }
6869
+ function validateW(W, bits) {
6870
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
6871
+ throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
6872
+ }
6873
+ function calcWOpts(W, bits) {
6874
+ validateW(W, bits);
6875
+ const windows = Math.ceil(bits / W) + 1; // +1, because
6876
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
6877
+ return { windows, windowSize };
6878
+ }
6879
+ function validateMSMPoints(points, c) {
6880
+ if (!Array.isArray(points))
6881
+ throw new Error('array expected');
6882
+ points.forEach((p, i) => {
6883
+ if (!(p instanceof c))
6884
+ throw new Error('invalid point at index ' + i);
6885
+ });
6886
+ }
6887
+ function validateMSMScalars(scalars, field) {
6888
+ if (!Array.isArray(scalars))
6889
+ throw new Error('array of scalars expected');
6890
+ scalars.forEach((s, i) => {
6891
+ if (!field.isValid(s))
6892
+ throw new Error('invalid scalar at index ' + i);
6893
+ });
6894
+ }
6756
6895
  // Since points in different groups cannot be equal (different object constructor),
6757
6896
  // we can have single place to store precomputes
6758
6897
  const pointPrecomputes = new WeakMap();
6759
6898
  const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
6760
- // Elliptic curve multiplication of Point by scalar. Fragile.
6761
- // Scalars should always be less than curve order: this should be checked inside of a curve itself.
6762
- // Creates precomputation tables for fast multiplication:
6763
- // - private scalar is split by fixed size windows of W bits
6764
- // - every window point is collected from window's table & added to accumulator
6765
- // - since windows are different, same point inside tables won't be accessed more than once per calc
6766
- // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
6767
- // - +1 window is neccessary for wNAF
6768
- // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
6769
- // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
6770
- // windows to be in different memory locations
6899
+ function getW(P) {
6900
+ return pointWindowSizes.get(P) || 1;
6901
+ }
6902
+ /**
6903
+ * Elliptic curve multiplication of Point by scalar. Fragile.
6904
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
6905
+ * Creates precomputation tables for fast multiplication:
6906
+ * - private scalar is split by fixed size windows of W bits
6907
+ * - every window point is collected from window's table & added to accumulator
6908
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
6909
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
6910
+ * - +1 window is neccessary for wNAF
6911
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
6912
+ *
6913
+ * @todo Research returning 2d JS array of windows, instead of a single window.
6914
+ * This would allow windows to be in different memory locations
6915
+ */
6771
6916
  function wNAF(c, bits) {
6772
- const constTimeNegate = (condition, item) => {
6773
- const neg = item.negate();
6774
- return condition ? neg : item;
6775
- };
6776
- const validateW = (W) => {
6777
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
6778
- throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
6779
- };
6780
- const opts = (W) => {
6781
- validateW(W);
6782
- const windows = Math.ceil(bits / W) + 1; // +1, because
6783
- const windowSize = 2 ** (W - 1); // -1 because we skip zero
6784
- return { windows, windowSize };
6785
- };
6786
6917
  return {
6787
6918
  constTimeNegate,
6919
+ hasPrecomputes(elm) {
6920
+ return getW(elm) !== 1;
6921
+ },
6788
6922
  // non-const time multiplication ladder
6789
- unsafeLadder(elm, n) {
6790
- let p = c.ZERO;
6923
+ unsafeLadder(elm, n, p = c.ZERO) {
6791
6924
  let d = elm;
6792
6925
  while (n > _0n$2) {
6793
6926
  if (n & _1n$4)
@@ -6805,10 +6938,12 @@ function wNAF(c, bits) {
6805
6938
  * - 𝑊 is the window size
6806
6939
  * - 𝑛 is the bitlength of the curve order.
6807
6940
  * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
6941
+ * @param elm Point instance
6942
+ * @param W window size
6808
6943
  * @returns precomputed point tables flattened to a single array
6809
6944
  */
6810
6945
  precomputeWindow(elm, W) {
6811
- const { windows, windowSize } = opts(W);
6946
+ const { windows, windowSize } = calcWOpts(W, bits);
6812
6947
  const points = [];
6813
6948
  let p = elm;
6814
6949
  let base = p;
@@ -6834,7 +6969,7 @@ function wNAF(c, bits) {
6834
6969
  wNAF(W, precomputes, n) {
6835
6970
  // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
6836
6971
  // But need to carefully remove other checks before wNAF. ORDER == bits here
6837
- const { windows, windowSize } = opts(W);
6972
+ const { windows, windowSize } = calcWOpts(W, bits);
6838
6973
  let p = c.ZERO;
6839
6974
  let f = c.BASE;
6840
6975
  const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
@@ -6878,8 +7013,44 @@ function wNAF(c, bits) {
6878
7013
  // which makes it less const-time: around 1 bigint multiply.
6879
7014
  return { p, f };
6880
7015
  },
6881
- wNAFCached(P, n, transform) {
6882
- const W = pointWindowSizes.get(P) || 1;
7016
+ /**
7017
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
7018
+ * @param W window size
7019
+ * @param precomputes precomputed tables
7020
+ * @param n scalar (we don't check here, but should be less than curve order)
7021
+ * @param acc accumulator point to add result of multiplication
7022
+ * @returns point
7023
+ */
7024
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
7025
+ const { windows, windowSize } = calcWOpts(W, bits);
7026
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
7027
+ const maxNumber = 2 ** W;
7028
+ const shiftBy = BigInt(W);
7029
+ for (let window = 0; window < windows; window++) {
7030
+ const offset = window * windowSize;
7031
+ if (n === _0n$2)
7032
+ break; // No need to go over empty scalar
7033
+ // Extract W bits.
7034
+ let wbits = Number(n & mask);
7035
+ // Shift number by W bits.
7036
+ n >>= shiftBy;
7037
+ // If the bits are bigger than max size, we'll split those.
7038
+ // +224 => 256 - 32
7039
+ if (wbits > windowSize) {
7040
+ wbits -= maxNumber;
7041
+ n += _1n$4;
7042
+ }
7043
+ if (wbits === 0)
7044
+ continue;
7045
+ let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero
7046
+ if (wbits < 0)
7047
+ curr = curr.negate();
7048
+ // NOTE: by re-using acc, we can save a lot of additions in case of MSM
7049
+ acc = acc.add(curr);
7050
+ }
7051
+ return acc;
7052
+ },
7053
+ getPrecomputes(W, P, transform) {
6883
7054
  // Calculate precomputes on a first run, reuse them after
6884
7055
  let comp = pointPrecomputes.get(P);
6885
7056
  if (!comp) {
@@ -6887,62 +7058,66 @@ function wNAF(c, bits) {
6887
7058
  if (W !== 1)
6888
7059
  pointPrecomputes.set(P, transform(comp));
6889
7060
  }
6890
- return this.wNAF(W, comp, n);
7061
+ return comp;
7062
+ },
7063
+ wNAFCached(P, n, transform) {
7064
+ const W = getW(P);
7065
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
7066
+ },
7067
+ wNAFCachedUnsafe(P, n, transform, prev) {
7068
+ const W = getW(P);
7069
+ if (W === 1)
7070
+ return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
7071
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
6891
7072
  },
6892
7073
  // We calculate precomputes for elliptic curve point multiplication
6893
7074
  // using windowed method. This specifies window size and
6894
7075
  // stores precomputed values. Usually only base point would be precomputed.
6895
7076
  setWindowSize(P, W) {
6896
- validateW(W);
7077
+ validateW(W, bits);
6897
7078
  pointWindowSizes.set(P, W);
6898
7079
  pointPrecomputes.delete(P);
6899
7080
  },
6900
7081
  };
6901
7082
  }
6902
7083
  /**
6903
- * Pippenger algorithm for multi-scalar multiplication (MSM).
6904
- * MSM is basically (Pa + Qb + Rc + ...).
7084
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
6905
7085
  * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
6906
7086
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
6907
7087
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
6908
7088
  * @param c Curve Point constructor
6909
- * @param field field over CURVE.N - important that it's not over CURVE.P
7089
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
6910
7090
  * @param points array of L curve points
6911
7091
  * @param scalars array of L scalars (aka private keys / bigints)
6912
7092
  */
6913
- function pippenger(c, field, points, scalars) {
7093
+ function pippenger(c, fieldN, points, scalars) {
6914
7094
  // If we split scalars by some window (let's say 8 bits), every chunk will only
6915
7095
  // take 256 buckets even if there are 4096 scalars, also re-uses double.
6916
7096
  // TODO:
6917
7097
  // - https://eprint.iacr.org/2024/750.pdf
6918
7098
  // - https://tches.iacr.org/index.php/TCHES/article/view/10287
6919
7099
  // 0 is accepted in scalars
6920
- if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
7100
+ validateMSMPoints(points, c);
7101
+ validateMSMScalars(scalars, fieldN);
7102
+ if (points.length !== scalars.length)
6921
7103
  throw new Error('arrays of points and scalars must have equal length');
6922
- scalars.forEach((s, i) => {
6923
- if (!field.isValid(s))
6924
- throw new Error(`wrong scalar at index ${i}`);
6925
- });
6926
- points.forEach((p, i) => {
6927
- if (!(p instanceof c))
6928
- throw new Error(`wrong point at index ${i}`);
6929
- });
7104
+ const zero = c.ZERO;
6930
7105
  const wbits = bitLen(BigInt(points.length));
6931
7106
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
6932
7107
  const MASK = (1 << windowSize) - 1;
6933
- const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
6934
- const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
6935
- let sum = c.ZERO;
7108
+ const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array
7109
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
7110
+ let sum = zero;
6936
7111
  for (let i = lastBits; i >= 0; i -= windowSize) {
6937
- buckets.fill(c.ZERO);
7112
+ buckets.fill(zero);
6938
7113
  for (let j = 0; j < scalars.length; j++) {
6939
7114
  const scalar = scalars[j];
6940
7115
  const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
6941
7116
  buckets[wbits] = buckets[wbits].add(points[j]);
6942
7117
  }
6943
- let resI = c.ZERO; // not using this will do small speed-up, but will lose ct
7118
+ let resI = zero; // not using this will do small speed-up, but will lose ct
6944
7119
  // Skip first bucket, because it is zero
6945
- for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
7120
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
6946
7121
  sumI = sumI.add(buckets[j]);
6947
7122
  resI = resI.add(sumI);
6948
7123
  }
@@ -6972,8 +7147,12 @@ function validateBasic(curve) {
6972
7147
  });
6973
7148
  }
6974
7149
 
7150
+ /**
7151
+ * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
7152
+ * For design rationale of types / exports, see weierstrass module documentation.
7153
+ * @module
7154
+ */
6975
7155
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6976
- // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
6977
7156
  // Be friendly to bad ECMAScript parsers by not using bigint literals
6978
7157
  // prettier-ignore
6979
7158
  const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n$1 = BigInt(8);
@@ -7005,6 +7184,10 @@ function validateOpts$1(curve) {
7005
7184
  function twistedEdwards(curveDef) {
7006
7185
  const CURVE = validateOpts$1(curveDef);
7007
7186
  const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
7187
+ // Important:
7188
+ // There are some places where Fp.BYTES is used instead of nByteLength.
7189
+ // So far, everything has been tested with curves of Fp.BYTES == nByteLength.
7190
+ // TODO: test and find curves which behave otherwise.
7008
7191
  const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3);
7009
7192
  const modP = Fp.create; // Function overrides
7010
7193
  const Fn = Field(CURVE.n, CURVE.nBitLength);
@@ -7218,16 +7401,15 @@ function twistedEdwards(curveDef) {
7218
7401
  // It's faster, but should only be used when you don't care about
7219
7402
  // an exposed private key e.g. sig verification.
7220
7403
  // Does NOT allow scalars higher than CURVE.n.
7221
- multiplyUnsafe(scalar) {
7404
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
7405
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
7222
7406
  const n = scalar;
7223
7407
  aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L
7224
7408
  if (n === _0n$1)
7225
7409
  return I;
7226
- if (this.equals(I) || n === _1n$3)
7410
+ if (this.is0() || n === _1n$3)
7227
7411
  return this;
7228
- if (this.equals(G))
7229
- return this.wNAF(n).p;
7230
- return wnaf.unsafeLadder(this, n);
7412
+ return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
7231
7413
  }
7232
7414
  // Checks if point is of small order.
7233
7415
  // If you add something to small order point, you will have "dirty"
@@ -7261,8 +7443,9 @@ function twistedEdwards(curveDef) {
7261
7443
  abool('zip215', zip215);
7262
7444
  const normed = hex.slice(); // copy again, we'll manipulate it
7263
7445
  const lastByte = hex[len - 1]; // select last byte
7264
- normed[len - 1] = lastByte & ~0x80; // clear last bit
7446
+ normed[len - 1] = lastByte & -129; // clear last bit
7265
7447
  const y = bytesToNumberLE(normed);
7448
+ // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
7266
7449
  // RFC8032 prohibits >= p, but ZIP215 doesn't
7267
7450
  // zip215=true: 0 <= y < MASK (2^256 for ed25519)
7268
7451
  // zip215=false: 0 <= y < P (2^255-19 for ed25519)
@@ -7311,7 +7494,7 @@ function twistedEdwards(curveDef) {
7311
7494
  }
7312
7495
  /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
7313
7496
  function getExtendedPublicKey(key) {
7314
- const len = nByteLength;
7497
+ const len = Fp.BYTES;
7315
7498
  key = ensureBytes('private key', key, len);
7316
7499
  // Hash private key with curve's hash function to produce uniformingly random input
7317
7500
  // Check byte lengths: ensure(64, h(ensure(32, key)))
@@ -7344,23 +7527,29 @@ function twistedEdwards(curveDef) {
7344
7527
  const s = modN(r + k * scalar); // S = (r + k * s) mod L
7345
7528
  aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l
7346
7529
  const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));
7347
- return ensureBytes('result', res, nByteLength * 2); // 64-byte signature
7530
+ return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature
7348
7531
  }
7349
7532
  const verifyOpts = VERIFY_DEFAULT;
7533
+ /**
7534
+ * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
7535
+ * An extended group equation is checked.
7536
+ */
7350
7537
  function verify(sig, msg, publicKey, options = verifyOpts) {
7351
7538
  const { context, zip215 } = options;
7352
7539
  const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
7353
7540
  sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.
7354
7541
  msg = ensureBytes('message', msg);
7542
+ publicKey = ensureBytes('publicKey', publicKey, len);
7355
7543
  if (zip215 !== undefined)
7356
7544
  abool('zip215', zip215);
7357
7545
  if (prehash)
7358
7546
  msg = prehash(msg); // for ed25519ph, etc
7359
7547
  const s = bytesToNumberLE(sig.slice(len, 2 * len));
7360
- // zip215: true is good for consensus-critical apps and allows points < 2^256
7361
- // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p
7362
7548
  let A, R, SB;
7363
7549
  try {
7550
+ // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
7551
+ // zip215=true: 0 <= y < MASK (2^256 for ed25519)
7552
+ // zip215=false: 0 <= y < P (2^255-19 for ed25519)
7364
7553
  A = Point.fromHex(publicKey, zip215);
7365
7554
  R = Point.fromHex(sig.slice(0, len), zip215);
7366
7555
  SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
@@ -7372,6 +7561,7 @@ function twistedEdwards(curveDef) {
7372
7561
  return false;
7373
7562
  const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
7374
7563
  const RkA = R.add(A.multiplyUnsafe(k));
7564
+ // Extended group equation
7375
7565
  // [8][S]B = [8]R + [8][k]A'
7376
7566
  return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
7377
7567
  }
@@ -7402,13 +7592,14 @@ function twistedEdwards(curveDef) {
7402
7592
  };
7403
7593
  }
7404
7594
 
7405
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7406
7595
  /**
7407
7596
  * ed25519 Twisted Edwards curve with following addons:
7408
7597
  * - X25519 ECDH
7409
7598
  * - Ristretto cofactor elimination
7410
7599
  * - Elligator hash-to-group / point indistinguishability
7600
+ * @module
7411
7601
  */
7602
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7412
7603
  const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
7413
7604
  // √(-1) aka √(a) aka 2^((p-1)/4)
7414
7605
  const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
@@ -7467,7 +7658,7 @@ function uvRatio(u, v) {
7467
7658
  x = mod(-x, P);
7468
7659
  return { isValid: useRoot1 || useRoot2, value: x };
7469
7660
  }
7470
- const Fp$1 = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7661
+ const Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7471
7662
  const ed25519Defaults = /* @__PURE__ */ (() => ({
7472
7663
  // Param: a
7473
7664
  a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
@@ -7475,7 +7666,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7475
7666
  // Negative number is P - number, and division is invert(number, P)
7476
7667
  d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
7477
7668
  // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
7478
- Fp: Fp$1,
7669
+ Fp,
7479
7670
  // Subgroup order: how many points curve has
7480
7671
  // 2n**252n + 27742317777372353535851937790883648493n;
7481
7672
  n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
@@ -7494,6 +7685,14 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7494
7685
  }))();
7495
7686
  /**
7496
7687
  * ed25519 curve with EdDSA signatures.
7688
+ * @example
7689
+ * import { ed25519 } from '@noble/curves/ed25519';
7690
+ * const priv = ed25519.utils.randomPrivateKey();
7691
+ * const pub = ed25519.getPublicKey(priv);
7692
+ * const msg = new TextEncoder().encode('hello');
7693
+ * const sig = ed25519.sign(msg, priv);
7694
+ * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215
7695
+ * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5
7497
7696
  */
7498
7697
  const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
7499
7698
 
@@ -8867,7 +9066,7 @@ var PrivateKey;
8867
9066
  /*!
8868
9067
  * MIT License
8869
9068
  *
8870
- * Copyright (c) 2017-2022 Peculiar Ventures, LLC
9069
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
8871
9070
  *
8872
9071
  * Permission is hereby granted, free of charge, to any person obtaining a copy
8873
9072
  * of this software and associated documentation files (the "Software"), to deal
@@ -8979,7 +9178,7 @@ class BufferSourceConverter {
8979
9178
  }
8980
9179
 
8981
9180
  const STRING_TYPE = "string";
8982
- const HEX_REGEX = /^[0-9a-f]+$/i;
9181
+ const HEX_REGEX = /^[0-9a-f\s]+$/i;
8983
9182
  const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
8984
9183
  const BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
8985
9184
  class Utf8Converter {
@@ -9213,7 +9412,7 @@ class Convert {
9213
9412
  return base64;
9214
9413
  }
9215
9414
  static formatString(data) {
9216
- return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || "";
9415
+ return (data === null || data === undefined ? undefined : data.replace(/[\n\r\t ]/g, "")) || "";
9217
9416
  }
9218
9417
  }
9219
9418
  Convert.DEFAULT_UTF8_ENCODING = "utf8";
@@ -9469,7 +9668,7 @@ function HexBlock(BaseClass) {
9469
9668
  var _a;
9470
9669
  super(...args);
9471
9670
  const params = args[0] || {};
9472
- this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;
9671
+ this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== undefined ? _a : false;
9473
9672
  this.valueHexView = params.valueHex ? BufferSourceConverter_1.toUint8Array(params.valueHex) : EMPTY_VIEW;
9474
9673
  }
9475
9674
  get valueHex() {
@@ -9559,11 +9758,11 @@ class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {
9559
9758
  var _a, _b, _c, _d;
9560
9759
  super();
9561
9760
  if (idBlock) {
9562
- this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;
9761
+ this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== undefined ? _a : false;
9563
9762
  this.valueHexView = idBlock.valueHex ? BufferSourceConverter_1.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;
9564
- this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;
9565
- this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;
9566
- this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;
9763
+ this.tagClass = (_b = idBlock.tagClass) !== null && _b !== undefined ? _b : -1;
9764
+ this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== undefined ? _c : -1;
9765
+ this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== undefined ? _d : false;
9567
9766
  }
9568
9767
  else {
9569
9768
  this.tagClass = -1;
@@ -9730,9 +9929,9 @@ class LocalLengthBlock extends LocalBaseBlock {
9730
9929
  constructor({ lenBlock = {}, } = {}) {
9731
9930
  var _a, _b, _c;
9732
9931
  super();
9733
- this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;
9734
- this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;
9735
- this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;
9932
+ this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== undefined ? _a : false;
9933
+ this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== undefined ? _b : false;
9934
+ this.length = (_c = lenBlock.length) !== null && _c !== undefined ? _c : 0;
9736
9935
  }
9737
9936
  fromBER(inputBuffer, inputOffset, inputLength) {
9738
9937
  const view = BufferSourceConverter_1.toUint8Array(inputBuffer);
@@ -10504,7 +10703,7 @@ var _a$r;
10504
10703
  class OctetString extends BaseBlock {
10505
10704
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
10506
10705
  var _b, _c;
10507
- (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
10706
+ (_b = parameters.isConstructed) !== null && _b !== undefined ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === undefined ? undefined : _c.length));
10508
10707
  super({
10509
10708
  idBlock: {
10510
10709
  isConstructed: parameters.isConstructed,
@@ -10665,7 +10864,7 @@ var _a$q;
10665
10864
  class BitString extends BaseBlock {
10666
10865
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
10667
10866
  var _b, _c;
10668
- (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
10867
+ (_b = parameters.isConstructed) !== null && _b !== undefined ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === undefined ? undefined : _c.length));
10669
10868
  super({
10670
10869
  idBlock: {
10671
10870
  isConstructed: parameters.isConstructed,
@@ -11867,7 +12066,7 @@ class GeneralizedTime extends UTCTime {
11867
12066
  constructor(parameters = {}) {
11868
12067
  var _b;
11869
12068
  super(parameters);
11870
- (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);
12069
+ (_b = this.millisecond) !== null && _b !== undefined ? _b : (this.millisecond = 0);
11871
12070
  this.idBlock.tagClass = 1;
11872
12071
  this.idBlock.tagNumber = 24;
11873
12072
  }
@@ -12290,15 +12489,18 @@ function pkixToRSAPublicKey(bytes) {
12290
12489
  return new RSAPublicKey(jwk, digest);
12291
12490
  }
12292
12491
 
12293
- // HMAC (RFC 2104)
12492
+ /**
12493
+ * HMAC: RFC2104 message authentication code.
12494
+ * @module
12495
+ */
12294
12496
  class HMAC extends Hash {
12295
- constructor(hash$1, _key) {
12497
+ constructor(hash, _key) {
12296
12498
  super();
12297
12499
  this.finished = false;
12298
12500
  this.destroyed = false;
12299
- hash(hash$1);
12501
+ ahash(hash);
12300
12502
  const key = toBytes$1(_key);
12301
- this.iHash = hash$1.create();
12503
+ this.iHash = hash.create();
12302
12504
  if (typeof this.iHash.update !== 'function')
12303
12505
  throw new Error('Expected instance of class which extends utils.Hash');
12304
12506
  this.blockLen = this.iHash.blockLen;
@@ -12306,12 +12508,12 @@ class HMAC extends Hash {
12306
12508
  const blockLen = this.blockLen;
12307
12509
  const pad = new Uint8Array(blockLen);
12308
12510
  // blockLen can be bigger than outputLen
12309
- pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
12511
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
12310
12512
  for (let i = 0; i < pad.length; i++)
12311
12513
  pad[i] ^= 0x36;
12312
12514
  this.iHash.update(pad);
12313
12515
  // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
12314
- this.oHash = hash$1.create();
12516
+ this.oHash = hash.create();
12315
12517
  // Undo internal XOR && apply outer XOR
12316
12518
  for (let i = 0; i < pad.length; i++)
12317
12519
  pad[i] ^= 0x36 ^ 0x5c;
@@ -12319,13 +12521,13 @@ class HMAC extends Hash {
12319
12521
  pad.fill(0);
12320
12522
  }
12321
12523
  update(buf) {
12322
- exists(this);
12524
+ aexists(this);
12323
12525
  this.iHash.update(buf);
12324
12526
  return this;
12325
12527
  }
12326
12528
  digestInto(out) {
12327
- exists(this);
12328
- bytes(out, this.outputLen);
12529
+ aexists(this);
12530
+ abytes$1(out, this.outputLen);
12329
12531
  this.finished = true;
12330
12532
  this.iHash.digestInto(out);
12331
12533
  this.oHash.update(out);
@@ -12369,8 +12571,33 @@ class HMAC extends Hash {
12369
12571
  const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
12370
12572
  hmac.create = (hash, key) => new HMAC(hash, key);
12371
12573
 
12574
+ /**
12575
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
12576
+ *
12577
+ * ### Design rationale for types
12578
+ *
12579
+ * * Interaction between classes from different curves should fail:
12580
+ * `k256.Point.BASE.add(p256.Point.BASE)`
12581
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
12582
+ * * Different calls of `curve()` would return different classes -
12583
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
12584
+ * it won't affect others
12585
+ *
12586
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
12587
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
12588
+ * unique type for every function call.
12589
+ *
12590
+ * We can use generic types via some param, like curve opts, but that would:
12591
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
12592
+ * which is hard to debug.
12593
+ * 2. Params can be generic and we can't enforce them to be constant value:
12594
+ * if somebody creates curve from non-constant params,
12595
+ * it would be allowed to interact with other curves with non-constant params
12596
+ *
12597
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
12598
+ * @module
12599
+ */
12372
12600
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
12373
- // Short Weierstrass curve. The formula is: y² = x³ + ax + b
12374
12601
  function validateSigVerOpts(opts) {
12375
12602
  if (opts.lowS !== undefined)
12376
12603
  abool('lowS', opts.lowS);
@@ -12394,17 +12621,22 @@ function validatePointOpts(curve) {
12394
12621
  const { endo, Fp, a } = opts;
12395
12622
  if (endo) {
12396
12623
  if (!Fp.eql(a, Fp.ZERO)) {
12397
- throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
12624
+ throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');
12398
12625
  }
12399
12626
  if (typeof endo !== 'object' ||
12400
12627
  typeof endo.beta !== 'bigint' ||
12401
12628
  typeof endo.splitScalar !== 'function') {
12402
- throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
12629
+ throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
12403
12630
  }
12404
12631
  }
12405
12632
  return Object.freeze({ ...opts });
12406
12633
  }
12407
12634
  const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
12635
+ class DERErr extends Error {
12636
+ constructor(m = '') {
12637
+ super(m);
12638
+ }
12639
+ }
12408
12640
  /**
12409
12641
  * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
12410
12642
  *
@@ -12414,11 +12646,7 @@ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
12414
12646
  */
12415
12647
  const DER = {
12416
12648
  // asn.1 DER encoding utils
12417
- Err: class DERErr extends Error {
12418
- constructor(m = '') {
12419
- super(m);
12420
- }
12421
- },
12649
+ Err: DERErr,
12422
12650
  // Basic building block is TLV (Tag-Length-Value)
12423
12651
  _tlv: {
12424
12652
  encode: (tag, data) => {
@@ -12433,7 +12661,8 @@ const DER = {
12433
12661
  throw new E('tlv.encode: long form length too big');
12434
12662
  // length of length with long form flag
12435
12663
  const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
12436
- return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
12664
+ const t = numberToHexUnpadded(tag);
12665
+ return t + lenLen + len + data;
12437
12666
  },
12438
12667
  // v - value, l - left bytes (unparsed)
12439
12668
  decode(tag, data) {
@@ -12486,15 +12715,15 @@ const DER = {
12486
12715
  if (Number.parseInt(hex[0], 16) & 0b1000)
12487
12716
  hex = '00' + hex;
12488
12717
  if (hex.length & 1)
12489
- throw new E('unexpected assertion');
12718
+ throw new E('unexpected DER parsing assertion: unpadded hex');
12490
12719
  return hex;
12491
12720
  },
12492
12721
  decode(data) {
12493
12722
  const { Err: E } = DER;
12494
12723
  if (data[0] & 128)
12495
- throw new E('Invalid signature integer: negative');
12724
+ throw new E('invalid signature integer: negative');
12496
12725
  if (data[0] === 0x00 && !(data[1] & 128))
12497
- throw new E('Invalid signature integer: unnecessary leading zero');
12726
+ throw new E('invalid signature integer: unnecessary leading zero');
12498
12727
  return b2n(data);
12499
12728
  },
12500
12729
  },
@@ -12505,16 +12734,18 @@ const DER = {
12505
12734
  abytes(data);
12506
12735
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
12507
12736
  if (seqLeftBytes.length)
12508
- throw new E('Invalid signature: left bytes after parsing');
12737
+ throw new E('invalid signature: left bytes after parsing');
12509
12738
  const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
12510
12739
  const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
12511
12740
  if (sLeftBytes.length)
12512
- throw new E('Invalid signature: left bytes after parsing');
12741
+ throw new E('invalid signature: left bytes after parsing');
12513
12742
  return { r: int.decode(rBytes), s: int.decode(sBytes) };
12514
12743
  },
12515
12744
  hexFromSig(sig) {
12516
12745
  const { _tlv: tlv, _int: int } = DER;
12517
- const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
12746
+ const rs = tlv.encode(0x02, int.encode(sig.r));
12747
+ const ss = tlv.encode(0x02, int.encode(sig.s));
12748
+ const seq = rs + ss;
12518
12749
  return tlv.encode(0x30, seq);
12519
12750
  },
12520
12751
  };
@@ -12568,7 +12799,7 @@ function weierstrassPoints(opts) {
12568
12799
  key = bytesToHex(key);
12569
12800
  // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
12570
12801
  if (typeof key !== 'string' || !lengths.includes(key.length))
12571
- throw new Error('Invalid key');
12802
+ throw new Error('invalid private key');
12572
12803
  key = key.padStart(nByteLength * 2, '0');
12573
12804
  }
12574
12805
  let num;
@@ -12579,7 +12810,7 @@ function weierstrassPoints(opts) {
12579
12810
  : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
12580
12811
  }
12581
12812
  catch (error) {
12582
- throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
12813
+ throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
12583
12814
  }
12584
12815
  if (wrapPrivateKey)
12585
12816
  num = mod(num, N); // disabled by default, enabled for BLS
@@ -12619,7 +12850,7 @@ function weierstrassPoints(opts) {
12619
12850
  if (p.is0()) {
12620
12851
  // (0, 1, 0) aka ZERO is invalid in most contexts.
12621
12852
  // In BLS, ZERO can be serialized, so we allow it.
12622
- // (0, 0, 0) is wrong representation of ZERO and is always invalid.
12853
+ // (0, 0, 0) is invalid representation of ZERO.
12623
12854
  if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
12624
12855
  return;
12625
12856
  throw new Error('bad point: ZERO');
@@ -12843,16 +13074,17 @@ function weierstrassPoints(opts) {
12843
13074
  * an exposed private key e.g. sig verification, which works over *public* keys.
12844
13075
  */
12845
13076
  multiplyUnsafe(sc) {
12846
- aInRange('scalar', sc, _0n, CURVE.n);
13077
+ const { endo, n: N } = CURVE;
13078
+ aInRange('scalar', sc, _0n, N);
12847
13079
  const I = Point.ZERO;
12848
13080
  if (sc === _0n)
12849
13081
  return I;
12850
- if (sc === _1n$1)
13082
+ if (this.is0() || sc === _1n$1)
12851
13083
  return this;
12852
- const { endo } = CURVE;
12853
- if (!endo)
12854
- return wnaf.unsafeLadder(this, sc);
12855
- // Apply endomorphism
13084
+ // Case a: no endomorphism. Case b: has precomputes.
13085
+ if (!endo || wnaf.hasPrecomputes(this))
13086
+ return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
13087
+ // Case c: endomorphism
12856
13088
  let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
12857
13089
  let k1p = I;
12858
13090
  let k2p = I;
@@ -13038,7 +13270,9 @@ function weierstrass(curveDef) {
13038
13270
  return { x, y };
13039
13271
  }
13040
13272
  else {
13041
- throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
13273
+ const cl = compressedLen;
13274
+ const ul = uncompressedLen;
13275
+ throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
13042
13276
  }
13043
13277
  },
13044
13278
  });
@@ -13203,6 +13437,9 @@ function weierstrass(curveDef) {
13203
13437
  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
13204
13438
  const bits2int = CURVE.bits2int ||
13205
13439
  function (bytes) {
13440
+ // Our custom check "just in case"
13441
+ if (bytes.length > 8192)
13442
+ throw new Error('input is too large');
13206
13443
  // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
13207
13444
  // for some cases, since bytes.length * 8 is not actual bitLength.
13208
13445
  const num = bytesToNumberBE(bytes); // check for == u8 done here
@@ -13219,15 +13456,15 @@ function weierstrass(curveDef) {
13219
13456
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
13220
13457
  */
13221
13458
  function int2octets(num) {
13222
- aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);
13459
+ aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);
13223
13460
  // works with order, can have different size than numToField!
13224
13461
  return numberToBytesBE(num, CURVE.nByteLength);
13225
13462
  }
13226
13463
  // Steps A, D of RFC6979 3.2
13227
13464
  // Creates RFC6979 seed; converts msg/privKey to numbers.
13228
13465
  // Used only in sign, not in verify.
13229
- // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
13230
- // Also it can be bigger for P224 + SHA256
13466
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,
13467
+ // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256
13231
13468
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
13232
13469
  if (['recovered', 'canonical'].some((k) => k in opts))
13233
13470
  throw new Error('sign() legacy options not supported');
@@ -13321,39 +13558,48 @@ function weierstrass(curveDef) {
13321
13558
  const sg = signature;
13322
13559
  msgHash = ensureBytes('msgHash', msgHash);
13323
13560
  publicKey = ensureBytes('publicKey', publicKey);
13561
+ const { lowS, prehash, format } = opts;
13562
+ // Verify opts, deduce signature format
13563
+ validateSigVerOpts(opts);
13324
13564
  if ('strict' in opts)
13325
13565
  throw new Error('options.strict was renamed to lowS');
13326
- validateSigVerOpts(opts);
13327
- const { lowS, prehash } = opts;
13566
+ if (format !== undefined && format !== 'compact' && format !== 'der')
13567
+ throw new Error('format must be compact or der');
13568
+ const isHex = typeof sg === 'string' || isBytes$1(sg);
13569
+ const isObj = !isHex &&
13570
+ !format &&
13571
+ typeof sg === 'object' &&
13572
+ sg !== null &&
13573
+ typeof sg.r === 'bigint' &&
13574
+ typeof sg.s === 'bigint';
13575
+ if (!isHex && !isObj)
13576
+ throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
13328
13577
  let _sig = undefined;
13329
13578
  let P;
13330
13579
  try {
13331
- if (typeof sg === 'string' || isBytes$1(sg)) {
13580
+ if (isObj)
13581
+ _sig = new Signature(sg.r, sg.s);
13582
+ if (isHex) {
13332
13583
  // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
13333
13584
  // Since DER can also be 2*nByteLength bytes, we check for it first.
13334
13585
  try {
13335
- _sig = Signature.fromDER(sg);
13586
+ if (format !== 'compact')
13587
+ _sig = Signature.fromDER(sg);
13336
13588
  }
13337
13589
  catch (derError) {
13338
13590
  if (!(derError instanceof DER.Err))
13339
13591
  throw derError;
13340
- _sig = Signature.fromCompact(sg);
13341
13592
  }
13342
- }
13343
- else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
13344
- const { r, s } = sg;
13345
- _sig = new Signature(r, s);
13346
- }
13347
- else {
13348
- throw new Error('PARSE');
13593
+ if (!_sig && format !== 'der')
13594
+ _sig = Signature.fromCompact(sg);
13349
13595
  }
13350
13596
  P = Point.fromHex(publicKey);
13351
13597
  }
13352
13598
  catch (error) {
13353
- if (error.message === 'PARSE')
13354
- throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
13355
13599
  return false;
13356
13600
  }
13601
+ if (!_sig)
13602
+ return false;
13357
13603
  if (lowS && _sig.hasHighS())
13358
13604
  return false;
13359
13605
  if (prehash)
@@ -13381,8 +13627,12 @@ function weierstrass(curveDef) {
13381
13627
  };
13382
13628
  }
13383
13629
 
13630
+ /**
13631
+ * Utilities for short weierstrass curves, combined with noble-hashes.
13632
+ * @module
13633
+ */
13384
13634
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13385
- // connects noble-curves to noble-hashes
13635
+ /** connects noble-curves to noble-hashes */
13386
13636
  function getHash(hash) {
13387
13637
  return {
13388
13638
  hash,
@@ -13392,9 +13642,21 @@ function getHash(hash) {
13392
13642
  }
13393
13643
  function createCurve(curveDef, defHash) {
13394
13644
  const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
13395
- return Object.freeze({ ...create(defHash), create });
13645
+ return { ...create(defHash), create };
13396
13646
  }
13397
13647
 
13648
+ /**
13649
+ * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
13650
+ *
13651
+ * Seems to be rigid (not backdoored)
13652
+ * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
13653
+ *
13654
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
13655
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
13656
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
13657
+ * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
13658
+ * @module
13659
+ */
13398
13660
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13399
13661
  const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
13400
13662
  const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
@@ -13425,31 +13687,35 @@ function sqrtMod(y) {
13425
13687
  const t1 = (pow2(b223, _23n, P) * b22) % P;
13426
13688
  const t2 = (pow2(t1, _6n, P) * b2) % P;
13427
13689
  const root = pow2(t2, _2n, P);
13428
- if (!Fp.eql(Fp.sqr(root), y))
13690
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
13429
13691
  throw new Error('Cannot find square root');
13430
13692
  return root;
13431
13693
  }
13432
- const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
13694
+ const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
13433
13695
  /**
13434
13696
  * secp256k1 short weierstrass curve and ECDSA signatures over it.
13697
+ *
13698
+ * @example
13699
+ * import { secp256k1 } from '@noble/curves/secp256k1';
13700
+ *
13701
+ * const priv = secp256k1.utils.randomPrivateKey();
13702
+ * const pub = secp256k1.getPublicKey(priv);
13703
+ * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
13704
+ * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
13705
+ * const isValid = secp256k1.verify(sig, msg, pub) === true;
13435
13706
  */
13436
13707
  const secp256k1 = createCurve({
13437
13708
  a: BigInt(0), // equation params: a, b
13438
- b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
13439
- Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
13709
+ b: BigInt(7),
13710
+ Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
13440
13711
  n: secp256k1N, // Curve order, total count of valid points in the field
13441
13712
  // Base point (x, y) aka generator point
13442
13713
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
13443
13714
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
13444
13715
  h: BigInt(1), // Cofactor
13445
13716
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
13446
- /**
13447
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
13448
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
13449
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
13450
- * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
13451
- */
13452
13717
  endo: {
13718
+ // Endomorphism, see above
13453
13719
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
13454
13720
  splitScalar: (k) => {
13455
13721
  const n = secp256k1N;
@@ -13586,28 +13852,6 @@ function publicKeyToProtobuf(key) {
13586
13852
  });
13587
13853
  }
13588
13854
 
13589
- /**
13590
- * All PeerId implementations must use this symbol as the name of a property
13591
- * with a boolean `true` value
13592
- */
13593
- const peerIdSymbol = Symbol.for('@libp2p/peer-id');
13594
-
13595
- /**
13596
- * When this error is thrown it means an operation was aborted,
13597
- * usually in response to the `abort` event being emitted by an
13598
- * AbortSignal.
13599
- */
13600
- /**
13601
- * Thrown when and attempt to operate on an unsupported key was made
13602
- */
13603
- class UnsupportedKeyTypeError extends Error {
13604
- static name = 'UnsupportedKeyTypeError';
13605
- constructor(message = 'Unsupported key type') {
13606
- super(message);
13607
- this.name = 'UnsupportedKeyTypeError';
13608
- }
13609
- }
13610
-
13611
13855
  /**
13612
13856
  * @packageDocumentation
13613
13857
  *