@waku/discovery 0.0.4-ce62600.0 → 0.0.4-f387f59.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
@@ -26,7 +26,7 @@ const peerIdSymbol = Symbol.for('@libp2p/peer-id');
26
26
  * usually in response to the `abort` event being emitted by an
27
27
  * AbortSignal.
28
28
  */
29
- let CodeError$1 = class CodeError extends Error {
29
+ class CodeError extends Error {
30
30
  code;
31
31
  props;
32
32
  constructor(message, code, props) {
@@ -35,7 +35,7 @@ let CodeError$1 = class CodeError extends Error {
35
35
  this.name = props?.name ?? 'CodeError';
36
36
  this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
37
37
  }
38
- };
38
+ }
39
39
  class AggregateCodeError extends AggregateError {
40
40
  code;
41
41
  props;
@@ -114,23 +114,7 @@ class TypedEventEmitter extends EventTarget {
114
114
  return this.dispatchEvent(new CustomEvent(type, detail));
115
115
  }
116
116
  }
117
- /**
118
- * CustomEvent is a standard event but it's not supported by node.
119
- *
120
- * Remove this when https://github.com/nodejs/node/issues/40678 is closed.
121
- *
122
- * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
123
- */
124
- class CustomEventPolyfill extends Event {
125
- /** Returns any custom data event was created with. Typically used for synthetic events. */
126
- detail;
127
- constructor(message, data) {
128
- super(message, data);
129
- // @ts-expect-error could be undefined
130
- this.detail = data?.detail;
131
- }
132
- }
133
- const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill;
117
+ const CustomEvent = globalThis.CustomEvent;
134
118
 
135
119
  function isDefined(value) {
136
120
  return Boolean(value);
@@ -537,6 +521,11 @@ var ProtocolError;
537
521
  * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.
538
522
  */
539
523
  ProtocolError["TOPIC_DECODER_MISMATCH"] = "Topic decoder mismatch";
524
+ /**
525
+ * The topics passed in the decoders do not match each other, or don't exist at all.
526
+ * Ensure that all the pubsub topics used in the decoders are valid and match each other.
527
+ */
528
+ ProtocolError["INVALID_DECODER_TOPICS"] = "Invalid decoder topics";
540
529
  /**
541
530
  * Failure to find a peer with suitable protocols. This may due to a connection issue.
542
531
  * Mitigation can be: retrying after a given time period, display connectivity issue
@@ -567,12 +556,6 @@ var ProtocolError;
567
556
  ProtocolError["REQUEST_TIMEOUT"] = "Request timeout";
568
557
  })(ProtocolError || (ProtocolError = {}));
569
558
 
570
- var PageDirection;
571
- (function (PageDirection) {
572
- PageDirection["BACKWARD"] = "backward";
573
- PageDirection["FORWARD"] = "forward";
574
- })(PageDirection || (PageDirection = {}));
575
-
576
559
  var Tags;
577
560
  (function (Tags) {
578
561
  Tags["BOOTSTRAP"] = "bootstrap";
@@ -591,13 +574,12 @@ var EConnectionStateEvents;
591
574
  EConnectionStateEvents["CONNECTION_STATUS"] = "waku:connection";
592
575
  })(EConnectionStateEvents || (EConnectionStateEvents = {}));
593
576
 
594
- /**
595
- * DefaultPubsubTopic is the default gossipsub topic to use for Waku.
596
- */
597
- /**
598
- * The default cluster ID for The Waku Network
599
- */
600
- const DEFAULT_CLUSTER_ID = 1;
577
+ var HealthStatus;
578
+ (function (HealthStatus) {
579
+ HealthStatus["Unhealthy"] = "Unhealthy";
580
+ HealthStatus["MinimallyHealthy"] = "MinimallyHealthy";
581
+ HealthStatus["SufficientlyHealthy"] = "SufficientlyHealthy";
582
+ })(HealthStatus || (HealthStatus = {}));
601
583
 
602
584
  function equals$2(aa, bb) {
603
585
  if (aa === bb)
@@ -1908,41 +1890,7 @@ const bytesToUtf8 = (b) => toString$6(b, "utf8");
1908
1890
  * Encode utf-8 string to byte array.
1909
1891
  */
1910
1892
  const utf8ToBytes$1 = (s) => fromString(s, "utf8");
1911
- /**
1912
- * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`
1913
- */
1914
- function concat$2(byteArrays, totalLength) {
1915
- const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);
1916
- const res = new Uint8Array(len);
1917
- let offset = 0;
1918
- for (const bytes of byteArrays) {
1919
- res.set(bytes, offset);
1920
- offset += bytes.length;
1921
- }
1922
- return res;
1923
- }
1924
1893
 
1925
- const shardInfoToPubsubTopics = (shardInfo) => {
1926
- if ("contentTopics" in shardInfo && shardInfo.contentTopics) {
1927
- // Autosharding: explicitly defined content topics
1928
- return Array.from(new Set(shardInfo.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, shardInfo.clusterId))));
1929
- }
1930
- else if ("shards" in shardInfo) {
1931
- // Static sharding
1932
- if (shardInfo.shards === undefined)
1933
- throw new Error("Invalid shard");
1934
- return Array.from(new Set(shardInfo.shards.map((index) => `/waku/2/rs/${shardInfo.clusterId ?? DEFAULT_CLUSTER_ID}/${index}`)));
1935
- }
1936
- else if ("application" in shardInfo && "version" in shardInfo) {
1937
- // Autosharding: single shard from application and version
1938
- return [
1939
- contentTopicToPubsubTopic(`/${shardInfo.application}/${shardInfo.version}/default/default`, shardInfo.clusterId)
1940
- ];
1941
- }
1942
- else {
1943
- throw new Error("Missing required configuration in shard parameters");
1944
- }
1945
- };
1946
1894
  const pubsubTopicToSingleShardInfo = (pubsubTopics) => {
1947
1895
  const parts = pubsubTopics.split("/");
1948
1896
  if (parts.length != 6 ||
@@ -1959,112 +1907,26 @@ const pubsubTopicToSingleShardInfo = (pubsubTopics) => {
1959
1907
  shard
1960
1908
  };
1961
1909
  };
1962
- /**
1963
- * Given a string, will throw an error if it is not formatted as a valid content topic for autosharding based on https://rfc.vac.dev/spec/51/
1964
- * @param contentTopic String to validate
1965
- * @returns Object with each content topic field as an attribute
1966
- */
1967
- function ensureValidContentTopic(contentTopic) {
1968
- const parts = contentTopic.split("/");
1969
- if (parts.length < 5 || parts.length > 6) {
1970
- throw Error("Content topic format is invalid");
1971
- }
1972
- // Validate generation field if present
1973
- let generation = 0;
1974
- if (parts.length == 6) {
1975
- generation = parseInt(parts[1]);
1976
- if (isNaN(generation)) {
1977
- throw new Error("Invalid generation field in content topic");
1978
- }
1979
- if (generation > 0) {
1980
- throw new Error("Generation greater than 0 is not supported");
1981
- }
1982
- }
1983
- // Validate remaining fields
1984
- const fields = parts.splice(-4);
1985
- // Validate application field
1986
- if (fields[0].length == 0) {
1987
- throw new Error("Application field cannot be empty");
1988
- }
1989
- // Validate version field
1990
- if (fields[1].length == 0) {
1991
- throw new Error("Version field cannot be empty");
1992
- }
1993
- // Validate topic name field
1994
- if (fields[2].length == 0) {
1995
- throw new Error("Topic name field cannot be empty");
1996
- }
1997
- // Validate encoding field
1998
- if (fields[3].length == 0) {
1999
- throw new Error("Encoding field cannot be empty");
2000
- }
1910
+ const pubsubTopicsToShardInfo = (pubsubTopics) => {
1911
+ const shardInfoSet = new Set();
1912
+ const clusterIds = new Set();
1913
+ for (const topic of pubsubTopics) {
1914
+ const { clusterId, shard } = pubsubTopicToSingleShardInfo(topic);
1915
+ shardInfoSet.add(`${clusterId}:${shard}`);
1916
+ clusterIds.add(clusterId);
1917
+ }
1918
+ if (shardInfoSet.size === 0) {
1919
+ throw new Error("No valid pubsub topics provided");
1920
+ }
1921
+ if (clusterIds.size > 1) {
1922
+ throw new Error("Pubsub topics from multiple cluster IDs are not supported");
1923
+ }
1924
+ const clusterId = clusterIds.values().next().value;
1925
+ const shards = Array.from(shardInfoSet).map((info) => parseInt(info.split(":")[1]));
2001
1926
  return {
2002
- generation,
2003
- application: fields[0],
2004
- version: fields[1],
2005
- topicName: fields[2],
2006
- encoding: fields[3]
1927
+ clusterId,
1928
+ shards
2007
1929
  };
2008
- }
2009
- /**
2010
- * Given a string, determines which autoshard index to use for its pubsub topic.
2011
- * Based on the algorithm described in the RFC: https://rfc.vac.dev/spec/51//#algorithm
2012
- */
2013
- function contentTopicToShardIndex(contentTopic, networkShards = 8) {
2014
- const { application, version } = ensureValidContentTopic(contentTopic);
2015
- const digest = sha256$1(concat$2([utf8ToBytes$1(application), utf8ToBytes$1(version)]));
2016
- const dataview = new DataView(digest.buffer.slice(-8));
2017
- return Number(dataview.getBigUint64(0, false) % BigInt(networkShards));
2018
- }
2019
- function contentTopicToPubsubTopic(contentTopic, clusterId = DEFAULT_CLUSTER_ID, networkShards = 8) {
2020
- if (!contentTopic) {
2021
- throw Error("Content topic must be specified");
2022
- }
2023
- const shardIndex = contentTopicToShardIndex(contentTopic, networkShards);
2024
- return `/waku/2/rs/${clusterId}/${shardIndex}`;
2025
- }
2026
- /**
2027
- * Validates sharding configuration and sets defaults where possible.
2028
- * @returns Validated sharding parameters, with any missing values set to defaults
2029
- */
2030
- const ensureShardingConfigured = (shardInfo) => {
2031
- const clusterId = shardInfo.clusterId ?? DEFAULT_CLUSTER_ID;
2032
- const shards = "shards" in shardInfo ? shardInfo.shards : [];
2033
- const contentTopics = "contentTopics" in shardInfo ? shardInfo.contentTopics : [];
2034
- const [application, version] = "application" in shardInfo && "version" in shardInfo
2035
- ? [shardInfo.application, shardInfo.version]
2036
- : [undefined, undefined];
2037
- const isShardsConfigured = shards && shards.length > 0;
2038
- const isContentTopicsConfigured = contentTopics && contentTopics.length > 0;
2039
- const isApplicationVersionConfigured = application && version;
2040
- if (isShardsConfigured) {
2041
- return {
2042
- shardingParams: { clusterId, shards },
2043
- shardInfo: { clusterId, shards },
2044
- pubsubTopics: shardInfoToPubsubTopics({ clusterId, shards })
2045
- };
2046
- }
2047
- if (isContentTopicsConfigured) {
2048
- const pubsubTopics = Array.from(new Set(contentTopics.map((topic) => contentTopicToPubsubTopic(topic, clusterId))));
2049
- const shards = Array.from(new Set(contentTopics.map((topic) => contentTopicToShardIndex(topic))));
2050
- return {
2051
- shardingParams: { clusterId, contentTopics },
2052
- shardInfo: { clusterId, shards },
2053
- pubsubTopics
2054
- };
2055
- }
2056
- if (isApplicationVersionConfigured) {
2057
- const pubsubTopic = contentTopicToPubsubTopic(`/${application}/${version}/default/default`, clusterId);
2058
- return {
2059
- shardingParams: { clusterId, application, version },
2060
- shardInfo: {
2061
- clusterId,
2062
- shards: [pubsubTopicToSingleShardInfo(pubsubTopic).shard]
2063
- },
2064
- pubsubTopics: [pubsubTopic]
2065
- };
2066
- }
2067
- throw new Error("Missing minimum required configuration options for static sharding or autosharding.");
2068
1930
  };
2069
1931
 
2070
1932
  const decodeRelayShard = (bytes) => {
@@ -2710,6 +2572,8 @@ var common = setup;
2710
2572
  return false;
2711
2573
  }
2712
2574
 
2575
+ let m;
2576
+
2713
2577
  // Is webkit? http://stackoverflow.com/a/16459606/376773
2714
2578
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
2715
2579
  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
@@ -2717,7 +2581,7 @@ var common = setup;
2717
2581
  (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
2718
2582
  // Is firefox >= v31?
2719
2583
  // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
2720
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
2584
+ (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
2721
2585
  // Double check webkit in userAgent just in case we are in a worker
2722
2586
  (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
2723
2587
  }
@@ -2888,12 +2752,10 @@ let Logger$1 = class Logger {
2888
2752
  /**
2889
2753
  * The ENR tree for the different fleets.
2890
2754
  * SANDBOX and TEST fleets are for The Waku Network.
2891
- * DEPRECATED_DEFAULT_PUBSUB is the fleet of nodes supporting the now deprecated DefaultPubsubTopic.
2892
2755
  */
2893
2756
  const enrTree = {
2894
2757
  SANDBOX: "enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",
2895
- TEST: "enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",
2896
- DEPRECATED_DEFAULT_PUBSUB: "enrtree://ANEDLO25QVUGJOUTQFRYKWX6P4Z4GKVESBMHML7DZ6YK4LGS5FC5O@prod.wakuv2.nodes.status.im"
2758
+ TEST: "enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"
2897
2759
  };
2898
2760
  const DEFAULT_BOOTSTRAP_TAG_NAME = "bootstrap";
2899
2761
  const DEFAULT_BOOTSTRAP_TAG_VALUE = 50;
@@ -2922,7 +2784,7 @@ const _0n$5 = BigInt(0);
2922
2784
  const _1n$7 = BigInt(1);
2923
2785
  const _2n$5 = BigInt(2);
2924
2786
  const _3n$2 = BigInt(3);
2925
- const _8n$2 = BigInt(8);
2787
+ const _8n$3 = BigInt(8);
2926
2788
  const CURVE = Object.freeze({
2927
2789
  a: _0n$5,
2928
2790
  b: BigInt(7),
@@ -3026,7 +2888,7 @@ class JacobianPoint {
3026
2888
  const E = mod$1(_3n$2 * A);
3027
2889
  const F = mod$1(E * E);
3028
2890
  const X3 = mod$1(F - _2n$5 * D);
3029
- const Y3 = mod$1(E * (D - X3) - _8n$2 * C);
2891
+ const Y3 = mod$1(E * (D - X3) - _8n$3 * C);
3030
2892
  const Z3 = mod$1(_2n$5 * Y1 * Z1);
3031
2893
  return new JacobianPoint(X3, Y3, Z3);
3032
2894
  }
@@ -3126,12 +2988,12 @@ class JacobianPoint {
3126
2988
  if (256 % W) {
3127
2989
  throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');
3128
2990
  }
3129
- let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
2991
+ let precomputes = affinePoint && pointPrecomputes$1.get(affinePoint);
3130
2992
  if (!precomputes) {
3131
2993
  precomputes = this.precomputeWindow(W);
3132
2994
  if (affinePoint && W !== 1) {
3133
2995
  precomputes = JacobianPoint.normalizeZ(precomputes);
3134
- pointPrecomputes.set(affinePoint, precomputes);
2996
+ pointPrecomputes$1.set(affinePoint, precomputes);
3135
2997
  }
3136
2998
  }
3137
2999
  let p = JacobianPoint.ZERO;
@@ -3187,7 +3049,7 @@ class JacobianPoint {
3187
3049
  const { x, y, z } = this;
3188
3050
  const is0 = this.equals(JacobianPoint.ZERO);
3189
3051
  if (invZ == null)
3190
- invZ = is0 ? _8n$2 : invert$1(z);
3052
+ invZ = is0 ? _8n$3 : invert$1(z);
3191
3053
  const iz1 = invZ;
3192
3054
  const iz2 = mod$1(iz1 * iz1);
3193
3055
  const iz3 = mod$1(iz2 * iz1);
@@ -3207,7 +3069,7 @@ function constTimeNegate(condition, item) {
3207
3069
  const neg = item.negate();
3208
3070
  return condition ? neg : item;
3209
3071
  }
3210
- const pointPrecomputes = new WeakMap();
3072
+ const pointPrecomputes$1 = new WeakMap();
3211
3073
  class Point {
3212
3074
  constructor(x, y) {
3213
3075
  this.x = x;
@@ -3215,7 +3077,7 @@ class Point {
3215
3077
  }
3216
3078
  _setWindowSize(windowSize) {
3217
3079
  this._WINDOW_SIZE = windowSize;
3218
- pointPrecomputes.delete(this);
3080
+ pointPrecomputes$1.delete(this);
3219
3081
  }
3220
3082
  hasEvenY() {
3221
3083
  return this.y % _2n$5 === _0n$5;
@@ -5273,6 +5135,7 @@ const table = [
5273
5135
  [478, 0, 'wss'],
5274
5136
  [479, 0, 'p2p-websocket-star'],
5275
5137
  [480, 0, 'http'],
5138
+ [481, V, 'http-path'],
5276
5139
  [777, V, 'memory']
5277
5140
  ];
5278
5141
  // populate tables
@@ -5358,6 +5221,8 @@ function convertToString(proto, buf) {
5358
5221
  return bytes2onion(buf);
5359
5222
  case 466: // certhash
5360
5223
  return bytes2mb(buf);
5224
+ case 481: // http-path
5225
+ return globalThis.encodeURIComponent(bytes2str(buf));
5361
5226
  default:
5362
5227
  return toString$6(buf, 'base16'); // no clue. convert to hex
5363
5228
  }
@@ -5392,6 +5257,8 @@ function convertToBytes(proto, str) {
5392
5257
  return onion32bytes(str);
5393
5258
  case 466: // certhash
5394
5259
  return mb2bytes(str);
5260
+ case 481: // http-path
5261
+ return str2bytes(globalThis.decodeURIComponent(str));
5395
5262
  default:
5396
5263
  return fromString(str, 'base16'); // no clue. convert from hex
5397
5264
  }
@@ -5853,7 +5720,7 @@ class Multiaddr {
5853
5720
  }
5854
5721
  const resolver = resolvers$1.get(resolvableProto.name);
5855
5722
  if (resolver == null) {
5856
- throw new CodeError$1(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER');
5723
+ throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER');
5857
5724
  }
5858
5725
  const result = await resolver(this, options);
5859
5726
  return result.map(str => multiaddr(str));
@@ -6296,9 +6163,9 @@ const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
6296
6163
  // This is OK: `abstract` directory does not use noble-hashes.
6297
6164
  // User may opt-in into using different hashing library. This way, noble-hashes
6298
6165
  // won't be included into their bundle.
6299
- const _0n$4 = BigInt(0);
6300
- const _1n$6 = BigInt(1);
6301
- const _2n$4 = BigInt(2);
6166
+ const _0n$4 = /* @__PURE__ */ BigInt(0);
6167
+ const _1n$6 = /* @__PURE__ */ BigInt(1);
6168
+ const _2n$4 = /* @__PURE__ */ BigInt(2);
6302
6169
  function isBytes$1(a) {
6303
6170
  return (a instanceof Uint8Array ||
6304
6171
  (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
@@ -6307,6 +6174,10 @@ function abytes(item) {
6307
6174
  if (!isBytes$1(item))
6308
6175
  throw new Error('Uint8Array expected');
6309
6176
  }
6177
+ function abool(title, value) {
6178
+ if (typeof value !== 'boolean')
6179
+ throw new Error(`${title} must be valid boolean, got "${value}".`);
6180
+ }
6310
6181
  // Array where index 0xf0 (240) is mapped to string 'f0'
6311
6182
  const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
6312
6183
  /**
@@ -6449,6 +6320,25 @@ function utf8ToBytes(str) {
6449
6320
  throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
6450
6321
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
6451
6322
  }
6323
+ // Is positive bigint
6324
+ const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
6325
+ function inRange(n, min, max) {
6326
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
6327
+ }
6328
+ /**
6329
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
6330
+ * @example
6331
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
6332
+ */
6333
+ function aInRange(title, n, min, max) {
6334
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
6335
+ // consider P=256n, min=0n, max=P
6336
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
6337
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
6338
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
6339
+ if (!inRange(n, min, max))
6340
+ throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
6341
+ }
6452
6342
  // Bit operations
6453
6343
  /**
6454
6344
  * Calculates amount of bits in a bigint.
@@ -6579,9 +6469,32 @@ function validateObject(object, validators, optValidators = {}) {
6579
6469
  // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
6580
6470
  // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
6581
6471
  // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
6472
+ /**
6473
+ * throws not implemented error
6474
+ */
6475
+ const notImplemented = () => {
6476
+ throw new Error('not implemented');
6477
+ };
6478
+ /**
6479
+ * Memoizes (caches) computation result.
6480
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
6481
+ */
6482
+ function memoized(fn) {
6483
+ const map = new WeakMap();
6484
+ return (arg, ...args) => {
6485
+ const val = map.get(arg);
6486
+ if (val !== undefined)
6487
+ return val;
6488
+ const computed = fn(arg, ...args);
6489
+ map.set(arg, computed);
6490
+ return computed;
6491
+ };
6492
+ }
6582
6493
 
6583
6494
  var ut = /*#__PURE__*/Object.freeze({
6584
6495
  __proto__: null,
6496
+ aInRange: aInRange,
6497
+ abool: abool,
6585
6498
  abytes: abytes,
6586
6499
  bitGet: bitGet,
6587
6500
  bitLen: bitLen,
@@ -6596,7 +6509,10 @@ var ut = /*#__PURE__*/Object.freeze({
6596
6509
  equalBytes: equalBytes,
6597
6510
  hexToBytes: hexToBytes,
6598
6511
  hexToNumber: hexToNumber,
6512
+ inRange: inRange,
6599
6513
  isBytes: isBytes$1,
6514
+ memoized: memoized,
6515
+ notImplemented: notImplemented,
6600
6516
  numberToBytesBE: numberToBytesBE,
6601
6517
  numberToBytesLE: numberToBytesLE,
6602
6518
  numberToHexUnpadded: numberToHexUnpadded,
@@ -6610,7 +6526,7 @@ var ut = /*#__PURE__*/Object.freeze({
6610
6526
  // prettier-ignore
6611
6527
  const _0n$3 = BigInt(0), _1n$5 = BigInt(1), _2n$3 = BigInt(2), _3n$1 = BigInt(3);
6612
6528
  // prettier-ignore
6613
- const _4n = BigInt(4), _5n$1 = BigInt(5), _8n$1 = BigInt(8);
6529
+ const _4n = BigInt(4), _5n$1 = BigInt(5), _8n$2 = BigInt(8);
6614
6530
  // prettier-ignore
6615
6531
  BigInt(9); BigInt(16);
6616
6532
  // Calculates a modulo b
@@ -6756,8 +6672,8 @@ function FpSqrt(P) {
6756
6672
  };
6757
6673
  }
6758
6674
  // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
6759
- if (P % _8n$1 === _5n$1) {
6760
- const c1 = (P - _5n$1) / _8n$1;
6675
+ if (P % _8n$2 === _5n$1) {
6676
+ const c1 = (P - _5n$1) / _8n$2;
6761
6677
  return function sqrt5mod8(Fp, n) {
6762
6678
  const n2 = Fp.mul(n, _2n$3);
6763
6679
  const v = Fp.pow(n2, c1);
@@ -6855,6 +6771,9 @@ function nLength(n, nBitLength) {
6855
6771
  * * a) denormalized operations like mulN instead of mul
6856
6772
  * * b) same object shape: never add or remove keys
6857
6773
  * * c) Object.freeze
6774
+ * NOTE: operations don't check 'isValid' for all elements for performance reasons,
6775
+ * it is caller responsibility to check this.
6776
+ * This is low-level code, please make sure you know what you doing.
6858
6777
  * @param ORDER prime positive bigint
6859
6778
  * @param bitLen how many bits the field consumes
6860
6779
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -6910,12 +6829,6 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6910
6829
  });
6911
6830
  return Object.freeze(f);
6912
6831
  }
6913
- function FpSqrtEven(Fp, elm) {
6914
- if (!Fp.isOdd)
6915
- throw new Error(`Field doesn't have isOdd`);
6916
- const root = Fp.sqrt(elm);
6917
- return Fp.isOdd(root) ? Fp.neg(root) : root;
6918
- }
6919
6832
  /**
6920
6833
  * Returns total number of bytes consumed by the field element.
6921
6834
  * For example, 32 bytes for usual 256-bit weierstrass curve.
@@ -6969,6 +6882,10 @@ function mapHashToField(key, fieldOrder, isLE = false) {
6969
6882
  // Abelian group utilities
6970
6883
  const _0n$2 = BigInt(0);
6971
6884
  const _1n$4 = BigInt(1);
6885
+ // Since points in different groups cannot be equal (different object constructor),
6886
+ // we can have single place to store precomputes
6887
+ const pointPrecomputes = new WeakMap();
6888
+ const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
6972
6889
  // Elliptic curve multiplication of Point by scalar. Fragile.
6973
6890
  // Scalars should always be less than curve order: this should be checked inside of a curve itself.
6974
6891
  // Creates precomputation tables for fast multiplication:
@@ -6985,7 +6902,12 @@ function wNAF(c, bits) {
6985
6902
  const neg = item.negate();
6986
6903
  return condition ? neg : item;
6987
6904
  };
6905
+ const validateW = (W) => {
6906
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
6907
+ throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
6908
+ };
6988
6909
  const opts = (W) => {
6910
+ validateW(W);
6989
6911
  const windows = Math.ceil(bits / W) + 1; // +1, because
6990
6912
  const windowSize = 2 ** (W - 1); // -1 because we skip zero
6991
6913
  return { windows, windowSize };
@@ -7085,19 +7007,25 @@ function wNAF(c, bits) {
7085
7007
  // which makes it less const-time: around 1 bigint multiply.
7086
7008
  return { p, f };
7087
7009
  },
7088
- wNAFCached(P, precomputesMap, n, transform) {
7089
- // @ts-ignore
7090
- const W = P._WINDOW_SIZE || 1;
7010
+ wNAFCached(P, n, transform) {
7011
+ const W = pointWindowSizes.get(P) || 1;
7091
7012
  // Calculate precomputes on a first run, reuse them after
7092
- let comp = precomputesMap.get(P);
7013
+ let comp = pointPrecomputes.get(P);
7093
7014
  if (!comp) {
7094
7015
  comp = this.precomputeWindow(P, W);
7095
- if (W !== 1) {
7096
- precomputesMap.set(P, transform(comp));
7097
- }
7016
+ if (W !== 1)
7017
+ pointPrecomputes.set(P, transform(comp));
7098
7018
  }
7099
7019
  return this.wNAF(W, comp, n);
7100
7020
  },
7021
+ // We calculate precomputes for elliptic curve point multiplication
7022
+ // using windowed method. This specifies window size and
7023
+ // stores precomputed values. Usually only base point would be precomputed.
7024
+ setWindowSize(P, W) {
7025
+ validateW(W);
7026
+ pointWindowSizes.set(P, W);
7027
+ pointPrecomputes.delete(P);
7028
+ },
7101
7029
  };
7102
7030
  }
7103
7031
  function validateBasic(curve) {
@@ -7123,7 +7051,7 @@ function validateBasic(curve) {
7123
7051
  // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
7124
7052
  // Be friendly to bad ECMAScript parsers by not using bigint literals
7125
7053
  // prettier-ignore
7126
- const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n = BigInt(8);
7054
+ const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n$1 = BigInt(8);
7127
7055
  // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
7128
7056
  const VERIFY_DEFAULT = { zip215: true };
7129
7057
  function validateOpts$1(curve) {
@@ -7142,7 +7070,13 @@ function validateOpts$1(curve) {
7142
7070
  // Set defaults
7143
7071
  return Object.freeze({ ...opts });
7144
7072
  }
7145
- // It is not generic twisted curve for now, but ed25519/ed448 generic implementation
7073
+ /**
7074
+ * Creates Twisted Edwards curve with EdDSA signatures.
7075
+ * @example
7076
+ * import { Field } from '@noble/curves/abstract/modular';
7077
+ * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h
7078
+ * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })
7079
+ */
7146
7080
  function twistedEdwards(curveDef) {
7147
7081
  const CURVE = validateOpts$1(curveDef);
7148
7082
  const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
@@ -7161,28 +7095,59 @@ function twistedEdwards(curveDef) {
7161
7095
  const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP
7162
7096
  const domain = CURVE.domain ||
7163
7097
  ((data, ctx, phflag) => {
7098
+ abool('phflag', phflag);
7164
7099
  if (ctx.length || phflag)
7165
7100
  throw new Error('Contexts/pre-hash are not supported');
7166
7101
  return data;
7167
7102
  }); // NOOP
7168
- const inBig = (n) => typeof n === 'bigint' && _0n$1 < n; // n in [1..]
7169
- const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]
7170
- const in0MaskRange = (n) => n === _0n$1 || inRange(n, MASK); // n in [0..MASK-1]
7171
- function assertInRange(n, max) {
7172
- // n in [1..max-1]
7173
- if (inRange(n, max))
7174
- return n;
7175
- throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);
7176
- }
7177
- function assertGE0(n) {
7178
- // n in [0..CURVE_ORDER-1]
7179
- return n === _0n$1 ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group
7180
- }
7181
- const pointPrecomputes = new Map();
7182
- function isPoint(other) {
7103
+ // 0 <= n < MASK
7104
+ // Coordinates larger than Fp.ORDER are allowed for zip215
7105
+ function aCoordinate(title, n) {
7106
+ aInRange('coordinate ' + title, n, _0n$1, MASK);
7107
+ }
7108
+ function assertPoint(other) {
7183
7109
  if (!(other instanceof Point))
7184
7110
  throw new Error('ExtendedPoint expected');
7185
7111
  }
7112
+ // Converts Extended point to default (x, y) coordinates.
7113
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
7114
+ const toAffineMemo = memoized((p, iz) => {
7115
+ const { ex: x, ey: y, ez: z } = p;
7116
+ const is0 = p.is0();
7117
+ if (iz == null)
7118
+ iz = is0 ? _8n$1 : Fp.inv(z); // 8 was chosen arbitrarily
7119
+ const ax = modP(x * iz);
7120
+ const ay = modP(y * iz);
7121
+ const zz = modP(z * iz);
7122
+ if (is0)
7123
+ return { x: _0n$1, y: _1n$3 };
7124
+ if (zz !== _1n$3)
7125
+ throw new Error('invZ was invalid');
7126
+ return { x: ax, y: ay };
7127
+ });
7128
+ const assertValidMemo = memoized((p) => {
7129
+ const { a, d } = CURVE;
7130
+ if (p.is0())
7131
+ throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
7132
+ // Equation in affine coordinates: ax² + y² = 1 + dx²y²
7133
+ // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
7134
+ const { ex: X, ey: Y, ez: Z, et: T } = p;
7135
+ const X2 = modP(X * X); // X²
7136
+ const Y2 = modP(Y * Y); // Y²
7137
+ const Z2 = modP(Z * Z); // Z²
7138
+ const Z4 = modP(Z2 * Z2); // Z⁴
7139
+ const aX2 = modP(X2 * a); // aX²
7140
+ const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
7141
+ const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
7142
+ if (left !== right)
7143
+ throw new Error('bad point: equation left != right (1)');
7144
+ // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
7145
+ const XY = modP(X * Y);
7146
+ const ZT = modP(Z * T);
7147
+ if (XY !== ZT)
7148
+ throw new Error('bad point: equation left != right (2)');
7149
+ return true;
7150
+ });
7186
7151
  // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).
7187
7152
  // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
7188
7153
  class Point {
@@ -7191,14 +7156,11 @@ function twistedEdwards(curveDef) {
7191
7156
  this.ey = ey;
7192
7157
  this.ez = ez;
7193
7158
  this.et = et;
7194
- if (!in0MaskRange(ex))
7195
- throw new Error('x required');
7196
- if (!in0MaskRange(ey))
7197
- throw new Error('y required');
7198
- if (!in0MaskRange(ez))
7199
- throw new Error('z required');
7200
- if (!in0MaskRange(et))
7201
- throw new Error('t required');
7159
+ aCoordinate('x', ex);
7160
+ aCoordinate('y', ey);
7161
+ aCoordinate('z', ez);
7162
+ aCoordinate('t', et);
7163
+ Object.freeze(this);
7202
7164
  }
7203
7165
  get x() {
7204
7166
  return this.toAffine().x;
@@ -7210,8 +7172,8 @@ function twistedEdwards(curveDef) {
7210
7172
  if (p instanceof Point)
7211
7173
  throw new Error('extended point not allowed');
7212
7174
  const { x, y } = p || {};
7213
- if (!in0MaskRange(x) || !in0MaskRange(y))
7214
- throw new Error('invalid affine point');
7175
+ aCoordinate('x', x);
7176
+ aCoordinate('y', y);
7215
7177
  return new Point(x, y, _1n$3, modP(x * y));
7216
7178
  }
7217
7179
  static normalizeZ(points) {
@@ -7220,36 +7182,16 @@ function twistedEdwards(curveDef) {
7220
7182
  }
7221
7183
  // "Private method", don't use it directly
7222
7184
  _setWindowSize(windowSize) {
7223
- this._WINDOW_SIZE = windowSize;
7224
- pointPrecomputes.delete(this);
7185
+ wnaf.setWindowSize(this, windowSize);
7225
7186
  }
7226
7187
  // Not required for fromHex(), which always creates valid points.
7227
7188
  // Could be useful for fromAffine().
7228
7189
  assertValidity() {
7229
- const { a, d } = CURVE;
7230
- if (this.is0())
7231
- throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
7232
- // Equation in affine coordinates: ax² + y² = 1 + dx²y²
7233
- // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
7234
- const { ex: X, ey: Y, ez: Z, et: T } = this;
7235
- const X2 = modP(X * X); // X²
7236
- const Y2 = modP(Y * Y); // Y²
7237
- const Z2 = modP(Z * Z); // Z²
7238
- const Z4 = modP(Z2 * Z2); // Z⁴
7239
- const aX2 = modP(X2 * a); // aX²
7240
- const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
7241
- const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
7242
- if (left !== right)
7243
- throw new Error('bad point: equation left != right (1)');
7244
- // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
7245
- const XY = modP(X * Y);
7246
- const ZT = modP(Z * T);
7247
- if (XY !== ZT)
7248
- throw new Error('bad point: equation left != right (2)');
7190
+ assertValidMemo(this);
7249
7191
  }
7250
7192
  // Compare one point to another.
7251
7193
  equals(other) {
7252
- isPoint(other);
7194
+ assertPoint(other);
7253
7195
  const { ex: X1, ey: Y1, ez: Z1 } = this;
7254
7196
  const { ex: X2, ey: Y2, ez: Z2 } = other;
7255
7197
  const X1Z2 = modP(X1 * Z2);
@@ -7290,7 +7232,7 @@ function twistedEdwards(curveDef) {
7290
7232
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
7291
7233
  // Cost: 9M + 1*a + 1*d + 7add.
7292
7234
  add(other) {
7293
- isPoint(other);
7235
+ assertPoint(other);
7294
7236
  const { a, d } = CURVE;
7295
7237
  const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
7296
7238
  const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
@@ -7333,11 +7275,13 @@ function twistedEdwards(curveDef) {
7333
7275
  return this.add(other.negate());
7334
7276
  }
7335
7277
  wNAF(n) {
7336
- return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);
7278
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
7337
7279
  }
7338
7280
  // Constant-time multiplication.
7339
7281
  multiply(scalar) {
7340
- const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));
7282
+ const n = scalar;
7283
+ aInRange('scalar', n, _1n$3, CURVE_ORDER); // 1 <= scalar < L
7284
+ const { p, f } = this.wNAF(n);
7341
7285
  return Point.normalizeZ([p, f])[0];
7342
7286
  }
7343
7287
  // Non-constant-time multiplication. Uses double-and-add algorithm.
@@ -7345,7 +7289,8 @@ function twistedEdwards(curveDef) {
7345
7289
  // an exposed private key e.g. sig verification.
7346
7290
  // Does NOT allow scalars higher than CURVE.n.
7347
7291
  multiplyUnsafe(scalar) {
7348
- let n = assertGE0(scalar); // 0 <= scalar < CURVE.n
7292
+ const n = scalar;
7293
+ aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L
7349
7294
  if (n === _0n$1)
7350
7295
  return I;
7351
7296
  if (this.equals(I) || n === _1n$3)
@@ -7369,18 +7314,7 @@ function twistedEdwards(curveDef) {
7369
7314
  // Converts Extended point to default (x, y) coordinates.
7370
7315
  // Can accept precomputed Z^-1 - for example, from invertBatch.
7371
7316
  toAffine(iz) {
7372
- const { ex: x, ey: y, ez: z } = this;
7373
- const is0 = this.is0();
7374
- if (iz == null)
7375
- iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily
7376
- const ax = modP(x * iz);
7377
- const ay = modP(y * iz);
7378
- const zz = modP(z * iz);
7379
- if (is0)
7380
- return { x: _0n$1, y: _1n$3 };
7381
- if (zz !== _1n$3)
7382
- throw new Error('invZ was invalid');
7383
- return { x: ax, y: ay };
7317
+ return toAffineMemo(this, iz);
7384
7318
  }
7385
7319
  clearCofactor() {
7386
7320
  const { h: cofactor } = CURVE;
@@ -7394,18 +7328,16 @@ function twistedEdwards(curveDef) {
7394
7328
  const { d, a } = CURVE;
7395
7329
  const len = Fp.BYTES;
7396
7330
  hex = ensureBytes('pointHex', hex, len); // copy hex to a new array
7331
+ abool('zip215', zip215);
7397
7332
  const normed = hex.slice(); // copy again, we'll manipulate it
7398
7333
  const lastByte = hex[len - 1]; // select last byte
7399
7334
  normed[len - 1] = lastByte & ~0x80; // clear last bit
7400
7335
  const y = bytesToNumberLE(normed);
7401
- if (y === _0n$1) ;
7402
- else {
7403
- // RFC8032 prohibits >= p, but ZIP215 doesn't
7404
- if (zip215)
7405
- assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)
7406
- else
7407
- assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)
7408
- }
7336
+ // RFC8032 prohibits >= p, but ZIP215 doesn't
7337
+ // zip215=true: 0 <= y < MASK (2^256 for ed25519)
7338
+ // zip215=false: 0 <= y < P (2^255-19 for ed25519)
7339
+ const max = zip215 ? MASK : Fp.ORDER;
7340
+ aInRange('pointHex.y', y, _0n$1, max);
7409
7341
  // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
7410
7342
  // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
7411
7343
  const y2 = modP(y * y); // denominator is always non-0 mod p.
@@ -7480,7 +7412,7 @@ function twistedEdwards(curveDef) {
7480
7412
  const R = G.multiply(r).toRawBytes(); // R = rG
7481
7413
  const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
7482
7414
  const s = modN(r + k * scalar); // S = (r + k * s) mod L
7483
- assertGE0(s); // 0 <= s < l
7415
+ aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l
7484
7416
  const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));
7485
7417
  return ensureBytes('result', res, nByteLength * 2); // 64-byte signature
7486
7418
  }
@@ -7490,6 +7422,8 @@ function twistedEdwards(curveDef) {
7490
7422
  const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
7491
7423
  sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.
7492
7424
  msg = ensureBytes('message', msg);
7425
+ if (zip215 !== undefined)
7426
+ abool('zip215', zip215);
7493
7427
  if (prehash)
7494
7428
  msg = prehash(msg); // for ed25519ph, etc
7495
7429
  const s = bytesToNumberLE(sig.slice(len, 2 * len));
@@ -7547,12 +7481,14 @@ function twistedEdwards(curveDef) {
7547
7481
  */
7548
7482
  const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
7549
7483
  // √(-1) aka √(a) aka 2^((p-1)/4)
7550
- const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
7484
+ const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
7551
7485
  // prettier-ignore
7552
- BigInt(0); const _1n$2 = BigInt(1), _2n$1 = BigInt(2), _5n = BigInt(5);
7486
+ BigInt(0); const _1n$2 = BigInt(1), _2n$1 = BigInt(2); BigInt(3);
7553
7487
  // prettier-ignore
7554
- const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
7488
+ const _5n = BigInt(5), _8n = BigInt(8);
7555
7489
  function ed25519_pow_2_252_3(x) {
7490
+ // prettier-ignore
7491
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
7556
7492
  const P = ED25519_P;
7557
7493
  const x2 = (x * x) % P;
7558
7494
  const b2 = (x2 * x) % P; // x^3, 11
@@ -7601,8 +7537,8 @@ function uvRatio(u, v) {
7601
7537
  x = mod(-x, P);
7602
7538
  return { isValid: useRoot1 || useRoot2, value: x };
7603
7539
  }
7604
- const Fp$1 = Field(ED25519_P, undefined, true);
7605
- const ed25519Defaults = {
7540
+ const Fp$1 = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7541
+ const ed25519Defaults = /* @__PURE__ */ (() => ({
7606
7542
  // Param: a
7607
7543
  a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
7608
7544
  // d is equal to -121665/121666 over finite field.
@@ -7614,7 +7550,7 @@ const ed25519Defaults = {
7614
7550
  // 2n**252n + 27742317777372353535851937790883648493n;
7615
7551
  n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
7616
7552
  // Cofactor
7617
- h: BigInt(8),
7553
+ h: _8n,
7618
7554
  // Base point (x, y) aka generator point
7619
7555
  Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
7620
7556
  Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
@@ -7625,40 +7561,11 @@ const ed25519Defaults = {
7625
7561
  // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
7626
7562
  // Constant-time, u/√v
7627
7563
  uvRatio,
7628
- };
7629
- const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);
7630
- function ed25519_domain(data, ctx, phflag) {
7631
- if (ctx.length > 255)
7632
- throw new Error('Context is too big');
7633
- return concatBytes$2(utf8ToBytes$2('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
7634
- }
7635
- /* @__PURE__ */ twistedEdwards({
7636
- ...ed25519Defaults,
7637
- domain: ed25519_domain,
7638
- });
7639
- /* @__PURE__ */ twistedEdwards({
7640
- ...ed25519Defaults,
7641
- domain: ed25519_domain,
7642
- prehash: sha512,
7643
- });
7644
- // Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)
7645
- // NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since
7646
- // SageMath returns different root first and everything falls apart
7647
- const ELL2_C1 = (Fp$1.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic
7648
- Fp$1.pow(_2n$1, ELL2_C1); // 2. c2 = 2^c1
7649
- Fp$1.sqrt(Fp$1.neg(Fp$1.ONE)); // 3. c3 = sqrt(-1)
7650
- (Fp$1.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic
7651
- BigInt(486662);
7652
- FpSqrtEven(Fp$1, Fp$1.neg(BigInt(486664))); // sgn0(c1) MUST equal 0
7653
- // √(ad - 1)
7654
- BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
7655
- // 1 / √(a-d)
7656
- BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
7657
- // 1-d²
7658
- BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
7659
- // (d-1)²
7660
- BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
7661
- BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
7564
+ }))();
7565
+ /**
7566
+ * ed25519 curve with EdDSA signatures.
7567
+ */
7568
+ const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
7662
7569
 
7663
7570
  const PUBLIC_KEY_BYTE_LENGTH = 32;
7664
7571
  const PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys
@@ -7715,7 +7622,7 @@ function concatKeys(privateKeyRaw, publicKey) {
7715
7622
  var webcrypto = {
7716
7623
  get(win = globalThis) {
7717
7624
  const nativeCrypto = win.crypto;
7718
- if (nativeCrypto == null || nativeCrypto.subtle == null) {
7625
+ if (nativeCrypto?.subtle == null) {
7719
7626
  throw Object.assign(new Error('Missing Web Crypto API. ' +
7720
7627
  'The most likely cause of this error is that this page is being accessed ' +
7721
7628
  'from an insecure context (i.e. not HTTPS). For more information and ' +
@@ -7739,12 +7646,12 @@ var webcrypto = {
7739
7646
  const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };
7740
7647
  // Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples
7741
7648
  function create(opts) {
7742
- const algorithm = opts?.algorithm ?? 'AES-GCM';
7743
- let keyLength = opts?.keyLength ?? 16;
7744
- const nonceLength = opts?.nonceLength ?? 12;
7745
- const digest = opts?.digest ?? 'SHA-256';
7746
- const saltLength = opts?.saltLength ?? 16;
7747
- const iterations = opts?.iterations ?? 32767;
7649
+ const algorithm = 'AES-GCM';
7650
+ let keyLength = 16;
7651
+ const nonceLength = 12;
7652
+ const digest = 'SHA-256';
7653
+ const saltLength = 16;
7654
+ const iterations = 32767;
7748
7655
  const crypto = webcrypto.get();
7749
7656
  keyLength *= 8; // Browser crypto uses bits instead of bytes
7750
7657
  /**
@@ -8528,7 +8435,7 @@ function decodeMessage(buf, codec, opts) {
8528
8435
  * A general purpose buffer pool
8529
8436
  */
8530
8437
  function pool(size) {
8531
- const SIZE = size ?? 8192;
8438
+ const SIZE = 8192;
8532
8439
  const MAX = SIZE >>> 1;
8533
8440
  let slab;
8534
8441
  let offset = SIZE;
@@ -9041,12 +8948,17 @@ function message(encode, decode) {
9041
8948
  * npm i protons-runtime
9042
8949
  * ```
9043
8950
  */
9044
- class CodeError extends Error {
9045
- code;
9046
- constructor(message, code, options) {
9047
- super(message, options);
9048
- this.code = code;
9049
- }
8951
+ /**
8952
+ * Thrown when a repeated field has too many elements
8953
+ */
8954
+ class MaxLengthError extends Error {
8955
+ /**
8956
+ * This will be removed in a future release
8957
+ *
8958
+ * @deprecated use the `.name` property instead
8959
+ */
8960
+ code = 'ERR_MAX_LENGTH';
8961
+ name = 'MaxLengthError';
9050
8962
  }
9051
8963
 
9052
8964
  /* eslint-disable import/export */
@@ -9257,7 +9169,7 @@ class Ed25519PrivateKey {
9257
9169
  return exporter(this.bytes, password);
9258
9170
  }
9259
9171
  else {
9260
- throw new CodeError$1(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
9172
+ throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
9261
9173
  }
9262
9174
  }
9263
9175
  }
@@ -9289,7 +9201,7 @@ async function generateKeyPairFromSeed(seed) {
9289
9201
  function ensureKey(key, length) {
9290
9202
  key = Uint8Array.from(key ?? []);
9291
9203
  if (key.length !== length) {
9292
- throw new CodeError$1(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');
9204
+ throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');
9293
9205
  }
9294
9206
  return key;
9295
9207
  }
@@ -9309,7 +9221,7 @@ var Ed25519 = /*#__PURE__*/Object.freeze({
9309
9221
  */
9310
9222
  function randomBytes(length) {
9311
9223
  if (isNaN(length) || length <= 0) {
9312
- throw new CodeError$1('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');
9224
+ throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');
9313
9225
  }
9314
9226
  return randomBytes$1(length);
9315
9227
  }
@@ -12718,7 +12630,7 @@ function pkcs1ToJwk(bytes) {
12718
12630
  */
12719
12631
  function jwkToPkcs1(jwk) {
12720
12632
  if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {
12721
- throw new CodeError$1('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12633
+ throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12722
12634
  }
12723
12635
  const root = new Sequence({
12724
12636
  value: [
@@ -12755,7 +12667,7 @@ function pkixToJwk(bytes) {
12755
12667
  */
12756
12668
  function jwkToPkix(jwk) {
12757
12669
  if (jwk.n == null || jwk.e == null) {
12758
- throw new CodeError$1('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12670
+ throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12759
12671
  }
12760
12672
  const root = new Sequence({
12761
12673
  value: [
@@ -12967,7 +12879,7 @@ async function hashAndVerify$1(key, sig, msg) {
12967
12879
  }
12968
12880
  async function exportKey(pair) {
12969
12881
  if (pair.privateKey == null || pair.publicKey == null) {
12970
- throw new CodeError$1('Private and public key are required', 'ERR_INVALID_PARAMETERS');
12882
+ throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');
12971
12883
  }
12972
12884
  return Promise.all([
12973
12885
  webcrypto.get().subtle.exportKey('jwk', pair.privateKey),
@@ -12986,10 +12898,10 @@ async function derivePublicFromPrivate(jwKey) {
12986
12898
  }
12987
12899
  function keySize(jwk) {
12988
12900
  if (jwk.kty !== 'RSA') {
12989
- throw new CodeError$1('invalid key type', 'ERR_INVALID_KEY_TYPE');
12901
+ throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');
12990
12902
  }
12991
12903
  else if (jwk.n == null) {
12992
- throw new CodeError$1('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');
12904
+ throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');
12993
12905
  }
12994
12906
  const bytes = fromString(jwk.n, 'base64url');
12995
12907
  return bytes.length * 8;
@@ -13039,7 +12951,7 @@ class RsaPrivateKey {
13039
12951
  }
13040
12952
  get public() {
13041
12953
  if (this._publicKey == null) {
13042
- throw new CodeError$1('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');
12954
+ throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');
13043
12955
  }
13044
12956
  return new RsaPublicKey(this._publicKey);
13045
12957
  }
@@ -13088,14 +13000,14 @@ class RsaPrivateKey {
13088
13000
  return exporter(this.bytes, password);
13089
13001
  }
13090
13002
  else {
13091
- throw new CodeError$1(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
13003
+ throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
13092
13004
  }
13093
13005
  }
13094
13006
  }
13095
13007
  async function unmarshalRsaPrivateKey(bytes) {
13096
13008
  const jwk = pkcs1ToJwk(bytes);
13097
13009
  if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
13098
- throw new CodeError$1('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
13010
+ throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
13099
13011
  }
13100
13012
  const keys = await unmarshalPrivateKey$1(jwk);
13101
13013
  return new RsaPrivateKey(keys.privateKey, keys.publicKey);
@@ -13103,20 +13015,20 @@ async function unmarshalRsaPrivateKey(bytes) {
13103
13015
  function unmarshalRsaPublicKey(bytes) {
13104
13016
  const jwk = pkixToJwk(bytes);
13105
13017
  if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
13106
- throw new CodeError$1('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
13018
+ throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
13107
13019
  }
13108
13020
  return new RsaPublicKey(jwk);
13109
13021
  }
13110
13022
  async function fromJwk(jwk) {
13111
13023
  if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
13112
- throw new CodeError$1('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
13024
+ throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
13113
13025
  }
13114
13026
  const keys = await unmarshalPrivateKey$1(jwk);
13115
13027
  return new RsaPrivateKey(keys.privateKey, keys.publicKey);
13116
13028
  }
13117
13029
  async function generateKeyPair$1(bits) {
13118
13030
  if (bits > MAX_RSA_KEY_SIZE) {
13119
- throw new CodeError$1('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
13031
+ throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
13120
13032
  }
13121
13033
  const keys = await generateKey$1(bits);
13122
13034
  return new RsaPrivateKey(keys.privateKey, keys.publicKey);
@@ -13135,6 +13047,12 @@ var RSA = /*#__PURE__*/Object.freeze({
13135
13047
 
13136
13048
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13137
13049
  // Short Weierstrass curve. The formula is: y² = x³ + ax + b
13050
+ function validateSigVerOpts(opts) {
13051
+ if (opts.lowS !== undefined)
13052
+ abool('lowS', opts.lowS);
13053
+ if (opts.prehash !== undefined)
13054
+ abool('prehash', opts.prehash);
13055
+ }
13138
13056
  function validatePointOpts(curve) {
13139
13057
  const opts = validateBasic(curve);
13140
13058
  validateObject(opts, {
@@ -13259,16 +13177,12 @@ function weierstrassPoints(opts) {
13259
13177
  throw new Error('bad generator point: equation left != right');
13260
13178
  // Valid group elements reside in range 1..n-1
13261
13179
  function isWithinCurveOrder(num) {
13262
- return typeof num === 'bigint' && _0n < num && num < CURVE.n;
13263
- }
13264
- function assertGE(num) {
13265
- if (!isWithinCurveOrder(num))
13266
- throw new Error('Expected valid bigint: 0 < bigint < curve.n');
13180
+ return inRange(num, _1n$1, CURVE.n);
13267
13181
  }
13268
13182
  // Validates if priv key is valid and converts it to bigint.
13269
13183
  // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
13270
13184
  function normPrivateKeyToScalar(key) {
13271
- const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
13185
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
13272
13186
  if (lengths && typeof key !== 'bigint') {
13273
13187
  if (isBytes$1(key))
13274
13188
  key = bytesToHex(key);
@@ -13288,15 +13202,61 @@ function weierstrassPoints(opts) {
13288
13202
  throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
13289
13203
  }
13290
13204
  if (wrapPrivateKey)
13291
- num = mod(num, n); // disabled by default, enabled for BLS
13292
- assertGE(num); // num in range [1..N-1]
13205
+ num = mod(num, N); // disabled by default, enabled for BLS
13206
+ aInRange('private key', num, _1n$1, N); // num in range [1..N-1]
13293
13207
  return num;
13294
13208
  }
13295
- const pointPrecomputes = new Map();
13296
13209
  function assertPrjPoint(other) {
13297
13210
  if (!(other instanceof Point))
13298
13211
  throw new Error('ProjectivePoint expected');
13299
13212
  }
13213
+ // Memoized toAffine / validity check. They are heavy. Points are immutable.
13214
+ // Converts Projective point to affine (x, y) coordinates.
13215
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
13216
+ // (x, y, z) ∋ (x=x/z, y=y/z)
13217
+ const toAffineMemo = memoized((p, iz) => {
13218
+ const { px: x, py: y, pz: z } = p;
13219
+ // Fast-path for normalized points
13220
+ if (Fp.eql(z, Fp.ONE))
13221
+ return { x, y };
13222
+ const is0 = p.is0();
13223
+ // If invZ was 0, we return zero point. However we still want to execute
13224
+ // all operations, so we replace invZ with a random number, 1.
13225
+ if (iz == null)
13226
+ iz = is0 ? Fp.ONE : Fp.inv(z);
13227
+ const ax = Fp.mul(x, iz);
13228
+ const ay = Fp.mul(y, iz);
13229
+ const zz = Fp.mul(z, iz);
13230
+ if (is0)
13231
+ return { x: Fp.ZERO, y: Fp.ZERO };
13232
+ if (!Fp.eql(zz, Fp.ONE))
13233
+ throw new Error('invZ was invalid');
13234
+ return { x: ax, y: ay };
13235
+ });
13236
+ // NOTE: on exception this will crash 'cached' and no value will be set.
13237
+ // Otherwise true will be return
13238
+ const assertValidMemo = memoized((p) => {
13239
+ if (p.is0()) {
13240
+ // (0, 1, 0) aka ZERO is invalid in most contexts.
13241
+ // In BLS, ZERO can be serialized, so we allow it.
13242
+ // (0, 0, 0) is wrong representation of ZERO and is always invalid.
13243
+ if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
13244
+ return;
13245
+ throw new Error('bad point: ZERO');
13246
+ }
13247
+ // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
13248
+ const { x, y } = p.toAffine();
13249
+ // Check if x, y are valid field elements
13250
+ if (!Fp.isValid(x) || !Fp.isValid(y))
13251
+ throw new Error('bad point: x or y not FE');
13252
+ const left = Fp.sqr(y); // y²
13253
+ const right = weierstrassEquation(x); // x³ + ax + b
13254
+ if (!Fp.eql(left, right))
13255
+ throw new Error('bad point: equation left != right');
13256
+ if (!p.isTorsionFree())
13257
+ throw new Error('bad point: not in prime-order subgroup');
13258
+ return true;
13259
+ });
13300
13260
  /**
13301
13261
  * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
13302
13262
  * Default Point works in 2d / affine coordinates: (x, y)
@@ -13313,6 +13273,7 @@ function weierstrassPoints(opts) {
13313
13273
  throw new Error('y required');
13314
13274
  if (pz == null || !Fp.isValid(pz))
13315
13275
  throw new Error('z required');
13276
+ Object.freeze(this);
13316
13277
  }
13317
13278
  // Does not validate if the point is on-curve.
13318
13279
  // Use fromHex instead, or call assertValidity() later.
@@ -13359,30 +13320,11 @@ function weierstrassPoints(opts) {
13359
13320
  }
13360
13321
  // "Private method", don't use it directly
13361
13322
  _setWindowSize(windowSize) {
13362
- this._WINDOW_SIZE = windowSize;
13363
- pointPrecomputes.delete(this);
13323
+ wnaf.setWindowSize(this, windowSize);
13364
13324
  }
13365
13325
  // A point on curve is valid if it conforms to equation.
13366
13326
  assertValidity() {
13367
- if (this.is0()) {
13368
- // (0, 1, 0) aka ZERO is invalid in most contexts.
13369
- // In BLS, ZERO can be serialized, so we allow it.
13370
- // (0, 0, 0) is wrong representation of ZERO and is always invalid.
13371
- if (CURVE.allowInfinityPoint && !Fp.is0(this.py))
13372
- return;
13373
- throw new Error('bad point: ZERO');
13374
- }
13375
- // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
13376
- const { x, y } = this.toAffine();
13377
- // Check if x, y are valid field elements
13378
- if (!Fp.isValid(x) || !Fp.isValid(y))
13379
- throw new Error('bad point: x or y not FE');
13380
- const left = Fp.sqr(y); // y²
13381
- const right = weierstrassEquation(x); // x³ + ax + b
13382
- if (!Fp.eql(left, right))
13383
- throw new Error('bad point: equation left != right');
13384
- if (!this.isTorsionFree())
13385
- throw new Error('bad point: not in prime-order subgroup');
13327
+ assertValidMemo(this);
13386
13328
  }
13387
13329
  hasEvenY() {
13388
13330
  const { y } = this.toAffine();
@@ -13509,28 +13451,25 @@ function weierstrassPoints(opts) {
13509
13451
  return this.equals(Point.ZERO);
13510
13452
  }
13511
13453
  wNAF(n) {
13512
- return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
13513
- const toInv = Fp.invertBatch(comp.map((p) => p.pz));
13514
- return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
13515
- });
13454
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
13516
13455
  }
13517
13456
  /**
13518
13457
  * Non-constant-time multiplication. Uses double-and-add algorithm.
13519
13458
  * It's faster, but should only be used when you don't care about
13520
13459
  * an exposed private key e.g. sig verification, which works over *public* keys.
13521
13460
  */
13522
- multiplyUnsafe(n) {
13461
+ multiplyUnsafe(sc) {
13462
+ aInRange('scalar', sc, _0n, CURVE.n);
13523
13463
  const I = Point.ZERO;
13524
- if (n === _0n)
13464
+ if (sc === _0n)
13525
13465
  return I;
13526
- assertGE(n); // Will throw on 0
13527
- if (n === _1n$1)
13466
+ if (sc === _1n$1)
13528
13467
  return this;
13529
13468
  const { endo } = CURVE;
13530
13469
  if (!endo)
13531
- return wnaf.unsafeLadder(this, n);
13470
+ return wnaf.unsafeLadder(this, sc);
13532
13471
  // Apply endomorphism
13533
- let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
13472
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
13534
13473
  let k1p = I;
13535
13474
  let k2p = I;
13536
13475
  let d = this;
@@ -13560,12 +13499,11 @@ function weierstrassPoints(opts) {
13560
13499
  * @returns New point
13561
13500
  */
13562
13501
  multiply(scalar) {
13563
- assertGE(scalar);
13564
- let n = scalar;
13502
+ const { endo, n: N } = CURVE;
13503
+ aInRange('scalar', scalar, _1n$1, N);
13565
13504
  let point, fake; // Fake point is used to const-time mult
13566
- const { endo } = CURVE;
13567
13505
  if (endo) {
13568
- const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
13506
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
13569
13507
  let { p: k1p, f: f1p } = this.wNAF(k1);
13570
13508
  let { p: k2p, f: f2p } = this.wNAF(k2);
13571
13509
  k1p = wnaf.constTimeNegate(k1neg, k1p);
@@ -13575,7 +13513,7 @@ function weierstrassPoints(opts) {
13575
13513
  fake = f1p.add(f2p);
13576
13514
  }
13577
13515
  else {
13578
- const { p, f } = this.wNAF(n);
13516
+ const { p, f } = this.wNAF(scalar);
13579
13517
  point = p;
13580
13518
  fake = f;
13581
13519
  }
@@ -13599,20 +13537,7 @@ function weierstrassPoints(opts) {
13599
13537
  // Can accept precomputed Z^-1 - for example, from invertBatch.
13600
13538
  // (x, y, z) ∋ (x=x/z, y=y/z)
13601
13539
  toAffine(iz) {
13602
- const { px: x, py: y, pz: z } = this;
13603
- const is0 = this.is0();
13604
- // If invZ was 0, we return zero point. However we still want to execute
13605
- // all operations, so we replace invZ with a random number, 1.
13606
- if (iz == null)
13607
- iz = is0 ? Fp.ONE : Fp.inv(z);
13608
- const ax = Fp.mul(x, iz);
13609
- const ay = Fp.mul(y, iz);
13610
- const zz = Fp.mul(z, iz);
13611
- if (is0)
13612
- return { x: Fp.ZERO, y: Fp.ZERO };
13613
- if (!Fp.eql(zz, Fp.ONE))
13614
- throw new Error('invZ was invalid');
13615
- return { x: ax, y: ay };
13540
+ return toAffineMemo(this, iz);
13616
13541
  }
13617
13542
  isTorsionFree() {
13618
13543
  const { h: cofactor, isTorsionFree } = CURVE;
@@ -13631,10 +13556,12 @@ function weierstrassPoints(opts) {
13631
13556
  return this.multiplyUnsafe(CURVE.h);
13632
13557
  }
13633
13558
  toRawBytes(isCompressed = true) {
13559
+ abool('isCompressed', isCompressed);
13634
13560
  this.assertValidity();
13635
13561
  return toBytes(Point, this, isCompressed);
13636
13562
  }
13637
13563
  toHex(isCompressed = true) {
13564
+ abool('isCompressed', isCompressed);
13638
13565
  return bytesToHex(this.toRawBytes(isCompressed));
13639
13566
  }
13640
13567
  }
@@ -13664,14 +13591,18 @@ function validateOpts(curve) {
13664
13591
  });
13665
13592
  return Object.freeze({ lowS: true, ...opts });
13666
13593
  }
13594
+ /**
13595
+ * Creates short weierstrass curve and ECDSA signature methods for it.
13596
+ * @example
13597
+ * import { Field } from '@noble/curves/abstract/modular';
13598
+ * // Before that, define BigInt-s: a, b, p, n, Gx, Gy
13599
+ * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })
13600
+ */
13667
13601
  function weierstrass(curveDef) {
13668
13602
  const CURVE = validateOpts(curveDef);
13669
13603
  const { Fp, n: CURVE_ORDER } = CURVE;
13670
13604
  const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
13671
13605
  const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
13672
- function isValidFieldElement(num) {
13673
- return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
13674
- }
13675
13606
  function modN(a) {
13676
13607
  return mod(a, CURVE_ORDER);
13677
13608
  }
@@ -13684,6 +13615,7 @@ function weierstrass(curveDef) {
13684
13615
  const a = point.toAffine();
13685
13616
  const x = Fp.toBytes(a.x);
13686
13617
  const cat = concatBytes;
13618
+ abool('isCompressed', isCompressed);
13687
13619
  if (isCompressed) {
13688
13620
  return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
13689
13621
  }
@@ -13698,7 +13630,7 @@ function weierstrass(curveDef) {
13698
13630
  // this.assertValidity() is done inside of fromHex
13699
13631
  if (len === compressedLen && (head === 0x02 || head === 0x03)) {
13700
13632
  const x = bytesToNumberBE(tail);
13701
- if (!isValidFieldElement(x))
13633
+ if (!inRange(x, _1n$1, Fp.ORDER))
13702
13634
  throw new Error('Point is not on curve');
13703
13635
  const y2 = weierstrassEquation(x); // y² = x³ + ax + b
13704
13636
  let y;
@@ -13759,11 +13691,8 @@ function weierstrass(curveDef) {
13759
13691
  return new Signature(r, s);
13760
13692
  }
13761
13693
  assertValidity() {
13762
- // can use assertGE here
13763
- if (!isWithinCurveOrder(this.r))
13764
- throw new Error('r must be 0 < r < CURVE.n');
13765
- if (!isWithinCurveOrder(this.s))
13766
- throw new Error('s must be 0 < s < CURVE.n');
13694
+ aInRange('r', this.r, _1n$1, CURVE_ORDER); // r in [1..N]
13695
+ aInRange('s', this.s, _1n$1, CURVE_ORDER); // s in [1..N]
13767
13696
  }
13768
13697
  addRecoveryBit(recovery) {
13769
13698
  return new Signature(this.r, this.s, recovery);
@@ -13906,10 +13835,7 @@ function weierstrass(curveDef) {
13906
13835
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
13907
13836
  */
13908
13837
  function int2octets(num) {
13909
- if (typeof num !== 'bigint')
13910
- throw new Error('bigint expected');
13911
- if (!(_0n <= num && num < ORDER_MASK))
13912
- throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
13838
+ aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);
13913
13839
  // works with order, can have different size than numToField!
13914
13840
  return numberToBytesBE(num, CURVE.nByteLength);
13915
13841
  }
@@ -13926,6 +13852,7 @@ function weierstrass(curveDef) {
13926
13852
  if (lowS == null)
13927
13853
  lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
13928
13854
  msgHash = ensureBytes('msgHash', msgHash);
13855
+ validateSigVerOpts(opts);
13929
13856
  if (prehash)
13930
13857
  msgHash = ensureBytes('prehashed msgHash', hash(msgHash));
13931
13858
  // We can't later call bits2octets, since nested bits2int is broken for curves
@@ -14012,6 +13939,7 @@ function weierstrass(curveDef) {
14012
13939
  publicKey = ensureBytes('publicKey', publicKey);
14013
13940
  if ('strict' in opts)
14014
13941
  throw new Error('options.strict was renamed to lowS');
13942
+ validateSigVerOpts(opts);
14015
13943
  const { lowS, prehash } = opts;
14016
13944
  let _sig = undefined;
14017
13945
  let P;
@@ -14118,6 +14046,9 @@ function sqrtMod(y) {
14118
14046
  return root;
14119
14047
  }
14120
14048
  const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
14049
+ /**
14050
+ * secp256k1 short weierstrass curve and ECDSA signatures over it.
14051
+ */
14121
14052
  const secp256k1 = createCurve({
14122
14053
  a: BigInt(0), // equation params: a, b
14123
14054
  b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
@@ -14176,14 +14107,14 @@ function hashAndSign(key, msg) {
14176
14107
  if (isPromise$1(p)) {
14177
14108
  return p.then(({ digest }) => secp256k1.sign(digest, key).toDERRawBytes())
14178
14109
  .catch(err => {
14179
- throw new CodeError$1(String(err), 'ERR_INVALID_INPUT');
14110
+ throw new CodeError(String(err), 'ERR_INVALID_INPUT');
14180
14111
  });
14181
14112
  }
14182
14113
  try {
14183
14114
  return secp256k1.sign(p.digest, key).toDERRawBytes();
14184
14115
  }
14185
14116
  catch (err) {
14186
- throw new CodeError$1(String(err), 'ERR_INVALID_INPUT');
14117
+ throw new CodeError(String(err), 'ERR_INVALID_INPUT');
14187
14118
  }
14188
14119
  }
14189
14120
  /**
@@ -14194,14 +14125,14 @@ function hashAndVerify(key, sig, msg) {
14194
14125
  if (isPromise$1(p)) {
14195
14126
  return p.then(({ digest }) => secp256k1.verify(sig, digest, key))
14196
14127
  .catch(err => {
14197
- throw new CodeError$1(String(err), 'ERR_INVALID_INPUT');
14128
+ throw new CodeError(String(err), 'ERR_INVALID_INPUT');
14198
14129
  });
14199
14130
  }
14200
14131
  try {
14201
14132
  return secp256k1.verify(sig, p.digest, key);
14202
14133
  }
14203
14134
  catch (err) {
14204
- throw new CodeError$1(String(err), 'ERR_INVALID_INPUT');
14135
+ throw new CodeError(String(err), 'ERR_INVALID_INPUT');
14205
14136
  }
14206
14137
  }
14207
14138
  function compressPublicKey(key) {
@@ -14213,7 +14144,7 @@ function validatePrivateKey(key) {
14213
14144
  secp256k1.getPublicKey(key, true);
14214
14145
  }
14215
14146
  catch (err) {
14216
- throw new CodeError$1(String(err), 'ERR_INVALID_PRIVATE_KEY');
14147
+ throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
14217
14148
  }
14218
14149
  }
14219
14150
  function validatePublicKey(key) {
@@ -14221,7 +14152,7 @@ function validatePublicKey(key) {
14221
14152
  secp256k1.ProjectivePoint.fromHex(key);
14222
14153
  }
14223
14154
  catch (err) {
14224
- throw new CodeError$1(String(err), 'ERR_INVALID_PUBLIC_KEY');
14155
+ throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');
14225
14156
  }
14226
14157
  }
14227
14158
  function computePublicKey(privateKey) {
@@ -14229,7 +14160,7 @@ function computePublicKey(privateKey) {
14229
14160
  return secp256k1.getPublicKey(privateKey, true);
14230
14161
  }
14231
14162
  catch (err) {
14232
- throw new CodeError$1(String(err), 'ERR_INVALID_PRIVATE_KEY');
14163
+ throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
14233
14164
  }
14234
14165
  }
14235
14166
 
@@ -14319,7 +14250,7 @@ class Secp256k1PrivateKey {
14319
14250
  return exporter(this.bytes, password);
14320
14251
  }
14321
14252
  else {
14322
- throw new CodeError$1(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
14253
+ throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
14323
14254
  }
14324
14255
  }
14325
14256
  }
@@ -14361,7 +14292,7 @@ const supportedKeys = {
14361
14292
  };
14362
14293
  function unsupportedKey(type) {
14363
14294
  const supported = Object.keys(supportedKeys).join(' / ');
14364
- return new CodeError$1(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');
14295
+ return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');
14365
14296
  }
14366
14297
  function typeToKey(type) {
14367
14298
  type = type.toLowerCase();
@@ -14546,6 +14477,41 @@ class Secp256k1PeerIdImpl extends PeerIdImpl {
14546
14477
  this.publicKey = init.multihash.digest;
14547
14478
  }
14548
14479
  }
14480
+ // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
14481
+ const TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;
14482
+ class URLPeerIdImpl {
14483
+ type = 'url';
14484
+ multihash;
14485
+ privateKey;
14486
+ publicKey;
14487
+ url;
14488
+ constructor(url) {
14489
+ this.url = url.toString();
14490
+ this.multihash = identity.digest(fromString(this.url));
14491
+ }
14492
+ [inspect]() {
14493
+ return `PeerId(${this.url})`;
14494
+ }
14495
+ [peerIdSymbol] = true;
14496
+ toString() {
14497
+ return this.toCID().toString();
14498
+ }
14499
+ toCID() {
14500
+ return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);
14501
+ }
14502
+ toBytes() {
14503
+ return this.toCID().bytes;
14504
+ }
14505
+ equals(other) {
14506
+ if (other == null) {
14507
+ return false;
14508
+ }
14509
+ if (other instanceof Uint8Array) {
14510
+ other = toString$6(other);
14511
+ }
14512
+ return other.toString() === this.toString();
14513
+ }
14514
+ }
14549
14515
  function peerIdFromString(str, decoder) {
14550
14516
  if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
14551
14517
  // identity hash ed25519/secp256k1 key or sha2-256 hash of
@@ -14584,9 +14550,13 @@ function peerIdFromBytes(buf) {
14584
14550
  throw new Error('Supplied PeerID CID is invalid');
14585
14551
  }
14586
14552
  function peerIdFromCID(cid) {
14587
- if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {
14553
+ if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {
14588
14554
  throw new Error('Supplied PeerID CID is invalid');
14589
14555
  }
14556
+ if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {
14557
+ const url = toString$6(cid.multihash.digest);
14558
+ return new URLPeerIdImpl(new URL(url));
14559
+ }
14590
14560
  const multihash = cid.multihash;
14591
14561
  if (multihash.code === sha256.code) {
14592
14562
  return new RSAPeerIdImpl({ multihash: cid.multihash });
@@ -15432,9 +15402,6 @@ function isHexString(value, length) {
15432
15402
  if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
15433
15403
  return false;
15434
15404
  }
15435
- if (length && value.length !== 2 + 2 * length) {
15436
- return false;
15437
- }
15438
15405
  return true;
15439
15406
  }
15440
15407
  const HexCharacters = "0123456789abcdef";
@@ -17858,7 +17825,7 @@ if (!AbortError$1) {
17858
17825
  AbortError$1.prototype.name = 'AbortError';
17859
17826
  AbortError$1.prototype.code = 'ABORT_ERR';
17860
17827
 
17861
- const URL = (typeof globalThis !== 'undefined' && globalThis.URL) || require('url').URL;
17828
+ const URL$1 = (typeof globalThis !== 'undefined' && globalThis.URL) || require('url').URL;
17862
17829
 
17863
17830
  class HTTPStatusError extends Error {
17864
17831
  constructor (uri, code, method) {
@@ -18107,7 +18074,7 @@ class HTTPEndpoint extends BaseEndpoint {
18107
18074
  }
18108
18075
  const url = `${this.protocol}//${safeHost(this.host)}:${this.port}${this.path}`;
18109
18076
  try {
18110
- this.url = new URL(url);
18077
+ this.url = new URL$1(url);
18111
18078
  } catch (err) {
18112
18079
  throw new Error(err.message + ` [${url}]`)
18113
18080
  }
@@ -18189,7 +18156,7 @@ async function loadJSON (url, cache, timeout, abortSignal) {
18189
18156
 
18190
18157
  function requestRaw (url, method, data, timeout, abortSignal) {
18191
18158
  return new Promise((resolve, reject) => {
18192
- const target = new URL(url);
18159
+ const target = new URL$1(url);
18193
18160
  if (method === 'GET' && data) {
18194
18161
  target.search = '?dns=' + base64URL.decode(data);
18195
18162
  }
@@ -19568,7 +19535,7 @@ function queryDoh (endpoint, query, timeout, abortSignal) {
19568
19535
  )
19569
19536
  }
19570
19537
 
19571
- const UPDATE_URL = new URL('https://martinheidegger.github.io/dns-query/resolvers.json');
19538
+ const UPDATE_URL = new URL$1('https://martinheidegger.github.io/dns-query/resolvers.json');
19572
19539
 
19573
19540
  function isNameString (entry) {
19574
19541
  return /^@/.test(entry)
@@ -20769,24 +20736,6 @@ async function getConnectedPeersForProtocolAndShard(connections, peerStore, prot
20769
20736
  const peersWithNulls = await Promise.all(peerPromises);
20770
20737
  return peersWithNulls.filter((peer) => peer !== null);
20771
20738
  }
20772
- function selectConnection(connections) {
20773
- if (!connections.length)
20774
- return;
20775
- if (connections.length === 1)
20776
- return connections[0];
20777
- let latestConnection;
20778
- connections.forEach((connection) => {
20779
- if (connection.status === "open") {
20780
- if (!latestConnection) {
20781
- latestConnection = connection;
20782
- }
20783
- else if (connection.timeline.open > latestConnection.timeline.open) {
20784
- latestConnection = connection;
20785
- }
20786
- }
20787
- });
20788
- return latestConnection;
20789
- }
20790
20739
 
20791
20740
  /**
20792
20741
  * Retrieves a list of peers based on the specified criteria:
@@ -20825,6 +20774,25 @@ function filterPeersByDiscovery(peers, numPeers, maxBootstrapPeers) {
20825
20774
  return selectedPeers;
20826
20775
  }
20827
20776
 
20777
+ function selectConnection(connections) {
20778
+ if (!connections.length)
20779
+ return;
20780
+ if (connections.length === 1)
20781
+ return connections[0];
20782
+ let latestConnection;
20783
+ connections.forEach((connection) => {
20784
+ if (connection.status === "open") {
20785
+ if (!latestConnection) {
20786
+ latestConnection = connection;
20787
+ }
20788
+ else if (connection.timeline.open > latestConnection.timeline.open) {
20789
+ latestConnection = connection;
20790
+ }
20791
+ }
20792
+ });
20793
+ return latestConnection;
20794
+ }
20795
+
20828
20796
  const CONNECTION_TIMEOUT = 5_000;
20829
20797
  const RETRY_BACKOFF_BASE = 1_000;
20830
20798
  const MAX_RETRIES = 3;
@@ -20922,16 +20890,14 @@ class BaseProtocol {
20922
20890
  components;
20923
20891
  log;
20924
20892
  pubsubTopics;
20925
- options;
20926
20893
  addLibp2pEventListener;
20927
20894
  removeLibp2pEventListener;
20928
20895
  streamManager;
20929
- constructor(multicodec, components, log, pubsubTopics, options) {
20896
+ constructor(multicodec, components, log, pubsubTopics) {
20930
20897
  this.multicodec = multicodec;
20931
20898
  this.components = components;
20932
20899
  this.log = log;
20933
20900
  this.pubsubTopics = pubsubTopics;
20934
- this.options = options;
20935
20901
  this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
20936
20902
  this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
20937
20903
  this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
@@ -20969,9 +20935,7 @@ class BaseProtocol {
20969
20935
  numPeers: 0
20970
20936
  }) {
20971
20937
  // Retrieve all connected peers that support the protocol & shard (if configured)
20972
- const connectedPeersForProtocolAndShard = await getConnectedPeersForProtocolAndShard(this.components.connectionManager.getConnections(), this.peerStore, [this.multicodec], this.options?.shardInfo
20973
- ? ensureShardingConfigured(this.options.shardInfo).shardInfo
20974
- : undefined);
20938
+ const connectedPeersForProtocolAndShard = await getConnectedPeersForProtocolAndShard(this.components.connectionManager.getConnections(), this.peerStore, [this.multicodec], pubsubTopicsToShardInfo(this.pubsubTopics));
20975
20939
  // Filter the peers based on discovery & number of peers requested
20976
20940
  const filteredPeers = filterPeersByDiscovery(connectedPeersForProtocolAndShard, numPeers, maxBootstrapPeers);
20977
20941
  // Sort the peers by latency
@@ -21661,74 +21625,35 @@ encode.single = (chunk, options) => {
21661
21625
  };
21662
21626
 
21663
21627
  /**
21664
- * @typedef {{ [key: string]: any }} Extensions
21665
- * @typedef {Error} Err
21666
- * @property {string} message
21628
+ * The reported length of the next data message was not a positive integer
21667
21629
  */
21668
-
21630
+ class InvalidMessageLengthError extends Error {
21631
+ name = 'InvalidMessageLengthError';
21632
+ code = 'ERR_INVALID_MSG_LENGTH';
21633
+ }
21669
21634
  /**
21670
- *
21671
- * @param {Error} obj
21672
- * @param {Extensions} props
21673
- * @returns {Error & Extensions}
21635
+ * The reported length of the next data message was larger than the configured
21636
+ * max allowable value
21674
21637
  */
21675
- function assign(obj, props) {
21676
- for (const key in props) {
21677
- Object.defineProperty(obj, key, {
21678
- value: props[key],
21679
- enumerable: true,
21680
- configurable: true,
21681
- });
21682
- }
21683
-
21684
- return obj;
21638
+ class InvalidDataLengthError extends Error {
21639
+ name = 'InvalidDataLengthError';
21640
+ code = 'ERR_MSG_DATA_TOO_LONG';
21685
21641
  }
21686
-
21687
21642
  /**
21688
- *
21689
- * @param {any} err - An Error
21690
- * @param {string|Extensions} code - A string code or props to set on the error
21691
- * @param {Extensions} [props] - Props to set on the error
21692
- * @returns {Error & Extensions}
21643
+ * The varint used to specify the length of the next data message contained more
21644
+ * bytes than the configured max allowable value
21693
21645
  */
21694
- function createError(err, code, props) {
21695
- if (!err || typeof err === 'string') {
21696
- throw new TypeError('Please pass an Error to err-code');
21697
- }
21698
-
21699
- if (!props) {
21700
- props = {};
21701
- }
21702
-
21703
- if (typeof code === 'object') {
21704
- props = code;
21705
- code = '';
21706
- }
21707
-
21708
- if (code) {
21709
- props.code = code;
21710
- }
21711
-
21712
- try {
21713
- return assign(err, props);
21714
- } catch (_) {
21715
- props.message = err.message;
21716
- props.stack = err.stack;
21717
-
21718
- const ErrClass = function () {};
21719
-
21720
- ErrClass.prototype = Object.create(Object.getPrototypeOf(err));
21721
-
21722
- // @ts-ignore
21723
- const output = assign(new ErrClass(), props);
21724
-
21725
- return output;
21726
- }
21646
+ class InvalidDataLengthLengthError extends Error {
21647
+ name = 'InvalidDataLengthLengthError';
21648
+ code = 'ERR_MSG_LENGTH_TOO_LONG';
21649
+ }
21650
+ /**
21651
+ * The incoming stream ended before the expected number of bytes were read
21652
+ */
21653
+ class UnexpectedEOFError extends Error {
21654
+ name = 'UnexpectedEOFError';
21655
+ code = 'ERR_UNEXPECTED_EOF';
21727
21656
  }
21728
-
21729
- var errCode = createError;
21730
-
21731
- var errCode$1 = /*@__PURE__*/getDefaultExportFromCjs(errCode);
21732
21657
 
21733
21658
  /* eslint max-depth: ["error", 6] */
21734
21659
  // Maximum length of the length section of the message
@@ -21760,10 +21685,10 @@ function decode(source, options) {
21760
21685
  try {
21761
21686
  dataLength = lengthDecoder(buffer);
21762
21687
  if (dataLength < 0) {
21763
- throw errCode$1(new Error('invalid message length'), 'ERR_INVALID_MSG_LENGTH');
21688
+ throw new InvalidMessageLengthError('Invalid message length');
21764
21689
  }
21765
21690
  if (dataLength > maxDataLength) {
21766
- throw errCode$1(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG');
21691
+ throw new InvalidDataLengthError('Message length too long');
21767
21692
  }
21768
21693
  const dataLengthLength = lengthDecoder.bytes;
21769
21694
  buffer.consume(dataLengthLength);
@@ -21775,7 +21700,7 @@ function decode(source, options) {
21775
21700
  catch (err) {
21776
21701
  if (err instanceof RangeError) {
21777
21702
  if (buffer.byteLength > maxLengthLength) {
21778
- throw errCode$1(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG');
21703
+ throw new InvalidDataLengthLengthError('Message length length too long');
21779
21704
  }
21780
21705
  break;
21781
21706
  }
@@ -21804,7 +21729,7 @@ function decode(source, options) {
21804
21729
  yield* maybeYield();
21805
21730
  }
21806
21731
  if (buffer.byteLength > 0) {
21807
- throw errCode$1(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF');
21732
+ throw new UnexpectedEOFError('Unexpected end of input');
21808
21733
  }
21809
21734
  })();
21810
21735
  }
@@ -21814,7 +21739,7 @@ function decode(source, options) {
21814
21739
  yield* maybeYield();
21815
21740
  }
21816
21741
  if (buffer.byteLength > 0) {
21817
- throw errCode$1(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF');
21742
+ throw new UnexpectedEOFError('Unexpected end of input');
21818
21743
  }
21819
21744
  })();
21820
21745
  }
@@ -22649,7 +22574,7 @@ var FilterRequest;
22649
22574
  }
22650
22575
  case 3: {
22651
22576
  if (opts.limits?.contentFilters != null && obj.contentFilters.length === opts.limits.contentFilters) {
22652
- throw new CodeError('decode error - map field "contentFilters" had too many elements', 'ERR_MAX_LENGTH');
22577
+ throw new MaxLengthError('Decode error - map field "contentFilters" had too many elements');
22653
22578
  }
22654
22579
  obj.contentFilters.push(FilterRequest.ContentFilter.codec().decode(reader, reader.uint32(), {
22655
22580
  limits: opts.limits?.contentFilters$
@@ -22702,7 +22627,7 @@ var MessagePush$1;
22702
22627
  switch (tag >>> 3) {
22703
22628
  case 1: {
22704
22629
  if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {
22705
- throw new CodeError('decode error - map field "messages" had too many elements', 'ERR_MAX_LENGTH');
22630
+ throw new MaxLengthError('Decode error - map field "messages" had too many elements');
22706
22631
  }
22707
22632
  obj.messages.push(WakuMessage$3.codec().decode(reader, reader.uint32(), {
22708
22633
  limits: opts.limits?.messages$
@@ -23121,7 +23046,7 @@ var FilterSubscribeRequest;
23121
23046
  }
23122
23047
  case 11: {
23123
23048
  if (opts.limits?.contentTopics != null && obj.contentTopics.length === opts.limits.contentTopics) {
23124
- throw new CodeError('decode error - map field "contentTopics" had too many elements', 'ERR_MAX_LENGTH');
23049
+ throw new MaxLengthError('Decode error - map field "contentTopics" had too many elements');
23125
23050
  }
23126
23051
  obj.contentTopics.push(reader.string());
23127
23052
  break;
@@ -23843,113 +23768,26 @@ var WakuMessage$1;
23843
23768
  /* eslint-disable @typescript-eslint/no-namespace */
23844
23769
  /* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */
23845
23770
  /* eslint-disable @typescript-eslint/no-empty-interface */
23846
- var Index;
23847
- (function (Index) {
23771
+ var WakuMessageKeyValue;
23772
+ (function (WakuMessageKeyValue) {
23848
23773
  let _codec;
23849
- Index.codec = () => {
23774
+ WakuMessageKeyValue.codec = () => {
23850
23775
  if (_codec == null) {
23851
23776
  _codec = message((obj, w, opts = {}) => {
23852
23777
  if (opts.lengthDelimited !== false) {
23853
23778
  w.fork();
23854
23779
  }
23855
- if ((obj.digest != null && obj.digest.byteLength > 0)) {
23780
+ if (obj.messageHash != null) {
23856
23781
  w.uint32(10);
23857
- w.bytes(obj.digest);
23858
- }
23859
- if ((obj.receiverTime != null && obj.receiverTime !== 0n)) {
23860
- w.uint32(16);
23861
- w.sint64(obj.receiverTime);
23782
+ w.bytes(obj.messageHash);
23862
23783
  }
23863
- if ((obj.senderTime != null && obj.senderTime !== 0n)) {
23864
- w.uint32(24);
23865
- w.sint64(obj.senderTime);
23866
- }
23867
- if ((obj.pubsubTopic != null && obj.pubsubTopic !== '')) {
23868
- w.uint32(34);
23869
- w.string(obj.pubsubTopic);
23870
- }
23871
- if (opts.lengthDelimited !== false) {
23872
- w.ldelim();
23873
- }
23874
- }, (reader, length, opts = {}) => {
23875
- const obj = {
23876
- digest: alloc$2(0),
23877
- receiverTime: 0n,
23878
- senderTime: 0n,
23879
- pubsubTopic: ''
23880
- };
23881
- const end = length == null ? reader.len : reader.pos + length;
23882
- while (reader.pos < end) {
23883
- const tag = reader.uint32();
23884
- switch (tag >>> 3) {
23885
- case 1: {
23886
- obj.digest = reader.bytes();
23887
- break;
23888
- }
23889
- case 2: {
23890
- obj.receiverTime = reader.sint64();
23891
- break;
23892
- }
23893
- case 3: {
23894
- obj.senderTime = reader.sint64();
23895
- break;
23896
- }
23897
- case 4: {
23898
- obj.pubsubTopic = reader.string();
23899
- break;
23900
- }
23901
- default: {
23902
- reader.skipType(tag & 7);
23903
- break;
23904
- }
23905
- }
23906
- }
23907
- return obj;
23908
- });
23909
- }
23910
- return _codec;
23911
- };
23912
- Index.encode = (obj) => {
23913
- return encodeMessage(obj, Index.codec());
23914
- };
23915
- Index.decode = (buf, opts) => {
23916
- return decodeMessage(buf, Index.codec(), opts);
23917
- };
23918
- })(Index || (Index = {}));
23919
- var PagingInfo;
23920
- (function (PagingInfo) {
23921
- (function (Direction) {
23922
- Direction["BACKWARD"] = "BACKWARD";
23923
- Direction["FORWARD"] = "FORWARD";
23924
- })(PagingInfo.Direction || (PagingInfo.Direction = {}));
23925
- let __DirectionValues;
23926
- (function (__DirectionValues) {
23927
- __DirectionValues[__DirectionValues["BACKWARD"] = 0] = "BACKWARD";
23928
- __DirectionValues[__DirectionValues["FORWARD"] = 1] = "FORWARD";
23929
- })(__DirectionValues || (__DirectionValues = {}));
23930
- (function (Direction) {
23931
- Direction.codec = () => {
23932
- return enumeration(__DirectionValues);
23933
- };
23934
- })(PagingInfo.Direction || (PagingInfo.Direction = {}));
23935
- let _codec;
23936
- PagingInfo.codec = () => {
23937
- if (_codec == null) {
23938
- _codec = message((obj, w, opts = {}) => {
23939
- if (opts.lengthDelimited !== false) {
23940
- w.fork();
23941
- }
23942
- if (obj.pageSize != null) {
23943
- w.uint32(8);
23944
- w.uint64(obj.pageSize);
23945
- }
23946
- if (obj.cursor != null) {
23784
+ if (obj.message != null) {
23947
23785
  w.uint32(18);
23948
- Index.codec().encode(obj.cursor, w);
23786
+ WakuMessage.codec().encode(obj.message, w);
23949
23787
  }
23950
- if (obj.direction != null) {
23951
- w.uint32(24);
23952
- PagingInfo.Direction.codec().encode(obj.direction, w);
23788
+ if (obj.pubsubTopic != null) {
23789
+ w.uint32(26);
23790
+ w.string(obj.pubsubTopic);
23953
23791
  }
23954
23792
  if (opts.lengthDelimited !== false) {
23955
23793
  w.ldelim();
@@ -23961,17 +23799,17 @@ var PagingInfo;
23961
23799
  const tag = reader.uint32();
23962
23800
  switch (tag >>> 3) {
23963
23801
  case 1: {
23964
- obj.pageSize = reader.uint64();
23802
+ obj.messageHash = reader.bytes();
23965
23803
  break;
23966
23804
  }
23967
23805
  case 2: {
23968
- obj.cursor = Index.codec().decode(reader, reader.uint32(), {
23969
- limits: opts.limits?.cursor
23806
+ obj.message = WakuMessage.codec().decode(reader, reader.uint32(), {
23807
+ limits: opts.limits?.message
23970
23808
  });
23971
23809
  break;
23972
23810
  }
23973
23811
  case 3: {
23974
- obj.direction = PagingInfo.Direction.codec().decode(reader);
23812
+ obj.pubsubTopic = reader.string();
23975
23813
  break;
23976
23814
  }
23977
23815
  default: {
@@ -23985,217 +23823,125 @@ var PagingInfo;
23985
23823
  }
23986
23824
  return _codec;
23987
23825
  };
23988
- PagingInfo.encode = (obj) => {
23989
- return encodeMessage(obj, PagingInfo.codec());
23826
+ WakuMessageKeyValue.encode = (obj) => {
23827
+ return encodeMessage(obj, WakuMessageKeyValue.codec());
23990
23828
  };
23991
- PagingInfo.decode = (buf, opts) => {
23992
- return decodeMessage(buf, PagingInfo.codec(), opts);
23829
+ WakuMessageKeyValue.decode = (buf, opts) => {
23830
+ return decodeMessage(buf, WakuMessageKeyValue.codec(), opts);
23993
23831
  };
23994
- })(PagingInfo || (PagingInfo = {}));
23995
- var ContentFilter;
23996
- (function (ContentFilter) {
23832
+ })(WakuMessageKeyValue || (WakuMessageKeyValue = {}));
23833
+ var StoreQueryRequest;
23834
+ (function (StoreQueryRequest) {
23997
23835
  let _codec;
23998
- ContentFilter.codec = () => {
23836
+ StoreQueryRequest.codec = () => {
23999
23837
  if (_codec == null) {
24000
23838
  _codec = message((obj, w, opts = {}) => {
24001
23839
  if (opts.lengthDelimited !== false) {
24002
23840
  w.fork();
24003
23841
  }
24004
- if ((obj.contentTopic != null && obj.contentTopic !== '')) {
23842
+ if ((obj.requestId != null && obj.requestId !== '')) {
24005
23843
  w.uint32(10);
24006
- w.string(obj.contentTopic);
23844
+ w.string(obj.requestId);
24007
23845
  }
24008
- if (opts.lengthDelimited !== false) {
24009
- w.ldelim();
23846
+ if ((obj.includeData != null && obj.includeData !== false)) {
23847
+ w.uint32(16);
23848
+ w.bool(obj.includeData);
24010
23849
  }
24011
- }, (reader, length, opts = {}) => {
24012
- const obj = {
24013
- contentTopic: ''
24014
- };
24015
- const end = length == null ? reader.len : reader.pos + length;
24016
- while (reader.pos < end) {
24017
- const tag = reader.uint32();
24018
- switch (tag >>> 3) {
24019
- case 1: {
24020
- obj.contentTopic = reader.string();
24021
- break;
24022
- }
24023
- default: {
24024
- reader.skipType(tag & 7);
24025
- break;
24026
- }
23850
+ if (obj.pubsubTopic != null) {
23851
+ w.uint32(82);
23852
+ w.string(obj.pubsubTopic);
23853
+ }
23854
+ if (obj.contentTopics != null) {
23855
+ for (const value of obj.contentTopics) {
23856
+ w.uint32(90);
23857
+ w.string(value);
24027
23858
  }
24028
23859
  }
24029
- return obj;
24030
- });
24031
- }
24032
- return _codec;
24033
- };
24034
- ContentFilter.encode = (obj) => {
24035
- return encodeMessage(obj, ContentFilter.codec());
24036
- };
24037
- ContentFilter.decode = (buf, opts) => {
24038
- return decodeMessage(buf, ContentFilter.codec(), opts);
24039
- };
24040
- })(ContentFilter || (ContentFilter = {}));
24041
- var HistoryQuery;
24042
- (function (HistoryQuery) {
24043
- let _codec;
24044
- HistoryQuery.codec = () => {
24045
- if (_codec == null) {
24046
- _codec = message((obj, w, opts = {}) => {
24047
- if (opts.lengthDelimited !== false) {
24048
- w.fork();
23860
+ if (obj.timeStart != null) {
23861
+ w.uint32(96);
23862
+ w.sint64(obj.timeStart);
24049
23863
  }
24050
- if (obj.pubsubTopic != null) {
24051
- w.uint32(18);
24052
- w.string(obj.pubsubTopic);
23864
+ if (obj.timeEnd != null) {
23865
+ w.uint32(104);
23866
+ w.sint64(obj.timeEnd);
24053
23867
  }
24054
- if (obj.contentFilters != null) {
24055
- for (const value of obj.contentFilters) {
24056
- w.uint32(26);
24057
- ContentFilter.codec().encode(value, w);
23868
+ if (obj.messageHashes != null) {
23869
+ for (const value of obj.messageHashes) {
23870
+ w.uint32(162);
23871
+ w.bytes(value);
24058
23872
  }
24059
23873
  }
24060
- if (obj.pagingInfo != null) {
24061
- w.uint32(34);
24062
- PagingInfo.codec().encode(obj.pagingInfo, w);
23874
+ if (obj.paginationCursor != null) {
23875
+ w.uint32(410);
23876
+ w.bytes(obj.paginationCursor);
24063
23877
  }
24064
- if (obj.startTime != null) {
24065
- w.uint32(40);
24066
- w.sint64(obj.startTime);
23878
+ if ((obj.paginationForward != null && obj.paginationForward !== false)) {
23879
+ w.uint32(416);
23880
+ w.bool(obj.paginationForward);
24067
23881
  }
24068
- if (obj.endTime != null) {
24069
- w.uint32(48);
24070
- w.sint64(obj.endTime);
23882
+ if (obj.paginationLimit != null) {
23883
+ w.uint32(424);
23884
+ w.uint64(obj.paginationLimit);
24071
23885
  }
24072
23886
  if (opts.lengthDelimited !== false) {
24073
23887
  w.ldelim();
24074
23888
  }
24075
23889
  }, (reader, length, opts = {}) => {
24076
23890
  const obj = {
24077
- contentFilters: []
23891
+ requestId: '',
23892
+ includeData: false,
23893
+ contentTopics: [],
23894
+ messageHashes: [],
23895
+ paginationForward: false
24078
23896
  };
24079
23897
  const end = length == null ? reader.len : reader.pos + length;
24080
23898
  while (reader.pos < end) {
24081
23899
  const tag = reader.uint32();
24082
23900
  switch (tag >>> 3) {
24083
- case 2: {
24084
- obj.pubsubTopic = reader.string();
23901
+ case 1: {
23902
+ obj.requestId = reader.string();
24085
23903
  break;
24086
23904
  }
24087
- case 3: {
24088
- if (opts.limits?.contentFilters != null && obj.contentFilters.length === opts.limits.contentFilters) {
24089
- throw new CodeError('decode error - map field "contentFilters" had too many elements', 'ERR_MAX_LENGTH');
24090
- }
24091
- obj.contentFilters.push(ContentFilter.codec().decode(reader, reader.uint32(), {
24092
- limits: opts.limits?.contentFilters$
24093
- }));
23905
+ case 2: {
23906
+ obj.includeData = reader.bool();
24094
23907
  break;
24095
23908
  }
24096
- case 4: {
24097
- obj.pagingInfo = PagingInfo.codec().decode(reader, reader.uint32(), {
24098
- limits: opts.limits?.pagingInfo
24099
- });
23909
+ case 10: {
23910
+ obj.pubsubTopic = reader.string();
24100
23911
  break;
24101
23912
  }
24102
- case 5: {
24103
- obj.startTime = reader.sint64();
23913
+ case 11: {
23914
+ if (opts.limits?.contentTopics != null && obj.contentTopics.length === opts.limits.contentTopics) {
23915
+ throw new MaxLengthError('Decode error - map field "contentTopics" had too many elements');
23916
+ }
23917
+ obj.contentTopics.push(reader.string());
24104
23918
  break;
24105
23919
  }
24106
- case 6: {
24107
- obj.endTime = reader.sint64();
23920
+ case 12: {
23921
+ obj.timeStart = reader.sint64();
24108
23922
  break;
24109
23923
  }
24110
- default: {
24111
- reader.skipType(tag & 7);
23924
+ case 13: {
23925
+ obj.timeEnd = reader.sint64();
24112
23926
  break;
24113
23927
  }
24114
- }
24115
- }
24116
- return obj;
24117
- });
24118
- }
24119
- return _codec;
24120
- };
24121
- HistoryQuery.encode = (obj) => {
24122
- return encodeMessage(obj, HistoryQuery.codec());
24123
- };
24124
- HistoryQuery.decode = (buf, opts) => {
24125
- return decodeMessage(buf, HistoryQuery.codec(), opts);
24126
- };
24127
- })(HistoryQuery || (HistoryQuery = {}));
24128
- var HistoryResponse;
24129
- (function (HistoryResponse) {
24130
- let HistoryError;
24131
- (function (HistoryError) {
24132
- HistoryError["NONE"] = "NONE";
24133
- HistoryError["INVALID_CURSOR"] = "INVALID_CURSOR";
24134
- HistoryError["TOO_MANY_REQUESTS"] = "TOO_MANY_REQUESTS";
24135
- HistoryError["SERVICE_UNAVAILABLE"] = "SERVICE_UNAVAILABLE";
24136
- })(HistoryError = HistoryResponse.HistoryError || (HistoryResponse.HistoryError = {}));
24137
- let __HistoryErrorValues;
24138
- (function (__HistoryErrorValues) {
24139
- __HistoryErrorValues[__HistoryErrorValues["NONE"] = 0] = "NONE";
24140
- __HistoryErrorValues[__HistoryErrorValues["INVALID_CURSOR"] = 1] = "INVALID_CURSOR";
24141
- __HistoryErrorValues[__HistoryErrorValues["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
24142
- __HistoryErrorValues[__HistoryErrorValues["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
24143
- })(__HistoryErrorValues || (__HistoryErrorValues = {}));
24144
- (function (HistoryError) {
24145
- HistoryError.codec = () => {
24146
- return enumeration(__HistoryErrorValues);
24147
- };
24148
- })(HistoryError = HistoryResponse.HistoryError || (HistoryResponse.HistoryError = {}));
24149
- let _codec;
24150
- HistoryResponse.codec = () => {
24151
- if (_codec == null) {
24152
- _codec = message((obj, w, opts = {}) => {
24153
- if (opts.lengthDelimited !== false) {
24154
- w.fork();
24155
- }
24156
- if (obj.messages != null) {
24157
- for (const value of obj.messages) {
24158
- w.uint32(18);
24159
- WakuMessage.codec().encode(value, w);
24160
- }
24161
- }
24162
- if (obj.pagingInfo != null) {
24163
- w.uint32(26);
24164
- PagingInfo.codec().encode(obj.pagingInfo, w);
24165
- }
24166
- if (obj.error != null && __HistoryErrorValues[obj.error] !== 0) {
24167
- w.uint32(32);
24168
- HistoryResponse.HistoryError.codec().encode(obj.error, w);
24169
- }
24170
- if (opts.lengthDelimited !== false) {
24171
- w.ldelim();
24172
- }
24173
- }, (reader, length, opts = {}) => {
24174
- const obj = {
24175
- messages: [],
24176
- error: HistoryError.NONE
24177
- };
24178
- const end = length == null ? reader.len : reader.pos + length;
24179
- while (reader.pos < end) {
24180
- const tag = reader.uint32();
24181
- switch (tag >>> 3) {
24182
- case 2: {
24183
- if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {
24184
- throw new CodeError('decode error - map field "messages" had too many elements', 'ERR_MAX_LENGTH');
23928
+ case 20: {
23929
+ if (opts.limits?.messageHashes != null && obj.messageHashes.length === opts.limits.messageHashes) {
23930
+ throw new MaxLengthError('Decode error - map field "messageHashes" had too many elements');
24185
23931
  }
24186
- obj.messages.push(WakuMessage.codec().decode(reader, reader.uint32(), {
24187
- limits: opts.limits?.messages$
24188
- }));
23932
+ obj.messageHashes.push(reader.bytes());
24189
23933
  break;
24190
23934
  }
24191
- case 3: {
24192
- obj.pagingInfo = PagingInfo.codec().decode(reader, reader.uint32(), {
24193
- limits: opts.limits?.pagingInfo
24194
- });
23935
+ case 51: {
23936
+ obj.paginationCursor = reader.bytes();
24195
23937
  break;
24196
23938
  }
24197
- case 4: {
24198
- obj.error = HistoryResponse.HistoryError.codec().decode(reader);
23939
+ case 52: {
23940
+ obj.paginationForward = reader.bool();
23941
+ break;
23942
+ }
23943
+ case 53: {
23944
+ obj.paginationLimit = reader.uint64();
24199
23945
  break;
24200
23946
  }
24201
23947
  default: {
@@ -24209,17 +23955,17 @@ var HistoryResponse;
24209
23955
  }
24210
23956
  return _codec;
24211
23957
  };
24212
- HistoryResponse.encode = (obj) => {
24213
- return encodeMessage(obj, HistoryResponse.codec());
23958
+ StoreQueryRequest.encode = (obj) => {
23959
+ return encodeMessage(obj, StoreQueryRequest.codec());
24214
23960
  };
24215
- HistoryResponse.decode = (buf, opts) => {
24216
- return decodeMessage(buf, HistoryResponse.codec(), opts);
23961
+ StoreQueryRequest.decode = (buf, opts) => {
23962
+ return decodeMessage(buf, StoreQueryRequest.codec(), opts);
24217
23963
  };
24218
- })(HistoryResponse || (HistoryResponse = {}));
24219
- var HistoryRpc;
24220
- (function (HistoryRpc) {
23964
+ })(StoreQueryRequest || (StoreQueryRequest = {}));
23965
+ var StoreQueryResponse;
23966
+ (function (StoreQueryResponse) {
24221
23967
  let _codec;
24222
- HistoryRpc.codec = () => {
23968
+ StoreQueryResponse.codec = () => {
24223
23969
  if (_codec == null) {
24224
23970
  _codec = message((obj, w, opts = {}) => {
24225
23971
  if (opts.lengthDelimited !== false) {
@@ -24229,20 +23975,31 @@ var HistoryRpc;
24229
23975
  w.uint32(10);
24230
23976
  w.string(obj.requestId);
24231
23977
  }
24232
- if (obj.query != null) {
24233
- w.uint32(18);
24234
- HistoryQuery.codec().encode(obj.query, w);
23978
+ if (obj.statusCode != null) {
23979
+ w.uint32(80);
23980
+ w.uint32(obj.statusCode);
24235
23981
  }
24236
- if (obj.response != null) {
24237
- w.uint32(26);
24238
- HistoryResponse.codec().encode(obj.response, w);
23982
+ if (obj.statusDesc != null) {
23983
+ w.uint32(90);
23984
+ w.string(obj.statusDesc);
23985
+ }
23986
+ if (obj.messages != null) {
23987
+ for (const value of obj.messages) {
23988
+ w.uint32(162);
23989
+ WakuMessageKeyValue.codec().encode(value, w);
23990
+ }
23991
+ }
23992
+ if (obj.paginationCursor != null) {
23993
+ w.uint32(410);
23994
+ w.bytes(obj.paginationCursor);
24239
23995
  }
24240
23996
  if (opts.lengthDelimited !== false) {
24241
23997
  w.ldelim();
24242
23998
  }
24243
23999
  }, (reader, length, opts = {}) => {
24244
24000
  const obj = {
24245
- requestId: ''
24001
+ requestId: '',
24002
+ messages: []
24246
24003
  };
24247
24004
  const end = length == null ? reader.len : reader.pos + length;
24248
24005
  while (reader.pos < end) {
@@ -24252,16 +24009,25 @@ var HistoryRpc;
24252
24009
  obj.requestId = reader.string();
24253
24010
  break;
24254
24011
  }
24255
- case 2: {
24256
- obj.query = HistoryQuery.codec().decode(reader, reader.uint32(), {
24257
- limits: opts.limits?.query
24258
- });
24012
+ case 10: {
24013
+ obj.statusCode = reader.uint32();
24259
24014
  break;
24260
24015
  }
24261
- case 3: {
24262
- obj.response = HistoryResponse.codec().decode(reader, reader.uint32(), {
24263
- limits: opts.limits?.response
24264
- });
24016
+ case 11: {
24017
+ obj.statusDesc = reader.string();
24018
+ break;
24019
+ }
24020
+ case 20: {
24021
+ if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {
24022
+ throw new MaxLengthError('Decode error - map field "messages" had too many elements');
24023
+ }
24024
+ obj.messages.push(WakuMessageKeyValue.codec().decode(reader, reader.uint32(), {
24025
+ limits: opts.limits?.messages$
24026
+ }));
24027
+ break;
24028
+ }
24029
+ case 51: {
24030
+ obj.paginationCursor = reader.bytes();
24265
24031
  break;
24266
24032
  }
24267
24033
  default: {
@@ -24275,13 +24041,13 @@ var HistoryRpc;
24275
24041
  }
24276
24042
  return _codec;
24277
24043
  };
24278
- HistoryRpc.encode = (obj) => {
24279
- return encodeMessage(obj, HistoryRpc.codec());
24044
+ StoreQueryResponse.encode = (obj) => {
24045
+ return encodeMessage(obj, StoreQueryResponse.codec());
24280
24046
  };
24281
- HistoryRpc.decode = (buf, opts) => {
24282
- return decodeMessage(buf, HistoryRpc.codec(), opts);
24047
+ StoreQueryResponse.decode = (buf, opts) => {
24048
+ return decodeMessage(buf, StoreQueryResponse.codec(), opts);
24283
24049
  };
24284
- })(HistoryRpc || (HistoryRpc = {}));
24050
+ })(StoreQueryResponse || (StoreQueryResponse = {}));
24285
24051
  var RateLimitProof;
24286
24052
  (function (RateLimitProof) {
24287
24053
  let _codec;
@@ -24601,7 +24367,7 @@ var PeerExchangeResponse;
24601
24367
  switch (tag >>> 3) {
24602
24368
  case 1: {
24603
24369
  if (opts.limits?.peerInfos != null && obj.peerInfos.length === opts.limits.peerInfos) {
24604
- throw new CodeError('decode error - map field "peerInfos" had too many elements', 'ERR_MAX_LENGTH');
24370
+ throw new MaxLengthError('Decode error - map field "peerInfos" had too many elements');
24605
24371
  }
24606
24372
  obj.peerInfos.push(PeerInfo.codec().decode(reader, reader.uint32(), {
24607
24373
  limits: opts.limits?.peerInfos$
@@ -24724,7 +24490,7 @@ var WakuMetadataRequest;
24724
24490
  }
24725
24491
  case 2: {
24726
24492
  if (opts.limits?.shards != null && obj.shards.length === opts.limits.shards) {
24727
- throw new CodeError('decode error - map field "shards" had too many elements', 'ERR_MAX_LENGTH');
24493
+ throw new MaxLengthError('Decode error - map field "shards" had too many elements');
24728
24494
  }
24729
24495
  obj.shards.push(reader.uint32());
24730
24496
  break;
@@ -24783,7 +24549,7 @@ var WakuMetadataResponse;
24783
24549
  }
24784
24550
  case 2: {
24785
24551
  if (opts.limits?.shards != null && obj.shards.length === opts.limits.shards) {
24786
- throw new CodeError('decode error - map field "shards" had too many elements', 'ERR_MAX_LENGTH');
24552
+ throw new MaxLengthError('Decode error - map field "shards" had too many elements');
24787
24553
  }
24788
24554
  obj.shards.push(reader.uint32());
24789
24555
  break;
@@ -24863,11 +24629,11 @@ class WakuPeerExchange extends BaseProtocol {
24863
24629
  * Make a peer exchange query to a peer
24864
24630
  */
24865
24631
  async query(params) {
24866
- const { numPeers } = params;
24632
+ const { numPeers, peerId } = params;
24867
24633
  const rpcQuery = PeerExchangeRPC.createRequest({
24868
24634
  numPeers: BigInt(numPeers)
24869
24635
  });
24870
- const peer = await this.peerStore.get(params.peerId);
24636
+ const peer = await this.peerStore.get(peerId);
24871
24637
  if (!peer) {
24872
24638
  return {
24873
24639
  peerInfos: null,
@@ -24963,6 +24729,7 @@ class PeerExchangeDiscovery extends TypedEventEmitter {
24963
24729
  if (this.isStarted) {
24964
24730
  return;
24965
24731
  }
24732
+ this.dispatchEvent(new CustomEvent("waku:peer-exchange:started", { detail: true }));
24966
24733
  log$1.info("Starting peer exchange node discovery, discovering peers");
24967
24734
  // might be better to use "peer:identify" or "peer:update"
24968
24735
  this.components.events.addEventListener("peer:identify", this.handleDiscoveredPeer);
@@ -25022,7 +24789,31 @@ class PeerExchangeDiscovery extends TypedEventEmitter {
25022
24789
  }
25023
24790
  const hasPeer = await this.components.peerStore.has(peerId);
25024
24791
  if (hasPeer) {
25025
- continue;
24792
+ const { hasMultiaddrDiff, hasShardDiff } = await this.checkPeerInfoDiff(peerInfo, shardInfo);
24793
+ if (hasMultiaddrDiff || hasShardDiff) {
24794
+ log$1.info(`Peer ${peerId.toString()} has updated multiaddrs or shardInfo, updating`);
24795
+ if (hasMultiaddrDiff) {
24796
+ log$1.info(`Peer ${peerId.toString()} has updated multiaddrs, updating`);
24797
+ await this.components.peerStore.patch(peerId, {
24798
+ multiaddrs: peerInfo.multiaddrs
24799
+ });
24800
+ }
24801
+ if (hasShardDiff && shardInfo) {
24802
+ log$1.info(`Peer ${peerId.toString()} has updated shardInfo, updating`);
24803
+ await this.components.peerStore.merge(peerId, {
24804
+ metadata: {
24805
+ shardInfo: encodeRelayShard(shardInfo)
24806
+ }
24807
+ });
24808
+ this.dispatchEvent(new CustomEvent("peer", {
24809
+ detail: {
24810
+ id: peerId,
24811
+ multiaddrs: peerInfo.multiaddrs
24812
+ }
24813
+ }));
24814
+ }
24815
+ continue;
24816
+ }
25026
24817
  }
25027
24818
  // update the tags for the peer
25028
24819
  await this.components.peerStore.save(peerId, {
@@ -25036,6 +24827,9 @@ class PeerExchangeDiscovery extends TypedEventEmitter {
25036
24827
  metadata: {
25037
24828
  shardInfo: encodeRelayShard(shardInfo)
25038
24829
  }
24830
+ }),
24831
+ ...(peerInfo.multiaddrs && {
24832
+ multiaddrs: peerInfo.multiaddrs
25039
24833
  })
25040
24834
  });
25041
24835
  log$1.info(`Discovered peer: ${peerId.toString()}`);
@@ -25053,6 +24847,24 @@ class PeerExchangeDiscovery extends TypedEventEmitter {
25053
24847
  this.queryingPeers.delete(peerIdStr);
25054
24848
  this.queryAttempts.delete(peerIdStr);
25055
24849
  }
24850
+ async checkPeerInfoDiff(peerInfo, shardInfo) {
24851
+ const { id: peerId } = peerInfo;
24852
+ const peer = await this.components.peerStore.get(peerId);
24853
+ const existingMultiaddrs = peer.addresses.map((a) => a.multiaddr.toString());
24854
+ const newMultiaddrs = peerInfo.multiaddrs.map((ma) => ma.toString());
24855
+ const hasMultiaddrDiff = existingMultiaddrs.some((ma) => !newMultiaddrs.includes(ma));
24856
+ let hasShardDiff = false;
24857
+ const existingShardInfoBytes = peer.metadata.get("shardInfo");
24858
+ if (existingShardInfoBytes) {
24859
+ const existingShardInfo = decodeRelayShard(existingShardInfoBytes);
24860
+ if (existingShardInfo || shardInfo) {
24861
+ hasShardDiff =
24862
+ existingShardInfo.clusterId !== shardInfo?.clusterId ||
24863
+ existingShardInfo.shards.some((shard) => !shardInfo?.shards.includes(shard));
24864
+ }
24865
+ }
24866
+ return { hasMultiaddrDiff, hasShardDiff };
24867
+ }
25056
24868
  }
25057
24869
  function wakuPeerExchangeDiscovery(pubsubTopics) {
25058
24870
  return (components) => new PeerExchangeDiscovery(components, pubsubTopics);
@@ -25098,7 +24910,13 @@ async function createFromParts(multihash, privKey, pubKey) {
25098
24910
  const key = unmarshalPublicKey(pubKey);
25099
24911
  return createFromPubKey(key);
25100
24912
  }
25101
- return peerIdFromBytes(multihash);
24913
+ const peerId = peerIdFromBytes(multihash);
24914
+ if (peerId.type !== 'Ed25519' && peerId.type !== 'secp256k1' && peerId.type !== 'RSA') {
24915
+ // should not be possible since `multihash` is derived from keys and these
24916
+ // are the cryptographic peer id types
24917
+ throw new Error('Supplied PeerID is invalid');
24918
+ }
24919
+ return peerId;
25102
24920
  }
25103
24921
 
25104
24922
  const log = new Logger$1("peer-exchange-discovery");