@waku/discovery 0.0.7-c41b319.0 → 0.0.7-c43cec2.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
@@ -259,10 +259,6 @@ var EConnectionStateEvents;
259
259
 
260
260
  const DNS_DISCOVERY_TAG = "@waku/bootstrap";
261
261
 
262
- var HealthStatusChangeEvents;
263
- (function (HealthStatusChangeEvents) {
264
- HealthStatusChangeEvents["StatusChange"] = "health:change";
265
- })(HealthStatusChangeEvents || (HealthStatusChangeEvents = {}));
266
262
  var HealthStatus;
267
263
  (function (HealthStatus) {
268
264
  HealthStatus["Unhealthy"] = "Unhealthy";
@@ -274,55 +270,43 @@ function isDefined(value) {
274
270
  return Boolean(value);
275
271
  }
276
272
 
277
- /**
278
- * Internal assertion helpers.
279
- * @module
280
- */
281
- /** Asserts something is positive integer. */
282
- function anumber(n) {
273
+ function number(n) {
283
274
  if (!Number.isSafeInteger(n) || n < 0)
284
- throw new Error('positive integer expected, got ' + n);
275
+ throw new Error(`positive integer expected, not ${n}`);
285
276
  }
286
- /** Is number an Uint8Array? Copied from utils for perf. */
277
+ // copied from utils
287
278
  function isBytes$2(a) {
288
- return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
279
+ return (a instanceof Uint8Array ||
280
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
289
281
  }
290
- /** Asserts something is Uint8Array. */
291
- function abytes$1(b, ...lengths) {
282
+ function bytes(b, ...lengths) {
292
283
  if (!isBytes$2(b))
293
284
  throw new Error('Uint8Array expected');
294
285
  if (lengths.length > 0 && !lengths.includes(b.length))
295
- throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
286
+ throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
296
287
  }
297
- /** Asserts something is hash */
298
- function ahash(h) {
288
+ function hash(h) {
299
289
  if (typeof h !== 'function' || typeof h.create !== 'function')
300
290
  throw new Error('Hash should be wrapped by utils.wrapConstructor');
301
- anumber(h.outputLen);
302
- anumber(h.blockLen);
291
+ number(h.outputLen);
292
+ number(h.blockLen);
303
293
  }
304
- /** Asserts a hash instance has not been destroyed / finished */
305
- function aexists(instance, checkFinished = true) {
294
+ function exists(instance, checkFinished = true) {
306
295
  if (instance.destroyed)
307
296
  throw new Error('Hash instance has been destroyed');
308
297
  if (checkFinished && instance.finished)
309
298
  throw new Error('Hash#digest() has already been called');
310
299
  }
311
- /** Asserts output is properly-sized byte array */
312
- function aoutput(out, instance) {
313
- abytes$1(out);
300
+ function output(out, instance) {
301
+ bytes(out);
314
302
  const min = instance.outputLen;
315
303
  if (out.length < min) {
316
- throw new Error('digestInto() expects output buffer of length at least ' + min);
304
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
317
305
  }
318
306
  }
319
307
 
320
308
  const crypto$2 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
321
309
 
322
- /**
323
- * Utilities for hex, bytes, CSPRNG.
324
- * @module
325
- */
326
310
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
327
311
  // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
328
312
  // node.js versions earlier than v19 don't declare it in global scope.
@@ -331,20 +315,16 @@ const crypto$2 = typeof globalThis === 'object' && 'crypto' in globalThis ? glob
331
315
  // Makes the utils un-importable in browsers without a bundler.
332
316
  // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
333
317
  // Cast array to view
334
- function createView(arr) {
335
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
336
- }
337
- /** The rotate right (circular right shift) operation for uint32 */
338
- function rotr(word, shift) {
339
- return (word << (32 - shift)) | (word >>> shift);
340
- }
318
+ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
319
+ // The rotate right (circular right shift) operation for uint32
320
+ const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
321
+ new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
341
322
  /**
342
- * Convert JS string to byte array.
343
323
  * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
344
324
  */
345
325
  function utf8ToBytes$2(str) {
346
326
  if (typeof str !== 'string')
347
- throw new Error('utf8ToBytes expected string, got ' + typeof str);
327
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
348
328
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
349
329
  }
350
330
  /**
@@ -355,7 +335,7 @@ function utf8ToBytes$2(str) {
355
335
  function toBytes$1(data) {
356
336
  if (typeof data === 'string')
357
337
  data = utf8ToBytes$2(data);
358
- abytes$1(data);
338
+ bytes(data);
359
339
  return data;
360
340
  }
361
341
  /**
@@ -365,7 +345,7 @@ function concatBytes$2(...arrays) {
365
345
  let sum = 0;
366
346
  for (let i = 0; i < arrays.length; i++) {
367
347
  const a = arrays[i];
368
- abytes$1(a);
348
+ bytes(a);
369
349
  sum += a.length;
370
350
  }
371
351
  const res = new Uint8Array(sum);
@@ -376,14 +356,13 @@ function concatBytes$2(...arrays) {
376
356
  }
377
357
  return res;
378
358
  }
379
- /** For runtime check if class implements interface */
359
+ // For runtime check if class implements interface
380
360
  class Hash {
381
361
  // Safe version that clones internal state
382
362
  clone() {
383
363
  return this._cloneInto();
384
364
  }
385
365
  }
386
- /** Wraps hash function, creating an interface on top of it */
387
366
  function wrapConstructor(hashCons) {
388
367
  const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
389
368
  const tmp = hashCons();
@@ -392,7 +371,9 @@ function wrapConstructor(hashCons) {
392
371
  hashC.create = () => hashCons();
393
372
  return hashC;
394
373
  }
395
- /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
374
+ /**
375
+ * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
376
+ */
396
377
  function randomBytes(bytesLength = 32) {
397
378
  if (crypto$2 && typeof crypto$2.getRandomValues === 'function') {
398
379
  return crypto$2.getRandomValues(new Uint8Array(bytesLength));
@@ -405,10 +386,8 @@ function randomBytes(bytesLength = 32) {
405
386
  }
406
387
 
407
388
  /**
408
- * Internal Merkle-Damgard hash utils.
409
- * @module
389
+ * Polyfill for Safari 14
410
390
  */
411
- /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
412
391
  function setBigUint64(view, byteOffset, value, isLE) {
413
392
  if (typeof view.setBigUint64 === 'function')
414
393
  return view.setBigUint64(byteOffset, value, isLE);
@@ -421,14 +400,14 @@ function setBigUint64(view, byteOffset, value, isLE) {
421
400
  view.setUint32(byteOffset + h, wh, isLE);
422
401
  view.setUint32(byteOffset + l, wl, isLE);
423
402
  }
424
- /** Choice: a ? b : c */
425
- function Chi(a, b, c) {
426
- return (a & b) ^ (~a & c);
427
- }
428
- /** Majority function, true if any two inputs is true. */
429
- function Maj(a, b, c) {
430
- return (a & b) ^ (a & c) ^ (b & c);
431
- }
403
+ /**
404
+ * Choice: a ? b : c
405
+ */
406
+ const Chi = (a, b, c) => (a & b) ^ (~a & c);
407
+ /**
408
+ * Majority function, true if any two inputs is true
409
+ */
410
+ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
432
411
  /**
433
412
  * Merkle-Damgard hash construction base class.
434
413
  * Could be used to create MD5, RIPEMD, SHA1, SHA2.
@@ -448,7 +427,7 @@ class HashMD extends Hash {
448
427
  this.view = createView(this.buffer);
449
428
  }
450
429
  update(data) {
451
- aexists(this);
430
+ exists(this);
452
431
  const { view, buffer, blockLen } = this;
453
432
  data = toBytes$1(data);
454
433
  const len = data.length;
@@ -474,8 +453,8 @@ class HashMD extends Hash {
474
453
  return this;
475
454
  }
476
455
  digestInto(out) {
477
- aexists(this);
478
- aoutput(out, this);
456
+ exists(this);
457
+ output(out, this);
479
458
  this.finished = true;
480
459
  // Padding
481
460
  // We can avoid allocation of buffer for padding completely if it
@@ -532,16 +511,10 @@ class HashMD extends Hash {
532
511
  }
533
512
  }
534
513
 
535
- /**
536
- * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
537
- *
538
- * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
539
- * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
540
- *
541
- * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
542
- * @module
543
- */
544
- /** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */
514
+ // SHA2-256 need to try 2^128 hashes to execute birthday attack.
515
+ // BTC network is doing 2^67 hashes/sec as per early 2023.
516
+ // Round constants:
517
+ // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
545
518
  // prettier-ignore
546
519
  const SHA256_K = /* @__PURE__ */ new Uint32Array([
547
520
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
@@ -553,15 +526,14 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([
553
526
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
554
527
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
555
528
  ]);
556
- /** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */
529
+ // Initial state:
530
+ // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
557
531
  // prettier-ignore
558
532
  const SHA256_IV = /* @__PURE__ */ new Uint32Array([
559
533
  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
560
534
  ]);
561
- /**
562
- * Temporary buffer, not used to store anything between runs.
563
- * Named this way because it matches specification.
564
- */
535
+ // Temporary buffer, not used to store anything between runs
536
+ // Named this way because it matches specification.
565
537
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
566
538
  class SHA256 extends HashMD {
567
539
  constructor() {
@@ -638,7 +610,10 @@ class SHA256 extends HashMD {
638
610
  this.buffer.fill(0);
639
611
  }
640
612
  }
641
- /** SHA2-256 hash function */
613
+ /**
614
+ * SHA2-256 hash function
615
+ * @param message - data that would be hashed
616
+ */
642
617
  const sha256$1 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
643
618
 
644
619
  function equals$2(aa, bb) {
@@ -1290,7 +1265,7 @@ new TextDecoder();
1290
1265
 
1291
1266
  /* eslint-disable */
1292
1267
  var encode_1 = encode$7;
1293
- var MSB$1 = 0x80, MSBALL = -128, INT = Math.pow(2, 31);
1268
+ var MSB$1 = 0x80, REST$1 = 0x7F, MSBALL = ~REST$1, INT = Math.pow(2, 31);
1294
1269
  /**
1295
1270
  * @param {number} num
1296
1271
  * @param {number[]} out
@@ -1314,7 +1289,7 @@ function encode$7(num, out, offset) {
1314
1289
  return out;
1315
1290
  }
1316
1291
  var decode$8 = read$1;
1317
- var MSB$1$1 = 0x80, REST$1 = 0x7F;
1292
+ var MSB$1$1 = 0x80, REST$1$1 = 0x7F;
1318
1293
  /**
1319
1294
  * @param {string | any[]} buf
1320
1295
  * @param {number} offset
@@ -1329,8 +1304,8 @@ function read$1(buf, offset) {
1329
1304
  }
1330
1305
  b = buf[counter++];
1331
1306
  res += shift < 28
1332
- ? (b & REST$1) << shift
1333
- : (b & REST$1) * Math.pow(2, shift);
1307
+ ? (b & REST$1$1) << shift
1308
+ : (b & REST$1$1) * Math.pow(2, shift);
1334
1309
  shift += 7;
1335
1310
  } while (b >= MSB$1$1);
1336
1311
  // @ts-ignore
@@ -2375,62 +2350,24 @@ function setup(env) {
2375
2350
  createDebug.names = [];
2376
2351
  createDebug.skips = [];
2377
2352
 
2378
- const split = (typeof namespaces === 'string' ? namespaces : '')
2379
- .trim()
2380
- .replace(' ', ',')
2381
- .split(',')
2382
- .filter(Boolean);
2353
+ let i;
2354
+ const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
2355
+ const len = split.length;
2383
2356
 
2384
- for (const ns of split) {
2385
- if (ns[0] === '-') {
2386
- createDebug.skips.push(ns.slice(1));
2387
- } else {
2388
- createDebug.names.push(ns);
2357
+ for (i = 0; i < len; i++) {
2358
+ if (!split[i]) {
2359
+ // ignore empty strings
2360
+ continue;
2389
2361
  }
2390
- }
2391
- }
2392
2362
 
2393
- /**
2394
- * Checks if the given string matches a namespace template, honoring
2395
- * asterisks as wildcards.
2396
- *
2397
- * @param {String} search
2398
- * @param {String} template
2399
- * @return {Boolean}
2400
- */
2401
- function matchesTemplate(search, template) {
2402
- let searchIndex = 0;
2403
- let templateIndex = 0;
2404
- let starIndex = -1;
2405
- let matchIndex = 0;
2406
-
2407
- while (searchIndex < search.length) {
2408
- if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
2409
- // Match character or proceed with wildcard
2410
- if (template[templateIndex] === '*') {
2411
- starIndex = templateIndex;
2412
- matchIndex = searchIndex;
2413
- templateIndex++; // Skip the '*'
2414
- } else {
2415
- searchIndex++;
2416
- templateIndex++;
2417
- }
2418
- } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
2419
- // Backtrack to the last '*' and try to match more characters
2420
- templateIndex = starIndex + 1;
2421
- matchIndex++;
2422
- searchIndex = matchIndex;
2363
+ namespaces = split[i].replace(/\*/g, '.*?');
2364
+
2365
+ if (namespaces[0] === '-') {
2366
+ createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
2423
2367
  } else {
2424
- return false; // No match
2368
+ createDebug.names.push(new RegExp('^' + namespaces + '$'));
2425
2369
  }
2426
2370
  }
2427
-
2428
- // Handle trailing '*' in template
2429
- while (templateIndex < template.length && template[templateIndex] === '*') {
2430
- templateIndex++;
2431
- }
2432
-
2433
- return templateIndex === template.length;
2434
2371
  }
2435
2372
 
2436
2373
  /**
@@ -2441,8 +2378,8 @@ function setup(env) {
2441
2378
  */
2442
2379
  function disable() {
2443
2380
  const namespaces = [
2444
- ...createDebug.names,
2445
- ...createDebug.skips.map(namespace => '-' + namespace)
2381
+ ...createDebug.names.map(toNamespace),
2382
+ ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
2446
2383
  ].join(',');
2447
2384
  createDebug.enable('');
2448
2385
  return namespaces;
@@ -2456,14 +2393,21 @@ function setup(env) {
2456
2393
  * @api public
2457
2394
  */
2458
2395
  function enabled(name) {
2459
- for (const skip of createDebug.skips) {
2460
- if (matchesTemplate(name, skip)) {
2396
+ if (name[name.length - 1] === '*') {
2397
+ return true;
2398
+ }
2399
+
2400
+ let i;
2401
+ let len;
2402
+
2403
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
2404
+ if (createDebug.skips[i].test(name)) {
2461
2405
  return false;
2462
2406
  }
2463
2407
  }
2464
2408
 
2465
- for (const ns of createDebug.names) {
2466
- if (matchesTemplate(name, ns)) {
2409
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
2410
+ if (createDebug.names[i].test(name)) {
2467
2411
  return true;
2468
2412
  }
2469
2413
  }
@@ -2471,6 +2415,19 @@ function setup(env) {
2471
2415
  return false;
2472
2416
  }
2473
2417
 
2418
+ /**
2419
+ * Convert regexp to namespace
2420
+ *
2421
+ * @param {RegExp} regxep
2422
+ * @return {String} namespace
2423
+ * @api private
2424
+ */
2425
+ function toNamespace(regexp) {
2426
+ return regexp.toString()
2427
+ .substring(2, regexp.toString().length - 2)
2428
+ .replace(/\.\*\?$/, '*');
2429
+ }
2430
+
2474
2431
  /**
2475
2432
  * Coerce `val`.
2476
2433
  *
@@ -2632,7 +2589,6 @@ var common = setup;
2632
2589
 
2633
2590
  // Is webkit? http://stackoverflow.com/a/16459606/376773
2634
2591
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
2635
- // eslint-disable-next-line no-return-assign
2636
2592
  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
2637
2593
  // Is firebug? http://stackoverflow.com/a/398120/376773
2638
2594
  (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
@@ -3073,10 +3029,10 @@ class JacobianPoint {
3073
3029
  const cond1 = window % 2 !== 0;
3074
3030
  const cond2 = wbits < 0;
3075
3031
  if (wbits === 0) {
3076
- f = f.add(constTimeNegate$1(cond1, precomputes[offset1]));
3032
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
3077
3033
  }
3078
3034
  else {
3079
- p = p.add(constTimeNegate$1(cond2, precomputes[offset2]));
3035
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
3080
3036
  }
3081
3037
  }
3082
3038
  return { p, f };
@@ -3089,8 +3045,8 @@ class JacobianPoint {
3089
3045
  const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
3090
3046
  let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
3091
3047
  let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);
3092
- k1p = constTimeNegate$1(k1neg, k1p);
3093
- k2p = constTimeNegate$1(k2neg, k2p);
3048
+ k1p = constTimeNegate(k1neg, k1p);
3049
+ k2p = constTimeNegate(k2neg, k2p);
3094
3050
  k2p = new JacobianPoint(mod$1(k2p.x * endo.beta), k2p.y, k2p.z);
3095
3051
  point = k1p.add(k2p);
3096
3052
  fake = f1p.add(f2p);
@@ -3122,7 +3078,7 @@ class JacobianPoint {
3122
3078
  }
3123
3079
  JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n$7);
3124
3080
  JacobianPoint.ZERO = new JacobianPoint(_0n$5, _1n$7, _0n$5);
3125
- function constTimeNegate$1(condition, item) {
3081
+ function constTimeNegate(condition, item) {
3126
3082
  const neg = item.negate();
3127
3083
  return condition ? neg : item;
3128
3084
  }
@@ -5042,7 +4998,7 @@ function parseIPv6(input) {
5042
4998
  return parser.new(input).parseWith(() => parser.readIPv6Addr());
5043
4999
  }
5044
5000
  /** Parse `input` into IPv4 or IPv6 bytes. */
5045
- function parseIP(input, mapIPv4ToIPv6 = false) {
5001
+ function parseIP(input) {
5046
5002
  // strip zone index if it is present
5047
5003
  if (input.includes("%")) {
5048
5004
  input = input.split("%")[0];
@@ -5050,14 +5006,7 @@ function parseIP(input, mapIPv4ToIPv6 = false) {
5050
5006
  if (input.length > MAX_IPV6_LENGTH) {
5051
5007
  return undefined;
5052
5008
  }
5053
- const addr = parser.new(input).parseWith(() => parser.readIPAddr());
5054
- if (!addr) {
5055
- return undefined;
5056
- }
5057
- if (mapIPv4ToIPv6 && addr.length === 4) {
5058
- return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, addr[0], addr[1], addr[2], addr[3]]);
5059
- }
5060
- return addr;
5009
+ return parser.new(input).parseWith(() => parser.readIPAddr());
5061
5010
  }
5062
5011
 
5063
5012
  /** Check if `input` is IPv4. */
@@ -5245,13 +5194,17 @@ function getProtocol(proto) {
5245
5194
  throw new Error(`invalid protocol id type: ${typeof proto}`);
5246
5195
  }
5247
5196
 
5197
+ /**
5198
+ * @packageDocumentation
5199
+ *
5200
+ * Provides methods for converting
5201
+ */
5248
5202
  getProtocol('ip4');
5249
5203
  getProtocol('ip6');
5250
5204
  getProtocol('ipcidr');
5251
5205
  /**
5252
5206
  * Convert [code,Uint8Array] to string
5253
5207
  */
5254
- // eslint-disable-next-line complexity
5255
5208
  function convertToString(proto, buf) {
5256
5209
  const protocol = getProtocol(proto);
5257
5210
  switch (protocol.code) {
@@ -5260,8 +5213,6 @@ function convertToString(proto, buf) {
5260
5213
  return bytes2ip(buf);
5261
5214
  case 42: // ipv6zone
5262
5215
  return bytes2str(buf);
5263
- case 43: // ipcidr
5264
- return toString$6(buf, 'base10');
5265
5216
  case 6: // tcp
5266
5217
  case 273: // udp
5267
5218
  case 33: // dccp
@@ -5289,7 +5240,6 @@ function convertToString(proto, buf) {
5289
5240
  return toString$6(buf, 'base16'); // no clue. convert to hex
5290
5241
  }
5291
5242
  }
5292
- // eslint-disable-next-line complexity
5293
5243
  function convertToBytes(proto, str) {
5294
5244
  const protocol = getProtocol(proto);
5295
5245
  switch (protocol.code) {
@@ -5299,8 +5249,6 @@ function convertToBytes(proto, str) {
5299
5249
  return ip2bytes(str);
5300
5250
  case 42: // ipv6zone
5301
5251
  return str2bytes(str);
5302
- case 43: // ipcidr
5303
- return fromString(str, 'base10');
5304
5252
  case 6: // tcp
5305
5253
  case 273: // udp
5306
5254
  case 33: // dccp
@@ -5595,6 +5543,19 @@ function ParseError(str) {
5595
5543
  return new Error('Error parsing address: ' + str);
5596
5544
  }
5597
5545
 
5546
+ /**
5547
+ * @packageDocumentation
5548
+ *
5549
+ * An implementation of a Multiaddr in JavaScript
5550
+ *
5551
+ * @example
5552
+ *
5553
+ * ```js
5554
+ * import { multiaddr } from '@multiformats/multiaddr'
5555
+ *
5556
+ * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')
5557
+ * ```
5558
+ */
5598
5559
  const inspect$2 = Symbol.for('nodejs.util.inspect.custom');
5599
5560
  const symbol$1 = Symbol.for('@multiformats/js-multiaddr/multiaddr');
5600
5561
  const DNS_CODES = [
@@ -5706,20 +5667,10 @@ class Multiaddr {
5706
5667
  return this.#tuples.map(([code]) => getProtocol(code).name);
5707
5668
  }
5708
5669
  tuples() {
5709
- return this.#tuples.map(([code, value]) => {
5710
- if (value == null) {
5711
- return [code];
5712
- }
5713
- return [code, value];
5714
- });
5670
+ return this.#tuples;
5715
5671
  }
5716
5672
  stringTuples() {
5717
- return this.#stringTuples.map(([code, value]) => {
5718
- if (value == null) {
5719
- return [code];
5720
- }
5721
- return [code, value];
5722
- });
5673
+ return this.#stringTuples;
5723
5674
  }
5724
5675
  encapsulate(addr) {
5725
5676
  addr = new Multiaddr(addr);
@@ -5849,8 +5800,10 @@ class Multiaddr {
5849
5800
  *
5850
5801
  * ```TypeScript
5851
5802
  * import { multiaddr } from '@multiformats/multiaddr'
5803
+ * const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
5804
+ * // Multiaddr(/ip4/127.0.0.1/udp/1234)
5852
5805
  *
5853
- * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')
5806
+ * const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
5854
5807
  * // Multiaddr(/ip4/127.0.0.1/udp/1234)
5855
5808
  *
5856
5809
  * addr.bytes
@@ -5889,9 +5842,9 @@ class Multiaddr {
5889
5842
  *
5890
5843
  * ```TypeScript
5891
5844
  * import { multiaddr, resolvers } from '@multiformats/multiaddr'
5892
- * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'
5845
+ * import { dnsaddr } from '@multiformats/multiaddr/resolvers'
5893
5846
  *
5894
- * resolvers.set('dnsaddr', dnsaddrResolver)
5847
+ * resolvers.set('dnsaddr', dnsaddr)
5895
5848
  *
5896
5849
  * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
5897
5850
  *
@@ -5900,7 +5853,7 @@ class Multiaddr {
5900
5853
  * signal: AbortSignal.timeout(5000)
5901
5854
  * })
5902
5855
  *
5903
- * console.info(resolved)
5856
+ * console.info(await ma.resolve(resolved)
5904
5857
  * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]
5905
5858
  * ```
5906
5859
  *
@@ -5914,9 +5867,7 @@ class Multiaddr {
5914
5867
  * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'
5915
5868
  *
5916
5869
  * const resolver = dns({
5917
- * resolvers: {
5918
- * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')
5919
- * }
5870
+ * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')
5920
5871
  * })
5921
5872
  *
5922
5873
  * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
@@ -6002,13 +5953,9 @@ function locationMultiaddrFromEnrFields(enr, protocol) {
6002
5953
  return multiaddrFromFields(isIpv6 ? "ip6" : "ip4", protoName, ipVal, protoVal);
6003
5954
  }
6004
5955
 
6005
- /**
6006
- * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
6007
- * @todo re-check https://issues.chromium.org/issues/42212588
6008
- * @module
6009
- */
6010
5956
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
6011
5957
  const _32n = /* @__PURE__ */ BigInt(32);
5958
+ // We are not using BigUint64Array, because they are extremely slow as per 2022
6012
5959
  function fromBig(n, le = false) {
6013
5960
  if (le)
6014
5961
  return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
@@ -6065,13 +6012,6 @@ const u64 = {
6065
6012
  add, add3L, add3H, add4L, add4H, add5H, add5L,
6066
6013
  };
6067
6014
 
6068
- /**
6069
- * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.
6070
- *
6071
- * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
6072
- * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
6073
- * @module
6074
- */
6075
6015
  // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
6076
6016
  // prettier-ignore
6077
6017
  const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
@@ -6226,13 +6166,8 @@ class SHA512 extends HashMD {
6226
6166
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
6227
6167
  }
6228
6168
  }
6229
- /** SHA2-512 hash function. */
6230
6169
  const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
6231
6170
 
6232
- /**
6233
- * Hex, bytes and number utilities.
6234
- * @module
6235
- */
6236
6171
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6237
6172
  // 100 lines of code in the file are duplicated from noble-hashes (utils).
6238
6173
  // This is OK: `abstract` directory does not use noble-hashes.
@@ -6242,7 +6177,8 @@ const _0n$4 = /* @__PURE__ */ BigInt(0);
6242
6177
  const _1n$6 = /* @__PURE__ */ BigInt(1);
6243
6178
  const _2n$4 = /* @__PURE__ */ BigInt(2);
6244
6179
  function isBytes$1(a) {
6245
- return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
6180
+ return (a instanceof Uint8Array ||
6181
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
6246
6182
  }
6247
6183
  function abytes(item) {
6248
6184
  if (!isBytes$1(item))
@@ -6250,7 +6186,7 @@ function abytes(item) {
6250
6186
  }
6251
6187
  function abool(title, value) {
6252
6188
  if (typeof value !== 'boolean')
6253
- throw new Error(title + ' boolean expected, got ' + value);
6189
+ throw new Error(`${title} must be valid boolean, got "${value}".`);
6254
6190
  }
6255
6191
  // Array where index 0xf0 (240) is mapped to string 'f0'
6256
6192
  const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
@@ -6268,22 +6204,23 @@ function bytesToHex(bytes) {
6268
6204
  }
6269
6205
  function numberToHexUnpadded(num) {
6270
6206
  const hex = num.toString(16);
6271
- return hex.length & 1 ? '0' + hex : hex;
6207
+ return hex.length & 1 ? `0${hex}` : hex;
6272
6208
  }
6273
6209
  function hexToNumber(hex) {
6274
6210
  if (typeof hex !== 'string')
6275
6211
  throw new Error('hex string expected, got ' + typeof hex);
6276
- return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
6212
+ // Big Endian
6213
+ return BigInt(hex === '' ? '0' : `0x${hex}`);
6277
6214
  }
6278
6215
  // We use optimized technique to convert hex string to byte array
6279
- const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
6280
- function asciiToBase16(ch) {
6281
- if (ch >= asciis._0 && ch <= asciis._9)
6282
- return ch - asciis._0; // '2' => 50-48
6283
- if (ch >= asciis.A && ch <= asciis.F)
6284
- return ch - (asciis.A - 10); // 'B' => 66-(65-10)
6285
- if (ch >= asciis.a && ch <= asciis.f)
6286
- return ch - (asciis.a - 10); // 'b' => 98-(97-10)
6216
+ const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
6217
+ function asciiToBase16(char) {
6218
+ if (char >= asciis._0 && char <= asciis._9)
6219
+ return char - asciis._0;
6220
+ if (char >= asciis._A && char <= asciis._F)
6221
+ return char - (asciis._A - 10);
6222
+ if (char >= asciis._a && char <= asciis._f)
6223
+ return char - (asciis._a - 10);
6287
6224
  return;
6288
6225
  }
6289
6226
  /**
@@ -6295,7 +6232,7 @@ function hexToBytes(hex) {
6295
6232
  const hl = hex.length;
6296
6233
  const al = hl / 2;
6297
6234
  if (hl % 2)
6298
- throw new Error('hex string expected, got unpadded hex of length ' + hl);
6235
+ throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
6299
6236
  const array = new Uint8Array(al);
6300
6237
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
6301
6238
  const n1 = asciiToBase16(hex.charCodeAt(hi));
@@ -6304,7 +6241,7 @@ function hexToBytes(hex) {
6304
6241
  const char = hex[hi] + hex[hi + 1];
6305
6242
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
6306
6243
  }
6307
- array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
6244
+ array[ai] = n1 * 16 + n2;
6308
6245
  }
6309
6246
  return array;
6310
6247
  }
@@ -6342,7 +6279,7 @@ function ensureBytes(title, hex, expectedLength) {
6342
6279
  res = hexToBytes(hex);
6343
6280
  }
6344
6281
  catch (e) {
6345
- throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
6282
+ throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
6346
6283
  }
6347
6284
  }
6348
6285
  else if (isBytes$1(hex)) {
@@ -6351,11 +6288,11 @@ function ensureBytes(title, hex, expectedLength) {
6351
6288
  res = Uint8Array.from(hex);
6352
6289
  }
6353
6290
  else {
6354
- throw new Error(title + ' must be hex string or Uint8Array');
6291
+ throw new Error(`${title} must be hex string or Uint8Array`);
6355
6292
  }
6356
6293
  const len = res.length;
6357
6294
  if (typeof expectedLength === 'number' && len !== expectedLength)
6358
- throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
6295
+ throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
6359
6296
  return res;
6360
6297
  }
6361
6298
  /**
@@ -6390,7 +6327,7 @@ function equalBytes(a, b) {
6390
6327
  */
6391
6328
  function utf8ToBytes(str) {
6392
6329
  if (typeof str !== 'string')
6393
- throw new Error('string expected');
6330
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
6394
6331
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
6395
6332
  }
6396
6333
  // Is positive bigint
@@ -6410,7 +6347,7 @@ function aInRange(title, n, min, max) {
6410
6347
  // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
6411
6348
  // - our way is the cleanest: `inRange('x', x, 0n, P)
6412
6349
  if (!inRange(n, min, max))
6413
- throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
6350
+ throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
6414
6351
  }
6415
6352
  // Bit operations
6416
6353
  /**
@@ -6520,12 +6457,12 @@ function validateObject(object, validators, optValidators = {}) {
6520
6457
  const checkField = (fieldName, type, isOptional) => {
6521
6458
  const checkVal = validatorFns[type];
6522
6459
  if (typeof checkVal !== 'function')
6523
- throw new Error('invalid validator function');
6460
+ throw new Error(`Invalid validator "${type}", expected function`);
6524
6461
  const val = object[fieldName];
6525
6462
  if (isOptional && val === undefined)
6526
6463
  return;
6527
6464
  if (!checkVal(val, object)) {
6528
- throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
6465
+ throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
6529
6466
  }
6530
6467
  };
6531
6468
  for (const [fieldName, type] of Object.entries(validators))
@@ -6594,17 +6531,14 @@ var ut = /*#__PURE__*/Object.freeze({
6594
6531
  validateObject: validateObject
6595
6532
  });
6596
6533
 
6597
- /**
6598
- * Utils for modular division and finite fields.
6599
- * A finite field over 11 is integer number operations `mod 11`.
6600
- * There is no division: it is replaced by modular multiplicative inverse.
6601
- * @module
6602
- */
6603
6534
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6535
+ // Utilities for modular arithmetics and finite fields
6604
6536
  // prettier-ignore
6605
- const _0n$3 = BigInt(0), _1n$5 = BigInt(1), _2n$3 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
6537
+ const _0n$3 = BigInt(0), _1n$5 = BigInt(1), _2n$3 = BigInt(2), _3n$1 = BigInt(3);
6606
6538
  // prettier-ignore
6607
- const _4n = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5), _8n$2 = /* @__PURE__ */ BigInt(8);
6539
+ const _4n = BigInt(4), _5n$1 = BigInt(5), _8n$2 = BigInt(8);
6540
+ // prettier-ignore
6541
+ BigInt(9); BigInt(16);
6608
6542
  // Calculates a modulo b
6609
6543
  function mod(a, b) {
6610
6544
  const result = a % b;
@@ -6613,15 +6547,13 @@ function mod(a, b) {
6613
6547
  /**
6614
6548
  * Efficiently raise num to power and do modular division.
6615
6549
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
6616
- * @todo use field version && remove
6617
6550
  * @example
6618
6551
  * pow(2n, 6n, 11n) // 64n % 11n == 9n
6619
6552
  */
6553
+ // TODO: use field version && remove
6620
6554
  function pow(num, power, modulo) {
6621
- if (power < _0n$3)
6622
- throw new Error('invalid exponent, negatives unsupported');
6623
- if (modulo <= _0n$3)
6624
- throw new Error('invalid modulus');
6555
+ if (modulo <= _0n$3 || power < _0n$3)
6556
+ throw new Error('Expected power/modulo > 0');
6625
6557
  if (modulo === _1n$5)
6626
6558
  return _0n$3;
6627
6559
  let res = _1n$5;
@@ -6633,7 +6565,7 @@ function pow(num, power, modulo) {
6633
6565
  }
6634
6566
  return res;
6635
6567
  }
6636
- /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
6568
+ // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
6637
6569
  function pow2(x, power, modulo) {
6638
6570
  let res = x;
6639
6571
  while (power-- > _0n$3) {
@@ -6642,15 +6574,12 @@ function pow2(x, power, modulo) {
6642
6574
  }
6643
6575
  return res;
6644
6576
  }
6645
- /**
6646
- * Inverses number over modulo.
6647
- * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
6648
- */
6577
+ // Inverses number over modulo
6649
6578
  function invert(number, modulo) {
6650
- if (number === _0n$3)
6651
- throw new Error('invert: expected non-zero number');
6652
- if (modulo <= _0n$3)
6653
- throw new Error('invert: expected positive modulus, got ' + modulo);
6579
+ if (number === _0n$3 || modulo <= _0n$3) {
6580
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
6581
+ }
6582
+ // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
6654
6583
  // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
6655
6584
  let a = mod(number, modulo);
6656
6585
  let b = modulo;
@@ -6690,11 +6619,8 @@ function tonelliShanks(P) {
6690
6619
  for (Q = P - _1n$5, S = 0; Q % _2n$3 === _0n$3; Q /= _2n$3, S++)
6691
6620
  ;
6692
6621
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
6693
- for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$5; Z++) {
6694
- // Crash instead of infinity loop, we cannot reasonable count until P.
6695
- if (Z > 1000)
6696
- throw new Error('Cannot find square root: likely non-prime P');
6697
- }
6622
+ for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$5; Z++)
6623
+ ;
6698
6624
  // Fast-path
6699
6625
  if (S === 1) {
6700
6626
  const p1div4 = (P + _1n$5) / _4n;
@@ -6736,18 +6662,9 @@ function tonelliShanks(P) {
6736
6662
  return x;
6737
6663
  };
6738
6664
  }
6739
- /**
6740
- * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:
6741
- *
6742
- * 1. P ≡ 3 (mod 4)
6743
- * 2. P ≡ 5 (mod 8)
6744
- * 3. P ≡ 9 (mod 16)
6745
- * 4. Tonelli-Shanks algorithm
6746
- *
6747
- * Different algorithms can give different roots, it is up to user to decide which one they want.
6748
- * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
6749
- */
6750
6665
  function FpSqrt(P) {
6666
+ // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
6667
+ // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
6751
6668
  // P ≡ 3 (mod 4)
6752
6669
  // √n = n^((P+1)/4)
6753
6670
  if (P % _4n === _3n$1) {
@@ -6811,7 +6728,7 @@ function FpPow(f, num, power) {
6811
6728
  // Should have same speed as pow for bigints
6812
6729
  // TODO: benchmark!
6813
6730
  if (power < _0n$3)
6814
- throw new Error('invalid exponent, negatives unsupported');
6731
+ throw new Error('Expected power > 0');
6815
6732
  if (power === _0n$3)
6816
6733
  return f.ONE;
6817
6734
  if (power === _1n$5)
@@ -6858,15 +6775,15 @@ function nLength(n, nBitLength) {
6858
6775
  return { nBitLength: _nBitLength, nByteLength };
6859
6776
  }
6860
6777
  /**
6861
- * Initializes a finite field over prime.
6778
+ * Initializes a finite field over prime. **Non-primes are not supported.**
6779
+ * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
6862
6780
  * Major performance optimizations:
6863
6781
  * * a) denormalized operations like mulN instead of mul
6864
6782
  * * b) same object shape: never add or remove keys
6865
6783
  * * c) Object.freeze
6866
- * Fragile: always run a benchmark on a change.
6867
- * Security note: operations don't check 'isValid' for all elements for performance reasons,
6784
+ * NOTE: operations don't check 'isValid' for all elements for performance reasons,
6868
6785
  * it is caller responsibility to check this.
6869
- * This is low-level code, please make sure you know what you're doing.
6786
+ * This is low-level code, please make sure you know what you doing.
6870
6787
  * @param ORDER prime positive bigint
6871
6788
  * @param bitLen how many bits the field consumes
6872
6789
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -6874,14 +6791,13 @@ function nLength(n, nBitLength) {
6874
6791
  */
6875
6792
  function Field(ORDER, bitLen, isLE = false, redef = {}) {
6876
6793
  if (ORDER <= _0n$3)
6877
- throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
6794
+ throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
6878
6795
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
6879
6796
  if (BYTES > 2048)
6880
- throw new Error('invalid field: expected ORDER of <= 2048 bytes');
6881
- let sqrtP; // cached sqrtP
6797
+ throw new Error('Field lengths over 2048 bytes are not supported');
6798
+ const sqrtP = FpSqrt(ORDER);
6882
6799
  const f = Object.freeze({
6883
6800
  ORDER,
6884
- isLE,
6885
6801
  BITS,
6886
6802
  BYTES,
6887
6803
  MASK: bitMask(BITS),
@@ -6890,7 +6806,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6890
6806
  create: (num) => mod(num, ORDER),
6891
6807
  isValid: (num) => {
6892
6808
  if (typeof num !== 'bigint')
6893
- throw new Error('invalid field element: expected bigint, got ' + typeof num);
6809
+ throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
6894
6810
  return _0n$3 <= num && num < ORDER; // 0 is valid element, but it's not invertible
6895
6811
  },
6896
6812
  is0: (num) => num === _0n$3,
@@ -6909,12 +6825,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6909
6825
  subN: (lhs, rhs) => lhs - rhs,
6910
6826
  mulN: (lhs, rhs) => lhs * rhs,
6911
6827
  inv: (num) => invert(num, ORDER),
6912
- sqrt: redef.sqrt ||
6913
- ((n) => {
6914
- if (!sqrtP)
6915
- sqrtP = FpSqrt(ORDER);
6916
- return sqrtP(f, n);
6917
- }),
6828
+ sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
6918
6829
  invertBatch: (lst) => FpInvertBatch(f, lst),
6919
6830
  // TODO: do we really need constant cmov?
6920
6831
  // We don't have const-time bigints anyway, so probably will be not very useful
@@ -6922,7 +6833,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6922
6833
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
6923
6834
  fromBytes: (bytes) => {
6924
6835
  if (bytes.length !== BYTES)
6925
- throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
6836
+ throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
6926
6837
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
6927
6838
  },
6928
6839
  });
@@ -6970,80 +6881,52 @@ function mapHashToField(key, fieldOrder, isLE = false) {
6970
6881
  const minLen = getMinHashLength(fieldOrder);
6971
6882
  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
6972
6883
  if (len < 16 || len < minLen || len > 1024)
6973
- throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
6974
- const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
6884
+ throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
6885
+ const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
6975
6886
  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
6976
6887
  const reduced = mod(num, fieldOrder - _1n$5) + _1n$5;
6977
6888
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
6978
6889
  }
6979
6890
 
6980
- /**
6981
- * Methods for elliptic curve multiplication by scalars.
6982
- * Contains wNAF, pippenger
6983
- * @module
6984
- */
6985
6891
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6892
+ // Abelian group utilities
6986
6893
  const _0n$2 = BigInt(0);
6987
6894
  const _1n$4 = BigInt(1);
6988
- function constTimeNegate(condition, item) {
6989
- const neg = item.negate();
6990
- return condition ? neg : item;
6991
- }
6992
- function validateW(W, bits) {
6993
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
6994
- throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
6995
- }
6996
- function calcWOpts(W, bits) {
6997
- validateW(W, bits);
6998
- const windows = Math.ceil(bits / W) + 1; // +1, because
6999
- const windowSize = 2 ** (W - 1); // -1 because we skip zero
7000
- return { windows, windowSize };
7001
- }
7002
- function validateMSMPoints(points, c) {
7003
- if (!Array.isArray(points))
7004
- throw new Error('array expected');
7005
- points.forEach((p, i) => {
7006
- if (!(p instanceof c))
7007
- throw new Error('invalid point at index ' + i);
7008
- });
7009
- }
7010
- function validateMSMScalars(scalars, field) {
7011
- if (!Array.isArray(scalars))
7012
- throw new Error('array of scalars expected');
7013
- scalars.forEach((s, i) => {
7014
- if (!field.isValid(s))
7015
- throw new Error('invalid scalar at index ' + i);
7016
- });
7017
- }
7018
6895
  // Since points in different groups cannot be equal (different object constructor),
7019
6896
  // we can have single place to store precomputes
7020
6897
  const pointPrecomputes = new WeakMap();
7021
6898
  const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
7022
- function getW(P) {
7023
- return pointWindowSizes.get(P) || 1;
7024
- }
7025
- /**
7026
- * Elliptic curve multiplication of Point by scalar. Fragile.
7027
- * Scalars should always be less than curve order: this should be checked inside of a curve itself.
7028
- * Creates precomputation tables for fast multiplication:
7029
- * - private scalar is split by fixed size windows of W bits
7030
- * - every window point is collected from window's table & added to accumulator
7031
- * - since windows are different, same point inside tables won't be accessed more than once per calc
7032
- * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
7033
- * - +1 window is neccessary for wNAF
7034
- * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
7035
- *
7036
- * @todo Research returning 2d JS array of windows, instead of a single window.
7037
- * This would allow windows to be in different memory locations
7038
- */
6899
+ // Elliptic curve multiplication of Point by scalar. Fragile.
6900
+ // Scalars should always be less than curve order: this should be checked inside of a curve itself.
6901
+ // Creates precomputation tables for fast multiplication:
6902
+ // - private scalar is split by fixed size windows of W bits
6903
+ // - every window point is collected from window's table & added to accumulator
6904
+ // - since windows are different, same point inside tables won't be accessed more than once per calc
6905
+ // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
6906
+ // - +1 window is neccessary for wNAF
6907
+ // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
6908
+ // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
6909
+ // windows to be in different memory locations
7039
6910
  function wNAF(c, bits) {
6911
+ const constTimeNegate = (condition, item) => {
6912
+ const neg = item.negate();
6913
+ return condition ? neg : item;
6914
+ };
6915
+ const validateW = (W) => {
6916
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
6917
+ throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
6918
+ };
6919
+ const opts = (W) => {
6920
+ validateW(W);
6921
+ const windows = Math.ceil(bits / W) + 1; // +1, because
6922
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
6923
+ return { windows, windowSize };
6924
+ };
7040
6925
  return {
7041
6926
  constTimeNegate,
7042
- hasPrecomputes(elm) {
7043
- return getW(elm) !== 1;
7044
- },
7045
6927
  // non-const time multiplication ladder
7046
- unsafeLadder(elm, n, p = c.ZERO) {
6928
+ unsafeLadder(elm, n) {
6929
+ let p = c.ZERO;
7047
6930
  let d = elm;
7048
6931
  while (n > _0n$2) {
7049
6932
  if (n & _1n$4)
@@ -7061,12 +6944,10 @@ function wNAF(c, bits) {
7061
6944
  * - 𝑊 is the window size
7062
6945
  * - 𝑛 is the bitlength of the curve order.
7063
6946
  * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
7064
- * @param elm Point instance
7065
- * @param W window size
7066
6947
  * @returns precomputed point tables flattened to a single array
7067
6948
  */
7068
6949
  precomputeWindow(elm, W) {
7069
- const { windows, windowSize } = calcWOpts(W, bits);
6950
+ const { windows, windowSize } = opts(W);
7070
6951
  const points = [];
7071
6952
  let p = elm;
7072
6953
  let base = p;
@@ -7092,7 +6973,7 @@ function wNAF(c, bits) {
7092
6973
  wNAF(W, precomputes, n) {
7093
6974
  // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
7094
6975
  // But need to carefully remove other checks before wNAF. ORDER == bits here
7095
- const { windows, windowSize } = calcWOpts(W, bits);
6976
+ const { windows, windowSize } = opts(W);
7096
6977
  let p = c.ZERO;
7097
6978
  let f = c.BASE;
7098
6979
  const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
@@ -7136,44 +7017,8 @@ function wNAF(c, bits) {
7136
7017
  // which makes it less const-time: around 1 bigint multiply.
7137
7018
  return { p, f };
7138
7019
  },
7139
- /**
7140
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
7141
- * @param W window size
7142
- * @param precomputes precomputed tables
7143
- * @param n scalar (we don't check here, but should be less than curve order)
7144
- * @param acc accumulator point to add result of multiplication
7145
- * @returns point
7146
- */
7147
- wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
7148
- const { windows, windowSize } = calcWOpts(W, bits);
7149
- const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
7150
- const maxNumber = 2 ** W;
7151
- const shiftBy = BigInt(W);
7152
- for (let window = 0; window < windows; window++) {
7153
- const offset = window * windowSize;
7154
- if (n === _0n$2)
7155
- break; // No need to go over empty scalar
7156
- // Extract W bits.
7157
- let wbits = Number(n & mask);
7158
- // Shift number by W bits.
7159
- n >>= shiftBy;
7160
- // If the bits are bigger than max size, we'll split those.
7161
- // +224 => 256 - 32
7162
- if (wbits > windowSize) {
7163
- wbits -= maxNumber;
7164
- n += _1n$4;
7165
- }
7166
- if (wbits === 0)
7167
- continue;
7168
- let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero
7169
- if (wbits < 0)
7170
- curr = curr.negate();
7171
- // NOTE: by re-using acc, we can save a lot of additions in case of MSM
7172
- acc = acc.add(curr);
7173
- }
7174
- return acc;
7175
- },
7176
- getPrecomputes(W, P, transform) {
7020
+ wNAFCached(P, n, transform) {
7021
+ const W = pointWindowSizes.get(P) || 1;
7177
7022
  // Calculate precomputes on a first run, reuse them after
7178
7023
  let comp = pointPrecomputes.get(P);
7179
7024
  if (!comp) {
@@ -7181,66 +7026,62 @@ function wNAF(c, bits) {
7181
7026
  if (W !== 1)
7182
7027
  pointPrecomputes.set(P, transform(comp));
7183
7028
  }
7184
- return comp;
7185
- },
7186
- wNAFCached(P, n, transform) {
7187
- const W = getW(P);
7188
- return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
7189
- },
7190
- wNAFCachedUnsafe(P, n, transform, prev) {
7191
- const W = getW(P);
7192
- if (W === 1)
7193
- return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
7194
- return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
7029
+ return this.wNAF(W, comp, n);
7195
7030
  },
7196
7031
  // We calculate precomputes for elliptic curve point multiplication
7197
7032
  // using windowed method. This specifies window size and
7198
7033
  // stores precomputed values. Usually only base point would be precomputed.
7199
7034
  setWindowSize(P, W) {
7200
- validateW(W, bits);
7035
+ validateW(W);
7201
7036
  pointWindowSizes.set(P, W);
7202
7037
  pointPrecomputes.delete(P);
7203
7038
  },
7204
7039
  };
7205
7040
  }
7206
7041
  /**
7207
- * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
7042
+ * Pippenger algorithm for multi-scalar multiplication (MSM).
7043
+ * MSM is basically (Pa + Qb + Rc + ...).
7208
7044
  * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
7209
7045
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
7210
7046
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
7211
7047
  * @param c Curve Point constructor
7212
- * @param fieldN field over CURVE.N - important that it's not over CURVE.P
7048
+ * @param field field over CURVE.N - important that it's not over CURVE.P
7213
7049
  * @param points array of L curve points
7214
7050
  * @param scalars array of L scalars (aka private keys / bigints)
7215
7051
  */
7216
- function pippenger(c, fieldN, points, scalars) {
7052
+ function pippenger(c, field, points, scalars) {
7217
7053
  // If we split scalars by some window (let's say 8 bits), every chunk will only
7218
7054
  // take 256 buckets even if there are 4096 scalars, also re-uses double.
7219
7055
  // TODO:
7220
7056
  // - https://eprint.iacr.org/2024/750.pdf
7221
7057
  // - https://tches.iacr.org/index.php/TCHES/article/view/10287
7222
7058
  // 0 is accepted in scalars
7223
- validateMSMPoints(points, c);
7224
- validateMSMScalars(scalars, fieldN);
7225
- if (points.length !== scalars.length)
7059
+ if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
7226
7060
  throw new Error('arrays of points and scalars must have equal length');
7227
- const zero = c.ZERO;
7061
+ scalars.forEach((s, i) => {
7062
+ if (!field.isValid(s))
7063
+ throw new Error(`wrong scalar at index ${i}`);
7064
+ });
7065
+ points.forEach((p, i) => {
7066
+ if (!(p instanceof c))
7067
+ throw new Error(`wrong point at index ${i}`);
7068
+ });
7228
7069
  const wbits = bitLen(BigInt(points.length));
7229
7070
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
7230
7071
  const MASK = (1 << windowSize) - 1;
7231
- const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array
7232
- const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
7233
- let sum = zero;
7072
+ const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
7073
+ const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
7074
+ let sum = c.ZERO;
7234
7075
  for (let i = lastBits; i >= 0; i -= windowSize) {
7235
- buckets.fill(zero);
7076
+ buckets.fill(c.ZERO);
7236
7077
  for (let j = 0; j < scalars.length; j++) {
7237
7078
  const scalar = scalars[j];
7238
7079
  const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
7239
7080
  buckets[wbits] = buckets[wbits].add(points[j]);
7240
7081
  }
7241
- let resI = zero; // not using this will do small speed-up, but will lose ct
7082
+ let resI = c.ZERO; // not using this will do small speed-up, but will lose ct
7242
7083
  // Skip first bucket, because it is zero
7243
- for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
7084
+ for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
7244
7085
  sumI = sumI.add(buckets[j]);
7245
7086
  resI = resI.add(sumI);
7246
7087
  }
@@ -7270,12 +7111,8 @@ function validateBasic(curve) {
7270
7111
  });
7271
7112
  }
7272
7113
 
7273
- /**
7274
- * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
7275
- * For design rationale of types / exports, see weierstrass module documentation.
7276
- * @module
7277
- */
7278
7114
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7115
+ // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
7279
7116
  // Be friendly to bad ECMAScript parsers by not using bigint literals
7280
7117
  // prettier-ignore
7281
7118
  const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n$1 = BigInt(8);
@@ -7307,10 +7144,6 @@ function validateOpts$1(curve) {
7307
7144
  function twistedEdwards(curveDef) {
7308
7145
  const CURVE = validateOpts$1(curveDef);
7309
7146
  const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
7310
- // Important:
7311
- // There are some places where Fp.BYTES is used instead of nByteLength.
7312
- // So far, everything has been tested with curves of Fp.BYTES == nByteLength.
7313
- // TODO: test and find curves which behave otherwise.
7314
7147
  const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3);
7315
7148
  const modP = Fp.create; // Function overrides
7316
7149
  const Fn = Field(CURVE.n, CURVE.nBitLength);
@@ -7524,15 +7357,16 @@ function twistedEdwards(curveDef) {
7524
7357
  // It's faster, but should only be used when you don't care about
7525
7358
  // an exposed private key e.g. sig verification.
7526
7359
  // Does NOT allow scalars higher than CURVE.n.
7527
- // Accepts optional accumulator to merge with multiply (important for sparse scalars)
7528
- multiplyUnsafe(scalar, acc = Point.ZERO) {
7360
+ multiplyUnsafe(scalar) {
7529
7361
  const n = scalar;
7530
7362
  aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L
7531
7363
  if (n === _0n$1)
7532
7364
  return I;
7533
- if (this.is0() || n === _1n$3)
7365
+ if (this.equals(I) || n === _1n$3)
7534
7366
  return this;
7535
- return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
7367
+ if (this.equals(G))
7368
+ return this.wNAF(n).p;
7369
+ return wnaf.unsafeLadder(this, n);
7536
7370
  }
7537
7371
  // Checks if point is of small order.
7538
7372
  // If you add something to small order point, you will have "dirty"
@@ -7566,9 +7400,8 @@ function twistedEdwards(curveDef) {
7566
7400
  abool('zip215', zip215);
7567
7401
  const normed = hex.slice(); // copy again, we'll manipulate it
7568
7402
  const lastByte = hex[len - 1]; // select last byte
7569
- normed[len - 1] = lastByte & -129; // clear last bit
7403
+ normed[len - 1] = lastByte & ~0x80; // clear last bit
7570
7404
  const y = bytesToNumberLE(normed);
7571
- // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
7572
7405
  // RFC8032 prohibits >= p, but ZIP215 doesn't
7573
7406
  // zip215=true: 0 <= y < MASK (2^256 for ed25519)
7574
7407
  // zip215=false: 0 <= y < P (2^255-19 for ed25519)
@@ -7617,7 +7450,7 @@ function twistedEdwards(curveDef) {
7617
7450
  }
7618
7451
  /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
7619
7452
  function getExtendedPublicKey(key) {
7620
- const len = Fp.BYTES;
7453
+ const len = nByteLength;
7621
7454
  key = ensureBytes('private key', key, len);
7622
7455
  // Hash private key with curve's hash function to produce uniformingly random input
7623
7456
  // Check byte lengths: ensure(64, h(ensure(32, key)))
@@ -7650,29 +7483,23 @@ function twistedEdwards(curveDef) {
7650
7483
  const s = modN(r + k * scalar); // S = (r + k * s) mod L
7651
7484
  aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l
7652
7485
  const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));
7653
- return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature
7486
+ return ensureBytes('result', res, nByteLength * 2); // 64-byte signature
7654
7487
  }
7655
7488
  const verifyOpts = VERIFY_DEFAULT;
7656
- /**
7657
- * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
7658
- * An extended group equation is checked.
7659
- */
7660
7489
  function verify(sig, msg, publicKey, options = verifyOpts) {
7661
7490
  const { context, zip215 } = options;
7662
7491
  const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
7663
7492
  sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.
7664
7493
  msg = ensureBytes('message', msg);
7665
- publicKey = ensureBytes('publicKey', publicKey, len);
7666
7494
  if (zip215 !== undefined)
7667
7495
  abool('zip215', zip215);
7668
7496
  if (prehash)
7669
7497
  msg = prehash(msg); // for ed25519ph, etc
7670
7498
  const s = bytesToNumberLE(sig.slice(len, 2 * len));
7499
+ // zip215: true is good for consensus-critical apps and allows points < 2^256
7500
+ // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p
7671
7501
  let A, R, SB;
7672
7502
  try {
7673
- // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
7674
- // zip215=true: 0 <= y < MASK (2^256 for ed25519)
7675
- // zip215=false: 0 <= y < P (2^255-19 for ed25519)
7676
7503
  A = Point.fromHex(publicKey, zip215);
7677
7504
  R = Point.fromHex(sig.slice(0, len), zip215);
7678
7505
  SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
@@ -7684,7 +7511,6 @@ function twistedEdwards(curveDef) {
7684
7511
  return false;
7685
7512
  const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
7686
7513
  const RkA = R.add(A.multiplyUnsafe(k));
7687
- // Extended group equation
7688
7514
  // [8][S]B = [8]R + [8][k]A'
7689
7515
  return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
7690
7516
  }
@@ -7715,14 +7541,13 @@ function twistedEdwards(curveDef) {
7715
7541
  };
7716
7542
  }
7717
7543
 
7544
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7718
7545
  /**
7719
7546
  * ed25519 Twisted Edwards curve with following addons:
7720
7547
  * - X25519 ECDH
7721
7548
  * - Ristretto cofactor elimination
7722
7549
  * - Elligator hash-to-group / point indistinguishability
7723
- * @module
7724
7550
  */
7725
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7726
7551
  const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
7727
7552
  // √(-1) aka √(a) aka 2^((p-1)/4)
7728
7553
  const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
@@ -7781,7 +7606,7 @@ function uvRatio(u, v) {
7781
7606
  x = mod(-x, P);
7782
7607
  return { isValid: useRoot1 || useRoot2, value: x };
7783
7608
  }
7784
- const Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7609
+ const Fp$1 = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7785
7610
  const ed25519Defaults = /* @__PURE__ */ (() => ({
7786
7611
  // Param: a
7787
7612
  a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
@@ -7789,7 +7614,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7789
7614
  // Negative number is P - number, and division is invert(number, P)
7790
7615
  d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
7791
7616
  // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
7792
- Fp,
7617
+ Fp: Fp$1,
7793
7618
  // Subgroup order: how many points curve has
7794
7619
  // 2n**252n + 27742317777372353535851937790883648493n;
7795
7620
  n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
@@ -7808,14 +7633,6 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7808
7633
  }))();
7809
7634
  /**
7810
7635
  * ed25519 curve with EdDSA signatures.
7811
- * @example
7812
- * import { ed25519 } from '@noble/curves/ed25519';
7813
- * const priv = ed25519.utils.randomPrivateKey();
7814
- * const pub = ed25519.getPublicKey(priv);
7815
- * const msg = new TextEncoder().encode('hello');
7816
- * const sig = ed25519.sign(msg, priv);
7817
- * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215
7818
- * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5
7819
7636
  */
7820
7637
  const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
7821
7638
 
@@ -9213,7 +9030,7 @@ var PrivateKey;
9213
9030
  /*!
9214
9031
  * MIT License
9215
9032
  *
9216
- * Copyright (c) 2017-2024 Peculiar Ventures, LLC
9033
+ * Copyright (c) 2017-2022 Peculiar Ventures, LLC
9217
9034
  *
9218
9035
  * Permission is hereby granted, free of charge, to any person obtaining a copy
9219
9036
  * of this software and associated documentation files (the "Software"), to deal
@@ -9325,7 +9142,7 @@ class BufferSourceConverter {
9325
9142
  }
9326
9143
 
9327
9144
  const STRING_TYPE = "string";
9328
- const HEX_REGEX = /^[0-9a-f\s]+$/i;
9145
+ const HEX_REGEX = /^[0-9a-f]+$/i;
9329
9146
  const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
9330
9147
  const BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
9331
9148
  class Utf8Converter {
@@ -9559,7 +9376,7 @@ class Convert {
9559
9376
  return base64;
9560
9377
  }
9561
9378
  static formatString(data) {
9562
- return (data === null || data === undefined ? undefined : data.replace(/[\n\r\t ]/g, "")) || "";
9379
+ return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || "";
9563
9380
  }
9564
9381
  }
9565
9382
  Convert.DEFAULT_UTF8_ENCODING = "utf8";
@@ -9815,7 +9632,7 @@ function HexBlock(BaseClass) {
9815
9632
  var _a;
9816
9633
  super(...args);
9817
9634
  const params = args[0] || {};
9818
- this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== undefined ? _a : false;
9635
+ this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;
9819
9636
  this.valueHexView = params.valueHex ? BufferSourceConverter_1.toUint8Array(params.valueHex) : EMPTY_VIEW;
9820
9637
  }
9821
9638
  get valueHex() {
@@ -9905,11 +9722,11 @@ class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {
9905
9722
  var _a, _b, _c, _d;
9906
9723
  super();
9907
9724
  if (idBlock) {
9908
- this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== undefined ? _a : false;
9725
+ this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;
9909
9726
  this.valueHexView = idBlock.valueHex ? BufferSourceConverter_1.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;
9910
- this.tagClass = (_b = idBlock.tagClass) !== null && _b !== undefined ? _b : -1;
9911
- this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== undefined ? _c : -1;
9912
- this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== undefined ? _d : false;
9727
+ this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;
9728
+ this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;
9729
+ this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;
9913
9730
  }
9914
9731
  else {
9915
9732
  this.tagClass = -1;
@@ -10076,9 +9893,9 @@ class LocalLengthBlock extends LocalBaseBlock {
10076
9893
  constructor({ lenBlock = {}, } = {}) {
10077
9894
  var _a, _b, _c;
10078
9895
  super();
10079
- this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== undefined ? _a : false;
10080
- this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== undefined ? _b : false;
10081
- this.length = (_c = lenBlock.length) !== null && _c !== undefined ? _c : 0;
9896
+ this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;
9897
+ this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;
9898
+ this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;
10082
9899
  }
10083
9900
  fromBER(inputBuffer, inputOffset, inputLength) {
10084
9901
  const view = BufferSourceConverter_1.toUint8Array(inputBuffer);
@@ -10850,7 +10667,7 @@ var _a$r;
10850
10667
  class OctetString extends BaseBlock {
10851
10668
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
10852
10669
  var _b, _c;
10853
- (_b = parameters.isConstructed) !== null && _b !== undefined ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === undefined ? undefined : _c.length));
10670
+ (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
10854
10671
  super({
10855
10672
  idBlock: {
10856
10673
  isConstructed: parameters.isConstructed,
@@ -11011,7 +10828,7 @@ var _a$q;
11011
10828
  class BitString extends BaseBlock {
11012
10829
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
11013
10830
  var _b, _c;
11014
- (_b = parameters.isConstructed) !== null && _b !== undefined ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === undefined ? undefined : _c.length));
10831
+ (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
11015
10832
  super({
11016
10833
  idBlock: {
11017
10834
  isConstructed: parameters.isConstructed,
@@ -12213,7 +12030,7 @@ class GeneralizedTime extends UTCTime {
12213
12030
  constructor(parameters = {}) {
12214
12031
  var _b;
12215
12032
  super(parameters);
12216
- (_b = this.millisecond) !== null && _b !== undefined ? _b : (this.millisecond = 0);
12033
+ (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);
12217
12034
  this.idBlock.tagClass = 1;
12218
12035
  this.idBlock.tagNumber = 24;
12219
12036
  }
@@ -12564,8 +12381,8 @@ function pkixToJwk(bytes) {
12564
12381
  const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
12565
12382
  return {
12566
12383
  kty: 'RSA',
12567
- n: asn1jsIntegerToBase64(values[0]),
12568
- e: asn1jsIntegerToBase64(values[1])
12384
+ n: toString$6(bnToBuf(values[0].toBigInt()), 'base64url'),
12385
+ e: toString$6(bnToBuf(values[1].toBigInt()), 'base64url')
12569
12386
  };
12570
12387
  }
12571
12388
  /**
@@ -12601,13 +12418,21 @@ function jwkToPkix(jwk) {
12601
12418
  const der = root.toBER();
12602
12419
  return new Uint8Array(der, 0, der.byteLength);
12603
12420
  }
12604
- function asn1jsIntegerToBase64(int) {
12605
- let buf = int.valueBlock.valueHexView;
12606
- // chrome rejects values with leading 0s
12607
- while (buf[0] === 0) {
12608
- buf = buf.subarray(1);
12421
+ function bnToBuf(bn) {
12422
+ let hex = bn.toString(16);
12423
+ if (hex.length % 2 > 0) {
12424
+ hex = `0${hex}`;
12425
+ }
12426
+ const len = hex.length / 2;
12427
+ const u8 = new Uint8Array(len);
12428
+ let i = 0;
12429
+ let j = 0;
12430
+ while (i < len) {
12431
+ u8[i] = parseInt(hex.slice(j, j + 2), 16);
12432
+ i += 1;
12433
+ j += 2;
12609
12434
  }
12610
- return toString$6(buf, 'base64url');
12435
+ return u8;
12611
12436
  }
12612
12437
  function bufToBn(u8) {
12613
12438
  const hex = [];
@@ -12636,18 +12461,15 @@ function pkixToRSAPublicKey(bytes) {
12636
12461
  return new RSAPublicKey(jwk, digest);
12637
12462
  }
12638
12463
 
12639
- /**
12640
- * HMAC: RFC2104 message authentication code.
12641
- * @module
12642
- */
12464
+ // HMAC (RFC 2104)
12643
12465
  class HMAC extends Hash {
12644
- constructor(hash, _key) {
12466
+ constructor(hash$1, _key) {
12645
12467
  super();
12646
12468
  this.finished = false;
12647
12469
  this.destroyed = false;
12648
- ahash(hash);
12470
+ hash(hash$1);
12649
12471
  const key = toBytes$1(_key);
12650
- this.iHash = hash.create();
12472
+ this.iHash = hash$1.create();
12651
12473
  if (typeof this.iHash.update !== 'function')
12652
12474
  throw new Error('Expected instance of class which extends utils.Hash');
12653
12475
  this.blockLen = this.iHash.blockLen;
@@ -12655,12 +12477,12 @@ class HMAC extends Hash {
12655
12477
  const blockLen = this.blockLen;
12656
12478
  const pad = new Uint8Array(blockLen);
12657
12479
  // blockLen can be bigger than outputLen
12658
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
12480
+ pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
12659
12481
  for (let i = 0; i < pad.length; i++)
12660
12482
  pad[i] ^= 0x36;
12661
12483
  this.iHash.update(pad);
12662
12484
  // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
12663
- this.oHash = hash.create();
12485
+ this.oHash = hash$1.create();
12664
12486
  // Undo internal XOR && apply outer XOR
12665
12487
  for (let i = 0; i < pad.length; i++)
12666
12488
  pad[i] ^= 0x36 ^ 0x5c;
@@ -12668,13 +12490,13 @@ class HMAC extends Hash {
12668
12490
  pad.fill(0);
12669
12491
  }
12670
12492
  update(buf) {
12671
- aexists(this);
12493
+ exists(this);
12672
12494
  this.iHash.update(buf);
12673
12495
  return this;
12674
12496
  }
12675
12497
  digestInto(out) {
12676
- aexists(this);
12677
- abytes$1(out, this.outputLen);
12498
+ exists(this);
12499
+ bytes(out, this.outputLen);
12678
12500
  this.finished = true;
12679
12501
  this.iHash.digestInto(out);
12680
12502
  this.oHash.update(out);
@@ -12718,33 +12540,8 @@ class HMAC extends Hash {
12718
12540
  const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
12719
12541
  hmac.create = (hash, key) => new HMAC(hash, key);
12720
12542
 
12721
- /**
12722
- * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
12723
- *
12724
- * ### Design rationale for types
12725
- *
12726
- * * Interaction between classes from different curves should fail:
12727
- * `k256.Point.BASE.add(p256.Point.BASE)`
12728
- * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
12729
- * * Different calls of `curve()` would return different classes -
12730
- * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
12731
- * it won't affect others
12732
- *
12733
- * TypeScript can't infer types for classes created inside a function. Classes is one instance
12734
- * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
12735
- * unique type for every function call.
12736
- *
12737
- * We can use generic types via some param, like curve opts, but that would:
12738
- * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
12739
- * which is hard to debug.
12740
- * 2. Params can be generic and we can't enforce them to be constant value:
12741
- * if somebody creates curve from non-constant params,
12742
- * it would be allowed to interact with other curves with non-constant params
12743
- *
12744
- * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
12745
- * @module
12746
- */
12747
12543
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
12544
+ // Short Weierstrass curve. The formula is: y² = x³ + ax + b
12748
12545
  function validateSigVerOpts(opts) {
12749
12546
  if (opts.lowS !== undefined)
12750
12547
  abool('lowS', opts.lowS);
@@ -12768,22 +12565,17 @@ function validatePointOpts(curve) {
12768
12565
  const { endo, Fp, a } = opts;
12769
12566
  if (endo) {
12770
12567
  if (!Fp.eql(a, Fp.ZERO)) {
12771
- throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');
12568
+ throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
12772
12569
  }
12773
12570
  if (typeof endo !== 'object' ||
12774
12571
  typeof endo.beta !== 'bigint' ||
12775
12572
  typeof endo.splitScalar !== 'function') {
12776
- throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
12573
+ throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
12777
12574
  }
12778
12575
  }
12779
12576
  return Object.freeze({ ...opts });
12780
12577
  }
12781
12578
  const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
12782
- class DERErr extends Error {
12783
- constructor(m = '') {
12784
- super(m);
12785
- }
12786
- }
12787
12579
  /**
12788
12580
  * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
12789
12581
  *
@@ -12793,7 +12585,11 @@ class DERErr extends Error {
12793
12585
  */
12794
12586
  const DER = {
12795
12587
  // asn.1 DER encoding utils
12796
- Err: DERErr,
12588
+ Err: class DERErr extends Error {
12589
+ constructor(m = '') {
12590
+ super(m);
12591
+ }
12592
+ },
12797
12593
  // Basic building block is TLV (Tag-Length-Value)
12798
12594
  _tlv: {
12799
12595
  encode: (tag, data) => {
@@ -12808,8 +12604,7 @@ const DER = {
12808
12604
  throw new E('tlv.encode: long form length too big');
12809
12605
  // length of length with long form flag
12810
12606
  const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
12811
- const t = numberToHexUnpadded(tag);
12812
- return t + lenLen + len + data;
12607
+ return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
12813
12608
  },
12814
12609
  // v - value, l - left bytes (unparsed)
12815
12610
  decode(tag, data) {
@@ -12862,15 +12657,15 @@ const DER = {
12862
12657
  if (Number.parseInt(hex[0], 16) & 0b1000)
12863
12658
  hex = '00' + hex;
12864
12659
  if (hex.length & 1)
12865
- throw new E('unexpected DER parsing assertion: unpadded hex');
12660
+ throw new E('unexpected assertion');
12866
12661
  return hex;
12867
12662
  },
12868
12663
  decode(data) {
12869
12664
  const { Err: E } = DER;
12870
12665
  if (data[0] & 128)
12871
- throw new E('invalid signature integer: negative');
12666
+ throw new E('Invalid signature integer: negative');
12872
12667
  if (data[0] === 0x00 && !(data[1] & 128))
12873
- throw new E('invalid signature integer: unnecessary leading zero');
12668
+ throw new E('Invalid signature integer: unnecessary leading zero');
12874
12669
  return b2n(data);
12875
12670
  },
12876
12671
  },
@@ -12881,18 +12676,16 @@ const DER = {
12881
12676
  abytes(data);
12882
12677
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
12883
12678
  if (seqLeftBytes.length)
12884
- throw new E('invalid signature: left bytes after parsing');
12679
+ throw new E('Invalid signature: left bytes after parsing');
12885
12680
  const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
12886
12681
  const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
12887
12682
  if (sLeftBytes.length)
12888
- throw new E('invalid signature: left bytes after parsing');
12683
+ throw new E('Invalid signature: left bytes after parsing');
12889
12684
  return { r: int.decode(rBytes), s: int.decode(sBytes) };
12890
12685
  },
12891
12686
  hexFromSig(sig) {
12892
12687
  const { _tlv: tlv, _int: int } = DER;
12893
- const rs = tlv.encode(0x02, int.encode(sig.r));
12894
- const ss = tlv.encode(0x02, int.encode(sig.s));
12895
- const seq = rs + ss;
12688
+ const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
12896
12689
  return tlv.encode(0x30, seq);
12897
12690
  },
12898
12691
  };
@@ -12946,7 +12739,7 @@ function weierstrassPoints(opts) {
12946
12739
  key = bytesToHex(key);
12947
12740
  // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
12948
12741
  if (typeof key !== 'string' || !lengths.includes(key.length))
12949
- throw new Error('invalid private key');
12742
+ throw new Error('Invalid key');
12950
12743
  key = key.padStart(nByteLength * 2, '0');
12951
12744
  }
12952
12745
  let num;
@@ -12957,7 +12750,7 @@ function weierstrassPoints(opts) {
12957
12750
  : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
12958
12751
  }
12959
12752
  catch (error) {
12960
- throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
12753
+ throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
12961
12754
  }
12962
12755
  if (wrapPrivateKey)
12963
12756
  num = mod(num, N); // disabled by default, enabled for BLS
@@ -12997,7 +12790,7 @@ function weierstrassPoints(opts) {
12997
12790
  if (p.is0()) {
12998
12791
  // (0, 1, 0) aka ZERO is invalid in most contexts.
12999
12792
  // In BLS, ZERO can be serialized, so we allow it.
13000
- // (0, 0, 0) is invalid representation of ZERO.
12793
+ // (0, 0, 0) is wrong representation of ZERO and is always invalid.
13001
12794
  if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
13002
12795
  return;
13003
12796
  throw new Error('bad point: ZERO');
@@ -13221,17 +13014,16 @@ function weierstrassPoints(opts) {
13221
13014
  * an exposed private key e.g. sig verification, which works over *public* keys.
13222
13015
  */
13223
13016
  multiplyUnsafe(sc) {
13224
- const { endo, n: N } = CURVE;
13225
- aInRange('scalar', sc, _0n, N);
13017
+ aInRange('scalar', sc, _0n, CURVE.n);
13226
13018
  const I = Point.ZERO;
13227
13019
  if (sc === _0n)
13228
13020
  return I;
13229
- if (this.is0() || sc === _1n$1)
13021
+ if (sc === _1n$1)
13230
13022
  return this;
13231
- // Case a: no endomorphism. Case b: has precomputes.
13232
- if (!endo || wnaf.hasPrecomputes(this))
13233
- return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
13234
- // Case c: endomorphism
13023
+ const { endo } = CURVE;
13024
+ if (!endo)
13025
+ return wnaf.unsafeLadder(this, sc);
13026
+ // Apply endomorphism
13235
13027
  let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
13236
13028
  let k1p = I;
13237
13029
  let k2p = I;
@@ -13417,9 +13209,7 @@ function weierstrass(curveDef) {
13417
13209
  return { x, y };
13418
13210
  }
13419
13211
  else {
13420
- const cl = compressedLen;
13421
- const ul = uncompressedLen;
13422
- throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
13212
+ throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
13423
13213
  }
13424
13214
  },
13425
13215
  });
@@ -13584,9 +13374,6 @@ function weierstrass(curveDef) {
13584
13374
  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
13585
13375
  const bits2int = CURVE.bits2int ||
13586
13376
  function (bytes) {
13587
- // Our custom check "just in case"
13588
- if (bytes.length > 8192)
13589
- throw new Error('input is too large');
13590
13377
  // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
13591
13378
  // for some cases, since bytes.length * 8 is not actual bitLength.
13592
13379
  const num = bytesToNumberBE(bytes); // check for == u8 done here
@@ -13603,15 +13390,15 @@ function weierstrass(curveDef) {
13603
13390
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
13604
13391
  */
13605
13392
  function int2octets(num) {
13606
- aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);
13393
+ aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);
13607
13394
  // works with order, can have different size than numToField!
13608
13395
  return numberToBytesBE(num, CURVE.nByteLength);
13609
13396
  }
13610
13397
  // Steps A, D of RFC6979 3.2
13611
13398
  // Creates RFC6979 seed; converts msg/privKey to numbers.
13612
13399
  // Used only in sign, not in verify.
13613
- // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,
13614
- // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256
13400
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
13401
+ // Also it can be bigger for P224 + SHA256
13615
13402
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
13616
13403
  if (['recovered', 'canonical'].some((k) => k in opts))
13617
13404
  throw new Error('sign() legacy options not supported');
@@ -13705,48 +13492,39 @@ function weierstrass(curveDef) {
13705
13492
  const sg = signature;
13706
13493
  msgHash = ensureBytes('msgHash', msgHash);
13707
13494
  publicKey = ensureBytes('publicKey', publicKey);
13708
- const { lowS, prehash, format } = opts;
13709
- // Verify opts, deduce signature format
13710
- validateSigVerOpts(opts);
13711
13495
  if ('strict' in opts)
13712
13496
  throw new Error('options.strict was renamed to lowS');
13713
- if (format !== undefined && format !== 'compact' && format !== 'der')
13714
- throw new Error('format must be compact or der');
13715
- const isHex = typeof sg === 'string' || isBytes$1(sg);
13716
- const isObj = !isHex &&
13717
- !format &&
13718
- typeof sg === 'object' &&
13719
- sg !== null &&
13720
- typeof sg.r === 'bigint' &&
13721
- typeof sg.s === 'bigint';
13722
- if (!isHex && !isObj)
13723
- throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
13497
+ validateSigVerOpts(opts);
13498
+ const { lowS, prehash } = opts;
13724
13499
  let _sig = undefined;
13725
13500
  let P;
13726
13501
  try {
13727
- if (isObj)
13728
- _sig = new Signature(sg.r, sg.s);
13729
- if (isHex) {
13502
+ if (typeof sg === 'string' || isBytes$1(sg)) {
13730
13503
  // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
13731
13504
  // Since DER can also be 2*nByteLength bytes, we check for it first.
13732
13505
  try {
13733
- if (format !== 'compact')
13734
- _sig = Signature.fromDER(sg);
13506
+ _sig = Signature.fromDER(sg);
13735
13507
  }
13736
13508
  catch (derError) {
13737
13509
  if (!(derError instanceof DER.Err))
13738
13510
  throw derError;
13739
- }
13740
- if (!_sig && format !== 'der')
13741
13511
  _sig = Signature.fromCompact(sg);
13512
+ }
13513
+ }
13514
+ else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
13515
+ const { r, s } = sg;
13516
+ _sig = new Signature(r, s);
13517
+ }
13518
+ else {
13519
+ throw new Error('PARSE');
13742
13520
  }
13743
13521
  P = Point.fromHex(publicKey);
13744
13522
  }
13745
13523
  catch (error) {
13524
+ if (error.message === 'PARSE')
13525
+ throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
13746
13526
  return false;
13747
13527
  }
13748
- if (!_sig)
13749
- return false;
13750
13528
  if (lowS && _sig.hasHighS())
13751
13529
  return false;
13752
13530
  if (prehash)
@@ -13774,12 +13552,8 @@ function weierstrass(curveDef) {
13774
13552
  };
13775
13553
  }
13776
13554
 
13777
- /**
13778
- * Utilities for short weierstrass curves, combined with noble-hashes.
13779
- * @module
13780
- */
13781
13555
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13782
- /** connects noble-curves to noble-hashes */
13556
+ // connects noble-curves to noble-hashes
13783
13557
  function getHash(hash) {
13784
13558
  return {
13785
13559
  hash,
@@ -13789,21 +13563,9 @@ function getHash(hash) {
13789
13563
  }
13790
13564
  function createCurve(curveDef, defHash) {
13791
13565
  const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
13792
- return { ...create(defHash), create };
13566
+ return Object.freeze({ ...create(defHash), create });
13793
13567
  }
13794
13568
 
13795
- /**
13796
- * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
13797
- *
13798
- * Seems to be rigid (not backdoored)
13799
- * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
13800
- *
13801
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
13802
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
13803
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
13804
- * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
13805
- * @module
13806
- */
13807
13569
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13808
13570
  const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
13809
13571
  const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
@@ -13834,35 +13596,31 @@ function sqrtMod(y) {
13834
13596
  const t1 = (pow2(b223, _23n, P) * b22) % P;
13835
13597
  const t2 = (pow2(t1, _6n, P) * b2) % P;
13836
13598
  const root = pow2(t2, _2n, P);
13837
- if (!Fpk1.eql(Fpk1.sqr(root), y))
13599
+ if (!Fp.eql(Fp.sqr(root), y))
13838
13600
  throw new Error('Cannot find square root');
13839
13601
  return root;
13840
13602
  }
13841
- const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
13603
+ const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
13842
13604
  /**
13843
13605
  * secp256k1 short weierstrass curve and ECDSA signatures over it.
13844
- *
13845
- * @example
13846
- * import { secp256k1 } from '@noble/curves/secp256k1';
13847
- *
13848
- * const priv = secp256k1.utils.randomPrivateKey();
13849
- * const pub = secp256k1.getPublicKey(priv);
13850
- * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
13851
- * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
13852
- * const isValid = secp256k1.verify(sig, msg, pub) === true;
13853
13606
  */
13854
13607
  const secp256k1 = createCurve({
13855
13608
  a: BigInt(0), // equation params: a, b
13856
- b: BigInt(7),
13857
- Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
13609
+ b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
13610
+ Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
13858
13611
  n: secp256k1N, // Curve order, total count of valid points in the field
13859
13612
  // Base point (x, y) aka generator point
13860
13613
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
13861
13614
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
13862
13615
  h: BigInt(1), // Cofactor
13863
13616
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
13617
+ /**
13618
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
13619
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
13620
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
13621
+ * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
13622
+ */
13864
13623
  endo: {
13865
- // Endomorphism, see above
13866
13624
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
13867
13625
  splitScalar: (k) => {
13868
13626
  const n = secp256k1N;
@@ -15876,9 +15634,9 @@ function _copyActual (source, target, targetStart, sourceStart, sourceEnd) {
15876
15634
  const QUERY_FLAG = 0;
15877
15635
  const RESPONSE_FLAG = 1 << 15;
15878
15636
  const FLUSH_MASK = 1 << 15;
15879
- const NOT_FLUSH_MASK = -32769;
15637
+ const NOT_FLUSH_MASK = ~FLUSH_MASK;
15880
15638
  const QU_MASK = 1 << 15;
15881
- const NOT_QU_MASK = -32769;
15639
+ const NOT_QU_MASK = ~QU_MASK;
15882
15640
 
15883
15641
  function codec ({ bytes = 0, encode, decode, encodingLength }) {
15884
15642
  encode.bytes = bytes;
@@ -20285,36 +20043,36 @@ class StreamManager {
20285
20043
  this.log = new Logger$1(`stream-manager:${multicodec}`);
20286
20044
  this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
20287
20045
  }
20288
- async getStream(peerId) {
20289
- const peerIdStr = peerId.toString();
20290
- const scheduledStream = this.streamPool.get(peerIdStr);
20046
+ async getStream(peer) {
20047
+ const peerId = peer.id.toString();
20048
+ const scheduledStream = this.streamPool.get(peerId);
20291
20049
  if (scheduledStream) {
20292
- this.streamPool.delete(peerIdStr);
20050
+ this.streamPool.delete(peerId);
20293
20051
  await scheduledStream;
20294
20052
  }
20295
- let stream = this.getOpenStreamForCodec(peerId);
20053
+ let stream = this.getOpenStreamForCodec(peer.id);
20296
20054
  if (stream) {
20297
- this.log.info(`Found existing stream peerId=${peerIdStr} multicodec=${this.multicodec}`);
20298
- this.lockStream(peerIdStr, stream);
20055
+ this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
20056
+ this.lockStream(peer.id.toString(), stream);
20299
20057
  return stream;
20300
20058
  }
20301
- stream = await this.createStream(peerId);
20302
- this.lockStream(peerIdStr, stream);
20059
+ stream = await this.createStream(peer);
20060
+ this.lockStream(peer.id.toString(), stream);
20303
20061
  return stream;
20304
20062
  }
20305
- async createStream(peerId, retries = 0) {
20306
- const connections = this.getConnections(peerId);
20063
+ async createStream(peer, retries = 0) {
20064
+ const connections = this.getConnections(peer.id);
20307
20065
  const connection = selectOpenConnection(connections);
20308
20066
  if (!connection) {
20309
- throw new Error(`Failed to get a connection to the peer peerId=${peerId.toString()} multicodec=${this.multicodec}`);
20067
+ throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
20310
20068
  }
20311
20069
  let lastError;
20312
20070
  let stream;
20313
20071
  for (let i = 0; i < retries + 1; i++) {
20314
20072
  try {
20315
- this.log.info(`Attempting to create a stream for peerId=${peerId.toString()} multicodec=${this.multicodec}`);
20073
+ this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
20316
20074
  stream = await connection.newStream(this.multicodec);
20317
- this.log.info(`Created stream for peerId=${peerId.toString()} multicodec=${this.multicodec}`);
20075
+ this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
20318
20076
  break;
20319
20077
  }
20320
20078
  catch (error) {
@@ -20322,7 +20080,8 @@ class StreamManager {
20322
20080
  }
20323
20081
  }
20324
20082
  if (!stream) {
20325
- throw new Error(`Failed to create a new stream for ${peerId.toString()} -- ` + lastError);
20083
+ throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +
20084
+ lastError);
20326
20085
  }
20327
20086
  return stream;
20328
20087
  }
@@ -20334,7 +20093,7 @@ class StreamManager {
20334
20093
  }
20335
20094
  try {
20336
20095
  this.ongoingCreation.add(peerId);
20337
- await this.createStream(peer.id);
20096
+ await this.createStream(peer);
20338
20097
  }
20339
20098
  catch (error) {
20340
20099
  this.log.error(`Failed to createStreamWithLock:`, error);
@@ -20407,8 +20166,8 @@ class BaseProtocol {
20407
20166
  this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
20408
20167
  this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
20409
20168
  }
20410
- async getStream(peerId) {
20411
- return this.streamManager.getStream(peerId);
20169
+ async getStream(peer) {
20170
+ return this.streamManager.getStream(peer);
20412
20171
  }
20413
20172
  }
20414
20173
 
@@ -24035,105 +23794,6 @@ var WakuMetadataResponse;
24035
23794
  };
24036
23795
  })(WakuMetadataResponse || (WakuMetadataResponse = {}));
24037
23796
 
24038
- /* eslint-disable import/export */
24039
- /* eslint-disable complexity */
24040
- /* eslint-disable @typescript-eslint/no-namespace */
24041
- /* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */
24042
- /* eslint-disable @typescript-eslint/no-empty-interface */
24043
- var SdsMessage;
24044
- (function (SdsMessage) {
24045
- let _codec;
24046
- SdsMessage.codec = () => {
24047
- if (_codec == null) {
24048
- _codec = message((obj, w, opts = {}) => {
24049
- if (opts.lengthDelimited !== false) {
24050
- w.fork();
24051
- }
24052
- if ((obj.messageId != null && obj.messageId !== '')) {
24053
- w.uint32(18);
24054
- w.string(obj.messageId);
24055
- }
24056
- if ((obj.channelId != null && obj.channelId !== '')) {
24057
- w.uint32(26);
24058
- w.string(obj.channelId);
24059
- }
24060
- if (obj.lamportTimestamp != null) {
24061
- w.uint32(80);
24062
- w.int32(obj.lamportTimestamp);
24063
- }
24064
- if (obj.causalHistory != null) {
24065
- for (const value of obj.causalHistory) {
24066
- w.uint32(90);
24067
- w.string(value);
24068
- }
24069
- }
24070
- if (obj.bloomFilter != null) {
24071
- w.uint32(98);
24072
- w.bytes(obj.bloomFilter);
24073
- }
24074
- if (obj.content != null) {
24075
- w.uint32(162);
24076
- w.bytes(obj.content);
24077
- }
24078
- if (opts.lengthDelimited !== false) {
24079
- w.ldelim();
24080
- }
24081
- }, (reader, length, opts = {}) => {
24082
- const obj = {
24083
- messageId: '',
24084
- channelId: '',
24085
- causalHistory: []
24086
- };
24087
- const end = length == null ? reader.len : reader.pos + length;
24088
- while (reader.pos < end) {
24089
- const tag = reader.uint32();
24090
- switch (tag >>> 3) {
24091
- case 2: {
24092
- obj.messageId = reader.string();
24093
- break;
24094
- }
24095
- case 3: {
24096
- obj.channelId = reader.string();
24097
- break;
24098
- }
24099
- case 10: {
24100
- obj.lamportTimestamp = reader.int32();
24101
- break;
24102
- }
24103
- case 11: {
24104
- if (opts.limits?.causalHistory != null && obj.causalHistory.length === opts.limits.causalHistory) {
24105
- throw new MaxLengthError('Decode error - map field "causalHistory" had too many elements');
24106
- }
24107
- obj.causalHistory.push(reader.string());
24108
- break;
24109
- }
24110
- case 12: {
24111
- obj.bloomFilter = reader.bytes();
24112
- break;
24113
- }
24114
- case 20: {
24115
- obj.content = reader.bytes();
24116
- break;
24117
- }
24118
- default: {
24119
- reader.skipType(tag & 7);
24120
- break;
24121
- }
24122
- }
24123
- }
24124
- return obj;
24125
- });
24126
- }
24127
- return _codec;
24128
- };
24129
- SdsMessage.encode = (obj) => {
24130
- return encodeMessage(obj, SdsMessage.codec());
24131
- };
24132
- SdsMessage.decode = (buf, opts) => {
24133
- return decodeMessage(buf, SdsMessage.codec(), opts);
24134
- };
24135
- })(SdsMessage || (SdsMessage = {}));
24136
-
24137
23797
  /**
24138
23798
  * PeerExchangeRPC represents a message conforming to the Waku Peer Exchange protocol
24139
23799
  */
@@ -24203,7 +23863,7 @@ class WakuPeerExchange extends BaseProtocol {
24203
23863
  }
24204
23864
  let stream;
24205
23865
  try {
24206
- stream = await this.getStream(peerId);
23866
+ stream = await this.getStream(peer);
24207
23867
  }
24208
23868
  catch (err) {
24209
23869
  log$2.error("Failed to get stream", err);
@@ -24418,7 +24078,7 @@ class PeerExchangeDiscovery extends TypedEventEmitter {
24418
24078
  const existingShardInfoBytes = peer.metadata.get("shardInfo");
24419
24079
  if (existingShardInfoBytes) {
24420
24080
  const existingShardInfo = decodeRelayShard(existingShardInfoBytes);
24421
- {
24081
+ if (existingShardInfo || shardInfo) {
24422
24082
  hasShardDiff =
24423
24083
  existingShardInfo.clusterId !== shardInfo?.clusterId ||
24424
24084
  existingShardInfo.shards.some((shard) => !shardInfo?.shards.includes(shard));