@waku/core 0.0.34-9f1d8ca.0 → 0.0.34-c41b319.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/bundle/base_protocol-CCK9RCtH.js +152 -0
  2. package/bundle/{index-BIW3qNYx.js → index-Db7LxDrL.js} +78 -159
  3. package/bundle/index.js +1882 -158
  4. package/bundle/lib/base_protocol.js +2 -2
  5. package/bundle/lib/message/version_0.js +2 -2
  6. package/bundle/{version_0-CdmZMfkQ.js → version_0-ANFNAdFD.js} +283 -45
  7. package/dist/.tsbuildinfo +1 -1
  8. package/dist/index.d.ts +1 -3
  9. package/dist/index.js +1 -3
  10. package/dist/index.js.map +1 -1
  11. package/dist/lib/base_protocol.d.ts +3 -23
  12. package/dist/lib/base_protocol.js +3 -47
  13. package/dist/lib/base_protocol.js.map +1 -1
  14. package/dist/lib/connection_manager/connection_manager.d.ts +118 -0
  15. package/dist/lib/{connection_manager.js → connection_manager/connection_manager.js} +136 -36
  16. package/dist/lib/connection_manager/connection_manager.js.map +1 -0
  17. package/dist/lib/connection_manager/index.d.ts +1 -0
  18. package/dist/lib/connection_manager/index.js +2 -0
  19. package/dist/lib/connection_manager/index.js.map +1 -0
  20. package/dist/lib/{keep_alive_manager.d.ts → connection_manager/keep_alive_manager.d.ts} +4 -2
  21. package/dist/lib/{keep_alive_manager.js → connection_manager/keep_alive_manager.js} +2 -2
  22. package/dist/lib/connection_manager/keep_alive_manager.js.map +1 -0
  23. package/dist/lib/connection_manager/utils.d.ts +7 -0
  24. package/dist/lib/connection_manager/utils.js +22 -0
  25. package/dist/lib/connection_manager/utils.js.map +1 -0
  26. package/dist/lib/filter/filter.d.ts +18 -0
  27. package/dist/lib/filter/filter.js +209 -0
  28. package/dist/lib/filter/filter.js.map +1 -0
  29. package/dist/lib/filter/index.d.ts +1 -18
  30. package/dist/lib/filter/index.js +1 -208
  31. package/dist/lib/filter/index.js.map +1 -1
  32. package/dist/lib/light_push/index.d.ts +1 -15
  33. package/dist/lib/light_push/index.js +1 -143
  34. package/dist/lib/light_push/index.js.map +1 -1
  35. package/dist/lib/light_push/light_push.d.ts +15 -0
  36. package/dist/lib/light_push/light_push.js +144 -0
  37. package/dist/lib/light_push/light_push.js.map +1 -0
  38. package/dist/lib/metadata/index.d.ts +1 -3
  39. package/dist/lib/metadata/index.js +1 -118
  40. package/dist/lib/metadata/index.js.map +1 -1
  41. package/dist/lib/metadata/metadata.d.ts +3 -0
  42. package/dist/lib/metadata/metadata.js +119 -0
  43. package/dist/lib/metadata/metadata.js.map +1 -0
  44. package/dist/lib/store/index.d.ts +1 -9
  45. package/dist/lib/store/index.js +1 -82
  46. package/dist/lib/store/index.js.map +1 -1
  47. package/dist/lib/store/store.d.ts +9 -0
  48. package/dist/lib/store/store.js +83 -0
  49. package/dist/lib/store/store.js.map +1 -0
  50. package/dist/lib/stream_manager/stream_manager.d.ts +2 -2
  51. package/dist/lib/stream_manager/stream_manager.js +16 -17
  52. package/dist/lib/stream_manager/stream_manager.js.map +1 -1
  53. package/package.json +1 -1
  54. package/src/index.ts +1 -4
  55. package/src/lib/base_protocol.ts +3 -76
  56. package/src/lib/{connection_manager.ts → connection_manager/connection_manager.ts} +168 -63
  57. package/src/lib/connection_manager/index.ts +1 -0
  58. package/src/lib/{keep_alive_manager.ts → connection_manager/keep_alive_manager.ts} +7 -3
  59. package/src/lib/connection_manager/utils.ts +25 -0
  60. package/src/lib/filter/filter.ts +315 -0
  61. package/src/lib/filter/index.ts +1 -315
  62. package/src/lib/light_push/index.ts +1 -188
  63. package/src/lib/light_push/light_push.ts +188 -0
  64. package/src/lib/metadata/index.ts +1 -182
  65. package/src/lib/metadata/metadata.ts +182 -0
  66. package/src/lib/store/index.ts +1 -136
  67. package/src/lib/store/store.ts +136 -0
  68. package/src/lib/stream_manager/stream_manager.ts +16 -18
  69. package/bundle/base_protocol-Dzv-QHPR.js +0 -275
  70. package/dist/lib/connection_manager.d.ts +0 -62
  71. package/dist/lib/connection_manager.js.map +0 -1
  72. package/dist/lib/filterPeers.d.ts +0 -13
  73. package/dist/lib/filterPeers.js +0 -38
  74. package/dist/lib/filterPeers.js.map +0 -1
  75. package/dist/lib/health_manager.d.ts +0 -14
  76. package/dist/lib/health_manager.js +0 -70
  77. package/dist/lib/health_manager.js.map +0 -1
  78. package/dist/lib/keep_alive_manager.js.map +0 -1
  79. package/src/lib/filterPeers.ts +0 -51
  80. package/src/lib/health_manager.ts +0 -90
