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