@waku/core 0.0.26-678635e.0 → 0.0.26

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/bundle/base_protocol-pDODy0G6.js +260 -0
  3. package/bundle/{base_protocol-4bcf7514.js → browser-mTOOnVZp.js} +751 -381
  4. package/bundle/index-cmONXM-V.js +595 -0
  5. package/bundle/index.js +637 -1879
  6. package/bundle/lib/base_protocol.js +3 -3
  7. package/bundle/lib/message/version_0.js +3 -3
  8. package/bundle/lib/predefined_bootstrap_nodes.js +1 -1
  9. package/bundle/{version_0-2f1176e3.js → version_0-LQTFNC7k.js} +118 -11
  10. package/dist/.tsbuildinfo +1 -1
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.js +2 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/lib/base_protocol.d.ts +3 -2
  15. package/dist/lib/base_protocol.js +12 -6
  16. package/dist/lib/base_protocol.js.map +1 -1
  17. package/dist/lib/connection_manager.d.ts +8 -4
  18. package/dist/lib/connection_manager.js +34 -12
  19. package/dist/lib/connection_manager.js.map +1 -1
  20. package/dist/lib/filter/index.js +8 -5
  21. package/dist/lib/filter/index.js.map +1 -1
  22. package/dist/lib/filterPeers.js.map +1 -1
  23. package/dist/lib/keep_alive_manager.d.ts +1 -0
  24. package/dist/lib/keep_alive_manager.js +6 -3
  25. package/dist/lib/keep_alive_manager.js.map +1 -1
  26. package/dist/lib/light_push/index.js +1 -2
  27. package/dist/lib/light_push/index.js.map +1 -1
  28. package/dist/lib/message/version_0.d.ts +7 -7
  29. package/dist/lib/message/version_0.js +5 -6
  30. package/dist/lib/message/version_0.js.map +1 -1
  31. package/dist/lib/metadata/index.d.ts +3 -0
  32. package/dist/lib/metadata/index.js +67 -0
  33. package/dist/lib/metadata/index.js.map +1 -0
  34. package/dist/lib/predefined_bootstrap_nodes.js.map +1 -1
  35. package/dist/lib/store/history_rpc.js.map +1 -1
  36. package/dist/lib/store/index.js +10 -11
  37. package/dist/lib/store/index.js.map +1 -1
  38. package/dist/lib/stream_manager.js.map +1 -1
  39. package/dist/lib/wait_for_remote_peer.js.map +1 -1
  40. package/dist/lib/waku.d.ts +4 -3
  41. package/dist/lib/waku.js +15 -6
  42. package/dist/lib/waku.js.map +1 -1
  43. package/package.json +127 -1
  44. package/src/index.ts +3 -1
  45. package/src/lib/base_protocol.ts +29 -7
  46. package/src/lib/connection_manager.ts +44 -13
  47. package/src/lib/filter/index.ts +18 -11
  48. package/src/lib/keep_alive_manager.ts +9 -3
  49. package/src/lib/light_push/index.ts +3 -4
  50. package/src/lib/message/version_0.ts +18 -10
  51. package/src/lib/metadata/index.ts +110 -0
  52. package/src/lib/store/index.ts +12 -13
  53. package/src/lib/waku.ts +19 -5
  54. package/bundle/browser-90197c87.js +0 -754
  55. package/bundle/index-27b91e3b.js +0 -31
  56. package/dist/lib/constants.d.ts +0 -4
  57. package/dist/lib/constants.js +0 -5
  58. package/dist/lib/constants.js.map +0 -1
  59. package/src/lib/constants.ts +0 -4
package/bundle/index.js CHANGED
@@ -1,15 +1,54 @@
1
- import { c as coerce$1, e as equals$2, b as base32, a as base58btc, d as allocUnsafe, f as asUint8Array, t as toString$1, g as bases, h as fromString, u as utf8ToBytes$1, T as Tags, E as EPeersByDiscoveryEvents, P as Protocols, i as alloc, B as BaseProtocol, S as SendError, j as concat$1 } from './base_protocol-4bcf7514.js';
2
- export { k as StreamManager } from './base_protocol-4bcf7514.js';
3
- import { L as Logger } from './index-27b91e3b.js';
4
- import { c as commonjsGlobal, g as getAugmentedNamespace, a as getDefaultExportFromCjs } from './browser-90197c87.js';
5
- import { e as enumeration, m as message, a as encodeMessage, d as decodeMessage, c as createEncoder, v as version_0, M as MessagePush, F as FilterSubscribeRequest, b as FilterSubscribeResponse$1, D as DefaultPubSubTopic, P as PushRpc$1, f as PushResponse, H as HistoryRpc$1, g as PagingInfo, h as HistoryResponse } from './version_0-2f1176e3.js';
6
- export { i as createDecoder } from './version_0-2f1176e3.js';
1
+ import { c as coerce, e as equals$2, b as base32, a as base58btc, d as commonjsGlobal, g as getAugmentedNamespace, E as EConnectionStateEvents, T as Tags, f as EPeersByDiscoveryEvents, P as Protocols, h as getDefaultExportFromCjs, S as SendError } from './browser-mTOOnVZp.js';
2
+ import { a as allocUnsafe, b as asUint8Array, t as toString$1, c as bases, f as fromString, L as Logger, u as utf8ToBytes, p as pubsubTopicToSingleShardInfo, s as shardInfoToPubsubTopics, D as DefaultPubsubTopic, d as alloc, e as singleShardInfoToPubsubTopic, g as ensurePubsubTopicIsConfigured, h as sha256$1, i as concat$1 } from './index-cmONXM-V.js';
3
+ import { e as enumeration, m as message, a as encodeMessage, d as decodeMessage, c as createEncoder, v as version_0, M as MessagePush, F as FilterSubscribeRequest, b as FilterSubscribeResponse$1, P as PushRpc$1, f as PushResponse, H as HistoryRpc$1, g as PagingInfo, h as HistoryResponse, W as WakuMetadataResponse, i as WakuMetadataRequest } from './version_0-LQTFNC7k.js';
4
+ export { j as createDecoder } from './version_0-LQTFNC7k.js';
5
+ import { B as BaseProtocol } from './base_protocol-pDODy0G6.js';
6
+ export { S as StreamManager } from './base_protocol-pDODy0G6.js';
7
7
 
8
8
  const symbol$2 = Symbol.for('@libp2p/peer-id');
9
9
  function isPeerId(other) {
10
10
  return other != null && Boolean(other[symbol$2]);
11
11
  }
12
12
 
13
+ /**
14
+ * On the producing side:
15
+ * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.
16
+ *
17
+ * On the consuming side:
18
+ * * Enforce the fields to be present, reject otherwise.
19
+ * * Propagate only if the fields are valid and signature can be verified, reject otherwise.
20
+ */
21
+ var TopicValidatorResult$1;
22
+ (function (TopicValidatorResult) {
23
+ /**
24
+ * The message is considered valid, and it should be delivered and forwarded to the network
25
+ */
26
+ TopicValidatorResult["Accept"] = "accept";
27
+ /**
28
+ * The message is neither delivered nor forwarded to the network
29
+ */
30
+ TopicValidatorResult["Ignore"] = "ignore";
31
+ /**
32
+ * The message is considered invalid, and it should be rejected
33
+ */
34
+ TopicValidatorResult["Reject"] = "reject";
35
+ })(TopicValidatorResult$1 || (TopicValidatorResult$1 = {}));
36
+
37
+ /**
38
+ * Enum Transport Manager Fault Tolerance values
39
+ */
40
+ var FaultTolerance$1;
41
+ (function (FaultTolerance) {
42
+ /**
43
+ * should be used for failing in any listen circumstance
44
+ */
45
+ FaultTolerance[FaultTolerance["FATAL_ALL"] = 0] = "FATAL_ALL";
46
+ /**
47
+ * should be used for not failing when not listening
48
+ */
49
+ FaultTolerance[FaultTolerance["NO_FATAL"] = 1] = "NO_FATAL";
50
+ })(FaultTolerance$1 || (FaultTolerance$1 = {}));
51
+
13
52
  /**
14
53
  * When this error is thrown it means an operation was aborted,
15
54
  * usually in response to the `abort` event being emitted by an
@@ -26,14 +65,14 @@ class CodeError extends Error {
26
65
  }
27
66
  }
28
67
 
29
- var encode_1 = encode$3;
68
+ var encode_1 = encode$2;
30
69
 
31
70
  var MSB$1 = 0x80
32
71
  , REST$1 = 0x7F
33
72
  , MSBALL = ~REST$1
34
73
  , INT = Math.pow(2, 31);
35
74
 
36
- function encode$3(num, out, offset) {
75
+ function encode$2(num, out, offset) {
37
76
  out = out || [];
38
77
  offset = offset || 0;
39
78
  var oldOffset = offset;
@@ -48,12 +87,12 @@ function encode$3(num, out, offset) {
48
87
  }
49
88
  out[offset] = num | 0;
50
89
 
51
- encode$3.bytes = offset - oldOffset + 1;
90
+ encode$2.bytes = offset - oldOffset + 1;
52
91
 
53
92
  return out
54
93
  }
55
94
 
56
- var decode$5 = read;
95
+ var decode$4 = read;
57
96
 
58
97
  var MSB$1$1 = 0x80
59
98
  , REST$1$1 = 0x7F;
@@ -110,7 +149,7 @@ var length = function (value) {
110
149
 
111
150
  var varint = {
112
151
  encode: encode_1
113
- , decode: decode$5
152
+ , decode: decode$4
114
153
  , encodingLength: length
115
154
  };
116
155
 
@@ -121,7 +160,7 @@ var _brrp_varint = varint;
121
160
  * @param {number} [offset=0]
122
161
  * @returns {[number, number]}
123
162
  */