@@ -15,36 +15,36 @@ export class StreamManager {
15
15
  this.log = new Logger(`stream-manager:${multicodec}`);
16
16
  this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
17
17
  }
18
- async getStream(peer) {
19
- const peerId = peer.id.toString();
20
- const scheduledStream = this.streamPool.get(peerId);
18
+ async getStream(peerId) {
19
+ const peerIdStr = peerId.toString();
20
+ const scheduledStream = this.streamPool.get(peerIdStr);
21
21
  if (scheduledStream) {
22
- this.streamPool.delete(peerId);
22
+ this.streamPool.delete(peerIdStr);
23
23
  await scheduledStream;
24
24
  }
25
- let stream = this.getOpenStreamForCodec(peer.id);
25
+ let stream = this.getOpenStreamForCodec(peerId);
26
26
  if (stream) {
27
- this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
28
- this.lockStream(peer.id.toString(), stream);
27
+ this.log.info(`Found existing stream peerId=${peerIdStr} multicodec=${this.multicodec}`);
28
+ this.lockStream(peerIdStr, stream);
29
29
  return stream;
30
30
  }
31
- stream = await this.createStream(peer);
32
- this.lockStream(peer.id.toString(), stream);
31
+ stream = await this.createStream(peerId);
32
+ this.lockStream(peerIdStr, stream);
33
33
  return stream;
34
34
  }
35
- async createStream(peer, retries = 0) {
36
- const connections = this.getConnections(peer.id);
35
+ async createStream(peerId, retries = 0) {
36
+ const connections = this.getConnections(peerId);
37
37
  const connection = selectOpenConnection(connections);
38
38
  if (!connection) {
39
- throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
39
+ throw new Error(`Failed to get a connection to the peer peerId=${peerId.toString()} multicodec=${this.multicodec}`);
40
40
  }
41
41
  let lastError;
42
42
  let stream;
43
43
  for (let i = 0; i < retries + 1; i++) {
44
44
  try {
45
- this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
45
+ this.log.info(`Attempting to create a stream for peerId=${peerId.toString()} multicodec=${this.multicodec}`);
46
46
  stream = await connection.newStream(this.multicodec);
47
- this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
47
+ this.log.info(`Created stream for peerId=${peerId.toString()} multicodec=${this.multicodec}`);
48
48
  break;
49
49
  }
50
50
  catch (error) {
@@ -52,8 +52,7 @@ export class StreamManager {
52
52
  }
53
53
  }
54
54
  if (!stream) {
55
- throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +
56
- lastError);
55
+ throw new Error(`Failed to create a new stream for ${peerId.toString()} -- ` + lastError);
57
56
  }
58
57
  return stream;
59
58
  }
@@ -65,7 +64,7 @@ export class StreamManager {
65
64
  }
66
65
  try {
67
66
  this.ongoingCreation.add(peerId);
68
- await this.createStream(peer);
67
+ await this.createStream(peer.id);
69
68
  }
70
69
  catch (error) {
71
70
  this.log.error(`Failed to createStreamWithLock:`, error);
@@ -1 +1 @@
1
- {"version":3,"file":"stream_manager.js","sourceRoot":"","sources":["../../../src/lib/stream_manager/stream_manager.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,MAAM,eAAe,GAAG,UAAU,CAAC;AAEnC,MAAM,OAAO,aAAa;IAOd;IACA;IACA;IARO,GAAG,CAAS;IAErB,eAAe,GAAgB,IAAI,GAAG,EAAE,CAAC;IACzC,UAAU,GAA+B,IAAI,GAAG,EAAE,CAAC;IAE3D,YACU,UAAkB,EAClB,cAAwC,EACxC,gBAA4C;Q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M,cAAc,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;QAC5E,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,GAAG,IAAI,CAAC;IAC1C,CAAC;IAEO,cAAc,CAAC,MAAc;QACnC,OAAO,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC;IAC5C,CAAC;CACF"}
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@waku/core","version":"0.0.34-9f1d8ca.0","description":"TypeScript implementation of the Waku v2 protocol","types":"./dist/index.d.ts","module":"./dist/index.js","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./lib/message/version_0":{"types":"./dist/lib/message/version_0.d.ts","import":"./dist/lib/message/version_0.js"},"./lib/base_protocol":{"types":"./dist/lib/base_protocol.d.ts","import":"./dist/lib/base_protocol.js"}},"typesVersions":{"*":{"lib/*":["dist/lib/*"],"constants/*":["dist/constants/*"]}},"type":"module","homepage":"https://github.com/waku-org/js-waku/tree/master/packages/core#readme","repository":{"type":"git","url":"https://github.com/waku-org/js-waku.git"},"bugs":{"url":"https://github.com/waku-org/js-waku/issues"},"license":"MIT OR Apache-2.0","keywords":["waku","decentralised","communication","web3","ethereum","dapps"],"scripts":{"build":"run-s build:**","build:esm":"tsc","build:bundle":"rollup --config rollup.config.js","fix":"run-s fix:*","fix:lint":"eslint src *.js --fix","check":"run-s check:*","check:tsc":"tsc -p tsconfig.dev.json","check:lint":"eslint src *.js","check:spelling":"cspell \"{README.md,src/**/*.ts}\"","test":"NODE_ENV=test run-s test:*","test:node":"NODE_ENV=test TS_NODE_PROJECT=./tsconfig.dev.json mocha","test:browser":"NODE_ENV=test karma start karma.conf.cjs","watch:build":"tsc -p tsconfig.json -w","watch:test":"mocha --watch","prepublish":"npm run build","reset-hard":"git clean -dfx -e .idea && git reset --hard && npm i && npm run build"},"engines":{"node":">=20"},"dependencies":{"@waku/enr":"0.0.28-9f1d8ca.0","@waku/interfaces":"0.0.29-9f1d8ca.0","@libp2p/ping":"2.0.1","@waku/proto":"0.0.9-9f1d8ca.0","@waku/utils":"0.0.22-9f1d8ca.0","debug":"^4.3.4","it-all":"^3.0.4","it-length-prefixed":"^9.0.4","it-pipe":"^3.0.1","uint8arraylist":"^2.4.3","uuid":"^9.0.0"},"devDependencies":{"@libp2p/peer-id":"^5.0.1","@multiformats/multiaddr":"^12.0.0","@rollup/plugin-commonjs":"^25.0.7","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.2.3","@types/chai":"^4.3.11","@types/debug":"^4.1.12","@types/mocha":"^10.0.6","@types/uuid":"^9.0.8","@waku/build-utils":"*","chai":"^4.3.10","sinon":"^18.0.0","cspell":"^8.6.1","fast-check":"^3.19.0","ignore-loader":"^0.1.2","isomorphic-fetch":"^3.0.0","mocha":"^10.3.0","npm-run-all":"^4.1.5","process":"^0.11.10","rollup":"^4.12.0"},"peerDependencies":{"@multiformats/multiaddr":"^12.0.0","libp2p":"2.1.8"},"peerDependenciesMeta":{"@multiformats/multiaddr":{"optional":true},"libp2p":{"optional":true}},"files":["dist","bundle","src/**/*.ts","!**/*.spec.*","!**/*.json","CHANGELOG.md","LICENSE","README.md"]}
1
+ {"name":"@waku/core","version":"0.0.34-c41b319.0","description":"TypeScript implementation of the Waku v2 protocol","types":"./dist/index.d.ts","module":"./dist/index.js","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./lib/message/version_0":{"types":"./dist/lib/message/version_0.d.ts","import":"./dist/lib/message/version_0.js"},"./lib/base_protocol":{"types":"./dist/lib/base_protocol.d.ts","import":"./dist/lib/base_protocol.js"}},"typesVersions":{"*":{"lib/*":["dist/lib/*"],"constants/*":["dist/constants/*"]}},"type":"module","homepage":"https://github.com/waku-org/js-waku/tree/master/packages/core#readme","repository":{"type":"git","url":"https://github.com/waku-org/js-waku.git"},"bugs":{"url":"https://github.com/waku-org/js-waku/issues"},"license":"MIT OR Apache-2.0","keywords":["waku","decentralised","communication","web3","ethereum","dapps"],"scripts":{"build":"run-s build:**","build:esm":"tsc","build:bundle":"rollup --config rollup.config.js","fix":"run-s fix:*","fix:lint":"eslint src *.js --fix","check":"run-s check:*","check:tsc":"tsc -p tsconfig.dev.json","check:lint":"eslint src *.js","check:spelling":"cspell \"{README.md,src/**/*.ts}\"","test":"NODE_ENV=test run-s test:*","test:node":"NODE_ENV=test TS_NODE_PROJECT=./tsconfig.dev.json mocha","test:browser":"NODE_ENV=test karma start karma.conf.cjs","watch:build":"tsc -p tsconfig.json -w","watch:test":"mocha --watch","prepublish":"npm run build","reset-hard":"git clean -dfx -e .idea && git reset --hard && npm i && npm run build"},"engines":{"node":">=20"},"dependencies":{"@waku/enr":"0.0.28-c41b319.0","@waku/interfaces":"0.0.29-c41b319.0","@libp2p/ping":"2.0.1","@waku/proto":"0.0.9-c41b319.0","@waku/utils":"0.0.22-c41b319.0","debug":"^4.3.4","it-all":"^3.0.4","it-length-prefixed":"^9.0.4","it-pipe":"^3.0.1","uint8arraylist":"^2.4.3","uuid":"^9.0.0"},"devDependencies":{"@libp2p/peer-id":"^5.0.1","@libp2p/interface":"^2.1.3","@multiformats/multiaddr":"^12.0.0","@rollup/plugin-commonjs":"^25.0.7","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.2.3","@types/chai":"^4.3.11","@types/debug":"^4.1.12","@types/mocha":"^10.0.6","@types/uuid":"^9.0.8","@waku/build-utils":"*","chai":"^4.3.10","sinon":"^18.0.0","cspell":"^8.6.1","fast-check":"^3.19.0","ignore-loader":"^0.1.2","isomorphic-fetch":"^3.0.0","mocha":"^10.3.0","npm-run-all":"^4.1.5","process":"^0.11.10","rollup":"^4.12.0"},"peerDependencies":{"@multiformats/multiaddr":"^12.0.0","libp2p":"2.1.8"},"peerDependenciesMeta":{"@multiformats/multiaddr":{"optional":true},"libp2p":{"optional":true}},"files":["dist","bundle","src/**/*.ts","!**/*.spec.*","!**/*.json","CHANGELOG.md","LICENSE","README.md"]}
package/src/index.ts CHANGED
@@ -15,11 +15,8 @@ export { LightPushCodec, LightPushCore } from "./lib/light_push/index.js";
15
15
  export * as waku_store from "./lib/store/index.js";
16
16
  export { StoreCore, StoreCodec } from "./lib/store/index.js";
17
17
 
18
- export { ConnectionManager } from "./lib/connection_manager.js";
18
+ export { ConnectionManager } from "./lib/connection_manager/index.js";
19
19
 
20
- export { getHealthManager } from "./lib/health_manager.js";
21
-
22
- export { KeepAliveManager } from "./lib/keep_alive_manager.js";
23
20
  export { StreamManager } from "./lib/stream_manager/index.js";
24
21
 
25
22
  export { MetadataCodec, wakuMetadata } from "./lib/metadata/index.js";
@@ -1,14 +1,11 @@
1
1
  import type { Libp2p } from "@libp2p/interface";
2
- import type { Peer, Stream } from "@libp2p/interface";
2
+ import type { PeerId, Stream } from "@libp2p/interface";
3
3
  import type {
4
4
  IBaseProtocolCore,
5
5
  Libp2pComponents,
6
6
  PubsubTopic
7
7
  } from "@waku/interfaces";
8
- import { Logger } from "@waku/utils";
9
- import { getPeersForProtocol, sortPeersByLatency } from "@waku/utils/libp2p";
10
8
 
11
- import { filterPeersByDiscovery } from "./filterPeers.js";
12
9
  import { StreamManager } from "./stream_manager/index.js";