124
- const decode$4 = (data, offset = 0) => {
163
+ const decode$3 = (data, offset = 0) => {
125
164
  const code = _brrp_varint.decode(data, offset);
126
165
  return [code, _brrp_varint.decode.bytes]
127
166
  };
@@ -170,10 +209,10 @@ const create = (code, digest) => {
170
209
  * @param {Uint8Array} multihash
171
210
  * @returns {MultihashDigest}
172
211
  */
173
- const decode$3 = (multihash) => {
174
- const bytes = coerce$1(multihash);
175
- const [code, sizeOffset] = decode$4(bytes);
176
- const [size, digestOffset] = decode$4(bytes.subarray(sizeOffset));
212
+ const decode$2 = (multihash) => {
213
+ const bytes = coerce(multihash);
214
+ const [code, sizeOffset] = decode$3(bytes);
215
+ const [size, digestOffset] = decode$3(bytes.subarray(sizeOffset));
177
216
  const digest = bytes.subarray(sizeOffset + digestOffset);
178
217
 
179
218
  if (digest.byteLength !== size) {
@@ -489,7 +528,7 @@ class CID {
489
528
  const { version, multihash, code } = value;
490
529
  const digest =
491
530
  /** @type {API.MultihashDigest<Alg>} */
492
- (decode$3(multihash));
531
+ (decode$2(multihash));
493
532
  return CID.create(version, code, digest)
494
533
  } else {
495
534
  // Otherwise value is not a CID (or an incompatible version of it) in
@@ -604,7 +643,7 @@ class CID {
604
643
  static decodeFirst (bytes) {
605
644
  const specs = CID.inspectBytes(bytes);
606
645
  const prefixSize = specs.size - specs.multihashSize;
607
- const multihashBytes = coerce$1(
646
+ const multihashBytes = coerce(
608
647
  bytes.subarray(prefixSize, prefixSize + specs.multihashSize)
609
648
  );
610
649
  if (multihashBytes.byteLength !== specs.multihashSize) {
@@ -645,7 +684,7 @@ class CID {
645
684
  static inspectBytes (initialBytes) {
646
685
  let offset = 0;
647
686
  const next = () => {
648
- const [i, length] = decode$4(initialBytes.subarray(offset));
687
+ const [i, length] = decode$3(initialBytes.subarray(offset));
649
688
  offset += length;
650
689
  return i
651
690
  };
@@ -1027,7 +1066,7 @@ function decodeUint8ArrayList(buf, offset) {
1027
1066
  }
1028
1067
  throw new RangeError('Could not decode varint');
1029
1068
  }
1030
- function encode$2(value, buf, offset = 0) {
1069
+ function encode$1(value, buf, offset = 0) {
1031
1070
  if (buf == null) {
1032
1071
  buf = allocUnsafe(encodingLength(value));
1033
1072
  }
@@ -1038,7 +1077,7 @@ function encode$2(value, buf, offset = 0) {
1038
1077
  return encodeUint8ArrayList(value, buf, offset);
1039
1078
  }
1040
1079
  }
1041
- function decode$2(buf, offset = 0) {
1080
+ function decode$1(buf, offset = 0) {
1042
1081
  if (buf instanceof Uint8Array) {
1043
1082
  return decodeUint8Array(buf, offset);
1044
1083
  }
@@ -1315,7 +1354,7 @@ const isV4 = isIPv4;
1315
1354
  const isV6 = isIPv6;
1316
1355
  // Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7
1317
1356
  // but with buf/offset args removed because we don't use them
1318
- const toBytes$1 = function (ip) {
1357
+ const toBytes = function (ip) {
1319
1358
  let offset = 0;
1320
1359
  ip = ip.toString().trim();
1321
1360
  if (isV4(ip)) {
@@ -1332,7 +1371,7 @@ const toBytes$1 = function (ip) {
1332
1371
  const isv4 = isV4(sections[i]);
1333
1372
  let v4Buffer;
1334
1373
  if (isv4) {
1335
- v4Buffer = toBytes$1(sections[i]);
1374
+ v4Buffer = toBytes(sections[i]);
1336
1375
  sections[i] = toString$1(v4Buffer.slice(0, 2), 'base16');
1337
1376
  }
1338
1377
  if (v4Buffer != null && ++i < 8) {
@@ -1570,7 +1609,7 @@ function ip2bytes(ipString) {
1570
1609
  if (!isIP(ipString)) {
1571
1610
  throw new Error('invalid ip address');
1572
1611
  }
1573
- return toBytes$1(ipString);
1612
+ return toBytes(ipString);
1574
1613
  }
1575
1614
  function bytes2ip(ipBuff) {
1576
1615
  const ipString = toString(ipBuff, 0, ipBuff.length);
@@ -1594,11 +1633,11 @@ function bytes2port(buf) {
1594
1633
  }
1595
1634
  function str2bytes(str) {
1596
1635
  const buf = fromString(str);
1597
- const size = Uint8Array.from(encode$2(buf.length));
1636
+ const size = Uint8Array.from(encode$1(buf.length));
1598
1637
  return concat([size, buf], size.length + buf.length);
1599
1638
  }
1600
1639
  function bytes2str(buf) {
1601
- const size = decode$2(buf);
1640
+ const size = decode$1(buf);
1602
1641
  buf = buf.slice(encodingLength(size));
1603
1642
  if (buf.length !== size) {
1604
1643
  throw new Error('inconsistent lengths');
@@ -1608,22 +1647,22 @@ function bytes2str(buf) {
1608
1647
  function mh2bytes(hash) {
1609
1648
  let mh;
1610
1649
  if (hash[0] === 'Q' || hash[0] === '1') {
1611
- mh = decode$3(base58btc.decode(`z${hash}`)).bytes;
1650
+ mh = decode$2(base58btc.decode(`z${hash}`)).bytes;
1612
1651
  }
1613
1652
  else {
1614
1653
  mh = CID.parse(hash).multihash.bytes;
1615
1654
  }
1616
1655
  // the address is a varint prefixed multihash string representation
1617
- const size = Uint8Array.from(encode$2(mh.length));
1656
+ const size = Uint8Array.from(encode$1(mh.length));
1618
1657
  return concat([size, mh], size.length + mh.length);
1619
1658
  }
1620
1659
  function mb2bytes(mbstr) {
1621
1660
  const mb = anybaseDecoder.decode(mbstr);
1622
- const size = Uint8Array.from(encode$2(mb.length));
1661
+ const size = Uint8Array.from(encode$1(mb.length));
1623
1662
  return concat([size, mb], size.length + mb.length);
1624
1663
  }
1625
1664
  function bytes2mb(buf) {
1626
- const size = decode$2(buf);
1665
+ const size = decode$1(buf);
1627
1666
  const hash = buf.slice(encodingLength(size));
1628
1667
  if (hash.length !== size) {
1629
1668
  throw new Error('inconsistent lengths');
@@ -1634,7 +1673,7 @@ function bytes2mb(buf) {
1634
1673
  * Converts bytes to bas58btc string
1635
1674
  */
1636
1675
  function bytes2mh(buf) {
1637
- const size = decode$2(buf);
1676
+ const size = decode$1(buf);
1638
1677
  const address = buf.slice(encodingLength(size));
1639
1678
  if (address.length !== size) {
1640
1679
  throw new Error('inconsistent lengths');
@@ -1741,7 +1780,7 @@ function bytesToMultiaddrParts(bytes) {
1741
1780
  let path = null;
1742
1781
  let i = 0;
1743
1782
  while (i < bytes.length) {
1744
- const code = decode$2(bytes, i);
1783
+ const code = decode$1(bytes, i);
1745
1784
  const n = encodingLength(code);
1746
1785
  const p = getProtocol(code);
1747
1786
  const size = sizeForAddr(p, bytes.slice(i + n));
@@ -1798,7 +1837,7 @@ function stringTuplesToString(tuples) {
1798
1837
  function tuplesToBytes(tuples) {
1799
1838
  return concat(tuples.map((tup) => {
1800
1839
  const proto = getProtocol(tup[0]);
1801
- let buf = Uint8Array.from(encode$2(proto.code));
1840
+ let buf = Uint8Array.from(encode$1(proto.code));
1802
1841
  if (tup.length > 1 && tup[1] != null) {
1803
1842
  buf = concat([buf, tup[1]]); // add address buffer
1804
1843
  }
@@ -1816,7 +1855,7 @@ function sizeForAddr(p, addr) {
1816
1855
  return 0;
1817
1856
  }
1818
1857
  else {
1819
- const size = decode$2(addr instanceof Uint8Array ? addr : Uint8Array.from(addr));
1858
+ const size = decode$1(addr instanceof Uint8Array ? addr : Uint8Array.from(addr));
1820
1859
  return size + encodingLength(size);
1821
1860
  }
1822
1861
  }
@@ -1841,38 +1880,17 @@ function ParseError(str) {
1841
1880
  * ```
1842
1881
  */
1843
1882
  const inspect = Symbol.for('nodejs.util.inspect.custom');
1883
+ const symbol$1 = Symbol.for('@multiformats/js-multiaddr/multiaddr');
1844
1884
  const DNS_CODES = [
1845
1885
  getProtocol('dns').code,
1846
1886
  getProtocol('dns4').code,
1847
1887
  getProtocol('dns6').code,
1848
1888
  getProtocol('dnsaddr').code
1849
1889
  ];
1850
- /**
1851
- * All configured {@link Resolver}s
1852
- */
1853
- const resolvers = new Map();
1854
- const symbol$1 = Symbol.for('@multiformats/js-multiaddr/multiaddr');
1855
- /**
1856
- * Check if object is a {@link Multiaddr} instance
1857
- *
1858
- * @example
1859
- *
1860
- * ```js
1861
- * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'
1862
- *
1863
- * isMultiaddr(5)
1864
- * // false
1865
- * isMultiaddr(multiaddr('/ip4/127.0.0.1'))
1866
- * // true
1867
- * ```
1868
- */
1869
- function isMultiaddr(value) {
1870
- return Boolean(value?.[symbol$1]);
1871
- }
1872
1890
  /**
1873
1891
  * Creates a {@link Multiaddr} from a {@link MultiaddrInput}
1874
1892
  */
1875
- class DefaultMultiaddr {
1893
+ class Multiaddr {
1876
1894
  bytes;
1877
1895
  #string;
1878
1896
  #tuples;
@@ -1972,8 +1990,8 @@ class DefaultMultiaddr {
1972
1990
  return this.#stringTuples;
1973
1991
  }
1974
1992
  encapsulate(addr) {
1975
- addr = new DefaultMultiaddr(addr);
1976
- return new DefaultMultiaddr(this.toString() + addr.toString());
1993
+ addr = new Multiaddr(addr);
1994
+ return new Multiaddr(this.toString() + addr.toString());
1977
1995
  }
1978
1996
  decapsulate(addr) {
1979
1997
  const addrString = addr.toString();
@@ -1982,13 +2000,13 @@ class DefaultMultiaddr {
1982
2000
  if (i < 0) {
1983
2001
  throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);
1984
2002
  }
1985
- return new DefaultMultiaddr(s.slice(0, i));
2003
+ return new Multiaddr(s.slice(0, i));
1986
2004
  }
1987
2005
  decapsulateCode(code) {
1988
2006
  const tuples = this.tuples();
1989
2007
  for (let i = tuples.length - 1; i >= 0; i--) {
1990
2008
  if (tuples[i][0] === code) {
1991
- return new DefaultMultiaddr(tuplesToBytes(tuples.slice(0, i)));
2009
+ return new Multiaddr(tuplesToBytes(tuples.slice(0, i)));
1992
2010
  }
1993
2011
  }
1994
2012
  return this;
@@ -2041,7 +2059,7 @@ class DefaultMultiaddr {
2041
2059
  throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER');
2042
2060
  }
2043
2061
  const addresses = await resolver(this, options);
2044
- return addresses.map((a) => new DefaultMultiaddr(a));
2062
+ return addresses.map((a) => new Multiaddr(a));
2045
2063
  }
2046
2064
  nodeAddress() {
2047
2065
  const options = this.toOptions();
@@ -2083,6 +2101,93 @@ class DefaultMultiaddr {
2083
2101
  return `Multiaddr(${this.#string})`;
2084
2102
  }
2085
2103
  }
2104
+
2105
+ /**
2106
+ * @packageDocumentation
2107
+ *
2108
+ * A standard way to represent addresses that
2109
+ *
2110
+ * - support any standard network protocol
2111
+ * - are self-describing
2112
+ * - have a binary packed format
2113
+ * - have a nice string representation
2114
+ * - encapsulate well
2115
+ *
2116
+ * @example
2117
+ *
2118
+ * ```js
2119
+ * import { multiaddr } from '@multiformats/multiaddr'
2120
+ * const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
2121
+ * // Multiaddr(/ip4/127.0.0.1/udp/1234)
2122
+ *
2123
+ * const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
2124
+ * // Multiaddr(/ip4/127.0.0.1/udp/1234)
2125
+ *
2126
+ * addr.bytes
2127
+ * // <Uint8Array 04 7f 00 00 01 11 04 d2>
2128
+ *
2129
+ * addr.toString()
2130
+ * // '/ip4/127.0.0.1/udp/1234'
2131
+ *
2132
+ * addr.protos()
2133
+ * // [
2134
+ * // {code: 4, name: 'ip4', size: 32},
2135
+ * // {code: 273, name: 'udp', size: 16}
2136
+ * // ]
2137
+ *
2138
+ * // gives you an object that is friendly with what Node.js core modules expect for addresses
2139
+ * addr.nodeAddress()
2140
+ * // {
2141
+ * // family: 4,
2142
+ * // port: 1234,
2143
+ * // address: "127.0.0.1"
2144
+ * // }
2145
+ *
2146
+ * addr.encapsulate('/sctp/5678')
2147
+ * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)
2148
+ * ```
2149
+ *
2150
+ * ## Resolvers
2151
+ *
2152
+ * `multiaddr` allows multiaddrs to be resolved when appropriate resolvers are provided. This module already has resolvers available, but you can also create your own. Resolvers should always be set in the same module that is calling `multiaddr.resolve()` to avoid conflicts if multiple versions of `multiaddr` are in your dependency tree.
2153
+ *
2154
+ * To provide multiaddr resolvers you can do:
2155
+ *
2156
+ * ```js
2157
+ * import { resolvers } from '@multiformats/multiaddr'
2158
+ *
2159
+ * resolvers.set('dnsaddr', resolvers.dnsaddrResolver)
2160
+ * ```
2161
+ *
2162
+ * The available resolvers are:
2163
+ *
2164
+ * | Name | type | Description |
2165
+ * | ----------------- | --------- | ----------------------------------- |
2166
+ * | `dnsaddrResolver` | `dnsaddr` | dnsaddr resolution with TXT Records |
2167
+ *
2168
+ * A resolver receives a `Multiaddr` as a parameter and returns a `Promise<Array<string>>`.
2169
+ */
2170
+ /**
2171
+ * All configured {@link Resolver}s
2172
+ */
2173
+ const resolvers = new Map();
2174
+ /**
2175
+ * Check if object is a {@link Multiaddr} instance
2176
+ *
2177
+ * @example
2178
+ *
2179
+ * ```js
2180
+ * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'
2181
+ *
2182
+ * isMultiaddr(5)
2183
+ * // false
2184
+ * isMultiaddr(multiaddr('/ip4/127.0.0.1'))
2185
+ * // true
2186
+ * ```
2187
+ */
2188
+ function isMultiaddr(value) {
2189
+ return Boolean(value?.[symbol$1]);
2190
+ }
2086
2191
  /**
2087
2192
  * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}
2088
2193
  *
@@ -2097,7 +2202,7 @@ class DefaultMultiaddr {
2097
2202
  * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)
2098
2203
  */
2099
2204
  function multiaddr(addr) {
2100
- return new DefaultMultiaddr(addr);
2205
+ return new Multiaddr(addr);
2101
2206
  }
2102
2207
 
2103
2208
  function isDefined(value) {
@@ -2185,15 +2290,6 @@ async function isMessageSizeUnderCap(encoder, message) {
2185
2290
  }
2186
2291
  const isWireSizeUnderCap = (buf) => buf.length / MB <= SIZE_CAP_IN_MB;
2187
2292
 
2188
- const shardInfoToPubSubTopics = (shardInfo) => {
2189
- return shardInfo.indexList.map((index) => `/waku/2/rs/${shardInfo.cluster}/${index}`);
2190
- };
2191
- function ensurePubsubTopicIsConfigured(pubsubTopic, configuredTopics) {
2192
- if (!configuredTopics.includes(pubsubTopic)) {
2193
- throw new Error(`PubSub topic ${pubsubTopic} has not been configured on this instance. Configured topics are: ${configuredTopics}. Please update your configuration by passing in the topic during Waku node instantiation.`);
2194
- }
2195
- }
2196
-
2197
2293
  /**
2198
2294
  * Adds types to the EventTarget class. Hopefully this won't be necessary forever.
2199
2295
  *
@@ -2266,41 +2362,41 @@ const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill;
2266
2362
 
2267
2363
  var _nodeResolve_empty = {};
2268
2364
 
2269
- var nodeCrypto = /*#__PURE__*/Object.freeze({
2365
+ var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
2270
2366
  __proto__: null,
2271
2367
  default: _nodeResolve_empty
2272
2368
  });
2273
2369
 
2274
2370
  /*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
2275
- const _0n$1 = BigInt(0);
2276
- const _1n$1 = BigInt(1);
2277
- const _2n$1 = BigInt(2);
2371
+ const _0n = BigInt(0);
2372
+ const _1n = BigInt(1);
2373
+ const _2n = BigInt(2);
2278
2374
  const _3n = BigInt(3);
2279
- const _8n$1 = BigInt(8);
2280
- const CURVE$1 = Object.freeze({
2281
- a: _0n$1,
2375
+ const _8n = BigInt(8);
2376
+ const CURVE = Object.freeze({
2377
+ a: _0n,
2282
2378
  b: BigInt(7),
2283
2379
  P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
2284
2380
  n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
2285
- h: _1n$1,
2381
+ h: _1n,
2286
2382
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
2287
2383
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
2288
2384
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
2289
2385
  });
2290
- const divNearest = (a, b) => (a + b / _2n$1) / b;
2386
+ const divNearest = (a, b) => (a + b / _2n) / b;
2291
2387
  const endo = {
2292
2388
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
2293
2389
  splitScalar(k) {
2294
- const { n } = CURVE$1;
2390
+ const { n } = CURVE;
2295
2391
  const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
2296
- const b1 = -_1n$1 * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
2392
+ const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
2297
2393
  const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
2298
2394
  const b2 = a1;
2299
2395
  const POW_2_128 = BigInt('0x100000000000000000000000000000000');
2300
2396
  const c1 = divNearest(b2 * k, n);
2301
2397
  const c2 = divNearest(-b1 * k, n);
2302
- let k1 = mod$1(k - c1 * a1 - c2 * a2, n);
2303
- let k2 = mod$1(-c1 * b1 - c2 * b2, n);
2398
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
2399
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
2304
2400
  const k1neg = k1 > POW_2_128;
2305
2401
  const k2neg = k2 > POW_2_128;
2306
2402
  if (k1neg)
@@ -2318,12 +2414,12 @@ const groupLen = 32;
2318
2414
  const compressedLen = fieldLen + 1;
2319
2415
  const uncompressedLen = 2 * fieldLen + 1;
2320
2416
  function weierstrass(x) {
2321
- const { a, b } = CURVE$1;
2322
- const x2 = mod$1(x * x);
2323
- const x3 = mod$1(x2 * x);
2324
- return mod$1(x3 + a * x + b);
2417
+ const { a, b } = CURVE;
2418
+ const x2 = mod(x * x);
2419
+ const x3 = mod(x2 * x);
2420
+ return mod(x3 + a * x + b);
2325
2421
  }
2326
- const USE_ENDOMORPHISM = CURVE$1.a === _0n$1;
2422
+ const USE_ENDOMORPHISM = CURVE.a === _0n;
2327
2423
  function assertJacPoint(other) {
2328
2424
  if (!(other instanceof JacobianPoint))
2329
2425
  throw new TypeError('JacobianPoint expected');
@@ -2335,15 +2431,15 @@ class JacobianPoint {
2335
2431
  this.z = z;
2336
2432
  }
2337
2433
  static fromAffine(p) {
2338
- if (!(p instanceof Point$1)) {
2434
+ if (!(p instanceof Point)) {
2339
2435
  throw new TypeError('JacobianPoint#fromAffine: expected Point');
2340
2436
  }
2341
- if (p.equals(Point$1.ZERO))
2437
+ if (p.equals(Point.ZERO))
2342
2438
  return JacobianPoint.ZERO;
2343
- return new JacobianPoint(p.x, p.y, _1n$1);
2439
+ return new JacobianPoint(p.x, p.y, _1n);
2344
2440
  }
2345
2441
  static toAffineBatch(points) {
2346
- const toInv = invertBatch$1(points.map((p) => p.z));
2442
+ const toInv = invertBatch(points.map((p) => p.z));
2347
2443
  return points.map((p, i) => p.toAffine(toInv[i]));
2348
2444
  }
2349
2445
  static normalizeZ(points) {
@@ -2353,61 +2449,61 @@ class JacobianPoint {
2353
2449
  assertJacPoint(other);
2354
2450
  const { x: X1, y: Y1, z: Z1 } = this;
2355
2451
  const { x: X2, y: Y2, z: Z2 } = other;
2356
- const Z1Z1 = mod$1(Z1 * Z1);
2357
- const Z2Z2 = mod$1(Z2 * Z2);
2358
- const U1 = mod$1(X1 * Z2Z2);
2359
- const U2 = mod$1(X2 * Z1Z1);
2360
- const S1 = mod$1(mod$1(Y1 * Z2) * Z2Z2);
2361
- const S2 = mod$1(mod$1(Y2 * Z1) * Z1Z1);
2452
+ const Z1Z1 = mod(Z1 * Z1);
2453
+ const Z2Z2 = mod(Z2 * Z2);
2454
+ const U1 = mod(X1 * Z2Z2);
2455
+ const U2 = mod(X2 * Z1Z1);
2456
+ const S1 = mod(mod(Y1 * Z2) * Z2Z2);
2457
+ const S2 = mod(mod(Y2 * Z1) * Z1Z1);
2362
2458
  return U1 === U2 && S1 === S2;
2363
2459
  }
2364
2460
  negate() {
2365
- return new JacobianPoint(this.x, mod$1(-this.y), this.z);
2461
+ return new JacobianPoint(this.x, mod(-this.y), this.z);
2366
2462
  }
2367
2463
  double() {
2368
2464
  const { x: X1, y: Y1, z: Z1 } = this;
2369
- const A = mod$1(X1 * X1);
2370
- const B = mod$1(Y1 * Y1);
2371
- const C = mod$1(B * B);
2465
+ const A = mod(X1 * X1);
2466
+ const B = mod(Y1 * Y1);
2467
+ const C = mod(B * B);
2372
2468
  const x1b = X1 + B;
2373
- const D = mod$1(_2n$1 * (mod$1(x1b * x1b) - A - C));
2374
- const E = mod$1(_3n * A);
2375
- const F = mod$1(E * E);
2376
- const X3 = mod$1(F - _2n$1 * D);
2377
- const Y3 = mod$1(E * (D - X3) - _8n$1 * C);
2378
- const Z3 = mod$1(_2n$1 * Y1 * Z1);
2469
+ const D = mod(_2n * (mod(x1b * x1b) - A - C));
2470
+ const E = mod(_3n * A);
2471
+ const F = mod(E * E);
2472
+ const X3 = mod(F - _2n * D);
2473
+ const Y3 = mod(E * (D - X3) - _8n * C);
2474
+ const Z3 = mod(_2n * Y1 * Z1);
2379
2475
  return new JacobianPoint(X3, Y3, Z3);
2380
2476
  }
2381
2477
  add(other) {
2382
2478
  assertJacPoint(other);
2383
2479
  const { x: X1, y: Y1, z: Z1 } = this;
2384
2480
  const { x: X2, y: Y2, z: Z2 } = other;
2385
- if (X2 === _0n$1 || Y2 === _0n$1)
2481
+ if (X2 === _0n || Y2 === _0n)
2386
2482
  return this;
2387
- if (X1 === _0n$1 || Y1 === _0n$1)
2483
+ if (X1 === _0n || Y1 === _0n)
2388
2484
  return other;
2389
- const Z1Z1 = mod$1(Z1 * Z1);
2390
- const Z2Z2 = mod$1(Z2 * Z2);
2391
- const U1 = mod$1(X1 * Z2Z2);
2392
- const U2 = mod$1(X2 * Z1Z1);
2393
- const S1 = mod$1(mod$1(Y1 * Z2) * Z2Z2);
2394
- const S2 = mod$1(mod$1(Y2 * Z1) * Z1Z1);
2395
- const H = mod$1(U2 - U1);
2396
- const r = mod$1(S2 - S1);
2397
- if (H === _0n$1) {
2398
- if (r === _0n$1) {
2485
+ const Z1Z1 = mod(Z1 * Z1);
2486
+ const Z2Z2 = mod(Z2 * Z2);
2487
+ const U1 = mod(X1 * Z2Z2);
2488
+ const U2 = mod(X2 * Z1Z1);
2489
+ const S1 = mod(mod(Y1 * Z2) * Z2Z2);
2490
+ const S2 = mod(mod(Y2 * Z1) * Z1Z1);
2491
+ const H = mod(U2 - U1);
2492
+ const r = mod(S2 - S1);
2493
+ if (H === _0n) {
2494
+ if (r === _0n) {
2399
2495
  return this.double();
2400
2496
  }
2401
2497
  else {
2402
2498
  return JacobianPoint.ZERO;
2403
2499
  }
2404
2500
  }
2405
- const HH = mod$1(H * H);
2406
- const HHH = mod$1(H * HH);
2407
- const V = mod$1(U1 * HH);
2408
- const X3 = mod$1(r * r - HHH - _2n$1 * V);
2409
- const Y3 = mod$1(r * (V - X3) - S1 * HHH);
2410
- const Z3 = mod$1(Z1 * Z2 * H);
2501
+ const HH = mod(H * H);
2502
+ const HHH = mod(H * HH);
2503
+ const V = mod(U1 * HH);
2504
+ const X3 = mod(r * r - HHH - _2n * V);
2505
+ const Y3 = mod(r * (V - X3) - S1 * HHH);
2506
+ const Z3 = mod(Z1 * Z2 * H);
2411
2507
  return new JacobianPoint(X3, Y3, Z3);
2412
2508
  }
2413
2509
  subtract(other) {
@@ -2415,19 +2511,19 @@ class JacobianPoint {
2415
2511
  }
2416
2512
  multiplyUnsafe(scalar) {
2417
2513
  const P0 = JacobianPoint.ZERO;
2418
- if (typeof scalar === 'bigint' && scalar === _0n$1)
2514
+ if (typeof scalar === 'bigint' && scalar === _0n)
2419
2515
  return P0;
2420
- let n = normalizeScalar$1(scalar);
2421
- if (n === _1n$1)
2516
+ let n = normalizeScalar(scalar);
2517
+ if (n === _1n)
2422
2518
  return this;
2423
2519
  if (!USE_ENDOMORPHISM) {
2424
2520
  let p = P0;
2425
2521
  let d = this;
2426
- while (n > _0n$1) {
2427
- if (n & _1n$1)
2522
+ while (n > _0n) {
2523
+ if (n & _1n)
2428
2524
  p = p.add(d);
2429
2525
  d = d.double();
2430
- n >>= _1n$1;
2526
+ n >>= _1n;
2431
2527
  }
2432
2528
  return p;
2433
2529
  }
@@ -2435,20 +2531,20 @@ class JacobianPoint {
2435
2531
  let k1p = P0;
2436
2532
  let k2p = P0;
2437
2533
  let d = this;
2438
- while (k1 > _0n$1 || k2 > _0n$1) {
2439
- if (k1 & _1n$1)
2534
+ while (k1 > _0n || k2 > _0n) {
2535
+ if (k1 & _1n)
2440
2536
  k1p = k1p.add(d);
2441
- if (k2 & _1n$1)
2537
+ if (k2 & _1n)
2442
2538
  k2p = k2p.add(d);
2443
2539
  d = d.double();
2444
- k1 >>= _1n$1;
2445
- k2 >>= _1n$1;
2540
+ k1 >>= _1n;
2541
+ k2 >>= _1n;
2446
2542
  }
2447
2543
  if (k1neg)
2448
2544
  k1p = k1p.negate();
2449
2545
  if (k2neg)
2450
2546
  k2p = k2p.negate();
2451
- k2p = new JacobianPoint(mod$1(k2p.x * endo.beta), k2p.y, k2p.z);
2547
+ k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);
2452
2548
  return k1p.add(k2p);
2453
2549
  }
2454
2550
  precomputeWindow(W) {
@@ -2469,17 +2565,17 @@ class JacobianPoint {
2469
2565
  }
2470
2566
  wNAF(n, affinePoint) {
2471
2567
  if (!affinePoint && this.equals(JacobianPoint.BASE))
2472
- affinePoint = Point$1.BASE;
2568
+ affinePoint = Point.BASE;
2473
2569
  const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;
2474
2570
  if (256 % W) {
2475
2571
  throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');
2476
2572
  }
2477
- let precomputes = affinePoint && pointPrecomputes$1.get(affinePoint);
2573
+ let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
2478
2574
  if (!precomputes) {
2479
2575
  precomputes = this.precomputeWindow(W);
2480
2576
  if (affinePoint && W !== 1) {
2481
2577
  precomputes = JacobianPoint.normalizeZ(precomputes);
2482
- pointPrecomputes$1.set(affinePoint, precomputes);
2578
+ pointPrecomputes.set(affinePoint, precomputes);
2483
2579
  }
2484
2580
  }
2485
2581
  let p = JacobianPoint.ZERO;
@@ -2495,32 +2591,32 @@ class JacobianPoint {
2495
2591
  n >>= shiftBy;
2496
2592
  if (wbits > windowSize) {
2497
2593
  wbits -= maxNumber;
2498
- n += _1n$1;
2594
+ n += _1n;
2499
2595
  }
2500
2596
  const offset1 = offset;
2501
2597
  const offset2 = offset + Math.abs(wbits) - 1;
2502
2598
  const cond1 = window % 2 !== 0;
2503
2599
  const cond2 = wbits < 0;
2504
2600
  if (wbits === 0) {
2505
- f = f.add(constTimeNegate$1(cond1, precomputes[offset1]));
2601
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
2506
2602
  }
2507
2603
  else {
2508
- p = p.add(constTimeNegate$1(cond2, precomputes[offset2]));
2604
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
2509
2605
  }
2510
2606
  }
2511
2607
  return { p, f };
2512
2608
  }
2513
2609
  multiply(scalar, affinePoint) {
2514
- let n = normalizeScalar$1(scalar);
2610
+ let n = normalizeScalar(scalar);
2515
2611
  let point;
2516
2612
  let fake;
2517
2613
  if (USE_ENDOMORPHISM) {
2518
2614
  const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
2519
2615
  let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
2520
2616
  let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);
2521
- k1p = constTimeNegate$1(k1neg, k1p);
2522
- k2p = constTimeNegate$1(k2neg, k2p);
2523
- k2p = new JacobianPoint(mod$1(k2p.x * endo.beta), k2p.y, k2p.z);
2617
+ k1p = constTimeNegate(k1neg, k1p);
2618
+ k2p = constTimeNegate(k2neg, k2p);
2619
+ k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);
2524
2620
  point = k1p.add(k2p);
2525
2621
  fake = f1p.add(f2p);
2526
2622
  }
@@ -2535,38 +2631,38 @@ class JacobianPoint {
2535
2631
  const { x, y, z } = this;
2536
2632
  const is0 = this.equals(JacobianPoint.ZERO);
2537
2633
  if (invZ == null)
2538
- invZ = is0 ? _8n$1 : invert$1(z);
2634
+ invZ = is0 ? _8n : invert(z);
2539
2635
  const iz1 = invZ;
2540
- const iz2 = mod$1(iz1 * iz1);
2541
- const iz3 = mod$1(iz2 * iz1);
2542
- const ax = mod$1(x * iz2);
2543
- const ay = mod$1(y * iz3);
2544
- const zz = mod$1(z * iz1);
2636
+ const iz2 = mod(iz1 * iz1);
2637
+ const iz3 = mod(iz2 * iz1);
2638
+ const ax = mod(x * iz2);
2639
+ const ay = mod(y * iz3);
2640
+ const zz = mod(z * iz1);
2545
2641
  if (is0)
2546
- return Point$1.ZERO;
2547
- if (zz !== _1n$1)
2642
+ return Point.ZERO;
2643
+ if (zz !== _1n)
2548
2644
  throw new Error('invZ was invalid');
2549
- return new Point$1(ax, ay);
2645
+ return new Point(ax, ay);
2550
2646
  }
2551
2647
  }
2552
- JacobianPoint.BASE = new JacobianPoint(CURVE$1.Gx, CURVE$1.Gy, _1n$1);
2553
- JacobianPoint.ZERO = new JacobianPoint(_0n$1, _1n$1, _0n$1);
2554
- function constTimeNegate$1(condition, item) {
2648
+ JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n);
2649
+ JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n);
2650
+ function constTimeNegate(condition, item) {
2555
2651
  const neg = item.negate();
2556
2652
  return condition ? neg : item;
2557
2653
  }
2558
- const pointPrecomputes$1 = new WeakMap();
2559
- let Point$1 = class Point {
2654
+ const pointPrecomputes = new WeakMap();
2655
+ class Point {
2560
2656
  constructor(x, y) {
2561
2657
  this.x = x;
2562
2658
  this.y = y;
2563
2659
  }
2564
2660
  _setWindowSize(windowSize) {
2565
2661
  this._WINDOW_SIZE = windowSize;
2566
- pointPrecomputes$1.delete(this);
2662
+ pointPrecomputes.delete(this);
2567
2663
  }
2568
2664
  hasEvenY() {
2569
- return this.y % _2n$1 === _0n$1;
2665
+ return this.y % _2n === _0n;
2570
2666
  }
2571
2667
  static fromCompressedHex(bytes) {
2572
2668
  const isShort = bytes.length === 32;
@@ -2575,15 +2671,15 @@ let Point$1 = class Point {
2575
2671
  throw new Error('Point is not on curve');
2576
2672
  const y2 = weierstrass(x);
2577
2673
  let y = sqrtMod(y2);
2578
- const isYOdd = (y & _1n$1) === _1n$1;
2674
+ const isYOdd = (y & _1n) === _1n;
2579
2675
  if (isShort) {
2580
2676
  if (isYOdd)
2581
- y = mod$1(-y);
2677
+ y = mod(-y);
2582
2678
  }
2583
2679
  else {
2584
2680
  const isFirstByteOdd = (bytes[0] & 1) === 1;
2585
2681
  if (isFirstByteOdd !== isYOdd)
2586
- y = mod$1(-y);
2682
+ y = mod(-y);
2587
2683
  }
2588
2684
  const point = new Point(x, y);
2589
2685
  point.assertValidity();
@@ -2597,7 +2693,7 @@ let Point$1 = class Point {
2597
2693
  return point;
2598
2694
  }
2599
2695
  static fromHex(hex) {
2600
- const bytes = ensureBytes$1(hex);
2696
+ const bytes = ensureBytes(hex);
2601
2697
  const len = bytes.length;
2602
2698
  const header = bytes[0];
2603
2699
  if (len === fieldLen)
@@ -2616,12 +2712,12 @@ let Point$1 = class Point {
2616
2712
  const { r, s } = normalizeSignature(signature);
2617
2713
  if (![0, 1, 2, 3].includes(recovery))
2618
2714
  throw new Error('Cannot recover: invalid recovery bit');
2619
- const h = truncateHash(ensureBytes$1(msgHash));
2620
- const { n } = CURVE$1;
2715
+ const h = truncateHash(ensureBytes(msgHash));
2716
+ const { n } = CURVE;
2621
2717
  const radj = recovery === 2 || recovery === 3 ? r + n : r;
2622
- const rinv = invert$1(radj, n);
2623
- const u1 = mod$1(-h * rinv, n);
2624
- const u2 = mod$1(s * rinv, n);
2718
+ const rinv = invert(radj, n);
2719
+ const u1 = mod(-h * rinv, n);
2720
+ const u2 = mod(s * rinv, n);
2625
2721
  const prefix = recovery & 1 ? '03' : '02';
2626
2722
  const R = Point.fromHex(prefix + numTo32bStr(radj));
2627
2723
  const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
@@ -2631,7 +2727,7 @@ let Point$1 = class Point {
2631
2727
  return Q;
2632
2728
  }
2633
2729
  toRawBytes(isCompressed = false) {
2634
- return hexToBytes$1(this.toHex(isCompressed));
2730
+ return hexToBytes(this.toHex(isCompressed));
2635
2731
  }
2636
2732
  toHex(isCompressed = false) {
2637
2733
  const x = numTo32bStr(this.x);
@@ -2654,16 +2750,16 @@ let Point$1 = class Point {
2654
2750
  const { x, y } = this;
2655
2751
  if (!isValidFieldElement(x) || !isValidFieldElement(y))
2656
2752
  throw new Error(msg);
2657
- const left = mod$1(y * y);
2753
+ const left = mod(y * y);
2658
2754
  const right = weierstrass(x);
2659
- if (mod$1(left - right) !== _0n$1)
2755
+ if (mod(left - right) !== _0n)
2660
2756
  throw new Error(msg);
2661
2757
  }
2662
2758
  equals(other) {
2663
2759
  return this.x === other.x && this.y === other.y;
2664
2760
  }
2665
2761
  negate() {
2666
- return new Point(this.x, mod$1(-this.y));
2762
+ return new Point(this.x, mod(-this.y));
2667
2763
  }
2668
2764
  double() {
2669
2765
  return JacobianPoint.fromAffine(this).double().toAffine();
@@ -2679,20 +2775,20 @@ let Point$1 = class Point {
2679
2775
  }
2680
2776
  multiplyAndAddUnsafe(Q, a, b) {
2681
2777
  const P = JacobianPoint.fromAffine(this);
2682
- const aP = a === _0n$1 || a === _1n$1 || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);
2778
+ const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);
2683
2779
  const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);
2684
2780
  const sum = aP.add(bQ);
2685
2781
  return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine();
2686
2782
  }
2687
- };
2688
- Point$1.BASE = new Point$1(CURVE$1.Gx, CURVE$1.Gy);
2689
- Point$1.ZERO = new Point$1(_0n$1, _0n$1);
2783
+ }
2784
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy);
2785
+ Point.ZERO = new Point(_0n, _0n);
2690
2786
  function sliceDER(s) {
2691
2787
  return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s;
2692
2788
  }
2693
2789
  function parseDERInt(data) {
2694
2790
  if (data.length < 2 || data[0] !== 0x02) {
2695
- throw new Error(`Invalid signature integer tag: ${bytesToHex$1(data)}`);
2791
+ throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);
2696
2792
  }
2697
2793
  const len = data[1];
2698
2794
  const res = data.subarray(2, len + 2);
@@ -2706,7 +2802,7 @@ function parseDERInt(data) {
2706
2802
  }
2707
2803
  function parseDERSignature(data) {
2708
2804
  if (data.length < 2 || data[0] != 0x30) {
2709
- throw new Error(`Invalid signature tag: ${bytesToHex$1(data)}`);
2805
+ throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);
2710
2806
  }
2711
2807
  if (data[1] !== data.length - 2) {
2712
2808
  throw new Error('Invalid signature: incorrect length');
@@ -2714,7 +2810,7 @@ function parseDERSignature(data) {
2714
2810
  const { data: r, left: sBytes } = parseDERInt(data.subarray(2));
2715
2811
  const { data: s, left: rBytesLeft } = parseDERInt(sBytes);
2716
2812
  if (rBytesLeft.length) {
2717
- throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex$1(rBytesLeft)}`);
2813
+ throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);
2718
2814
  }
2719
2815
  return { r, s };
2720
2816
  }
@@ -2729,7 +2825,7 @@ class Signature {
2729
2825
  const name = 'Signature.fromCompact';
2730
2826
  if (typeof hex !== 'string' && !arr)
2731
2827
  throw new TypeError(`${name}: Expected string or Uint8Array`);
2732
- const str = arr ? bytesToHex$1(hex) : hex;
2828
+ const str = arr ? bytesToHex(hex) : hex;
2733
2829
  if (str.length !== 128)
2734
2830
  throw new Error(`${name}: Expected 64-byte hex`);
2735
2831
  return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));
@@ -2738,7 +2834,7 @@ class Signature {
2738
2834
  const arr = hex instanceof Uint8Array;
2739
2835
  if (typeof hex !== 'string' && !arr)
2740
2836
  throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
2741
- const { r, s } = parseDERSignature(arr ? hex : hexToBytes$1(hex));
2837
+ const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex));
2742
2838
  return new Signature(r, s);
2743
2839
  }
2744
2840
  static fromHex(hex) {
@@ -2752,14 +2848,14 @@ class Signature {
2752
2848
  throw new Error('Invalid Signature: s must be 0 < s < n');
2753
2849
  }
2754
2850
  hasHighS() {
2755
- const HALF = CURVE$1.n >> _1n$1;
2851
+ const HALF = CURVE.n >> _1n;
2756
2852
  return this.s > HALF;
2757
2853
  }
2758
2854
  normalizeS() {
2759
- return this.hasHighS() ? new Signature(this.r, mod$1(-this.s, CURVE$1.n)) : this;
2855
+ return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this;
2760
2856
  }
2761
2857
  toDERRawBytes() {
2762
- return hexToBytes$1(this.toDERHex());
2858
+ return hexToBytes(this.toDERHex());
2763
2859
  }
2764
2860
  toDERHex() {
2765
2861
  const sHex = sliceDER(numberToHexUnpadded(this.s));
@@ -2778,27 +2874,27 @@ class Signature {
2778
2874
  return this.toDERHex();
2779
2875
  }
2780
2876
  toCompactRawBytes() {
2781
- return hexToBytes$1(this.toCompactHex());
2877
+ return hexToBytes(this.toCompactHex());
2782
2878
  }
2783
2879
  toCompactHex() {
2784
2880
  return numTo32bStr(this.r) + numTo32bStr(this.s);
2785
2881
  }
2786
2882
  }
2787
- const hexes$1 = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
2788
- function bytesToHex$1(uint8a) {
2883
+ const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
2884
+ function bytesToHex(uint8a) {
2789
2885
  if (!(uint8a instanceof Uint8Array))
2790
2886
  throw new Error('Expected Uint8Array');
2791
2887
  let hex = '';
2792
2888
  for (let i = 0; i < uint8a.length; i++) {
2793
- hex += hexes$1[uint8a[i]];
2889
+ hex += hexes[uint8a[i]];
2794
2890
  }
2795
2891
  return hex;
2796
2892
  }
2797
- const POW_2_256$1 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
2893
+ const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
2798
2894
  function numTo32bStr(num) {
2799
2895
  if (typeof num !== 'bigint')
2800
2896
  throw new Error('Expected bigint');
2801
- if (!(_0n$1 <= num && num < POW_2_256$1))
2897
+ if (!(_0n <= num && num < POW_2_256))
2802
2898
  throw new Error('Expected number 0 <= n < 2^256');
2803
2899
  return num.toString(16).padStart(64, '0');
2804
2900
  }
@@ -2812,7 +2908,7 @@ function hexToNumber(hex) {
2812
2908
  }
2813
2909
  return BigInt(`0x${hex}`);
2814
2910
  }
2815
- function hexToBytes$1(hex) {
2911
+ function hexToBytes(hex) {
2816
2912
  if (typeof hex !== 'string') {
2817
2913
  throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
2818
2914
  }
@@ -2830,33 +2926,33 @@ function hexToBytes$1(hex) {
2830
2926
  return array;
2831
2927
  }
2832
2928
  function bytesToNumber(bytes) {
2833
- return hexToNumber(bytesToHex$1(bytes));
2929
+ return hexToNumber(bytesToHex(bytes));
2834
2930
  }
2835
- function ensureBytes$1(hex) {
2836
- return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes$1(hex);
2931
+ function ensureBytes(hex) {
2932
+ return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);
2837
2933
  }
2838
- function normalizeScalar$1(num) {
2934
+ function normalizeScalar(num) {
2839
2935
  if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)
2840
2936
  return BigInt(num);
2841
2937
  if (typeof num === 'bigint' && isWithinCurveOrder(num))
2842
2938
  return num;
2843
2939
  throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n');
2844
2940
  }
2845
- function mod$1(a, b = CURVE$1.P) {
2941
+ function mod(a, b = CURVE.P) {
2846
2942
  const result = a % b;
2847
- return result >= _0n$1 ? result : b + result;
2943
+ return result >= _0n ? result : b + result;
2848
2944
  }
2849
- function pow2$1(x, power) {
2850
- const { P } = CURVE$1;
2945
+ function pow2(x, power) {
2946
+ const { P } = CURVE;
2851
2947
  let res = x;
2852
- while (power-- > _0n$1) {
2948
+ while (power-- > _0n) {
2853
2949
  res *= res;
2854
2950
  res %= P;
2855
2951
  }
2856
2952
  return res;
2857
2953
  }
2858
2954
  function sqrtMod(x) {
2859
- const { P } = CURVE$1;
2955
+ const { P } = CURVE;
2860
2956
  const _6n = BigInt(6);
2861
2957
  const _11n = BigInt(11);
2862
2958
  const _22n = BigInt(22);
@@ -2865,55 +2961,55 @@ function sqrtMod(x) {
2865
2961
  const _88n = BigInt(88);
2866
2962
  const b2 = (x * x * x) % P;
2867
2963
  const b3 = (b2 * b2 * x) % P;
2868
- const b6 = (pow2$1(b3, _3n) * b3) % P;
2869
- const b9 = (pow2$1(b6, _3n) * b3) % P;
2870
- const b11 = (pow2$1(b9, _2n$1) * b2) % P;
2871
- const b22 = (pow2$1(b11, _11n) * b11) % P;
2872
- const b44 = (pow2$1(b22, _22n) * b22) % P;
2873
- const b88 = (pow2$1(b44, _44n) * b44) % P;
2874
- const b176 = (pow2$1(b88, _88n) * b88) % P;
2875
- const b220 = (pow2$1(b176, _44n) * b44) % P;
2876
- const b223 = (pow2$1(b220, _3n) * b3) % P;
2877
- const t1 = (pow2$1(b223, _23n) * b22) % P;
2878
- const t2 = (pow2$1(t1, _6n) * b2) % P;
2879
- const rt = pow2$1(t2, _2n$1);
2964
+ const b6 = (pow2(b3, _3n) * b3) % P;
2965
+ const b9 = (pow2(b6, _3n) * b3) % P;
2966
+ const b11 = (pow2(b9, _2n) * b2) % P;
2967
+ const b22 = (pow2(b11, _11n) * b11) % P;
2968
+ const b44 = (pow2(b22, _22n) * b22) % P;
2969
+ const b88 = (pow2(b44, _44n) * b44) % P;
2970
+ const b176 = (pow2(b88, _88n) * b88) % P;
2971
+ const b220 = (pow2(b176, _44n) * b44) % P;
2972
+ const b223 = (pow2(b220, _3n) * b3) % P;
2973
+ const t1 = (pow2(b223, _23n) * b22) % P;
2974
+ const t2 = (pow2(t1, _6n) * b2) % P;
2975
+ const rt = pow2(t2, _2n);
2880
2976
  const xc = (rt * rt) % P;
2881
2977
  if (xc !== x)
2882
2978
  throw new Error('Cannot find square root');
2883
2979
  return rt;
2884
2980
  }
2885
- function invert$1(number, modulo = CURVE$1.P) {
2886
- if (number === _0n$1 || modulo <= _0n$1) {
2981
+ function invert(number, modulo = CURVE.P) {
2982
+ if (number === _0n || modulo <= _0n) {
2887
2983
  throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
2888
2984
  }
2889
- let a = mod$1(number, modulo);
2985
+ let a = mod(number, modulo);
2890
2986
  let b = modulo;
2891
- let x = _0n$1, u = _1n$1;
2892
- while (a !== _0n$1) {
2987
+ let x = _0n, u = _1n;
2988
+ while (a !== _0n) {
2893
2989
  const q = b / a;
2894
2990
  const r = b % a;
2895
2991
  const m = x - u * q;
2896
2992
  b = a, a = r, x = u, u = m;
2897
2993
  }
2898
2994
  const gcd = b;
2899
- if (gcd !== _1n$1)
2995
+ if (gcd !== _1n)
2900
2996
  throw new Error('invert: does not exist');
2901
- return mod$1(x, modulo);
2997
+ return mod(x, modulo);
2902
2998
  }
2903
- function invertBatch$1(nums, p = CURVE$1.P) {
2999
+ function invertBatch(nums, p = CURVE.P) {
2904
3000
  const scratch = new Array(nums.length);
2905
3001
  const lastMultiplied = nums.reduce((acc, num, i) => {
2906
- if (num === _0n$1)
3002
+ if (num === _0n)
2907
3003
  return acc;
2908
3004
  scratch[i] = acc;
2909
- return mod$1(acc * num, p);
2910
- }, _1n$1);
2911
- const inverted = invert$1(lastMultiplied, p);
3005
+ return mod(acc * num, p);
3006
+ }, _1n);
3007
+ const inverted = invert(lastMultiplied, p);
2912
3008
  nums.reduceRight((acc, num, i) => {
2913
- if (num === _0n$1)
3009
+ if (num === _0n)
2914
3010
  return acc;
2915
- scratch[i] = mod$1(acc * scratch[i], p);
2916
- return mod$1(acc * num, p);
3011
+ scratch[i] = mod(acc * scratch[i], p);
3012
+ return mod(acc * num, p);
2917
3013
  }, inverted);
2918
3014
  return scratch;
2919
3015
  }
@@ -2926,14 +3022,14 @@ function truncateHash(hash, truncateOnly = false) {
2926
3022
  const h = bits2int_2(hash);
2927
3023
  if (truncateOnly)
2928
3024
  return h;
2929
- const { n } = CURVE$1;
3025
+ const { n } = CURVE;
2930
3026
  return h >= n ? h - n : h;
2931
3027
  }
2932
3028
  function isWithinCurveOrder(num) {
2933
- return _0n$1 < num && num < CURVE$1.n;
3029
+ return _0n < num && num < CURVE.n;
2934
3030
  }
2935
3031
  function isValidFieldElement(num) {
2936
- return _0n$1 < num && num < CURVE$1.P;
3032
+ return _0n < num && num < CURVE.P;
2937
3033
  }
2938
3034
  function normalizePrivateKey(key) {
2939
3035
  let num;
@@ -2972,7 +3068,7 @@ function normalizeSignature(signature) {
2972
3068
  return Signature.fromCompact(signature);
2973
3069
  }
2974
3070
  }
2975
- Point$1.BASE._setWindowSize(8);
3071
+ Point.BASE._setWindowSize(8);
2976
3072
 
2977
3073
  var sha3 = {exports: {}};
2978
3074
 
@@ -11081,7 +11177,7 @@ hmac.create = function() {
11081
11177
  return ctx;
11082
11178
  };
11083
11179
 
11084
- var require$$8 = /*@__PURE__*/getAugmentedNamespace(nodeCrypto);
11180
+ var require$$8 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1);
11085
11181
 
11086
11182
  /**
11087
11183
  * Password-Based Key-Derivation Function #2 implementation.
@@ -11100,9 +11196,9 @@ var forge$c = forge$m;
11100
11196
 
11101
11197
  var pkcs5 = forge$c.pkcs5 = forge$c.pkcs5 || {};
11102
11198
 
11103
- var crypto$2;
11199
+ var crypto$1;
11104
11200
  if(forge$c.util.isNodejs && !forge$c.options.usePureJavaScript) {
11105
- crypto$2 = require$$8;
11201
+ crypto$1 = require$$8;
11106
11202
  }
11107
11203
 
11108
11204
  /**
@@ -11131,8 +11227,8 @@ forge$c.pbkdf2 = pkcs5.pbkdf2 = function(
11131
11227
  // use native implementation if possible and not disabled, note that
11132
11228
  // some node versions only support SHA-1, others allow digest to be changed
11133
11229
  if(forge$c.util.isNodejs && !forge$c.options.usePureJavaScript &&
11134
- crypto$2.pbkdf2 && (md === null || typeof md !== 'object') &&
11135
- (crypto$2.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {
11230
+ crypto$1.pbkdf2 && (md === null || typeof md !== 'object') &&
11231
+ (crypto$1.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {
11136
11232
  if(typeof md !== 'string') {
11137
11233
  // default prf to SHA-1
11138
11234
  md = 'sha1';
@@ -11140,20 +11236,20 @@ forge$c.pbkdf2 = pkcs5.pbkdf2 = function(
11140
11236
  p = Buffer.from(p, 'binary');
11141
11237
  s = Buffer.from(s, 'binary');
11142
11238
  if(!callback) {
11143
- if(crypto$2.pbkdf2Sync.length === 4) {
11144
- return crypto$2.pbkdf2Sync(p, s, c, dkLen).toString('binary');
11239
+ if(crypto$1.pbkdf2Sync.length === 4) {
11240
+ return crypto$1.pbkdf2Sync(p, s, c, dkLen).toString('binary');
11145
11241
  }
11146
- return crypto$2.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');
11242
+ return crypto$1.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');
11147
11243
  }
11148
- if(crypto$2.pbkdf2Sync.length === 4) {
11149
- return crypto$2.pbkdf2(p, s, c, dkLen, function(err, key) {
11244
+ if(crypto$1.pbkdf2Sync.length === 4) {
11245
+ return crypto$1.pbkdf2(p, s, c, dkLen, function(err, key) {
11150
11246
  if(err) {
11151
11247
  return callback(err);
11152
11248
  }
11153
11249
  callback(null, key.toString('binary'));
11154
11250
  });
11155
11251
  }
11156
- return crypto$2.pbkdf2(p, s, c, dkLen, md, function(err, key) {
11252
+ return crypto$1.pbkdf2(p, s, c, dkLen, md, function(err, key) {
11157
11253
  if(err) {
11158
11254
  return callback(err);
11159
11255
  }
@@ -11549,15 +11645,15 @@ var forge$a = forge$m;
11549
11645
 
11550
11646
 
11551
11647
 
11552
- var sha256$1 = forge$a.sha256 = forge$a.sha256 || {};
11553
- forge$a.md.sha256 = forge$a.md.algorithms.sha256 = sha256$1;
11648
+ var sha256 = forge$a.sha256 = forge$a.sha256 || {};
11649
+ forge$a.md.sha256 = forge$a.md.algorithms.sha256 = sha256;
11554
11650
 
11555
11651
  /**
11556
11652
  * Creates a SHA-256 message digest object.
11557
11653
  *
11558
11654
  * @return a message digest object.
11559
11655
  */
11560
- sha256$1.create = function() {
11656
+ sha256.create = function() {
11561
11657
  // do initialization as necessary
11562
11658
  if(!_initialized$2) {
11563
11659
  _init$2();
@@ -17979,1240 +18075,44 @@ function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {
17979
18075
  return params;
17980
18076
  }
17981
18077
 
17982
- // base-x encoding / decoding
17983
- // Copyright (c) 2018 base-x contributors
17984
- // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
17985
- // Distributed under the MIT software license, see the accompanying
17986
- // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
17987
- function base (ALPHABET, name) {
17988
- if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
17989
- var BASE_MAP = new Uint8Array(256);
17990
- for (var j = 0; j < BASE_MAP.length; j++) {
17991
- BASE_MAP[j] = 255;
17992
- }
17993
- for (var i = 0; i < ALPHABET.length; i++) {
17994
- var x = ALPHABET.charAt(i);
17995
- var xc = x.charCodeAt(0);
17996
- if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
17997
- BASE_MAP[xc] = i;
17998
- }
17999
- var BASE = ALPHABET.length;
18000
- var LEADER = ALPHABET.charAt(0);
18001
- var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
18002
- var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
18003
- function encode (source) {
18004
- if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
18005
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
18006
- } else if (Array.isArray(source)) {
18007
- source = Uint8Array.from(source);
18008
- }
18009
- if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
18010
- if (source.length === 0) { return '' }
18011
- // Skip & count leading zeroes.
18012
- var zeroes = 0;
18013
- var length = 0;
18014
- var pbegin = 0;
18015
- var pend = source.length;
18016
- while (pbegin !== pend && source[pbegin] === 0) {
18017
- pbegin++;
18018
- zeroes++;
18019
- }
18020
- // Allocate enough space in big-endian base58 representation.
18021
- var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
18022
- var b58 = new Uint8Array(size);
18023
- // Process the bytes.
18024
- while (pbegin !== pend) {
18025
- var carry = source[pbegin];
18026
- // Apply "b58 = b58 * 256 + ch".
18027
- var i = 0;
18028
- for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
18029
- carry += (256 * b58[it1]) >>> 0;
18030
- b58[it1] = (carry % BASE) >>> 0;
18031
- carry = (carry / BASE) >>> 0;
18032
- }
18033
- if (carry !== 0) { throw new Error('Non-zero carry') }
18034
- length = i;
18035
- pbegin++;
18036
- }
18037
- // Skip leading zeroes in base58 result.
18038
- var it2 = size - length;
18039
- while (it2 !== size && b58[it2] === 0) {
18040
- it2++;
18041
- }
18042
- // Translate the result into a string.
18043
- var str = LEADER.repeat(zeroes);
18044
- for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
18045
- return str
18046
- }
18047
- function decodeUnsafe (source) {
18048
- if (typeof source !== 'string') { throw new TypeError('Expected String') }
18049
- if (source.length === 0) { return new Uint8Array() }
18050
- var psz = 0;
18051
- // Skip leading spaces.
18052
- if (source[psz] === ' ') { return }
18053
- // Skip and count leading '1's.
18054
- var zeroes = 0;
18055
- var length = 0;
18056
- while (source[psz] === LEADER) {
18057
- zeroes++;
18058
- psz++;
18059
- }
18060
- // Allocate enough space in big-endian base256 representation.
18061
- var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
18062
- var b256 = new Uint8Array(size);
18063
- // Process the characters.
18064
- while (source[psz]) {
18065
- // Decode character
18066
- var carry = BASE_MAP[source.charCodeAt(psz)];
18067
- // Invalid character
18068
- if (carry === 255) { return }
18069
- var i = 0;
18070
- for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
18071
- carry += (BASE * b256[it3]) >>> 0;
18072
- b256[it3] = (carry % 256) >>> 0;
18073
- carry = (carry / 256) >>> 0;
18074
- }
18075
- if (carry !== 0) { throw new Error('Non-zero carry') }
18076
- length = i;
18077
- psz++;
18078
- }
18079
- // Skip trailing spaces.
18080
- if (source[psz] === ' ') { return }
18081
- // Skip leading zeroes in b256.
18082
- var it4 = size - length;
18083
- while (it4 !== size && b256[it4] === 0) {
18084
- it4++;
18085
- }
18086
- var vch = new Uint8Array(zeroes + (size - it4));
18087
- var j = zeroes;
18088
- while (it4 !== size) {
18089
- vch[j++] = b256[it4++];
18090
- }
18091
- return vch
18092
- }
18093
- function decode (string) {
18094
- var buffer = decodeUnsafe(string);
18095
- if (buffer) { return buffer }
18096
- throw new Error(`Non-${name} character`)
18097
- }
18098
- return {
18099
- encode: encode,
18100
- decodeUnsafe: decodeUnsafe,
18101
- decode: decode
18102
- }
18103
- }
18104
- var src = base;
18105
-
18106
- var _brrp__multiformats_scope_baseX = src;
18107
-
18108
- /**
18109
- * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o
18110
- * @returns {Uint8Array}
18111
- */
18112
- const coerce = o => {
18113
- if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o
18114
- if (o instanceof ArrayBuffer) return new Uint8Array(o)
18115
- if (ArrayBuffer.isView(o)) {
18116
- return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)
18117
- }
18118
- throw new Error('Unknown type, must be binary type')
18119
- };
18120
-
18121
- /**
18122
- * Class represents both BaseEncoder and MultibaseEncoder meaning it
18123
- * can be used to encode to multibase or base encode without multibase
18124
- * prefix.
18125
- *
18126
- * @class
18127
- * @template {string} Base
18128
- * @template {string} Prefix
18129
- * @implements {API.MultibaseEncoder<Prefix>}
18130
- * @implements {API.BaseEncoder}
18131
- */
18132
- class Encoder {
18133
- /**
18134
- * @param {Base} name
18135
- * @param {Prefix} prefix
18136
- * @param {(bytes:Uint8Array) => string} baseEncode
18137
- */
18138
- constructor (name, prefix, baseEncode) {
18139
- this.name = name;
18140
- this.prefix = prefix;
18141
- this.baseEncode = baseEncode;
18142
- }
18143
-
18144
- /**
18145
- * @param {Uint8Array} bytes
18146
- * @returns {API.Multibase<Prefix>}
18147
- */
18148
- encode (bytes) {
18149
- if (bytes instanceof Uint8Array) {
18150
- return `${this.prefix}${this.baseEncode(bytes)}`
18151
- } else {
18152
- throw Error('Unknown type, must be binary type')
18153
- }
18154
- }
18155
- }
18156
-
18157
- /**
18158
- * @template {string} Prefix
18159
- */
18160
18078
  /**
18161
- * Class represents both BaseDecoder and MultibaseDecoder so it could be used
18162
- * to decode multibases (with matching prefix) or just base decode strings
18163
- * with corresponding base encoding.
18079
+ * On the producing side:
18080
+ * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.
18164
18081
  *
18165
- * @class
18166
- * @template {string} Base
18167
- * @template {string} Prefix
18168
- * @implements {API.MultibaseDecoder<Prefix>}
18169
- * @implements {API.UnibaseDecoder<Prefix>}
18170
- * @implements {API.BaseDecoder}
18171
- */
18172
- class Decoder {
18173
- /**
18174
- * @param {Base} name
18175
- * @param {Prefix} prefix
18176
- * @param {(text:string) => Uint8Array} baseDecode
18177
- */
18178
- constructor (name, prefix, baseDecode) {
18179
- this.name = name;
18180
- this.prefix = prefix;
18181
- /* c8 ignore next 3 */
18182
- if (prefix.codePointAt(0) === undefined) {
18183
- throw new Error('Invalid prefix character')
18184
- }
18185
- /** @private */
18186
- this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0));
18187
- this.baseDecode = baseDecode;
18188
- }
18189
-
18190
- /**
18191
- * @param {string} text
18192
- */
18193
- decode (text) {
18194
- if (typeof text === 'string') {
18195
- if (text.codePointAt(0) !== this.prefixCodePoint) {
18196
- throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)
18197
- }
18198
- return this.baseDecode(text.slice(this.prefix.length))
18199
- } else {
18200
- throw Error('Can only multibase decode strings')
18201
- }
18202
- }
18203
-
18204
- /**
18205
- * @template {string} OtherPrefix
18206
- * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
18207
- * @returns {ComposedDecoder<Prefix|OtherPrefix>}
18208
- */
18209
- or (decoder) {
18210
- return or(this, decoder)
18211
- }
18212
- }
18213
-
18214
- /**
18215
- * @template {string} Prefix
18216
- * @typedef {Record<Prefix, API.UnibaseDecoder<Prefix>>} Decoders
18217
- */
18218
-
18219
- /**
18220
- * @template {string} Prefix
18221
- * @implements {API.MultibaseDecoder<Prefix>}
18222
- * @implements {API.CombobaseDecoder<Prefix>}
18223
- */
18224
- class ComposedDecoder {
18225
- /**
18226
- * @param {Decoders<Prefix>} decoders
18227
- */
18228
- constructor (decoders) {
18229
- this.decoders = decoders;
18230
- }
18231
-
18232
- /**
18233
- * @template {string} OtherPrefix
18234
- * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
18235
- * @returns {ComposedDecoder<Prefix|OtherPrefix>}
18236
- */
18237
- or (decoder) {
18238
- return or(this, decoder)
18239
- }
18240
-
18241
- /**
18242
- * @param {string} input
18243
- * @returns {Uint8Array}
18244
- */
18245
- decode (input) {
18246
- const prefix = /** @type {Prefix} */ (input[0]);
18247
- const decoder = this.decoders[prefix];
18248
- if (decoder) {
18249
- return decoder.decode(input)
18250
- } else {
18251
- throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)
18252
- }
18253
- }
18254
- }
18255
-
18256
- /**
18257
- * @template {string} L
18258
- * @template {string} R
18259
- * @param {API.UnibaseDecoder<L>|API.CombobaseDecoder<L>} left
18260
- * @param {API.UnibaseDecoder<R>|API.CombobaseDecoder<R>} right
18261
- * @returns {ComposedDecoder<L|R>}
18262
- */
18263
- const or = (left, right) => new ComposedDecoder(/** @type {Decoders<L|R>} */({
18264
- ...(left.decoders || { [/** @type API.UnibaseDecoder<L> */(left).prefix]: left }),
18265
- ...(right.decoders || { [/** @type API.UnibaseDecoder<R> */(right).prefix]: right })
18266
- }));
18267
-
18268
- /**
18269
- * @class
18270
- * @template {string} Base
18271
- * @template {string} Prefix
18272
- * @implements {API.MultibaseCodec<Prefix>}
18273
- * @implements {API.MultibaseEncoder<Prefix>}
18274
- * @implements {API.MultibaseDecoder<Prefix>}
18275
- * @implements {API.BaseCodec}
18276
- * @implements {API.BaseEncoder}
18277
- * @implements {API.BaseDecoder}
18278
- */
18279
- class Codec {
18280
- /**
18281
- * @param {Base} name
18282
- * @param {Prefix} prefix
18283
- * @param {(bytes:Uint8Array) => string} baseEncode
18284
- * @param {(text:string) => Uint8Array} baseDecode
18285
- */
18286
- constructor (name, prefix, baseEncode, baseDecode) {
18287
- this.name = name;
18288
- this.prefix = prefix;
18289
- this.baseEncode = baseEncode;
18290
- this.baseDecode = baseDecode;
18291
- this.encoder = new Encoder(name, prefix, baseEncode);
18292
- this.decoder = new Decoder(name, prefix, baseDecode);
18293
- }
18294
-
18295
- /**
18296
- * @param {Uint8Array} input
18297
- */
18298
- encode (input) {
18299
- return this.encoder.encode(input)
18300
- }
18301
-
18302
- /**
18303
- * @param {string} input
18304
- */
18305
- decode (input) {
18306
- return this.decoder.decode(input)
18307
- }
18308
- }
18309
-
18310
- /**
18311
- * @template {string} Base
18312
- * @template {string} Prefix
18313
- * @param {object} options
18314
- * @param {Base} options.name
18315
- * @param {Prefix} options.prefix
18316
- * @param {(bytes:Uint8Array) => string} options.encode
18317
- * @param {(input:string) => Uint8Array} options.decode
18318
- * @returns {Codec<Base, Prefix>}
18082
+ * On the consuming side:
18083
+ * * Enforce the fields to be present, reject otherwise.
18084
+ * * Propagate only if the fields are valid and signature can be verified, reject otherwise.
18319
18085
  */
18320
- const from = ({ name, prefix, encode, decode }) =>
18321
- new Codec(name, prefix, encode, decode);
18322
-
18323
- /**
18324
- * @template {string} Base
18325
- * @template {string} Prefix
18326
- * @param {object} options
18327
- * @param {Base} options.name
18328
- * @param {Prefix} options.prefix
18329
- * @param {string} options.alphabet
18330
- * @returns {Codec<Base, Prefix>}
18331
- */
18332
- const baseX = ({ prefix, name, alphabet }) => {
18333
- const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name);
18334
- return from({
18335
- prefix,
18336
- name,
18337
- encode,
18086
+ var TopicValidatorResult;
18087
+ (function (TopicValidatorResult) {
18338
18088
  /**
18339
- * @param {string} text
18089
+ * The message is considered valid, and it should be delivered and forwarded to the network
18340
18090
  */
18341
- decode: text => coerce(decode(text))
18342
- })
18343
- };
18091
+ TopicValidatorResult["Accept"] = "accept";
18092
+ /**
18093
+ * The message is neither delivered nor forwarded to the network
18094
+ */
18095
+ TopicValidatorResult["Ignore"] = "ignore";
18096
+ /**
18097
+ * The message is considered invalid, and it should be rejected
18098
+ */
18099
+ TopicValidatorResult["Reject"] = "reject";
18100
+ })(TopicValidatorResult || (TopicValidatorResult = {}));
18344
18101
 
18345
18102
  /**
18346
- * @param {string} string
18347
- * @param {string} alphabet
18348
- * @param {number} bitsPerChar
18349
- * @param {string} name
18350
- * @returns {Uint8Array}
18103
+ * Enum Transport Manager Fault Tolerance values
18351
18104
  */
18352
- const decode$1 = (string, alphabet, bitsPerChar, name) => {
18353
- // Build the character lookup table:
18354
- /** @type {Record<string, number>} */
18355
- const codes = {};
18356
- for (let i = 0; i < alphabet.length; ++i) {
18357
- codes[alphabet[i]] = i;
18358
- }
18359
-
18360
- // Count the padding bytes:
18361
- let end = string.length;
18362
- while (string[end - 1] === '=') {
18363
- --end;
18364
- }
18365
-
18366
- // Allocate the output:
18367
- const out = new Uint8Array((end * bitsPerChar / 8) | 0);
18368
-
18369
- // Parse the data:
18370
- let bits = 0; // Number of bits currently in the buffer
18371
- let buffer = 0; // Bits waiting to be written out, MSB first
18372
- let written = 0; // Next byte to write
18373
- for (let i = 0; i < end; ++i) {
18374
- // Read one character from the string:
18375
- const value = codes[string[i]];
18376
- if (value === undefined) {
18377
- throw new SyntaxError(`Non-${name} character`)
18378
- }
18379
-
18380
- // Append the bits to the buffer:
18381
- buffer = (buffer << bitsPerChar) | value;
18382
- bits += bitsPerChar;
18383
-
18384
- // Write out some bits if the buffer has a byte's worth:
18385
- if (bits >= 8) {
18386
- bits -= 8;
18387
- out[written++] = 0xff & (buffer >> bits);
18388
- }
18389
- }
18390
-
18391
- // Verify that we have received just enough bits:
18392
- if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {
18393
- throw new SyntaxError('Unexpected end of data')
18394
- }
18395
-
18396
- return out
18397
- };
18398
-
18399
- /**
18400
- * @param {Uint8Array} data
18401
- * @param {string} alphabet
18402
- * @param {number} bitsPerChar
18403
- * @returns {string}
18404
- */
18405
- const encode$1 = (data, alphabet, bitsPerChar) => {
18406
- const pad = alphabet[alphabet.length - 1] === '=';
18407
- const mask = (1 << bitsPerChar) - 1;
18408
- let out = '';
18409
-
18410
- let bits = 0; // Number of bits currently in the buffer
18411
- let buffer = 0; // Bits waiting to be written out, MSB first
18412
- for (let i = 0; i < data.length; ++i) {
18413
- // Slurp data into the buffer:
18414
- buffer = (buffer << 8) | data[i];
18415
- bits += 8;
18416
-
18417
- // Write out as much as we can:
18418
- while (bits > bitsPerChar) {
18419
- bits -= bitsPerChar;
18420
- out += alphabet[mask & (buffer >> bits)];
18421
- }
18422
- }
18423
-
18424
- // Partial character:
18425
- if (bits) {
18426
- out += alphabet[mask & (buffer << (bitsPerChar - bits))];
18427
- }
18428
-
18429
- // Add padding characters until we hit a byte boundary:
18430
- if (pad) {
18431
- while ((out.length * bitsPerChar) & 7) {
18432
- out += '=';
18433
- }
18434
- }
18435
-
18436
- return out
18437
- };
18438
-
18439
- /**
18440
- * RFC4648 Factory
18441
- *
18442
- * @template {string} Base
18443
- * @template {string} Prefix
18444
- * @param {object} options
18445
- * @param {Base} options.name
18446
- * @param {Prefix} options.prefix
18447
- * @param {string} options.alphabet
18448
- * @param {number} options.bitsPerChar
18449
- */
18450
- const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {
18451
- return from({
18452
- prefix,
18453
- name,
18454
- encode (input) {
18455
- return encode$1(input, alphabet, bitsPerChar)
18456
- },
18457
- decode (input) {
18458
- return decode$1(input, alphabet, bitsPerChar, name)
18459
- }
18460
- })
18461
- };
18462
-
18463
- baseX({
18464
- name: 'base58btc',
18465
- prefix: 'z',
18466
- alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
18467
- });
18468
-
18469
- baseX({
18470
- name: 'base58flickr',
18471
- prefix: 'Z',
18472
- alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
18473
- });
18474
-
18475
- /*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
18476
- const _0n = BigInt(0);
18477
- const _1n = BigInt(1);
18478
- const _2n = BigInt(2);
18479
- const _8n = BigInt(8);
18480
- const CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989');
18481
- const CURVE = Object.freeze({
18482
- a: BigInt(-1),
18483
- d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
18484
- P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'),
18485
- l: CU_O,
18486
- n: CU_O,
18487
- h: BigInt(8),
18488
- Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
18489
- Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
18490
- });
18491
- const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
18492
- const SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
18493
- BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742');
18494
- const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
18495
- const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
18496
- const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
18497
- const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
18498
- class ExtendedPoint {
18499
- constructor(x, y, z, t) {
18500
- this.x = x;
18501
- this.y = y;
18502
- this.z = z;
18503
- this.t = t;
18504
- }
18505
- static fromAffine(p) {
18506
- if (!(p instanceof Point)) {
18507
- throw new TypeError('ExtendedPoint#fromAffine: expected Point');
18508
- }
18509
- if (p.equals(Point.ZERO))
18510
- return ExtendedPoint.ZERO;
18511
- return new ExtendedPoint(p.x, p.y, _1n, mod(p.x * p.y));
18512
- }
18513
- static toAffineBatch(points) {
18514
- const toInv = invertBatch(points.map((p) => p.z));
18515
- return points.map((p, i) => p.toAffine(toInv[i]));
18516
- }
18517
- static normalizeZ(points) {
18518
- return this.toAffineBatch(points).map(this.fromAffine);
18519
- }
18520
- equals(other) {
18521
- assertExtPoint(other);
18522
- const { x: X1, y: Y1, z: Z1 } = this;
18523
- const { x: X2, y: Y2, z: Z2 } = other;
18524
- const X1Z2 = mod(X1 * Z2);
18525
- const X2Z1 = mod(X2 * Z1);
18526
- const Y1Z2 = mod(Y1 * Z2);
18527
- const Y2Z1 = mod(Y2 * Z1);
18528
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
18529
- }
18530
- negate() {
18531
- return new ExtendedPoint(mod(-this.x), this.y, this.z, mod(-this.t));
18532
- }
18533
- double() {
18534
- const { x: X1, y: Y1, z: Z1 } = this;
18535
- const { a } = CURVE;
18536
- const A = mod(X1 * X1);
18537
- const B = mod(Y1 * Y1);
18538
- const C = mod(_2n * mod(Z1 * Z1));
18539
- const D = mod(a * A);
18540
- const x1y1 = X1 + Y1;
18541
- const E = mod(mod(x1y1 * x1y1) - A - B);
18542
- const G = D + B;
18543
- const F = G - C;
18544
- const H = D - B;
18545
- const X3 = mod(E * F);
18546
- const Y3 = mod(G * H);
18547
- const T3 = mod(E * H);
18548
- const Z3 = mod(F * G);
18549
- return new ExtendedPoint(X3, Y3, Z3, T3);
18550
- }
18551
- add(other) {
18552
- assertExtPoint(other);
18553
- const { x: X1, y: Y1, z: Z1, t: T1 } = this;
18554
- const { x: X2, y: Y2, z: Z2, t: T2 } = other;
18555
- const A = mod((Y1 - X1) * (Y2 + X2));
18556
- const B = mod((Y1 + X1) * (Y2 - X2));
18557
- const F = mod(B - A);
18558
- if (F === _0n)
18559
- return this.double();
18560
- const C = mod(Z1 * _2n * T2);
18561
- const D = mod(T1 * _2n * Z2);
18562
- const E = D + C;
18563
- const G = B + A;
18564
- const H = D - C;
18565
- const X3 = mod(E * F);
18566
- const Y3 = mod(G * H);
18567
- const T3 = mod(E * H);
18568
- const Z3 = mod(F * G);
18569
- return new ExtendedPoint(X3, Y3, Z3, T3);
18570
- }
18571
- subtract(other) {
18572
- return this.add(other.negate());
18573
- }
18574
- precomputeWindow(W) {
18575
- const windows = 1 + 256 / W;
18576
- const points = [];
18577
- let p = this;
18578
- let base = p;
18579
- for (let window = 0; window < windows; window++) {
18580
- base = p;
18581
- points.push(base);
18582
- for (let i = 1; i < 2 ** (W - 1); i++) {
18583
- base = base.add(p);
18584
- points.push(base);
18585
- }
18586
- p = base.double();
18587
- }
18588
- return points;
18589
- }
18590
- wNAF(n, affinePoint) {
18591
- if (!affinePoint && this.equals(ExtendedPoint.BASE))
18592
- affinePoint = Point.BASE;
18593
- const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;
18594
- if (256 % W) {
18595
- throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');
18596
- }
18597
- let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
18598
- if (!precomputes) {
18599
- precomputes = this.precomputeWindow(W);
18600
- if (affinePoint && W !== 1) {
18601
- precomputes = ExtendedPoint.normalizeZ(precomputes);
18602
- pointPrecomputes.set(affinePoint, precomputes);
18603
- }
18604
- }
18605
- let p = ExtendedPoint.ZERO;
18606
- let f = ExtendedPoint.BASE;
18607
- const windows = 1 + 256 / W;
18608
- const windowSize = 2 ** (W - 1);
18609
- const mask = BigInt(2 ** W - 1);
18610
- const maxNumber = 2 ** W;
18611
- const shiftBy = BigInt(W);
18612
- for (let window = 0; window < windows; window++) {
18613
- const offset = window * windowSize;
18614
- let wbits = Number(n & mask);
18615
- n >>= shiftBy;
18616
- if (wbits > windowSize) {
18617
- wbits -= maxNumber;
18618
- n += _1n;
18619
- }
18620
- const offset1 = offset;
18621
- const offset2 = offset + Math.abs(wbits) - 1;
18622
- const cond1 = window % 2 !== 0;
18623
- const cond2 = wbits < 0;
18624
- if (wbits === 0) {
18625
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
18626
- }
18627
- else {
18628
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
18629
- }
18630
- }
18631
- return ExtendedPoint.normalizeZ([p, f])[0];
18632
- }
18633
- multiply(scalar, affinePoint) {
18634
- return this.wNAF(normalizeScalar(scalar, CURVE.l), affinePoint);
18635
- }
18636
- multiplyUnsafe(scalar) {
18637
- let n = normalizeScalar(scalar, CURVE.l, false);
18638
- const G = ExtendedPoint.BASE;
18639
- const P0 = ExtendedPoint.ZERO;
18640
- if (n === _0n)
18641
- return P0;
18642
- if (this.equals(P0) || n === _1n)
18643
- return this;
18644
- if (this.equals(G))
18645
- return this.wNAF(n);
18646
- let p = P0;
18647
- let d = this;
18648
- while (n > _0n) {
18649
- if (n & _1n)
18650
- p = p.add(d);
18651
- d = d.double();
18652
- n >>= _1n;
18653
- }
18654
- return p;
18655
- }
18656
- isSmallOrder() {
18657
- return this.multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);
18658
- }
18659
- isTorsionFree() {
18660
- let p = this.multiplyUnsafe(CURVE.l / _2n).double();
18661
- if (CURVE.l % _2n)
18662
- p = p.add(this);
18663
- return p.equals(ExtendedPoint.ZERO);
18664
- }
18665
- toAffine(invZ) {
18666
- const { x, y, z } = this;
18667
- const is0 = this.equals(ExtendedPoint.ZERO);
18668
- if (invZ == null)
18669
- invZ = is0 ? _8n : invert(z);
18670
- const ax = mod(x * invZ);
18671
- const ay = mod(y * invZ);
18672
- const zz = mod(z * invZ);
18673
- if (is0)
18674
- return Point.ZERO;
18675
- if (zz !== _1n)
18676
- throw new Error('invZ was invalid');
18677
- return new Point(ax, ay);
18678
- }
18679
- fromRistrettoBytes() {
18680
- legacyRist();
18681
- }
18682
- toRistrettoBytes() {
18683
- legacyRist();
18684
- }
18685
- fromRistrettoHash() {
18686
- legacyRist();
18687
- }
18688
- }
18689
- ExtendedPoint.BASE = new ExtendedPoint(CURVE.Gx, CURVE.Gy, _1n, mod(CURVE.Gx * CURVE.Gy));
18690
- ExtendedPoint.ZERO = new ExtendedPoint(_0n, _1n, _1n, _0n);
18691
- function constTimeNegate(condition, item) {
18692
- const neg = item.negate();
18693
- return condition ? neg : item;
18694
- }
18695
- function assertExtPoint(other) {
18696
- if (!(other instanceof ExtendedPoint))
18697
- throw new TypeError('ExtendedPoint expected');
18698
- }
18699
- function assertRstPoint(other) {
18700
- if (!(other instanceof RistrettoPoint))
18701
- throw new TypeError('RistrettoPoint expected');
18702
- }
18703
- function legacyRist() {
18704
- throw new Error('Legacy method: switch to RistrettoPoint');
18705
- }
18706
- class RistrettoPoint {
18707
- constructor(ep) {
18708
- this.ep = ep;
18709
- }
18710
- static calcElligatorRistrettoMap(r0) {
18711
- const { d } = CURVE;
18712
- const r = mod(SQRT_M1 * r0 * r0);
18713
- const Ns = mod((r + _1n) * ONE_MINUS_D_SQ);
18714
- let c = BigInt(-1);
18715
- const D = mod((c - d * r) * mod(r + d));
18716
- let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
18717
- let s_ = mod(s * r0);
18718
- if (!edIsNegative(s_))
18719
- s_ = mod(-s_);
18720
- if (!Ns_D_is_sq)
18721
- s = s_;
18722
- if (!Ns_D_is_sq)
18723
- c = r;
18724
- const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D);
18725
- const s2 = s * s;
18726
- const W0 = mod((s + s) * D);
18727
- const W1 = mod(Nt * SQRT_AD_MINUS_ONE);
18728
- const W2 = mod(_1n - s2);
18729
- const W3 = mod(_1n + s2);
18730
- return new ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
18731
- }
18732
- static hashToCurve(hex) {
18733
- hex = ensureBytes(hex, 64);
18734
- const r1 = bytes255ToNumberLE(hex.slice(0, 32));
18735
- const R1 = this.calcElligatorRistrettoMap(r1);
18736
- const r2 = bytes255ToNumberLE(hex.slice(32, 64));
18737
- const R2 = this.calcElligatorRistrettoMap(r2);
18738
- return new RistrettoPoint(R1.add(R2));
18739
- }
18740
- static fromHex(hex) {
18741
- hex = ensureBytes(hex, 32);
18742
- const { a, d } = CURVE;
18743
- const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';
18744
- const s = bytes255ToNumberLE(hex);
18745
- if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s))
18746
- throw new Error(emsg);
18747
- const s2 = mod(s * s);
18748
- const u1 = mod(_1n + a * s2);
18749
- const u2 = mod(_1n - a * s2);
18750
- const u1_2 = mod(u1 * u1);
18751
- const u2_2 = mod(u2 * u2);
18752
- const v = mod(a * d * u1_2 - u2_2);
18753
- const { isValid, value: I } = invertSqrt(mod(v * u2_2));
18754
- const Dx = mod(I * u2);
18755
- const Dy = mod(I * Dx * v);
18756
- let x = mod((s + s) * Dx);
18757
- if (edIsNegative(x))
18758
- x = mod(-x);
18759
- const y = mod(u1 * Dy);
18760
- const t = mod(x * y);
18761
- if (!isValid || edIsNegative(t) || y === _0n)
18762
- throw new Error(emsg);
18763
- return new RistrettoPoint(new ExtendedPoint(x, y, _1n, t));
18764
- }
18765
- toRawBytes() {
18766
- let { x, y, z, t } = this.ep;
18767
- const u1 = mod(mod(z + y) * mod(z - y));
18768
- const u2 = mod(x * y);
18769
- const u2sq = mod(u2 * u2);
18770
- const { value: invsqrt } = invertSqrt(mod(u1 * u2sq));
18771
- const D1 = mod(invsqrt * u1);
18772
- const D2 = mod(invsqrt * u2);
18773
- const zInv = mod(D1 * D2 * t);
18774
- let D;
18775
- if (edIsNegative(t * zInv)) {
18776
- let _x = mod(y * SQRT_M1);
18777
- let _y = mod(x * SQRT_M1);
18778
- x = _x;
18779
- y = _y;
18780
- D = mod(D1 * INVSQRT_A_MINUS_D);
18781
- }
18782
- else {
18783
- D = D2;
18784
- }
18785
- if (edIsNegative(x * zInv))
18786
- y = mod(-y);
18787
- let s = mod((z - y) * D);
18788
- if (edIsNegative(s))
18789
- s = mod(-s);
18790
- return numberTo32BytesLE(s);
18791
- }
18792
- toHex() {
18793
- return bytesToHex(this.toRawBytes());
18794
- }
18795
- toString() {
18796
- return this.toHex();
18797
- }
18798
- equals(other) {
18799
- assertRstPoint(other);
18800
- const a = this.ep;
18801
- const b = other.ep;
18802
- const one = mod(a.x * b.y) === mod(a.y * b.x);
18803
- const two = mod(a.y * b.y) === mod(a.x * b.x);
18804
- return one || two;
18805
- }
18806
- add(other) {
18807
- assertRstPoint(other);
18808
- return new RistrettoPoint(this.ep.add(other.ep));
18809
- }
18810
- subtract(other) {
18811
- assertRstPoint(other);
18812
- return new RistrettoPoint(this.ep.subtract(other.ep));
18813
- }
18814
- multiply(scalar) {
18815
- return new RistrettoPoint(this.ep.multiply(scalar));
18816
- }
18817
- multiplyUnsafe(scalar) {
18818
- return new RistrettoPoint(this.ep.multiplyUnsafe(scalar));
18819
- }
18820
- }
18821
- RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE);
18822
- RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO);
18823
- const pointPrecomputes = new WeakMap();
18824
- class Point {
18825
- constructor(x, y) {
18826
- this.x = x;
18827
- this.y = y;
18828
- }
18829
- _setWindowSize(windowSize) {
18830
- this._WINDOW_SIZE = windowSize;
18831
- pointPrecomputes.delete(this);
18832
- }
18833
- static fromHex(hex, strict = true) {
18834
- const { d, P } = CURVE;
18835
- hex = ensureBytes(hex, 32);
18836
- const normed = hex.slice();
18837
- normed[31] = hex[31] & ~0x80;
18838
- const y = bytesToNumberLE(normed);
18839
- if (strict && y >= P)
18840
- throw new Error('Expected 0 < hex < P');
18841
- if (!strict && y >= POW_2_256)
18842
- throw new Error('Expected 0 < hex < 2**256');
18843
- const y2 = mod(y * y);
18844
- const u = mod(y2 - _1n);
18845
- const v = mod(d * y2 + _1n);
18846
- let { isValid, value: x } = uvRatio(u, v);
18847
- if (!isValid)
18848
- throw new Error('Point.fromHex: invalid y coordinate');
18849
- const isXOdd = (x & _1n) === _1n;
18850
- const isLastByteOdd = (hex[31] & 0x80) !== 0;
18851
- if (isLastByteOdd !== isXOdd) {
18852
- x = mod(-x);
18853
- }
18854
- return new Point(x, y);
18855
- }
18856
- static async fromPrivateKey(privateKey) {
18857
- return (await getExtendedPublicKey(privateKey)).point;
18858
- }
18859
- toRawBytes() {
18860
- const bytes = numberTo32BytesLE(this.y);
18861
- bytes[31] |= this.x & _1n ? 0x80 : 0;
18862
- return bytes;
18863
- }
18864
- toHex() {
18865
- return bytesToHex(this.toRawBytes());
18866
- }
18867
- toX25519() {
18868
- const { y } = this;
18869
- const u = mod((_1n + y) * invert(_1n - y));
18870
- return numberTo32BytesLE(u);
18871
- }
18872
- isTorsionFree() {
18873
- return ExtendedPoint.fromAffine(this).isTorsionFree();
18874
- }
18875
- equals(other) {
18876
- return this.x === other.x && this.y === other.y;
18877
- }
18878
- negate() {
18879
- return new Point(mod(-this.x), this.y);
18880
- }
18881
- add(other) {
18882
- return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine();
18883
- }
18884
- subtract(other) {
18885
- return this.add(other.negate());
18886
- }
18887
- multiply(scalar) {
18888
- return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine();
18889
- }
18890
- }
18891
- Point.BASE = new Point(CURVE.Gx, CURVE.Gy);
18892
- Point.ZERO = new Point(_0n, _1n);
18893
- function concatBytes(...arrays) {
18894
- if (!arrays.every((a) => a instanceof Uint8Array))
18895
- throw new Error('Expected Uint8Array list');
18896
- if (arrays.length === 1)
18897
- return arrays[0];
18898
- const length = arrays.reduce((a, arr) => a + arr.length, 0);
18899
- const result = new Uint8Array(length);
18900
- for (let i = 0, pad = 0; i < arrays.length; i++) {
18901
- const arr = arrays[i];
18902
- result.set(arr, pad);
18903
- pad += arr.length;
18904
- }
18905
- return result;
18906
- }
18907
- const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
18908
- function bytesToHex(uint8a) {
18909
- if (!(uint8a instanceof Uint8Array))
18910
- throw new Error('Uint8Array expected');
18911
- let hex = '';
18912
- for (let i = 0; i < uint8a.length; i++) {
18913
- hex += hexes[uint8a[i]];
18914
- }
18915
- return hex;
18916
- }
18917
- function hexToBytes(hex) {
18918
- if (typeof hex !== 'string') {
18919
- throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
18920
- }
18921
- if (hex.length % 2)
18922
- throw new Error('hexToBytes: received invalid unpadded hex');
18923
- const array = new Uint8Array(hex.length / 2);
18924
- for (let i = 0; i < array.length; i++) {
18925
- const j = i * 2;
18926
- const hexByte = hex.slice(j, j + 2);
18927
- const byte = Number.parseInt(hexByte, 16);
18928
- if (Number.isNaN(byte) || byte < 0)
18929
- throw new Error('Invalid byte sequence');
18930
- array[i] = byte;
18931
- }
18932
- return array;
18933
- }
18934
- function numberTo32BytesBE(num) {
18935
- const length = 32;
18936
- const hex = num.toString(16).padStart(length * 2, '0');
18937
- return hexToBytes(hex);
18938
- }
18939
- function numberTo32BytesLE(num) {
18940
- return numberTo32BytesBE(num).reverse();
18941
- }
18942
- function edIsNegative(num) {
18943
- return (mod(num) & _1n) === _1n;
18944
- }
18945
- function bytesToNumberLE(uint8a) {
18946
- if (!(uint8a instanceof Uint8Array))
18947
- throw new Error('Expected Uint8Array');
18948
- return BigInt('0x' + bytesToHex(Uint8Array.from(uint8a).reverse()));
18949
- }
18950
- const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
18951
- function bytes255ToNumberLE(bytes) {
18952
- return mod(bytesToNumberLE(bytes) & MAX_255B);
18953
- }
18954
- function mod(a, b = CURVE.P) {
18955
- const res = a % b;
18956
- return res >= _0n ? res : b + res;
18957
- }
18958
- function invert(number, modulo = CURVE.P) {
18959
- if (number === _0n || modulo <= _0n) {
18960
- throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
18961
- }
18962
- let a = mod(number, modulo);
18963
- let b = modulo;
18964
- let x = _0n, u = _1n;
18965
- while (a !== _0n) {
18966
- const q = b / a;
18967
- const r = b % a;
18968
- const m = x - u * q;
18969
- b = a, a = r, x = u, u = m;
18970
- }
18971
- const gcd = b;
18972
- if (gcd !== _1n)
18973
- throw new Error('invert: does not exist');
18974
- return mod(x, modulo);
18975
- }
18976
- function invertBatch(nums, p = CURVE.P) {
18977
- const tmp = new Array(nums.length);
18978
- const lastMultiplied = nums.reduce((acc, num, i) => {
18979
- if (num === _0n)
18980
- return acc;
18981
- tmp[i] = acc;
18982
- return mod(acc * num, p);
18983
- }, _1n);
18984
- const inverted = invert(lastMultiplied, p);
18985
- nums.reduceRight((acc, num, i) => {
18986
- if (num === _0n)
18987
- return acc;
18988
- tmp[i] = mod(acc * tmp[i], p);
18989
- return mod(acc * num, p);
18990
- }, inverted);
18991
- return tmp;
18992
- }
18993
- function pow2(x, power) {
18994
- const { P } = CURVE;
18995
- let res = x;
18996
- while (power-- > _0n) {
18997
- res *= res;
18998
- res %= P;
18999
- }
19000
- return res;
19001
- }
19002
- function pow_2_252_3(x) {
19003
- const { P } = CURVE;
19004
- const _5n = BigInt(5);
19005
- const _10n = BigInt(10);
19006
- const _20n = BigInt(20);
19007
- const _40n = BigInt(40);
19008
- const _80n = BigInt(80);
19009
- const x2 = (x * x) % P;
19010
- const b2 = (x2 * x) % P;
19011
- const b4 = (pow2(b2, _2n) * b2) % P;
19012
- const b5 = (pow2(b4, _1n) * x) % P;
19013
- const b10 = (pow2(b5, _5n) * b5) % P;
19014
- const b20 = (pow2(b10, _10n) * b10) % P;
19015
- const b40 = (pow2(b20, _20n) * b20) % P;
19016
- const b80 = (pow2(b40, _40n) * b40) % P;
19017
- const b160 = (pow2(b80, _80n) * b80) % P;
19018
- const b240 = (pow2(b160, _80n) * b80) % P;
19019
- const b250 = (pow2(b240, _10n) * b10) % P;
19020
- const pow_p_5_8 = (pow2(b250, _2n) * x) % P;
19021
- return { pow_p_5_8, b2 };
19022
- }
19023
- function uvRatio(u, v) {
19024
- const v3 = mod(v * v * v);
19025
- const v7 = mod(v3 * v3 * v);
19026
- const pow = pow_2_252_3(u * v7).pow_p_5_8;
19027
- let x = mod(u * v3 * pow);
19028
- const vx2 = mod(v * x * x);
19029
- const root1 = x;
19030
- const root2 = mod(x * SQRT_M1);
19031
- const useRoot1 = vx2 === u;
19032
- const useRoot2 = vx2 === mod(-u);
19033
- const noRoot = vx2 === mod(-u * SQRT_M1);
19034
- if (useRoot1)
19035
- x = root1;
19036
- if (useRoot2 || noRoot)
19037
- x = root2;
19038
- if (edIsNegative(x))
19039
- x = mod(-x);
19040
- return { isValid: useRoot1 || useRoot2, value: x };
19041
- }
19042
- function invertSqrt(number) {
19043
- return uvRatio(_1n, number);
19044
- }
19045
- function modlLE(hash) {
19046
- return mod(bytesToNumberLE(hash), CURVE.l);
19047
- }
19048
- function equalBytes(b1, b2) {
19049
- if (b1.length !== b2.length) {
19050
- return false;
19051
- }
19052
- for (let i = 0; i < b1.length; i++) {
19053
- if (b1[i] !== b2[i]) {
19054
- return false;
19055
- }
19056
- }
19057
- return true;
19058
- }
19059
- function ensureBytes(hex, expectedLength) {
19060
- const bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);
19061
- if (typeof expectedLength === 'number' && bytes.length !== expectedLength)
19062
- throw new Error(`Expected ${expectedLength} bytes`);
19063
- return bytes;
19064
- }
19065
- function normalizeScalar(num, max, strict = true) {
19066
- if (!max)
19067
- throw new TypeError('Specify max value');
19068
- if (typeof num === 'number' && Number.isSafeInteger(num))
19069
- num = BigInt(num);
19070
- if (typeof num === 'bigint' && num < max) {
19071
- if (strict) {
19072
- if (_0n < num)
19073
- return num;
19074
- }
19075
- else {
19076
- if (_0n <= num)
19077
- return num;
19078
- }
19079
- }
19080
- throw new TypeError('Expected valid scalar: 0 < scalar < max');
19081
- }
19082
- function adjustBytes25519(bytes) {
19083
- bytes[0] &= 248;
19084
- bytes[31] &= 127;
19085
- bytes[31] |= 64;
19086
- return bytes;
19087
- }
19088
- function checkPrivateKey(key) {
19089
- key =
19090
- typeof key === 'bigint' || typeof key === 'number'
19091
- ? numberTo32BytesBE(normalizeScalar(key, POW_2_256))
19092
- : ensureBytes(key);
19093
- if (key.length !== 32)
19094
- throw new Error(`Expected 32 bytes`);
19095
- return key;
19096
- }
19097
- function getKeyFromHash(hashed) {
19098
- const head = adjustBytes25519(hashed.slice(0, 32));
19099
- const prefix = hashed.slice(32, 64);
19100
- const scalar = modlLE(head);
19101
- const point = Point.BASE.multiply(scalar);
19102
- const pointBytes = point.toRawBytes();
19103
- return { head, prefix, scalar, point, pointBytes };
19104
- }
19105
- let _sha512Sync;
19106
- async function getExtendedPublicKey(key) {
19107
- return getKeyFromHash(await utils.sha512(checkPrivateKey(key)));
19108
- }
19109
- Point.BASE._setWindowSize(8);
19110
- const crypto$1 = {
19111
- node: nodeCrypto,
19112
- web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,
19113
- };
19114
- const utils = {
19115
- bytesToHex,
19116
- hexToBytes,
19117
- concatBytes,
19118
- getExtendedPublicKey,
19119
- mod,
19120
- invert,
19121
- TORSION_SUBGROUP: [
19122
- '0100000000000000000000000000000000000000000000000000000000000000',
19123
- 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',
19124
- '0000000000000000000000000000000000000000000000000000000000000080',
19125
- '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',
19126
- 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',
19127
- '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',
19128
- '0000000000000000000000000000000000000000000000000000000000000000',
19129
- 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',
19130
- ],
19131
- hashToPrivateScalar: (hash) => {
19132
- hash = ensureBytes(hash);
19133
- if (hash.length < 40 || hash.length > 1024)
19134
- throw new Error('Expected 40-1024 bytes of private key as per FIPS 186');
19135
- return mod(bytesToNumberLE(hash), CURVE.l - _1n) + _1n;
19136
- },
19137
- randomBytes: (bytesLength = 32) => {
19138
- if (crypto$1.web) {
19139
- return crypto$1.web.getRandomValues(new Uint8Array(bytesLength));
19140
- }
19141
- else if (crypto$1.node) {
19142
- const { randomBytes } = crypto$1.node;
19143
- return new Uint8Array(randomBytes(bytesLength).buffer);
19144
- }
19145
- else {
19146
- throw new Error("The environment doesn't have randomBytes function");
19147
- }
19148
- },
19149
- randomPrivateKey: () => {
19150
- return utils.randomBytes(32);
19151
- },
19152
- sha512: async (...messages) => {
19153
- const message = concatBytes(...messages);
19154
- if (crypto$1.web) {
19155
- const buffer = await crypto$1.web.subtle.digest('SHA-512', message.buffer);
19156
- return new Uint8Array(buffer);
19157
- }
19158
- else if (crypto$1.node) {
19159
- return Uint8Array.from(crypto$1.node.createHash('sha512').update(message).digest());
19160
- }
19161
- else {
19162
- throw new Error("The environment doesn't have sha512 function");
19163
- }
19164
- },
19165
- precompute(windowSize = 8, point = Point.BASE) {
19166
- const cached = point.equals(Point.BASE) ? point : new Point(point.x, point.y);
19167
- cached._setWindowSize(windowSize);
19168
- cached.multiply(_2n);
19169
- return cached;
19170
- },
19171
- sha512Sync: undefined,
19172
- };
19173
- Object.defineProperties(utils, {
19174
- sha512Sync: {
19175
- configurable: false,
19176
- get() {
19177
- return _sha512Sync;
19178
- },
19179
- set(val) {
19180
- if (!_sha512Sync)
19181
- _sha512Sync = val;
19182
- },
19183
- },
19184
- });
19185
-
19186
- // @ts-check
19187
-
19188
-
19189
- rfc4648({
19190
- prefix: 'm',
19191
- name: 'base64',
19192
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
19193
- bitsPerChar: 6
19194
- });
19195
-
19196
- rfc4648({
19197
- prefix: 'M',
19198
- name: 'base64pad',
19199
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
19200
- bitsPerChar: 6
19201
- });
19202
-
19203
- rfc4648({
19204
- prefix: 'u',
19205
- name: 'base64url',
19206
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
19207
- bitsPerChar: 6
19208
- });
19209
-
19210
- rfc4648({
19211
- prefix: 'U',
19212
- name: 'base64urlpad',
19213
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
19214
- bitsPerChar: 6
19215
- });
18105
+ var FaultTolerance;
18106
+ (function (FaultTolerance) {
18107
+ /**
18108
+ * should be used for failing in any listen circumstance
18109
+ */
18110
+ FaultTolerance[FaultTolerance["FATAL_ALL"] = 0] = "FATAL_ALL";
18111
+ /**
18112
+ * should be used for not failing when not listening
18113
+ */
18114
+ FaultTolerance[FaultTolerance["NO_FATAL"] = 1] = "NO_FATAL";
18115
+ })(FaultTolerance || (FaultTolerance = {}));
19216
18116
 
19217
18117
  /* eslint-disable import/export */
19218
18118
  /* eslint-disable complexity */
@@ -19934,15 +18834,15 @@ const decodeRelayShard = (bytes) => {
19934
18834
  if (bytes.length < 3)
19935
18835
  throw new Error("Insufficient data");
19936
18836
  const view = new DataView(bytes.buffer);
19937
- const cluster = view.getUint16(0);
19938
- const indexList = [];
18837
+ const clusterId = view.getUint16(0);
18838
+ const shards = [];
19939
18839
  if (bytes.length === 130) {
19940
18840
  // rsv format (Bit Vector)
19941
18841
  for (let i = 0; i < 1024; i++) {
19942
18842
  const byteIndex = Math.floor(i / 8) + 2; // Adjusted for the 2-byte cluster field
19943
18843
  const bitIndex = 7 - (i % 8);
19944
18844
  if (view.getUint8(byteIndex) & (1 << bitIndex)) {
19945
- indexList.push(i);
18845
+ shards.push(i);
19946
18846
  }
19947
18847
  }
19948
18848
  }
@@ -19952,10 +18852,33 @@ const decodeRelayShard = (bytes) => {
19952
18852
  for (let i = 0, offset = 3; i < numIndices; i++, offset += 2) {
19953
18853
  if (offset + 1 >= bytes.length)
19954
18854
  throw new Error("Unexpected end of data");
19955
- indexList.push(view.getUint16(offset));
18855
+ shards.push(view.getUint16(offset));
19956
18856
  }
19957
18857
  }
19958
- return { cluster, indexList };
18858
+ return { clusterId, shards };
18859
+ };
18860
+ const encodeRelayShard = (shardInfo) => {
18861
+ const { clusterId, shards } = shardInfo;
18862
+ const totalLength = shards.length >= 64 ? 130 : 3 + 2 * shards.length;
18863
+ const buffer = new ArrayBuffer(totalLength);
18864
+ const view = new DataView(buffer);
18865
+ view.setUint16(0, clusterId);
18866
+ if (shards.length >= 64) {
18867
+ // rsv format (Bit Vector)
18868
+ for (const index of shards) {
18869
+ const byteIndex = Math.floor(index / 8) + 2; // Adjusted for the 2-byte cluster field
18870
+ const bitIndex = 7 - (index % 8);
18871
+ view.setUint8(byteIndex, view.getUint8(byteIndex) | (1 << bitIndex));
18872
+ }
18873
+ }
18874
+ else {
18875
+ // rs format (Index List)
18876
+ view.setUint8(2, shards.length);
18877
+ for (let i = 0, offset = 3; i < shards.length; i++, offset += 2) {
18878
+ view.setUint16(offset, shards[i]);
18879
+ }
18880
+ }
18881
+ return new Uint8Array(buffer);
19959
18882
  };
19960
18883
 
19961
18884
  new Logger("enr");
@@ -19975,7 +18898,7 @@ var TransportProtocolPerIpVersion;
19975
18898
  new Logger("enr:decoder");
19976
18899
 
19977
18900
  const RelayPingContentTopic = "/relay-ping/1/ping/null";
19978
- const log$6 = new Logger("keep-alive");
18901
+ const log$7 = new Logger("keep-alive");
19979
18902
  class KeepAliveManager {
19980
18903
  pingKeepAliveTimers;
19981
18904
  relayKeepAliveTimers;
@@ -20003,10 +18926,10 @@ class KeepAliveManager {
20003
18926
  // also update the peer store with the latency
20004
18927
  try {
20005
18928
  ping = await libp2pPing.ping(peerId);
20006
- log$6.info(`Ping succeeded (${peerIdStr})`, ping);
18929
+ log$7.info(`Ping succeeded (${peerIdStr})`, ping);
20007
18930
  }
20008
18931
  catch (error) {
20009
- log$6.error(`Ping failed for peer (${peerIdStr}).
18932
+ log$7.error(`Ping failed for peer (${peerIdStr}).
20010
18933
  Next ping will be attempted in ${pingPeriodSecs} seconds.
20011
18934
  `);
20012
18935
  return;
@@ -20014,16 +18937,16 @@ class KeepAliveManager {
20014
18937
  try {
20015
18938
  await peerStore.patch(peerId, {
20016
18939
  metadata: {
20017
- ping: utf8ToBytes$1(ping.toString())
18940
+ ping: utf8ToBytes(ping.toString())
20018
18941
  }
20019
18942
  });
20020
18943
  }
20021
18944
  catch (e) {
20022
- log$6.error("Failed to update ping", e);
18945
+ log$7.error("Failed to update ping", e);
20023
18946
  }
20024
18947
  }
20025
18948
  catch (e) {
20026
- log$6.error(`Ping failed (${peerIdStr})`, e);
18949
+ log$7.error(`Ping failed (${peerIdStr})`, e);
20027
18950
  }
20028
18951
  })();
20029
18952
  }, pingPeriodSecs * 1000);
@@ -20056,23 +18979,26 @@ class KeepAliveManager {
20056
18979
  this.pingKeepAliveTimers.clear();
20057
18980
  this.relayKeepAliveTimers.clear();
20058
18981
  }
18982
+ connectionsExist() {
18983
+ return (this.pingKeepAliveTimers.size > 0 || this.relayKeepAliveTimers.size > 0);
18984
+ }
20059
18985
  scheduleRelayPings(relay, relayPeriodSecs, peerIdStr) {
20060
- // send a ping message to each PubSubTopic the peer is part of
18986
+ // send a ping message to each PubsubTopic the peer is part of
20061
18987
  const intervals = [];
20062
18988
  for (const topic of relay.pubsubTopics) {
20063
18989
  const meshPeers = relay.getMeshPeers(topic);
20064
18990
  if (!meshPeers.includes(peerIdStr))
20065
18991
  continue;
20066
18992
  const encoder = createEncoder({
20067
- pubsubTopic: topic,
18993
+ pubsubTopicShardInfo: pubsubTopicToSingleShardInfo(topic),
20068
18994
  contentTopic: RelayPingContentTopic,
20069
18995
  ephemeral: true
20070
18996
  });
20071
18997
  const interval = setInterval(() => {
20072
- log$6.info("Sending Waku Relay ping message");
18998
+ log$7.info("Sending Waku Relay ping message");
20073
18999
  relay
20074
19000
  .send(encoder, { payload: new Uint8Array([1]) })
20075
- .catch((e) => log$6.error("Failed to send relay ping", e));
19001
+ .catch((e) => log$7.error("Failed to send relay ping", e));
20076
19002
  }, relayPeriodSecs * 1000);
20077
19003
  intervals.push(interval);
20078
19004
  }
@@ -20080,12 +19006,12 @@ class KeepAliveManager {
20080
19006
  }
20081
19007
  }
20082
19008
 
20083
- const log$5 = new Logger("connection-manager");
19009
+ const log$6 = new Logger("connection-manager");
20084
19010
  const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 1;
20085
19011
  const DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;
20086
19012
  const DEFAULT_MAX_PARALLEL_DIALS = 3;
20087
19013
  class ConnectionManager extends EventEmitter {
20088
- configuredPubSubTopics;
19014
+ configuredPubsubTopics;
20089
19015
  static instances = new Map();
20090
19016
  keepAliveManager;
20091
19017
  options;
@@ -20094,6 +19020,26 @@ class ConnectionManager extends EventEmitter {
20094
19020
  dialErrorsForPeer = new Map();
20095
19021
  currentActiveParallelDialCount = 0;
20096
19022
  pendingPeerDialQueue = [];
19023
+ online = false;
19024
+ isConnected() {
19025
+ return this.online;
19026
+ }
19027
+ toggleOnline() {
19028
+ if (!this.online) {
19029
+ this.online = true;
19030
+ this.dispatchEvent(new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {
19031
+ detail: this.online
19032
+ }));
19033
+ }
19034
+ }
19035
+ toggleOffline() {
19036
+ if (this.online && this.libp2p.getConnections().length == 0) {
19037
+ this.online = false;
19038
+ this.dispatchEvent(new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {
19039
+ detail: this.online
19040
+ }));
19041
+ }
19042
+ }
20097
19043
  static create(peerId, libp2p, keepAliveOptions, pubsubTopics, relay, options) {
20098
19044
  let instance = ConnectionManager.instances.get(peerId);
20099
19045
  if (!instance) {
@@ -20141,11 +19087,11 @@ class ConnectionManager extends EventEmitter {
20141
19087
  }
20142
19088
  };
20143
19089
  }
20144
- constructor(libp2p, keepAliveOptions, configuredPubSubTopics, relay, options) {
19090
+ constructor(libp2p, keepAliveOptions, configuredPubsubTopics, relay, options) {
20145
19091
  super();
20146
- this.configuredPubSubTopics = configuredPubSubTopics;
19092
+ this.configuredPubsubTopics = configuredPubsubTopics;
20147
19093
  this.libp2p = libp2p;
20148
- this.configuredPubSubTopics = configuredPubSubTopics;
19094
+ this.configuredPubsubTopics = configuredPubsubTopics;
20149
19095
  this.options = {
20150
19096
  maxDialAttemptsForPeer: DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER,
20151
19097
  maxBootstrapPeersAllowed: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,
@@ -20154,12 +19100,12 @@ class ConnectionManager extends EventEmitter {
20154
19100
  };
20155
19101
  this.keepAliveManager = new KeepAliveManager(keepAliveOptions, relay);
20156
19102
  this.run()
20157
- .then(() => log$5.info(`Connection Manager is now running`))
20158
- .catch((error) => log$5.error(`Unexpected error while running service`, error));
19103
+ .then(() => log$6.info(`Connection Manager is now running`))
19104
+ .catch((error) => log$6.error(`Unexpected error while running service`, error));
20159
19105
  // libp2p emits `peer:discovery` events during its initialization
20160
19106
  // which means that before the ConnectionManager is initialized, some peers may have been discovered
20161
19107
  // we will dial the peers in peerStore ONCE before we start to listen to the `peer:discovery` events within the ConnectionManager
20162
- this.dialPeerStorePeers().catch((error) => log$5.error(`Unexpected error while dialing peer store peers`, error));
19108
+ this.dialPeerStorePeers().catch((error) => log$6.error(`Unexpected error while dialing peer store peers`, error));
20163
19109
  }
20164
19110
  async dialPeerStorePeers() {
20165
19111
  const peerInfos = await this.libp2p.peerStore.all();
@@ -20173,7 +19119,7 @@ class ConnectionManager extends EventEmitter {
20173
19119
  await Promise.all(dialPromises);
20174
19120
  }
20175
19121
  catch (error) {
20176
- log$5.error(`Unexpected error while dialing peer store peers`, error);
19122
+ log$6.error(`Unexpected error while dialing peer store peers`, error);
20177
19123
  }
20178
19124
  }
20179
19125
  async run() {
@@ -20193,7 +19139,7 @@ class ConnectionManager extends EventEmitter {
20193
19139
  let dialAttempt = 0;
20194
19140
  while (dialAttempt < this.options.maxDialAttemptsForPeer) {
20195
19141
  try {
20196
- log$5.info(`Dialing peer ${peerId.toString()} on attempt ${dialAttempt + 1}`);
19142
+ log$6.info(`Dialing peer ${peerId.toString()} on attempt ${dialAttempt + 1}`);
20197
19143
  await this.libp2p.dial(peerId);
20198
19144
  const tags = await this.getTagNamesForPeer(peerId);
20199
19145
  // add tag to connection describing discovery mechanism
@@ -20210,11 +19156,11 @@ class ConnectionManager extends EventEmitter {
20210
19156
  catch (error) {
20211
19157
  if (error instanceof AggregateError) {
20212
19158
  // Handle AggregateError
20213
- log$5.error(`Error dialing peer ${peerId.toString()} - ${error.errors}`);
19159
+ log$6.error(`Error dialing peer ${peerId.toString()} - ${error.errors}`);
20214
19160
  }
20215
19161
  else {
20216
19162
  // Handle generic error
20217
- log$5.error(`Error dialing peer ${peerId.toString()} - ${error.message}`);
19163
+ log$6.error(`Error dialing peer ${peerId.toString()} - ${error.message}`);
20218
19164
  }
20219
19165
  this.dialErrorsForPeer.set(peerId.toString(), error);
20220
19166
  dialAttempt++;
@@ -20232,10 +19178,10 @@ class ConnectionManager extends EventEmitter {
20232
19178
  let errorMessage;
20233
19179
  if (error instanceof AggregateError) {
20234
19180
  if (!error.errors) {
20235
- log$5.warn(`No errors array found for AggregateError`);
19181
+ log$6.warn(`No errors array found for AggregateError`);
20236
19182
  }
20237
19183
  else if (error.errors.length === 0) {
20238
- log$5.warn(`Errors array is empty for AggregateError`);
19184
+ log$6.warn(`Errors array is empty for AggregateError`);
20239
19185
  }
20240
19186
  else {
20241
19187
  errorMessage = JSON.stringify(error.errors[0]);
@@ -20244,7 +19190,7 @@ class ConnectionManager extends EventEmitter {
20244
19190
  else {
20245
19191
  errorMessage = error.message;
20246
19192
  }
20247
- log$5.info(`Deleting undialable peer ${peerId.toString()} from peer store. Reason: ${errorMessage}`);
19193
+ log$6.info(`Deleting undialable peer ${peerId.toString()} from peer store. Reason: ${errorMessage}`);
20248
19194
  }
20249
19195
  this.dialErrorsForPeer.delete(peerId.toString());
20250
19196
  await this.libp2p.peerStore.delete(peerId);
@@ -20258,10 +19204,10 @@ class ConnectionManager extends EventEmitter {
20258
19204
  try {
20259
19205
  this.keepAliveManager.stop(peerId);
20260
19206
  await this.libp2p.hangUp(peerId);
20261
- log$5.info(`Dropped connection with peer ${peerId.toString()}`);
19207
+ log$6.info(`Dropped connection with peer ${peerId.toString()}`);
20262
19208
  }
20263
19209
  catch (error) {
20264
- log$5.error(`Error dropping connection with peer ${peerId.toString()} - ${error}`);
19210
+ log$6.error(`Error dropping connection with peer ${peerId.toString()} - ${error}`);
20265
19211
  }
20266
19212
  }
20267
19213
  processDialQueue() {
@@ -20271,7 +19217,7 @@ class ConnectionManager extends EventEmitter {
20271
19217
  if (!peerId)
20272
19218
  return;
20273
19219
  this.attemptDial(peerId).catch((error) => {
20274
- log$5.error(error);
19220
+ log$6.error(error);
20275
19221
  });
20276
19222
  }
20277
19223
  }
@@ -20304,7 +19250,7 @@ class ConnectionManager extends EventEmitter {
20304
19250
  return;
20305
19251
  }
20306
19252
  this.dialPeer(peerId).catch((err) => {
20307
- log$5.error(`Error dialing peer ${peerId.toString()} : ${err}`);
19253
+ log$6.error(`Error dialing peer ${peerId.toString()} : ${err}`);
20308
19254
  });
20309
19255
  }
20310
19256
  onEventHandlers = {
@@ -20316,7 +19262,7 @@ class ConnectionManager extends EventEmitter {
20316
19262
  await this.attemptDial(peerId);
20317
19263
  }
20318
19264
  catch (error) {
20319
- log$5.error(`Error dialing peer ${peerId.toString()} : ${error}`);
19265
+ log$6.error(`Error dialing peer ${peerId.toString()} : ${error}`);
20320
19266
  }
20321
19267
  })();
20322
19268
  },
@@ -20344,12 +19290,14 @@ class ConnectionManager extends EventEmitter {
20344
19290
  detail: peerId
20345
19291
  }));
20346
19292
  }
19293
+ this.toggleOnline();
20347
19294
  })();
20348
19295
  },
20349
- "peer:disconnect": () => {
20350
- return (evt) => {
19296
+ "peer:disconnect": (evt) => {
19297
+ void (async () => {
20351
19298
  this.keepAliveManager.stop(evt.detail);
20352
- };
19299
+ this.toggleOffline();
19300
+ })();
20353
19301
  }
20354
19302
  };
20355
19303
  /**
@@ -20364,24 +19312,24 @@ class ConnectionManager extends EventEmitter {
20364
19312
  // if we're already connected to the peer, don't dial
20365
19313
  const isConnected = this.libp2p.getConnections(peerId).length > 0;
20366
19314
  if (isConnected) {
20367
- log$5.warn(`Already connected to peer ${peerId.toString()}. Not dialing.`);
19315
+ log$6.warn(`Already connected to peer ${peerId.toString()}. Not dialing.`);
20368
19316
  return false;
20369
19317
  }
20370
19318
  // if the peer is not part of any of the configured pubsub topics, don't dial
20371
19319
  if (!(await this.isPeerTopicConfigured(peerId))) {
20372
19320
  const shardInfo = await this.getPeerShardInfo(peerId, this.libp2p.peerStore);
20373
- log$5.warn(`Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${this.configuredPubSubTopics}).
19321
+ log$6.warn(`Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}).
20374
19322
  Not dialing.`);
20375
19323
  return false;
20376
19324
  }
20377
19325
  // if the peer is not dialable based on bootstrap status, don't dial
20378
19326
  if (!(await this.isPeerDialableBasedOnBootstrapStatus(peerId))) {
20379
- log$5.warn(`Peer ${peerId.toString()} is not dialable based on bootstrap status. Not dialing.`);
19327
+ log$6.warn(`Peer ${peerId.toString()} is not dialable based on bootstrap status. Not dialing.`);
20380
19328
  return false;
20381
19329
  }
20382
19330
  // If the peer is already already has an active dial attempt, or has been dialed before, don't dial it
20383
19331
  if (this.dialAttemptsForPeer.has(peerId.toString())) {
20384
- log$5.warn(`Peer ${peerId.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`);
19332
+ log$6.warn(`Peer ${peerId.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`);
20385
19333
  return false;
20386
19334
  }
20387
19335
  return true;
@@ -20425,7 +19373,7 @@ class ConnectionManager extends EventEmitter {
20425
19373
  return Array.from(peer.tags.keys());
20426
19374
  }
20427
19375
  catch (error) {
20428
- log$5.error(`Failed to get peer ${peerId}, error: ${error}`);
19376
+ log$6.error(`Failed to get peer ${peerId}, error: ${error}`);
20429
19377
  return [];
20430
19378
  }
20431
19379
  }
@@ -20434,8 +19382,8 @@ class ConnectionManager extends EventEmitter {
20434
19382
  // If there's no shard information, simply return true
20435
19383
  if (!shardInfo)
20436
19384
  return true;
20437
- const pubsubTopics = shardInfoToPubSubTopics(shardInfo);
20438
- const isTopicConfigured = pubsubTopics.some((topic) => this.configuredPubSubTopics.includes(topic));
19385
+ const pubsubTopics = shardInfoToPubsubTopics(shardInfo);
19386
+ const isTopicConfigured = pubsubTopics.some((topic) => this.configuredPubsubTopics.includes(topic));
20439
19387
  return isTopicConfigured;
20440
19388
  }
20441
19389
  async getPeerShardInfo(peerId, peerStore) {
@@ -20450,17 +19398,23 @@ class ConnectionManager extends EventEmitter {
20450
19398
  const DefaultPingKeepAliveValueSecs = 5 * 60;
20451
19399
  const DefaultRelayKeepAliveValueSecs = 5 * 60;
20452
19400
  const DefaultUserAgent = "js-waku";
20453
- const log$4 = new Logger("waku");
19401
+ const log$5 = new Logger("waku");
20454
19402
  class WakuNode {
20455
- pubsubTopics;
20456
19403
  libp2p;
20457
19404
  relay;
20458
19405
  store;
20459
19406
  filter;
20460
19407
  lightPush;
20461
19408
  connectionManager;
20462
- constructor(options, pubsubTopics, libp2p, store, lightPush, filter, relay) {
20463
- this.pubsubTopics = pubsubTopics;
19409
+ pubsubTopics;
19410
+ constructor(options, pubsubTopics = [], libp2p, pubsubShardInfo, store, lightPush, filter, relay) {
19411
+ if (!pubsubShardInfo) {
19412
+ this.pubsubTopics =
19413
+ pubsubTopics.length > 0 ? pubsubTopics : [DefaultPubsubTopic];
19414
+ }
19415
+ else {
19416
+ this.pubsubTopics = shardInfoToPubsubTopics(pubsubShardInfo);
19417
+ }
20464
19418
  this.libp2p = libp2p;
20465
19419
  if (store) {
20466
19420
  this.store = store(libp2p);
@@ -20479,8 +19433,8 @@ class WakuNode {
20479
19433
  ? options.relayKeepAlive || DefaultRelayKeepAliveValueSecs
20480
19434
  : 0;
20481
19435
  const peerId = this.libp2p.peerId.toString();
20482
- this.connectionManager = ConnectionManager.create(peerId, libp2p, { pingKeepAlive, relayKeepAlive }, pubsubTopics, this.relay);
20483
- log$4.info("Waku node created", peerId, `relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this
19436
+ this.connectionManager = ConnectionManager.create(peerId, libp2p, { pingKeepAlive, relayKeepAlive }, this.pubsubTopics, this.relay);
19437
+ log$5.info("Waku node created", peerId, `relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this
20484
19438
  .lightPush}, filter: ${!!this.filter}`);
20485
19439
  }
20486
19440
  /**
@@ -20504,7 +19458,7 @@ class WakuNode {
20504
19458
  this.relay.gossipSub.multicodecs.forEach((codec) => codecs.push(codec));
20505
19459
  }
20506
19460
  else {
20507
- log$4.error("Relay codec not included in dial codec: protocol not mounted locally");
19461
+ log$5.error("Relay codec not included in dial codec: protocol not mounted locally");
20508
19462
  }
20509
19463
  }
20510
19464
  if (_protocols.includes(Protocols.Store)) {
@@ -20512,7 +19466,7 @@ class WakuNode {
20512
19466
  codecs.push(this.store.multicodec);
20513
19467
  }
20514
19468
  else {
20515
- log$4.error("Store codec not included in dial codec: protocol not mounted locally");
19469
+ log$5.error("Store codec not included in dial codec: protocol not mounted locally");
20516
19470
  }
20517
19471
  }
20518
19472
  if (_protocols.includes(Protocols.LightPush)) {
@@ -20520,7 +19474,7 @@ class WakuNode {
20520
19474
  codecs.push(this.lightPush.multicodec);
20521
19475
  }
20522
19476
  else {
20523
- log$4.error("Light Push codec not included in dial codec: protocol not mounted locally");
19477
+ log$5.error("Light Push codec not included in dial codec: protocol not mounted locally");
20524
19478
  }
20525
19479
  }
20526
19480
  if (_protocols.includes(Protocols.Filter)) {
@@ -20528,10 +19482,10 @@ class WakuNode {
20528
19482
  codecs.push(this.filter.multicodec);
20529
19483
  }
20530
19484
  else {
20531
- log$4.error("Filter codec not included in dial codec: protocol not mounted locally");
19485
+ log$5.error("Filter codec not included in dial codec: protocol not mounted locally");
20532
19486
  }
20533
19487
  }
20534
- log$4.info(`Dialing to ${peerId.toString()} with protocols ${_protocols}`);
19488
+ log$5.info(`Dialing to ${peerId.toString()} with protocols ${_protocols}`);
20535
19489
  return this.libp2p.dialProtocol(peerId, codecs);
20536
19490
  }
20537
19491
  async start() {
@@ -20544,6 +19498,9 @@ class WakuNode {
20544
19498
  isStarted() {
20545
19499
  return this.libp2p.isStarted();
20546
19500
  }
19501
+ isConnected() {
19502
+ return this.connectionManager.isConnected();
19503
+ }
20547
19504
  /**
20548
19505
  * Return the local multiaddr with peer id on which libp2p is listening.
20549
19506
  *
@@ -20576,6 +19533,38 @@ var index$3 = /*#__PURE__*/Object.freeze({
20576
19533
  version_0: version_0
20577
19534
  });
20578
19535
 
19536
+ /**
19537
+ * @packageDocumentation
19538
+ *
19539
+ * For when you need a one-liner to collect iterable values.
19540
+ *
19541
+ * @example
19542
+ *
19543
+ * ```javascript
19544
+ * import all from 'it-all'
19545
+ *
19546
+ * // This can also be an iterator, etc
19547
+ * const values = function * () {
19548
+ * yield * [0, 1, 2, 3, 4]
19549
+ * }
19550
+ *
19551
+ * const arr = all(values)
19552
+ *
19553
+ * console.info(arr) // 0, 1, 2, 3, 4
19554
+ * ```
19555
+ *
19556
+ * Async sources must be awaited:
19557
+ *
19558
+ * ```javascript
19559
+ * const values = async function * () {
19560
+ * yield * [0, 1, 2, 3, 4]
19561
+ * }
19562
+ *
19563
+ * const arr = await all(values())
19564
+ *
19565
+ * console.info(arr) // 0, 1, 2, 3, 4
19566
+ * ```
19567
+ */
20579
19568
  function isAsyncIterable$3(thing) {
20580
19569
  return thing[Symbol.asyncIterator] != null;
20581
19570
  }
@@ -21090,7 +20079,7 @@ function isAsyncIterable$2(thing) {
21090
20079
  const defaultEncoder = (length) => {
21091
20080
  const lengthLength = encodingLength(length);
21092
20081
  const lengthBuf = allocUnsafe(lengthLength);
21093
- encode$2(length, lengthBuf);
20082
+ encode$1(length, lengthBuf);
21094
20083
  defaultEncoder.bytes = lengthLength;
21095
20084
  return lengthBuf;
21096
20085
  };
@@ -21216,7 +20205,7 @@ var ReadMode;
21216
20205
  ReadMode[ReadMode["DATA"] = 1] = "DATA";
21217
20206
  })(ReadMode || (ReadMode = {}));
21218
20207
  const defaultDecoder = (buf) => {
21219
- const length = decode$2(buf);
20208
+ const length = decode$1(buf);
21220
20209
  defaultDecoder.bytes = encodingLength(length);
21221
20210
  return length;
21222
20211
  };
@@ -21953,7 +20942,7 @@ class FilterSubscribeResponse {
21953
20942
  }
21954
20943
  }
21955
20944
 
21956
- const log$3 = new Logger("filter:v2");
20945
+ const log$4 = new Logger("filter:v2");
21957
20946
  const FilterCodecs = {
21958
20947
  SUBSCRIBE: "/vac/waku/filter-subscribe/2.0.0-beta1",
21959
20948
  PUSH: "/vac/waku/filter-push/2.0.0-beta1"
@@ -21990,7 +20979,7 @@ class Subscription {
21990
20979
  if (statusCode < 200 || statusCode >= 300) {
21991
20980
  throw new Error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
21992
20981
  }
21993
- log$3.info("Subscribed to peer ", this.peer.id.toString(), "for content topics", contentTopics);
20982
+ log$4.info("Subscribed to peer ", this.peer.id.toString(), "for content topics", contentTopics);
21994
20983
  }
21995
20984
  catch (e) {
21996
20985
  throw new Error("Error subscribing to peer: " +
@@ -22040,10 +21029,10 @@ class Subscription {
22040
21029
  if (statusCode < 200 || statusCode >= 300) {
22041
21030
  throw new Error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
22042
21031
  }
22043
- log$3.info("Ping successful");
21032
+ log$4.info("Ping successful");
22044
21033
  }
22045
21034
  catch (error) {
22046
- log$3.error("Error pinging: ", error);
21035
+ log$4.error("Error pinging: ", error);
22047
21036
  throw new Error("Error pinging: " + error);
22048
21037
  }
22049
21038
  }
@@ -22060,7 +21049,7 @@ class Subscription {
22060
21049
  throw new Error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
22061
21050
  }
22062
21051
  this.subscriptionCallbacks.clear();
22063
- log$3.info("Unsubscribed from all content topics");
21052
+ log$4.info("Unsubscribed from all content topics");
22064
21053
  }
22065
21054
  catch (error) {
22066
21055
  throw new Error("Error unsubscribing from all content topics: " + error);
@@ -22070,7 +21059,7 @@ class Subscription {
22070
21059
  const contentTopic = message.contentTopic;
22071
21060
  const subscriptionCallback = this.subscriptionCallbacks.get(contentTopic);
22072
21061
  if (!subscriptionCallback) {
22073
- log$3.error("No subscription callback available for ", contentTopic);
21062
+ log$4.error("No subscription callback available for ", contentTopic);
22074
21063
  return;
22075
21064
  }
22076
21065
  await pushMessage(subscriptionCallback, this.pubsubTopic, message);
@@ -22089,13 +21078,16 @@ class Filter extends BaseProtocol {
22089
21078
  }
22090
21079
  constructor(libp2p, options) {
22091
21080
  super(FilterCodecs.SUBSCRIBE, libp2p.components);
22092
- this.pubsubTopics = options?.pubsubTopics || [DefaultPubSubTopic];
21081
+ this.pubsubTopics = this.initializePubsubTopic(options);
22093
21082
  libp2p.handle(FilterCodecs.PUSH, this.onRequest.bind(this)).catch((e) => {
22094
- log$3.error("Failed to register ", FilterCodecs.PUSH, e);
21083
+ log$4.error("Failed to register ", FilterCodecs.PUSH, e);
22095
21084
  });
22096
21085
  this.activeSubscriptions = new Map();
22097
21086
  }
22098
- async createSubscription(pubsubTopic = DefaultPubSubTopic) {
21087
+ async createSubscription(pubsubTopicShardInfo = DefaultPubsubTopic) {
21088
+ const pubsubTopic = typeof pubsubTopicShardInfo == "string"
21089
+ ? pubsubTopicShardInfo
21090
+ : singleShardInfoToPubsubTopic(pubsubTopicShardInfo);
22099
21091
  ensurePubsubTopicIsConfigured(pubsubTopic, this.pubsubTopics);
22100
21092
  //TODO: get a relevant peer for the topic/shard
22101
21093
  // https://github.com/waku-org/js-waku/pull/1586#discussion_r1336428230
@@ -22140,29 +21132,29 @@ class Filter extends BaseProtocol {
22140
21132
  const response = FilterPushRpc.decode(bytes.slice());
22141
21133
  const { pubsubTopic, wakuMessage } = response;
22142
21134
  if (!wakuMessage) {
22143
- log$3.error("Received empty message");
21135
+ log$4.error("Received empty message");
22144
21136
  return;
22145
21137
  }
22146
21138
  if (!pubsubTopic) {
22147
- log$3.error("PubSub topic missing from push message");
21139
+ log$4.error("Pubsub topic missing from push message");
22148
21140
  return;
22149
21141
  }
22150
21142
  const peerIdStr = streamData.connection.remotePeer.toString();
22151
21143
  const subscription = this.getActiveSubscription(pubsubTopic, peerIdStr);
22152
21144
  if (!subscription) {
22153
- log$3.error(`No subscription locally registered for topic ${pubsubTopic}`);
21145
+ log$4.error(`No subscription locally registered for topic ${pubsubTopic}`);
22154
21146
  return;
22155
21147
  }
22156
21148
  await subscription.processMessage(wakuMessage);
22157
21149
  }
22158
21150
  }).then(() => {
22159
- log$3.info("Receiving pipe closed.");
21151
+ log$4.info("Receiving pipe closed.");
22160
21152
  }, (e) => {
22161
- log$3.error("Error with receiving pipe", e);
21153
+ log$4.error("Error with receiving pipe", e);
22162
21154
  });
22163
21155
  }
22164
21156
  catch (e) {
22165
- log$3.error("Error decoding message", e);
21157
+ log$4.error("Error decoding message", e);
22166
21158
  }
22167
21159
  }
22168
21160
  }
@@ -22173,7 +21165,7 @@ async function pushMessage(subscriptionCallback, pubsubTopic, message) {
22173
21165
  const { decoders, callback } = subscriptionCallback;
22174
21166
  const { contentTopic } = message;
22175
21167
  if (!contentTopic) {
22176
- log$3.warn("Message has no content topic, skipping");
21168
+ log$4.warn("Message has no content topic, skipping");
22177
21169
  return;
22178
21170
  }
22179
21171
  try {
@@ -22184,7 +21176,7 @@ async function pushMessage(subscriptionCallback, pubsubTopic, message) {
22184
21176
  await callback(decodedMessage);
22185
21177
  }
22186
21178
  catch (e) {
22187
- log$3.error("Error decoding message", e);
21179
+ log$4.error("Error decoding message", e);
22188
21180
  }
22189
21181
  }
22190
21182
 
@@ -22224,7 +21216,7 @@ class PushRpc {
22224
21216
  }
22225
21217
  }
22226
21218
 
22227
- const log$2 = new Logger("light-push");
21219
+ const log$3 = new Logger("light-push");
22228
21220
  const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1";
22229
21221
  /**
22230
21222
  * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).
@@ -22234,21 +21226,21 @@ class LightPush extends BaseProtocol {
22234
21226
  NUM_PEERS_PROTOCOL = 1;
22235
21227
  constructor(libp2p, options) {
22236
21228
  super(LightPushCodec, libp2p.components);
22237
- this.pubsubTopics = options?.pubsubTopics ?? [DefaultPubSubTopic];
21229
+ this.pubsubTopics = this.initializePubsubTopic(options);
22238
21230
  }
22239
21231
  async preparePushMessage(encoder, message, pubsubTopic) {
22240
21232
  try {
22241
21233
  if (!message.payload || message.payload.length === 0) {
22242
- log$2.error("Failed to send waku light push: payload is empty");
21234
+ log$3.error("Failed to send waku light push: payload is empty");
22243
21235
  return { query: null, error: SendError.EMPTY_PAYLOAD };
22244
21236
  }
22245
21237
  if (!(await isMessageSizeUnderCap(encoder, message))) {
22246
- log$2.error("Failed to send waku light push: message is bigger than 1MB");
21238
+ log$3.error("Failed to send waku light push: message is bigger than 1MB");
22247
21239
  return { query: null, error: SendError.SIZE_TOO_BIG };
22248
21240
  }
22249
21241
  const protoMessage = await encoder.toProtoObj(message);
22250
21242
  if (!protoMessage) {
22251
- log$2.error("Failed to encode to protoMessage, aborting push");
21243
+ log$3.error("Failed to encode to protoMessage, aborting push");
22252
21244
  return {
22253
21245
  query: null,
22254
21246
  error: SendError.ENCODE_FAILED
@@ -22258,7 +21250,7 @@ class LightPush extends BaseProtocol {
22258
21250
  return { query, error: null };
22259
21251
  }
22260
21252
  catch (error) {
22261
- log$2.error("Failed to prepare push message", error);
21253
+ log$3.error("Failed to prepare push message", error);
22262
21254
  return {
22263
21255
  query: null,
22264
21256
  error: SendError.GENERIC_FAIL
@@ -22293,7 +21285,7 @@ class LightPush extends BaseProtocol {
22293
21285
  stream = await this.getStream(peer);
22294
21286
  }
22295
21287
  catch (err) {
22296
- log$2.error(`Failed to get a stream for remote peer${peer.id.toString()}`, err);
21288
+ log$3.error(`Failed to get a stream for remote peer${peer.id.toString()}`, err);
22297
21289
  return { recipients, error: SendError.REMOTE_PEER_FAULT };
22298
21290
  }
22299
21291
  let res;
@@ -22301,7 +21293,7 @@ class LightPush extends BaseProtocol {
22301
21293
  res = await pipe([query.encode()], encode, stream, decode, async (source) => await all(source));
22302
21294
  }
22303
21295
  catch (err) {
22304
- log$2.error("Failed to send waku light push request", err);
21296
+ log$3.error("Failed to send waku light push request", err);
22305
21297
  return { recipients, error: SendError.GENERIC_FAIL };
22306
21298
  }
22307
21299
  const bytes = new Uint8ArrayList();
@@ -22313,15 +21305,15 @@ class LightPush extends BaseProtocol {
22313
21305
  response = PushRpc.decode(bytes).response;
22314
21306
  }
22315
21307
  catch (err) {
22316
- log$2.error("Failed to decode push reply", err);
21308
+ log$3.error("Failed to decode push reply", err);
22317
21309
  return { recipients, error: SendError.DECODE_FAILED };
22318
21310
  }
22319
21311
  if (!response) {
22320
- log$2.error("Remote peer fault: No response in PushRPC");
21312
+ log$3.error("Remote peer fault: No response in PushRPC");
22321
21313
  return { recipients, error: SendError.REMOTE_PEER_FAULT };
22322
21314
  }
22323
21315
  if (!response.isSuccess) {
22324
- log$2.error("Remote peer rejected the message: ", response.info);
21316
+ log$3.error("Remote peer rejected the message: ", response.info);
22325
21317
  return { recipients, error: SendError.REMOTE_PEER_REJECTED };
22326
21318
  }
22327
21319
  recipients.some((recipient) => recipient.equals(peer.id)) ||
@@ -22350,299 +21342,6 @@ var index$1 = /*#__PURE__*/Object.freeze({
22350
21342
  wakuLightPush: wakuLightPush
22351
21343
  });
22352
21344
 
22353
- function bytes(b, ...lengths) {
22354
- if (!(b instanceof Uint8Array))
22355
- throw new Error('Expected Uint8Array');
22356
- if (lengths.length > 0 && !lengths.includes(b.length))
22357
- throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
22358
- }
22359
- function exists(instance, checkFinished = true) {
22360
- if (instance.destroyed)
22361
- throw new Error('Hash instance has been destroyed');
22362
- if (checkFinished && instance.finished)
22363
- throw new Error('Hash#digest() has already been called');
22364
- }
22365
- function output(out, instance) {
22366
- bytes(out);
22367
- const min = instance.outputLen;
22368
- if (out.length < min) {
22369
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
22370
- }
22371
- }
22372
-
22373
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
22374
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
22375
- // node.js versions earlier than v19 don't declare it in global scope.
22376
- // For node.js, package.json#exports field mapping rewrites import
22377
- // from `crypto` to `cryptoNode`, which imports native module.
22378
- // Makes the utils un-importable in browsers without a bundler.
22379
- // Once node.js 18 is deprecated, we can just drop the import.
22380
- const u8a = (a) => a instanceof Uint8Array;
22381
- // Cast array to view
22382
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
22383
- // The rotate right (circular right shift) operation for uint32
22384
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
22385
- // big-endian hardware is rare. Just in case someone still decides to run hashes:
22386
- // early-throw an error because we don't support BE yet.
22387
- const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
22388
- if (!isLE)
22389
- throw new Error('Non little-endian hardware is not supported');
22390
- /**
22391
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
22392
- */
22393
- function utf8ToBytes(str) {
22394
- if (typeof str !== 'string')
22395
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
22396
- return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
22397
- }
22398
- /**
22399
- * Normalizes (non-hex) string or Uint8Array to Uint8Array.
22400
- * Warning: when Uint8Array is passed, it would NOT get copied.
22401
- * Keep in mind for future mutable operations.
22402
- */
22403
- function toBytes(data) {
22404
- if (typeof data === 'string')
22405
- data = utf8ToBytes(data);
22406
- if (!u8a(data))
22407
- throw new Error(`expected Uint8Array, got ${typeof data}`);
22408
- return data;
22409
- }
22410
- // For runtime check if class implements interface
22411
- class Hash {
22412
- // Safe version that clones internal state
22413
- clone() {
22414
- return this._cloneInto();
22415
- }
22416
- }
22417
- function wrapConstructor(hashCons) {
22418
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
22419
- const tmp = hashCons();
22420
- hashC.outputLen = tmp.outputLen;
22421
- hashC.blockLen = tmp.blockLen;
22422
- hashC.create = () => hashCons();
22423
- return hashC;
22424
- }
22425
-
22426
- // Polyfill for Safari 14
22427
- function setBigUint64(view, byteOffset, value, isLE) {
22428
- if (typeof view.setBigUint64 === 'function')
22429
- return view.setBigUint64(byteOffset, value, isLE);
22430
- const _32n = BigInt(32);
22431
- const _u32_max = BigInt(0xffffffff);
22432
- const wh = Number((value >> _32n) & _u32_max);
22433
- const wl = Number(value & _u32_max);
22434
- const h = isLE ? 4 : 0;
22435
- const l = isLE ? 0 : 4;
22436
- view.setUint32(byteOffset + h, wh, isLE);
22437
- view.setUint32(byteOffset + l, wl, isLE);
22438
- }
22439
- // Base SHA2 class (RFC 6234)
22440
- class SHA2 extends Hash {
22441
- constructor(blockLen, outputLen, padOffset, isLE) {
22442
- super();
22443
- this.blockLen = blockLen;
22444
- this.outputLen = outputLen;
22445
- this.padOffset = padOffset;
22446
- this.isLE = isLE;
22447
- this.finished = false;
22448
- this.length = 0;
22449
- this.pos = 0;
22450
- this.destroyed = false;
22451
- this.buffer = new Uint8Array(blockLen);
22452
- this.view = createView(this.buffer);
22453
- }
22454
- update(data) {
22455
- exists(this);
22456
- const { view, buffer, blockLen } = this;
22457
- data = toBytes(data);
22458
- const len = data.length;
22459
- for (let pos = 0; pos < len;) {
22460
- const take = Math.min(blockLen - this.pos, len - pos);
22461
- // Fast path: we have at least one block in input, cast it to view and process
22462
- if (take === blockLen) {
22463
- const dataView = createView(data);
22464
- for (; blockLen <= len - pos; pos += blockLen)
22465
- this.process(dataView, pos);
22466
- continue;
22467
- }
22468
- buffer.set(data.subarray(pos, pos + take), this.pos);
22469
- this.pos += take;
22470
- pos += take;
22471
- if (this.pos === blockLen) {
22472
- this.process(view, 0);
22473
- this.pos = 0;
22474
- }
22475
- }
22476
- this.length += data.length;
22477
- this.roundClean();
22478
- return this;
22479
- }
22480
- digestInto(out) {
22481
- exists(this);
22482
- output(out, this);
22483
- this.finished = true;
22484
- // Padding
22485
- // We can avoid allocation of buffer for padding completely if it
22486
- // was previously not allocated here. But it won't change performance.
22487
- const { buffer, view, blockLen, isLE } = this;
22488
- let { pos } = this;
22489
- // append the bit '1' to the message
22490
- buffer[pos++] = 0b10000000;
22491
- this.buffer.subarray(pos).fill(0);
22492
- // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
22493
- if (this.padOffset > blockLen - pos) {
22494
- this.process(view, 0);
22495
- pos = 0;
22496
- }
22497
- // Pad until full block byte with zeros
22498
- for (let i = pos; i < blockLen; i++)
22499
- buffer[i] = 0;
22500
- // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
22501
- // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
22502
- // So we just write lowest 64 bits of that value.
22503
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
22504
- this.process(view, 0);
22505
- const oview = createView(out);
22506
- const len = this.outputLen;
22507
- // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
22508
- if (len % 4)
22509
- throw new Error('_sha2: outputLen should be aligned to 32bit');
22510
- const outLen = len / 4;
22511
- const state = this.get();
22512
- if (outLen > state.length)
22513
- throw new Error('_sha2: outputLen bigger than state');
22514
- for (let i = 0; i < outLen; i++)
22515
- oview.setUint32(4 * i, state[i], isLE);
22516
- }
22517
- digest() {
22518
- const { buffer, outputLen } = this;
22519
- this.digestInto(buffer);
22520
- const res = buffer.slice(0, outputLen);
22521
- this.destroy();
22522
- return res;
22523
- }
22524
- _cloneInto(to) {
22525
- to || (to = new this.constructor());
22526
- to.set(...this.get());
22527
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
22528
- to.length = length;
22529
- to.pos = pos;
22530
- to.finished = finished;
22531
- to.destroyed = destroyed;
22532
- if (length % blockLen)
22533
- to.buffer.set(buffer);
22534
- return to;
22535
- }
22536
- }
22537
-
22538
- // SHA2-256 need to try 2^128 hashes to execute birthday attack.
22539
- // BTC network is doing 2^67 hashes/sec as per early 2023.
22540
- // Choice: a ? b : c
22541
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
22542
- // Majority function, true if any two inpust is true
22543
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
22544
- // Round constants:
22545
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
22546
- // prettier-ignore
22547
- const SHA256_K = /* @__PURE__ */ new Uint32Array([
22548
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
22549
- 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
22550
- 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
22551
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
22552
- 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
22553
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
22554
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
22555
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
22556
- ]);
22557
- // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
22558
- // prettier-ignore
22559
- const IV = /* @__PURE__ */ new Uint32Array([
22560
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
22561
- ]);
22562
- // Temporary buffer, not used to store anything between runs
22563
- // Named this way because it matches specification.
22564
- const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
22565
- class SHA256 extends SHA2 {
22566
- constructor() {
22567
- super(64, 32, 8, false);
22568
- // We cannot use array here since array allows indexing by variable
22569
- // which means optimizer/compiler cannot use registers.
22570
- this.A = IV[0] | 0;
22571
- this.B = IV[1] | 0;
22572
- this.C = IV[2] | 0;
22573
- this.D = IV[3] | 0;
22574
- this.E = IV[4] | 0;
22575
- this.F = IV[5] | 0;
22576
- this.G = IV[6] | 0;
22577
- this.H = IV[7] | 0;
22578
- }
22579
- get() {
22580
- const { A, B, C, D, E, F, G, H } = this;
22581
- return [A, B, C, D, E, F, G, H];
22582
- }
22583
- // prettier-ignore
22584
- set(A, B, C, D, E, F, G, H) {
22585
- this.A = A | 0;
22586
- this.B = B | 0;
22587
- this.C = C | 0;
22588
- this.D = D | 0;
22589
- this.E = E | 0;
22590
- this.F = F | 0;
22591
- this.G = G | 0;
22592
- this.H = H | 0;
22593
- }
22594
- process(view, offset) {
22595
- // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
22596
- for (let i = 0; i < 16; i++, offset += 4)
22597
- SHA256_W[i] = view.getUint32(offset, false);
22598
- for (let i = 16; i < 64; i++) {
22599
- const W15 = SHA256_W[i - 15];
22600
- const W2 = SHA256_W[i - 2];
22601
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
22602
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
22603
- SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
22604
- }
22605
- // Compression function main loop, 64 rounds
22606
- let { A, B, C, D, E, F, G, H } = this;
22607
- for (let i = 0; i < 64; i++) {
22608
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
22609
- const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
22610
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
22611
- const T2 = (sigma0 + Maj(A, B, C)) | 0;
22612
- H = G;
22613
- G = F;
22614
- F = E;
22615
- E = (D + T1) | 0;
22616
- D = C;
22617
- C = B;
22618
- B = A;
22619
- A = (T1 + T2) | 0;
22620
- }
22621
- // Add the compressed chunk to the current hash value
22622
- A = (A + this.A) | 0;
22623
- B = (B + this.B) | 0;
22624
- C = (C + this.C) | 0;
22625
- D = (D + this.D) | 0;
22626
- E = (E + this.E) | 0;
22627
- F = (F + this.F) | 0;
22628
- G = (G + this.G) | 0;
22629
- H = (H + this.H) | 0;
22630
- this.set(A, B, C, D, E, F, G, H);
22631
- }
22632
- roundClean() {
22633
- SHA256_W.fill(0);
22634
- }
22635
- destroy() {
22636
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
22637
- this.buffer.fill(0);
22638
- }
22639
- }
22640
- /**
22641
- * SHA2-256 hash function
22642
- * @param message - data that would be hashed
22643
- */
22644
- const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
22645
-
22646
21345
  const EmptyMessage = {
22647
21346
  payload: new Uint8Array(),
22648
21347
  contentTopic: "",
@@ -22727,7 +21426,7 @@ function directionToProto(pageDirection) {
22727
21426
  }
22728
21427
 
22729
21428
  var HistoryError = HistoryResponse.HistoryError;
22730
- const log$1 = new Logger("store");
21429
+ const log$2 = new Logger("store");
22731
21430
  const StoreCodec = "/vac/waku/store/2.0.0-beta4";
22732
21431
  const DefaultPageSize = 10;
22733
21432
  /**
@@ -22740,7 +21439,7 @@ class Store extends BaseProtocol {
22740
21439
  NUM_PEERS_PROTOCOL = 1;
22741
21440
  constructor(libp2p, options) {
22742
21441
  super(StoreCodec, libp2p.components);
22743
- this.pubsubTopics = options?.pubsubTopics ?? [DefaultPubSubTopic];
21442
+ this.pubsubTopics = this.initializePubsubTopic(options);
22744
21443
  }
22745
21444
  /**
22746
21445
  * Processes messages based on the provided callback and options.
@@ -22859,18 +21558,18 @@ class Store extends BaseProtocol {
22859
21558
  endTime = options.timeFilter.endTime;
22860
21559
  }
22861
21560
  // convert array to set to remove duplicates
22862
- const uniquePubSubTopicsInQuery = Array.from(new Set(decoders.map((decoder) => decoder.pubsubTopic)));
21561
+ const uniquePubsubTopicsInQuery = Array.from(new Set(decoders.map((decoder) => decoder.pubsubTopic)));
22863
21562
  // If multiple pubsub topics are provided, throw an error
22864
- if (uniquePubSubTopicsInQuery.length > 1) {
21563
+ if (uniquePubsubTopicsInQuery.length > 1) {
22865
21564
  throw new Error("API does not support querying multiple pubsub topics at once");
22866
21565
  }
22867
21566
  // we can be certain that there is only one pubsub topic in the query
22868
- const pubSubTopicForQuery = uniquePubSubTopicsInQuery[0];
22869
- ensurePubsubTopicIsConfigured(pubSubTopicForQuery, this.pubsubTopics);
21567
+ const pubsubTopicForQuery = uniquePubsubTopicsInQuery[0];
21568
+ ensurePubsubTopicIsConfigured(pubsubTopicForQuery, this.pubsubTopics);
22870
21569
  // check that the pubsubTopic from the Cursor and Decoder match
22871
21570
  if (options?.cursor?.pubsubTopic &&
22872
- options.cursor.pubsubTopic !== pubSubTopicForQuery) {
22873
- throw new Error(`Cursor pubsub topic (${options?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${pubSubTopicForQuery})`);
21571
+ options.cursor.pubsubTopic !== pubsubTopicForQuery) {
21572
+ throw new Error(`Cursor pubsub topic (${options?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${pubsubTopicForQuery})`);
22874
21573
  }
22875
21574
  const decodersAsMap = new Map();
22876
21575
  decoders.forEach((dec) => {
@@ -22880,13 +21579,13 @@ class Store extends BaseProtocol {
22880
21579
  decodersAsMap.set(dec.contentTopic, dec);
22881
21580
  });
22882
21581
  const contentTopics = decoders
22883
- .filter((decoder) => decoder.pubsubTopic === pubSubTopicForQuery)
21582
+ .filter((decoder) => decoder.pubsubTopic === pubsubTopicForQuery)
22884
21583
  .map((dec) => dec.contentTopic);
22885
21584
  if (contentTopics.length === 0) {
22886
- throw new Error("No decoders found for topic " + pubSubTopicForQuery);
21585
+ throw new Error("No decoders found for topic " + pubsubTopicForQuery);
22887
21586
  }
22888
21587
  const queryOpts = Object.assign({
22889
- pubsubTopic: pubSubTopicForQuery,
21588
+ pubsubTopic: pubsubTopicForQuery,
22890
21589
  pageDirection: PageDirection.BACKWARD,
22891
21590
  pageSize: DefaultPageSize
22892
21591
  }, options, { contentTopics, startTime, endTime });
@@ -22908,7 +21607,7 @@ async function* paginate(streamFactory, queryOpts, decoders, cursor) {
22908
21607
  while (true) {
22909
21608
  queryOpts.cursor = currentCursor;
22910
21609
  const historyRpcQuery = HistoryRpc.createQuery(queryOpts);
22911
- log$1.info("Querying store peer", `for (${queryOpts.pubsubTopic})`, queryOpts.contentTopics);
21610
+ log$2.info("Querying store peer", `for (${queryOpts.pubsubTopic})`, queryOpts.contentTopics);
22912
21611
  const stream = await streamFactory();
22913
21612
  const res = await pipe([historyRpcQuery.encode()], encode, stream, decode, async (source) => await all(source));
22914
21613
  const bytes = new Uint8ArrayList();
@@ -22917,7 +21616,7 @@ async function* paginate(streamFactory, queryOpts, decoders, cursor) {
22917
21616
  });
22918
21617
  const reply = historyRpcQuery.decode(bytes);
22919
21618
  if (!reply.response) {
22920
- log$1.warn("Stopping pagination due to store `response` field missing");
21619
+ log$2.warn("Stopping pagination due to store `response` field missing");
22921
21620
  break;
22922
21621
  }
22923
21622
  const response = reply.response;
@@ -22925,10 +21624,10 @@ async function* paginate(streamFactory, queryOpts, decoders, cursor) {
22925
21624
  throw "History response contains an Error: " + response.error;
22926
21625
  }
22927
21626
  if (!response.messages || !response.messages.length) {
22928
- log$1.warn("Stopping pagination due to store `response.messages` field missing or empty");
21627
+ log$2.warn("Stopping pagination due to store `response.messages` field missing or empty");
22929
21628
  break;
22930
21629
  }
22931
- log$1.error(`${response.messages.length} messages retrieved from store`);
21630
+ log$2.error(`${response.messages.length} messages retrieved from store`);
22932
21631
  yield response.messages.map((protoMsg) => {
22933
21632
  const contentTopic = protoMsg.contentTopic;
22934
21633
  if (typeof contentTopic !== "undefined") {
@@ -22943,7 +21642,7 @@ async function* paginate(streamFactory, queryOpts, decoders, cursor) {
22943
21642
  if (typeof nextCursor === "undefined") {
22944
21643
  // If the server does not return cursor then there is an issue,
22945
21644
  // Need to abort, or we end up in an infinite loop
22946
- log$1.warn("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");
21645
+ log$2.warn("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");
22947
21646
  break;
22948
21647
  }
22949
21648
  currentCursor = nextCursor;
@@ -22965,8 +21664,8 @@ async function createCursor(message) {
22965
21664
  !message.contentTopic) {
22966
21665
  throw new Error("Message is missing required fields");
22967
21666
  }
22968
- const contentTopicBytes = utf8ToBytes$1(message.contentTopic);
22969
- const digest = sha256(concat$1([contentTopicBytes, message.payload]));
21667
+ const contentTopicBytes = utf8ToBytes(message.contentTopic);
21668
+ const digest = sha256$1(concat$1([contentTopicBytes, message.payload]));
22970
21669
  const messageTime = BigInt(message.timestamp.getTime()) * BigInt(1000000);
22971
21670
  return {
22972
21671
  digest,
@@ -23220,7 +21919,7 @@ function pEvent(emitter, event, options) {
23220
21919
  return promise;
23221
21920
  }
23222
21921
 
23223
- const log = new Logger("wait-for-remote-peer");
21922
+ const log$1 = new Logger("wait-for-remote-peer");
23224
21923
  /**
23225
21924
  * Wait for a remote peer to be ready given the passed protocols.
23226
21925
  * Must be used after attempting to connect to nodes, using
@@ -23279,7 +21978,7 @@ async function waitForConnectedPeer(protocol) {
23279
21978
  const codec = protocol.multicodec;
23280
21979
  const peers = await protocol.peers();
23281
21980
  if (peers.length) {
23282
- log.info(`${codec} peer found: `, peers[0].id.toString());
21981
+ log$1.info(`${codec} peer found: `, peers[0].id.toString());
23283
21982
  return;
23284
21983
  }
23285
21984
  await new Promise((resolve) => {
@@ -23327,4 +22026,63 @@ function getEnabledProtocols(waku) {
23327
22026
  return protocols;
23328
22027
  }
23329
22028
 
23330
- export { ConnectionManager, DefaultPubSubTopic, DefaultUserAgent, FilterCodecs, KeepAliveManager, PageDirection, WakuNode, createCursor, createEncoder, index$3 as message, waitForRemotePeer, waku, wakuFilter, wakuLightPush, wakuStore, index$2 as waku_filter, index$1 as waku_light_push, index as waku_store };
22029
+ const log = new Logger("metadata");
22030
+ const MetadataCodec = "/vac/waku/metadata/1.0.0";
22031
+ class Metadata extends BaseProtocol {
22032
+ shardInfo;
22033
+ libp2pComponents;
22034
+ constructor(shardInfo, libp2p) {
22035
+ super(MetadataCodec, libp2p.components);
22036
+ this.libp2pComponents = libp2p;
22037
+ this.shardInfo = shardInfo;
22038
+ void libp2p.registrar.handle(MetadataCodec, (streamData) => {
22039
+ void this.onRequest(streamData);
22040
+ });
22041
+ }
22042
+ /**
22043
+ * Handle an incoming metadata request
22044
+ */
22045
+ async onRequest(streamData) {
22046
+ try {
22047
+ const { stream, connection } = streamData;
22048
+ const encodedShardInfo = WakuMetadataResponse.encode(this.shardInfo);
22049
+ const encodedResponse = await pipe([encodedShardInfo], encode, stream, decode, async (source) => await all(source));
22050
+ const remoteShardInfoResponse = this.decodeMetadataResponse(encodedResponse);
22051
+ // add or update the shardInfo to peer store
22052
+ await this.libp2pComponents.peerStore.merge(connection.remotePeer, {
22053
+ metadata: {
22054
+ shardInfo: encodeRelayShard(remoteShardInfoResponse)
22055
+ }
22056
+ });
22057
+ }
22058
+ catch (error) {
22059
+ log.error("Error handling metadata request", error);
22060
+ }
22061
+ }
22062
+ /**
22063
+ * Make a metadata query to a peer
22064
+ */
22065
+ async query(peerId) {
22066
+ const request = WakuMetadataRequest.encode(this.shardInfo);
22067
+ const peer = await this.getPeer(peerId);
22068
+ const stream = await this.getStream(peer);
22069
+ const encodedResponse = await pipe([request], encode, stream, decode, async (source) => await all(source));
22070
+ const decodedResponse = this.decodeMetadataResponse(encodedResponse);
22071
+ return decodedResponse;
22072
+ }
22073
+ decodeMetadataResponse(encodedResponse) {
22074
+ const bytes = new Uint8ArrayList();
22075
+ encodedResponse.forEach((chunk) => {
22076
+ bytes.append(chunk);
22077
+ });
22078
+ const response = WakuMetadataResponse.decode(bytes);
22079
+ if (!response)
22080
+ log.error("Error decoding metadata response");
22081
+ return response;
22082
+ }
22083
+ }
22084
+ function wakuMetadata(shardInfo) {
22085
+ return (components) => new Metadata(shardInfo, components);
22086
+ }
22087
+
22088
+ export { ConnectionManager, DefaultUserAgent, FilterCodecs, KeepAliveManager, LightPushCodec, MetadataCodec, PageDirection, WakuNode, createCursor, createEncoder, index$3 as message, waitForRemotePeer, waku, wakuFilter, wakuLightPush, wakuMetadata, wakuStore, index$2 as waku_filter, index$1 as waku_light_push, index as waku_store };