13
10
 
14
11
  /**
@@ -23,7 +20,6 @@ export class BaseProtocol implements IBaseProtocolCore {
23
20
  protected constructor(
24
21
  public multicodec: string,
25
22
  protected components: Libp2pComponents,
26
- private log: Logger,
27
23
  public readonly pubsubTopics: PubsubTopic[]
28
24
  ) {
29
25
  this.addLibp2pEventListener = components.events.addEventListener.bind(
@@ -42,76 +38,7 @@ export class BaseProtocol implements IBaseProtocolCore {
42
38
  );
43
39
  }
44
40
 
45
- protected async getStream(peer: Peer): Promise<Stream> {
46
- return this.streamManager.getStream(peer);
47
- }
48
-
49
- /**
50
- * Returns known peers from the address book (`libp2p.peerStore`) that support
51
- * the class protocol. Waku may or may not be currently connected to these
52
- * peers.
53
- */
54
- public async allPeers(): Promise<Peer[]> {
55
- return getPeersForProtocol(this.components.peerStore, [this.multicodec]);
56
- }
57
-
58
- public async connectedPeers(): Promise<Peer[]> {
59
- const peers = await this.allPeers();
60
- return peers.filter((peer) => {
61
- const connections = this.components.connectionManager.getConnections(
62
- peer.id
63
- );
64
- return connections.length > 0;
65
- });
66
- }
67
-
68
- /**
69
- * Retrieves a list of connected peers that support the protocol. The list is sorted by latency.
70
- *
71
- * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
72
- * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
73
- * @returns A list of peers that support the protocol sorted by latency. By default, returns all peers available, including bootstrap.
74
- */
75
- public async getPeers(
76
- {
77
- numPeers,
78
- maxBootstrapPeers
79
- }: {
80
- numPeers: number;
81
- maxBootstrapPeers: number;
82
- } = {
83
- maxBootstrapPeers: 0,
84
- numPeers: 0
85
- }
86
- ): Promise<Peer[]> {
87
- // Retrieve all connected peers that support the protocol & shard (if configured)
88
- const allAvailableConnectedPeers = await this.connectedPeers();
89
-
90
- // Filter the peers based on discovery & number of peers requested
91
- const filteredPeers = filterPeersByDiscovery(
92
- allAvailableConnectedPeers,
93
- numPeers,
94
- maxBootstrapPeers
95
- );
96
-
97
- // Sort the peers by latency
98
- const sortedFilteredPeers = await sortPeersByLatency(
99
- this.components.peerStore,
100
- filteredPeers
101
- );
102
-
103
- if (sortedFilteredPeers.length === 0) {
104
- this.log.warn(
105
- "No peers found. Ensure you have a connection to the network."
106
- );
107
- }
108
-
109
- if (sortedFilteredPeers.length < numPeers) {
110
- this.log.warn(
111
- `Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`
112
- );
113
- }
114
-
115
- return sortedFilteredPeers;
41
+ protected async getStream(peerId: PeerId): Promise<Stream> {
42
+ return this.streamManager.getStream(peerId);
116
43
  }
117
44
  }
@@ -1,5 +1,14 @@
1
- import type { Peer, PeerId, PeerInfo, PeerStore } from "@libp2p/interface";
2
- import { TypedEventEmitter } from "@libp2p/interface";
1
+ import {
2
+ type Connection,
3
+ isPeerId,
4
+ type Peer,
5
+ type PeerId,
6
+ type PeerInfo,
7
+ type PeerStore,
8
+ type Stream,
9
+ TypedEventEmitter
10
+ } from "@libp2p/interface";
11
+ import { Multiaddr, multiaddr, MultiaddrInput } from "@multiformats/multiaddr";
3
12
  import {
4
13
  ConnectionManagerOptions,
5
14
  DiscoveryTrigger,
@@ -10,7 +19,6 @@ import {
10
19
  IConnectionStateEvents,
11
20
  IPeersByDiscoveryEvents,
12
21
  IRelay,
13
- KeepAliveOptions,
14
22
  PeersByDiscoveryResult,
15
23
  PubsubTopic,
16
24
  ShardInfo
@@ -20,18 +28,31 @@ import { decodeRelayShard, shardInfoToPubsubTopics } from "@waku/utils";
20
28
  import { Logger } from "@waku/utils";
21
29
 
22
30
  import { KeepAliveManager } from "./keep_alive_manager.js";
31
+ import { getPeerPing } from "./utils.js";
23
32
 
24
33
  const log = new Logger("connection-manager");
25
34
 
26
- export const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 1;
27
- export const DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;
28
- export const DEFAULT_MAX_PARALLEL_DIALS = 3;
35
+ const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 1;
36
+ const DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;
37
+ const DEFAULT_MAX_PARALLEL_DIALS = 3;
38
+
39
+ const DEFAULT_PING_KEEP_ALIVE_SEC = 5 * 60;
40
+ const DEFAULT_RELAY_KEEP_ALIVE_SEC = 5 * 60;
41
+
42
+ type ConnectionManagerConstructorOptions = {
43
+ libp2p: Libp2p;
44
+ pubsubTopics: PubsubTopic[];
45
+ relay?: IRelay;
46
+ config?: Partial<ConnectionManagerOptions>;
47
+ };
29
48
 
30
49
  export class ConnectionManager
31
50
  extends TypedEventEmitter<IPeersByDiscoveryEvents & IConnectionStateEvents>
32
51
  implements IConnectionManager
33
52
  {
34
- private static instances = new Map<string, ConnectionManager>();
53
+ // TODO(weboko): make it private
54
+ public readonly pubsubTopics: PubsubTopic[];
55
+
35
56
  private keepAliveManager: KeepAliveManager;
36
57
  private options: ConnectionManagerOptions;
37
58
  private libp2p: Libp2p;
@@ -51,29 +72,6 @@ export class ConnectionManager
51
72
  return this.isP2PNetworkConnected;
52
73
  }
53
74
 
54
- public static create(
55
- peerId: string,
56
- libp2p: Libp2p,
57
- keepAliveOptions: KeepAliveOptions,
58
- pubsubTopics: PubsubTopic[],
59
- relay?: IRelay,
60
- options?: ConnectionManagerOptions
61
- ): ConnectionManager {
62
- let instance = ConnectionManager.instances.get(peerId);
63
- if (!instance) {
64
- instance = new ConnectionManager(
65
- libp2p,
66
- keepAliveOptions,
67
- pubsubTopics,
68
- relay,
69
- options
70
- );
71
- ConnectionManager.instances.set(peerId, instance);
72
- }
73
-
74
- return instance;
75
- }
76
-
77
75
  public stop(): void {
78
76
  this.keepAliveManager.stopAll();
79
77
  this.libp2p.removeEventListener(
@@ -156,27 +154,26 @@ export class ConnectionManager
156
154
  };
157
155
  }
158
156
 
159
- private constructor(
160
- libp2p: Libp2p,
161
- keepAliveOptions: KeepAliveOptions,
162
- public readonly configuredPubsubTopics: PubsubTopic[],
163
- relay?: IRelay,
164
- options?: Partial<ConnectionManagerOptions>
165
- ) {
157
+ public constructor(options: ConnectionManagerConstructorOptions) {
166
158
  super();
167
- this.libp2p = libp2p;
168
- this.configuredPubsubTopics = configuredPubsubTopics;
159
+ this.libp2p = options.libp2p;
160
+ this.pubsubTopics = options.pubsubTopics;
169
161
  this.options = {
170
162
  maxDialAttemptsForPeer: DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER,
171
163
  maxBootstrapPeersAllowed: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,
172
164
  maxParallelDials: DEFAULT_MAX_PARALLEL_DIALS,
173
- ...options
165
+ pingKeepAlive: DEFAULT_PING_KEEP_ALIVE_SEC,
166
+ relayKeepAlive: DEFAULT_RELAY_KEEP_ALIVE_SEC,
167
+ ...options.config
174
168
  };
175
169
 
176
170
  this.keepAliveManager = new KeepAliveManager({
177
- relay,
178
- libp2p,
179
- options: keepAliveOptions
171
+ relay: options.relay,
172
+ libp2p: options.libp2p,
173
+ options: {
174
+ pingKeepAlive: this.options.pingKeepAlive,
175
+ relayKeepAlive: this.options.relayKeepAlive
176
+ }
180
177
  });
181
178
 
182
179
  this.startEventListeners()
@@ -193,6 +190,29 @@ export class ConnectionManager
193
190
  );
194
191
  }
195
192
 
193
+ public async getConnectedPeers(codec?: string): Promise<Peer[]> {
194
+ const peerIDs = this.libp2p.getPeers();
195
+
196
+ if (peerIDs.length === 0) {
197
+ return [];
198
+ }
199
+
200
+ const peers = await Promise.all(
201
+ peerIDs.map(async (id) => {
202
+ try {
203
+ return await this.libp2p.peerStore.get(id);
204
+ } catch (e) {
205
+ return null;
206
+ }
207
+ })
208
+ );
209
+
210
+ return peers
211
+ .filter((p) => !!p)
212
+ .filter((p) => (codec ? (p as Peer).protocols.includes(codec) : true))
213
+ .sort((left, right) => getPeerPing(left) - getPeerPing(right)) as Peer[];
214
+ }
215
+
196
216
  private async dialPeerStorePeers(): Promise<void> {
197
217
  const peerInfos = await this.libp2p.peerStore.all();
198
218
  const dialPromises = [];
@@ -219,15 +239,60 @@ export class ConnectionManager
219
239
  this.startNetworkStatusListener();
220
240
  }
221
241
 
222
- private async dialPeer(peerId: PeerId): Promise<void> {
242
+ /**
243
+ * Attempts to establish a connection with a peer and set up specified protocols.
244
+ * The method handles both PeerId and Multiaddr inputs, manages connection attempts,
245
+ * and maintains the connection state.
246
+ *
247
+ * The dialing process includes:
248
+ * 1. Converting input to dialable peer info
249
+ * 2. Managing parallel dial attempts
250
+ * 3. Attempting to establish protocol-specific connections
251
+ * 4. Handling connection failures and retries
252
+ * 5. Updating the peer store and connection state
253
+ *
254
+ * @param {PeerId | MultiaddrInput} peer - The peer to connect to, either as a PeerId or multiaddr
255
+ * @param {string[]} [protocolCodecs] - Optional array of protocol-specific codec strings to establish
256
+ * (e.g., for LightPush, Filter, Store protocols)
257
+ *
258
+ * @throws {Error} If the multiaddr is missing a peer ID
259
+ * @throws {Error} If the maximum dial attempts are reached and the peer cannot be dialed
260
+ * @throws {Error} If there's an error deleting an undialable peer from the peer store
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * // Dial using PeerId
265
+ * await connectionManager.dialPeer(peerId);
266
+ *
267
+ * // Dial using multiaddr with specific protocols
268
+ * await connectionManager.dialPeer(multiaddr, [
269
+ * "/vac/waku/relay/2.0.0",
270
+ * "/vac/waku/lightpush/2.0.0-beta1"
271
+ * ]);
272
+ * ```
273
+ *
274
+ * @remarks
275
+ * - The method implements exponential backoff through multiple dial attempts
276
+ * - Maintains a queue for parallel dial attempts (limited by maxParallelDials)
277
+ * - Integrates with the KeepAliveManager for connection maintenance
278
+ * - Updates the peer store and connection state after successful/failed attempts
279
+ * - If all dial attempts fail, triggers DNS discovery as a fallback
280
+ */
281
+ public async dialPeer(peer: PeerId | MultiaddrInput): Promise<Connection> {
282
+ let connection: Connection | undefined;
283
+ let peerId: PeerId | undefined;
284
+ const peerDialInfo = this.getDialablePeerInfo(peer);
285
+ const peerIdStr = isPeerId(peerDialInfo)
286
+ ? peerDialInfo.toString()
287
+ : peerDialInfo.getPeerId()!;
288
+
223
289
  this.currentActiveParallelDialCount += 1;
224
290
  let dialAttempt = 0;
225
291
  while (dialAttempt < this.options.maxDialAttemptsForPeer) {
226
292
  try {
227
- log.info(
228
- `Dialing peer ${peerId.toString()} on attempt ${dialAttempt + 1}`
229
- );
230
- await this.libp2p.dial(peerId);
293
+ log.info(`Dialing peer ${peerDialInfo} on attempt ${dialAttempt + 1}`);
294
+ connection = await this.libp2p.dial(peerDialInfo);
295
+ peerId = connection.remotePeer;
231
296
 
232
297
  const tags = await this.getTagNamesForPeer(peerId);
233
298
  // add tag to connection describing discovery mechanism
@@ -246,21 +311,17 @@ export class ConnectionManager
246
311
  } catch (error) {
247
312
  if (error instanceof AggregateError) {
248
313
  // Handle AggregateError
249
- log.error(
250
- `Error dialing peer ${peerId.toString()} - ${error.errors}`
251
- );
314
+ log.error(`Error dialing peer ${peerIdStr} - ${error.errors}`);
252
315
  } else {
253
316
  // Handle generic error
254
317
  log.error(
255
- `Error dialing peer ${peerId.toString()} - ${
256
- (error as any).message
257
- }`
318
+ `Error dialing peer ${peerIdStr} - ${(error as any).message}`
258
319
  );
259
320
  }
260
- this.dialErrorsForPeer.set(peerId.toString(), error);
321
+ this.dialErrorsForPeer.set(peerIdStr, error);
261
322
 
262
323
  dialAttempt++;
263
- this.dialAttemptsForPeer.set(peerId.toString(), dialAttempt);
324
+ this.dialAttemptsForPeer.set(peerIdStr, dialAttempt);
264
325
  }
265
326
  }
266
327
 
@@ -271,7 +332,7 @@ export class ConnectionManager
271
332
  // If max dial attempts reached and dialing failed, delete the peer
272
333
  if (dialAttempt === this.options.maxDialAttemptsForPeer) {
273
334
  try {
274
- const error = this.dialErrorsForPeer.get(peerId.toString());
335
+ const error = this.dialErrorsForPeer.get(peerIdStr);
275
336
 
276
337
  if (error) {
277
338
  let errorMessage;
@@ -288,21 +349,65 @@ export class ConnectionManager
288
349
  }
289
350
 
290
351
  log.info(
291
- `Deleting undialable peer ${peerId.toString()} from peer store. Reason: ${errorMessage}`
352
+ `Deleting undialable peer ${peerIdStr} from peer store. Reason: ${errorMessage}`
292
353
  );
293
354
  }
294
355
 
295
- this.dialErrorsForPeer.delete(peerId.toString());
296
- await this.libp2p.peerStore.delete(peerId);
356
+ this.dialErrorsForPeer.delete(peerIdStr);
357
+ if (peerId) {
358
+ await this.libp2p.peerStore.delete(peerId);
359
+ }
297
360
 
298
361
  // if it was last available peer - attempt DNS discovery
299
362
  await this.attemptDnsDiscovery();
300
363
  } catch (error) {
301
364
  throw new Error(
302
- `Error deleting undialable peer ${peerId.toString()} from peer store - ${error}`
365
+ `Error deleting undialable peer ${peerIdStr} from peer store - ${error}`
303
366
  );
304
367
  }
305
368
  }
369
+
370
+ if (!connection) {
371
+ throw new Error(`Failed to dial peer ${peerDialInfo}`);
372
+ }
373
+
374
+ return connection;
375
+ }
376
+
377
+ /**
378
+ * Dial a peer with specific protocols.
379
+ * This method is a raw proxy to the libp2p dialProtocol method.
380
+ * @param peer - The peer to connect to, either as a PeerId or multiaddr
381
+ * @param protocolCodecs - Optional array of protocol-specific codec strings to establish
382
+ * @returns A stream to the peer
383
+ */
384
+ public async rawDialPeerWithProtocols(
385
+ peer: PeerId | MultiaddrInput,
386
+ protocolCodecs: string[]
387
+ ): Promise<Stream> {
388
+ const peerDialInfo = this.getDialablePeerInfo(peer);
389
+ return await this.libp2p.dialProtocol(peerDialInfo, protocolCodecs);
390
+ }
391
+
392
+ /**
393
+ * Internal utility to extract a PeerId or Multiaddr from a peer input.
394
+ * This is used internally by the connection manager to handle different peer input formats.
395
+ * @internal
396
+ */
397
+ private getDialablePeerInfo(
398
+ peer: PeerId | MultiaddrInput
399
+ ): PeerId | Multiaddr {
400
+ if (isPeerId(peer)) {
401
+ return peer;
402
+ } else {
403
+ // peer is of MultiaddrInput type
404
+ const ma = multiaddr(peer);
405
+ const peerIdStr = ma.getPeerId();
406
+ if (!peerIdStr) {
407
+ throw new Error("Failed to dial multiaddr: missing peer ID");
408
+ }
409
+ return ma;
410
+ }
306
411
  }
307
412
 
308
413
  private async attemptDnsDiscovery(): Promise<void> {
@@ -478,7 +583,7 @@ export class ConnectionManager
478
583
 
479
584
  log.warn(
480
585
  `Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${
481
- this.configuredPubsubTopics
586
+ this.pubsubTopics
482
587
  }).
483
588
  Not dialing.`
484
589
  );
@@ -573,7 +678,7 @@ export class ConnectionManager
573
678
  const pubsubTopics = shardInfoToPubsubTopics(shardInfo);
574
679
 
575
680
  const isTopicConfigured = pubsubTopics.some((topic) =>
576
- this.configuredPubsubTopics.includes(topic)
681
+ this.pubsubTopics.includes(topic)
577
682
  );
578
683
  return isTopicConfigured;
579
684
  }
@@ -0,0 +1 @@
1
+ export { ConnectionManager } from "./connection_manager.js";
@@ -1,14 +1,18 @@
1
1
  import type { PeerId } from "@libp2p/interface";
2
2
  import type { IRelay, Libp2p, PeerIdStr } from "@waku/interfaces";
3
- import type { KeepAliveOptions } from "@waku/interfaces";
4
3
  import { Logger, pubsubTopicToSingleShardInfo } from "@waku/utils";
5
4
  import { utf8ToBytes } from "@waku/utils/bytes";
6
5
 
7
- import { createEncoder } from "./message/version_0.js";
6
+ import { createEncoder } from "../message/version_0.js";
8
7
 
9
- export const RelayPingContentTopic = "/relay-ping/1/ping/null";
8
+ const RelayPingContentTopic = "/relay-ping/1/ping/null";
10
9
  const log = new Logger("keep-alive");
11
10
 
11
+ type KeepAliveOptions = {
12
+ pingKeepAlive: number;
13
+ relayKeepAlive: number;
14
+ };
15
+
12
16
  type CreateKeepAliveManagerOptions = {
13
17
  options: KeepAliveOptions;
14
18
  libp2p: Libp2p;
@@ -0,0 +1,25 @@
1
+ import type { Peer } from "@libp2p/interface";
2
+ import { bytesToUtf8 } from "@waku/utils/bytes";
3
+
4
+ /**
5
+ * Reads peer's metadata and retrieves ping value.
6
+ * @param peer Peer or null
7
+ * @returns -1 if no ping attached, otherwise returns ping value
8
+ */
9
+ export const getPeerPing = (peer: Peer | null): number => {
10
+ if (!peer) {
11
+ return -1;
12
+ }
13
+
14
+ try {
15
+ const bytes = peer.metadata.get("ping");
16
+
17
+ if (!bytes) {
18
+ return -1;
19
+ }
20
+
21
+ return Number(bytesToUtf8(bytes));
22
+ } catch (e) {
23
+ return -1;
24
+ }
25
+ };