@waku/core 0.0.37-7a9850d.0 → 0.0.37-987c6cd.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/index.js +4745 -899
- package/bundle/lib/message/version_0.js +1 -1
- package/bundle/{version_0-9DPFjcJG.js → version_0-BpF0pNhc.js} +314 -35
- package/dist/.tsbuildinfo +1 -1
- package/dist/lib/connection_manager/connection_limiter.d.ts +37 -0
- package/dist/lib/connection_manager/connection_limiter.js +124 -0
- package/dist/lib/connection_manager/connection_limiter.js.map +1 -0
- package/dist/lib/connection_manager/connection_manager.d.ts +20 -105
- package/dist/lib/connection_manager/connection_manager.js +83 -508
- package/dist/lib/connection_manager/connection_manager.js.map +1 -1
- package/dist/lib/connection_manager/dialer.d.ts +28 -0
- package/dist/lib/connection_manager/dialer.js +100 -0
- package/dist/lib/connection_manager/dialer.js.map +1 -0
- package/dist/lib/connection_manager/discovery_dialer.d.ts +26 -0
- package/dist/lib/connection_manager/discovery_dialer.js +68 -0
- package/dist/lib/connection_manager/discovery_dialer.js.map +1 -0
- package/dist/lib/connection_manager/keep_alive_manager.d.ts +17 -7
- package/dist/lib/connection_manager/keep_alive_manager.js +110 -74
- package/dist/lib/connection_manager/keep_alive_manager.js.map +1 -1
- package/dist/lib/connection_manager/network_monitor.d.ts +36 -0
- package/dist/lib/connection_manager/network_monitor.js +81 -0
- package/dist/lib/connection_manager/network_monitor.js.map +1 -0
- package/dist/lib/connection_manager/shard_reader.d.ts +28 -0
- package/dist/lib/connection_manager/shard_reader.js +70 -0
- package/dist/lib/connection_manager/shard_reader.js.map +1 -0
- package/dist/lib/connection_manager/utils.d.ts +16 -1
- package/dist/lib/connection_manager/utils.js +23 -0
- package/dist/lib/connection_manager/utils.js.map +1 -1
- package/dist/lib/filter/filter.d.ts +2 -3
- package/dist/lib/filter/filter.js +5 -25
- package/dist/lib/filter/filter.js.map +1 -1
- package/dist/lib/light_push/light_push.d.ts +2 -3
- package/dist/lib/light_push/light_push.js +1 -3
- package/dist/lib/light_push/light_push.js.map +1 -1
- package/package.json +1 -1
- package/src/lib/connection_manager/connection_limiter.ts +201 -0
- package/src/lib/connection_manager/connection_manager.ts +104 -669
- package/src/lib/connection_manager/dialer.ts +139 -0
- package/src/lib/connection_manager/discovery_dialer.ts +106 -0
- package/src/lib/connection_manager/keep_alive_manager.ts +154 -87
- package/src/lib/connection_manager/network_monitor.ts +112 -0
- package/src/lib/connection_manager/shard_reader.ts +134 -0
- package/src/lib/connection_manager/utils.ts +27 -1
- package/src/lib/filter/filter.ts +3 -28
- package/src/lib/light_push/light_push.ts +1 -5
@@ -1,166 +1,58 @@
|
|
1
|
-
import {
|
2
|
-
|
3
|
-
isPeerId,
|
4
|
-
type Peer,
|
5
|
-
type PeerId,
|
6
|
-
type PeerInfo,
|
7
|
-
type Stream,
|
8
|
-
TypedEventEmitter
|
9
|
-
} from "@libp2p/interface";
|
10
|
-
import { Multiaddr, multiaddr, MultiaddrInput } from "@multiformats/multiaddr";
|
1
|
+
import { type Peer, type PeerId, type Stream } from "@libp2p/interface";
|
2
|
+
import { MultiaddrInput } from "@multiformats/multiaddr";
|
11
3
|
import {
|
12
4
|
ConnectionManagerOptions,
|
13
|
-
DiscoveryTrigger,
|
14
|
-
DNS_DISCOVERY_TAG,
|
15
|
-
EConnectionStateEvents,
|
16
|
-
EPeersByDiscoveryEvents,
|
17
5
|
IConnectionManager,
|
18
|
-
IConnectionStateEvents,
|
19
|
-
IPeersByDiscoveryEvents,
|
20
6
|
IRelay,
|
21
|
-
|
22
|
-
|
23
|
-
|
7
|
+
IWakuEventEmitter,
|
8
|
+
NetworkConfig,
|
9
|
+
PubsubTopic
|
24
10
|
} from "@waku/interfaces";
|
25
|
-
import { Libp2p
|
26
|
-
import { decodeRelayShard, shardInfoToPubsubTopics } from "@waku/utils";
|
11
|
+
import { Libp2p } from "@waku/interfaces";
|
27
12
|
import { Logger } from "@waku/utils";
|
28
13
|
|
14
|
+
import { ConnectionLimiter } from "./connection_limiter.js";
|
15
|
+
import { Dialer } from "./dialer.js";
|
16
|
+
import { DiscoveryDialer } from "./discovery_dialer.js";
|
29
17
|
import { KeepAliveManager } from "./keep_alive_manager.js";
|
30
|
-
import {
|
18
|
+
import { NetworkMonitor } from "./network_monitor.js";
|
19
|
+
import { ShardReader } from "./shard_reader.js";
|
20
|
+
import { getPeerPing, mapToPeerId, mapToPeerIdOrMultiaddr } from "./utils.js";
|
31
21
|
|
32
22
|
const log = new Logger("connection-manager");
|
33
23
|
|
34
24
|
const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 1;
|
35
|
-
const DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;
|
36
|
-
const DEFAULT_MAX_PARALLEL_DIALS = 3;
|
37
|
-
|
38
25
|
const DEFAULT_PING_KEEP_ALIVE_SEC = 5 * 60;
|
39
26
|
const DEFAULT_RELAY_KEEP_ALIVE_SEC = 5 * 60;
|
40
27
|
|
41
28
|
type ConnectionManagerConstructorOptions = {
|
42
29
|
libp2p: Libp2p;
|
30
|
+
events: IWakuEventEmitter;
|
43
31
|
pubsubTopics: PubsubTopic[];
|
32
|
+
networkConfig: NetworkConfig;
|
44
33
|
relay?: IRelay;
|
45
34
|
config?: Partial<ConnectionManagerOptions>;
|
46
35
|
};
|
47
36
|
|
48
|
-
export class ConnectionManager
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
|
53
|
-
|
37
|
+
export class ConnectionManager implements IConnectionManager {
|
38
|
+
private readonly pubsubTopics: PubsubTopic[];
|
39
|
+
|
40
|
+
private readonly keepAliveManager: KeepAliveManager;
|
41
|
+
private readonly discoveryDialer: DiscoveryDialer;
|
42
|
+
private readonly dialer: Dialer;
|
43
|
+
private readonly shardReader: ShardReader;
|
44
|
+
private readonly networkMonitor: NetworkMonitor;
|
45
|
+
private readonly connectionLimiter: ConnectionLimiter;
|
54
46
|
|
55
|
-
private keepAliveManager: KeepAliveManager;
|
56
47
|
private options: ConnectionManagerOptions;
|
57
48
|
private libp2p: Libp2p;
|
58
|
-
private dialAttemptsForPeer: Map<string, number> = new Map();
|
59
|
-
private dialErrorsForPeer: Map<string, any> = new Map();
|
60
|
-
|
61
|
-
private currentActiveParallelDialCount = 0;
|
62
|
-
private pendingPeerDialQueue: Array<PeerId> = [];
|
63
|
-
|
64
|
-
private isP2PNetworkConnected: boolean = false;
|
65
|
-
|
66
|
-
public isConnected(): boolean {
|
67
|
-
if (globalThis?.navigator && !globalThis?.navigator?.onLine) {
|
68
|
-
return false;
|
69
|
-
}
|
70
|
-
|
71
|
-
return this.isP2PNetworkConnected;
|
72
|
-
}
|
73
|
-
|
74
|
-
public stop(): void {
|
75
|
-
this.keepAliveManager.stopAll();
|
76
|
-
this.libp2p.removeEventListener(
|
77
|
-
"peer:connect",
|
78
|
-
this.onEventHandlers["peer:connect"]
|
79
|
-
);
|
80
|
-
this.libp2p.removeEventListener(
|
81
|
-
"peer:disconnect",
|
82
|
-
this.onEventHandlers["peer:disconnect"]
|
83
|
-
);
|
84
|
-
this.libp2p.removeEventListener(
|
85
|
-
"peer:discovery",
|
86
|
-
this.onEventHandlers["peer:discovery"]
|
87
|
-
);
|
88
|
-
this.stopNetworkStatusListener();
|
89
|
-
}
|
90
|
-
|
91
|
-
public async dropConnection(peerId: PeerId): Promise<void> {
|
92
|
-
try {
|
93
|
-
this.keepAliveManager.stop(peerId);
|
94
|
-
await this.libp2p.hangUp(peerId);
|
95
|
-
log.info(`Dropped connection with peer ${peerId.toString()}`);
|
96
|
-
} catch (error) {
|
97
|
-
log.error(
|
98
|
-
`Error dropping connection with peer ${peerId.toString()} - ${error}`
|
99
|
-
);
|
100
|
-
}
|
101
|
-
}
|
102
|
-
|
103
|
-
public async getPeersByDiscovery(): Promise<PeersByDiscoveryResult> {
|
104
|
-
const peersDiscovered = await this.libp2p.peerStore.all();
|
105
|
-
const peersConnected = this.libp2p
|
106
|
-
.getConnections()
|
107
|
-
.map((conn) => conn.remotePeer);
|
108
|
-
|
109
|
-
const peersDiscoveredByBootstrap: Peer[] = [];
|
110
|
-
const peersDiscoveredByPeerExchange: Peer[] = [];
|
111
|
-
const peersDiscoveredByLocal: Peer[] = [];
|
112
|
-
|
113
|
-
const peersConnectedByBootstrap: Peer[] = [];
|
114
|
-
const peersConnectedByPeerExchange: Peer[] = [];
|
115
|
-
const peersConnectedByLocal: Peer[] = [];
|
116
|
-
|
117
|
-
for (const peer of peersDiscovered) {
|
118
|
-
const tags = await this.getTagNamesForPeer(peer.id);
|
119
|
-
|
120
|
-
if (tags.includes(Tags.BOOTSTRAP)) {
|
121
|
-
peersDiscoveredByBootstrap.push(peer);
|
122
|
-
} else if (tags.includes(Tags.PEER_EXCHANGE)) {
|
123
|
-
peersDiscoveredByPeerExchange.push(peer);
|
124
|
-
} else if (tags.includes(Tags.LOCAL)) {
|
125
|
-
peersDiscoveredByLocal.push(peer);
|
126
|
-
}
|
127
|
-
}
|
128
|
-
|
129
|
-
for (const peerId of peersConnected) {
|
130
|
-
const peer = await this.libp2p.peerStore.get(peerId);
|
131
|
-
const tags = await this.getTagNamesForPeer(peerId);
|
132
|
-
|
133
|
-
if (tags.includes(Tags.BOOTSTRAP)) {
|
134
|
-
peersConnectedByBootstrap.push(peer);
|
135
|
-
} else if (tags.includes(Tags.PEER_EXCHANGE)) {
|
136
|
-
peersConnectedByPeerExchange.push(peer);
|
137
|
-
} else if (tags.includes(Tags.LOCAL)) {
|
138
|
-
peersConnectedByLocal.push(peer);
|
139
|
-
}
|
140
|
-
}
|
141
|
-
|
142
|
-
return {
|
143
|
-
DISCOVERED: {
|
144
|
-
[Tags.BOOTSTRAP]: peersDiscoveredByBootstrap,
|
145
|
-
[Tags.PEER_EXCHANGE]: peersDiscoveredByPeerExchange,
|
146
|
-
[Tags.LOCAL]: peersDiscoveredByLocal
|
147
|
-
},
|
148
|
-
CONNECTED: {
|
149
|
-
[Tags.BOOTSTRAP]: peersConnectedByBootstrap,
|
150
|
-
[Tags.PEER_EXCHANGE]: peersConnectedByPeerExchange,
|
151
|
-
[Tags.LOCAL]: peersConnectedByLocal
|
152
|
-
}
|
153
|
-
};
|
154
|
-
}
|
155
49
|
|
156
50
|
public constructor(options: ConnectionManagerConstructorOptions) {
|
157
|
-
super();
|
158
51
|
this.libp2p = options.libp2p;
|
159
52
|
this.pubsubTopics = options.pubsubTopics;
|
53
|
+
|
160
54
|
this.options = {
|
161
|
-
|
162
|
-
maxBootstrapPeersAllowed: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,
|
163
|
-
maxParallelDials: DEFAULT_MAX_PARALLEL_DIALS,
|
55
|
+
maxBootstrapPeers: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,
|
164
56
|
pingKeepAlive: DEFAULT_PING_KEEP_ALIVE_SEC,
|
165
57
|
relayKeepAlive: DEFAULT_RELAY_KEEP_ALIVE_SEC,
|
166
58
|
...options.config
|
@@ -175,584 +67,127 @@ export class ConnectionManager
|
|
175
67
|
}
|
176
68
|
});
|
177
69
|
|
178
|
-
this.
|
179
|
-
|
180
|
-
.
|
181
|
-
|
182
|
-
);
|
183
|
-
|
184
|
-
// libp2p emits `peer:discovery` events during its initialization
|
185
|
-
// which means that before the ConnectionManager is initialized, some peers may have been discovered
|
186
|
-
// we will dial the peers in peerStore ONCE before we start to listen to the `peer:discovery` events within the ConnectionManager
|
187
|
-
this.dialPeerStorePeers().catch((error) =>
|
188
|
-
log.error(`Unexpected error while dialing peer store peers`, error)
|
189
|
-
);
|
190
|
-
}
|
70
|
+
this.shardReader = new ShardReader({
|
71
|
+
libp2p: options.libp2p,
|
72
|
+
networkConfig: options.networkConfig
|
73
|
+
});
|
191
74
|
|
192
|
-
|
193
|
-
|
75
|
+
this.dialer = new Dialer({
|
76
|
+
libp2p: options.libp2p,
|
77
|
+
shardReader: this.shardReader
|
78
|
+
});
|
194
79
|
|
195
|
-
|
196
|
-
|
197
|
-
|
80
|
+
this.discoveryDialer = new DiscoveryDialer({
|
81
|
+
libp2p: options.libp2p,
|
82
|
+
dialer: this.dialer
|
83
|
+
});
|
198
84
|
|
199
|
-
|
200
|
-
|
201
|
-
|
202
|
-
|
203
|
-
} catch (e) {
|
204
|
-
return null;
|
205
|
-
}
|
206
|
-
})
|
207
|
-
);
|
85
|
+
this.networkMonitor = new NetworkMonitor({
|
86
|
+
libp2p: options.libp2p,
|
87
|
+
events: options.events
|
88
|
+
});
|
208
89
|
|
209
|
-
|
210
|
-
.
|
211
|
-
|
212
|
-
.
|
90
|
+
this.connectionLimiter = new ConnectionLimiter({
|
91
|
+
libp2p: options.libp2p,
|
92
|
+
events: options.events,
|
93
|
+
networkMonitor: this.networkMonitor,
|
94
|
+
dialer: this.dialer,
|
95
|
+
options: this.options
|
96
|
+
});
|
213
97
|
}
|
214
98
|
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
|
220
|
-
this.libp2p.getConnections().find((c) => c.remotePeer === peerInfo.id)
|
221
|
-
)
|
222
|
-
continue;
|
223
|
-
|
224
|
-
dialPromises.push(this.attemptDial(peerInfo.id));
|
225
|
-
}
|
226
|
-
try {
|
227
|
-
await Promise.all(dialPromises);
|
228
|
-
} catch (error) {
|
229
|
-
log.error(`Unexpected error while dialing peer store peers`, error);
|
230
|
-
}
|
99
|
+
public start(): void {
|
100
|
+
this.networkMonitor.start();
|
101
|
+
this.discoveryDialer.start();
|
102
|
+
this.keepAliveManager.start();
|
103
|
+
this.connectionLimiter.start();
|
231
104
|
}
|
232
105
|
|
233
|
-
|
234
|
-
this.
|
235
|
-
this.
|
236
|
-
this.
|
237
|
-
|
238
|
-
this.startNetworkStatusListener();
|
106
|
+
public stop(): void {
|
107
|
+
this.networkMonitor.stop();
|
108
|
+
this.discoveryDialer.stop();
|
109
|
+
this.keepAliveManager.stop();
|
110
|
+
this.connectionLimiter.stop();
|
239
111
|
}
|
240
112
|
|
241
|
-
|
242
|
-
|
243
|
-
* The method handles both PeerId and Multiaddr inputs, manages connection attempts,
|
244
|
-
* and maintains the connection state.
|
245
|
-
*
|
246
|
-
* The dialing process includes:
|
247
|
-
* 1. Converting input to dialable peer info
|
248
|
-
* 2. Managing parallel dial attempts
|
249
|
-
* 3. Attempting to establish protocol-specific connections
|
250
|
-
* 4. Handling connection failures and retries
|
251
|
-
* 5. Updating the peer store and connection state
|
252
|
-
*
|
253
|
-
* @param {PeerId | MultiaddrInput} peer - The peer to connect to, either as a PeerId or multiaddr
|
254
|
-
* @param {string[]} [protocolCodecs] - Optional array of protocol-specific codec strings to establish
|
255
|
-
* (e.g., for LightPush, Filter, Store protocols)
|
256
|
-
*
|
257
|
-
* @throws {Error} If the multiaddr is missing a peer ID
|
258
|
-
* @throws {Error} If the maximum dial attempts are reached and the peer cannot be dialed
|
259
|
-
* @throws {Error} If there's an error deleting an undialable peer from the peer store
|
260
|
-
*
|
261
|
-
* @example
|
262
|
-
* ```typescript
|
263
|
-
* // Dial using PeerId
|
264
|
-
* await connectionManager.dialPeer(peerId);
|
265
|
-
*
|
266
|
-
* // Dial using multiaddr with specific protocols
|
267
|
-
* await connectionManager.dialPeer(multiaddr, [
|
268
|
-
* "/vac/waku/relay/2.0.0",
|
269
|
-
* "/vac/waku/lightpush/2.0.0-beta1"
|
270
|
-
* ]);
|
271
|
-
* ```
|
272
|
-
*
|
273
|
-
* @remarks
|
274
|
-
* - The method implements exponential backoff through multiple dial attempts
|
275
|
-
* - Maintains a queue for parallel dial attempts (limited by maxParallelDials)
|
276
|
-
* - Integrates with the KeepAliveManager for connection maintenance
|
277
|
-
* - Updates the peer store and connection state after successful/failed attempts
|
278
|
-
* - If all dial attempts fail, triggers DNS discovery as a fallback
|
279
|
-
*/
|
280
|
-
public async dialPeer(peer: PeerId | MultiaddrInput): Promise<Connection> {
|
281
|
-
let connection: Connection | undefined;
|
282
|
-
let peerId: PeerId | undefined;
|
283
|
-
const peerDialInfo = this.getDialablePeerInfo(peer);
|
284
|
-
const peerIdStr = isPeerId(peerDialInfo)
|
285
|
-
? peerDialInfo.toString()
|
286
|
-
: peerDialInfo.getPeerId()!;
|
287
|
-
|
288
|
-
this.currentActiveParallelDialCount += 1;
|
289
|
-
let dialAttempt = 0;
|
290
|
-
while (dialAttempt < this.options.maxDialAttemptsForPeer) {
|
291
|
-
try {
|
292
|
-
log.info(`Dialing peer ${peerDialInfo} on attempt ${dialAttempt + 1}`);
|
293
|
-
connection = await this.libp2p.dial(peerDialInfo);
|
294
|
-
peerId = connection.remotePeer;
|
295
|
-
|
296
|
-
const tags = await this.getTagNamesForPeer(peerId);
|
297
|
-
// add tag to connection describing discovery mechanism
|
298
|
-
// don't add duplicate tags
|
299
|
-
this.libp2p.getConnections(peerId).forEach((conn) => {
|
300
|
-
conn.tags = Array.from(new Set([...conn.tags, ...tags]));
|
301
|
-
});
|
302
|
-
|
303
|
-
// instead of deleting the peer from the peer store, we set the dial attempt to -1
|
304
|
-
// this helps us keep track of peers that have been dialed before
|
305
|
-
this.dialAttemptsForPeer.set(peerId.toString(), -1);
|
306
|
-
|
307
|
-
// Dialing succeeded, break the loop
|
308
|
-
this.keepAliveManager.start(peerId);
|
309
|
-
break;
|
310
|
-
} catch (error) {
|
311
|
-
if (error instanceof AggregateError) {
|
312
|
-
// Handle AggregateError
|
313
|
-
log.error(`Error dialing peer ${peerIdStr} - ${error.errors}`);
|
314
|
-
} else {
|
315
|
-
// Handle generic error
|
316
|
-
log.error(
|
317
|
-
`Error dialing peer ${peerIdStr} - ${(error as any).message}`
|
318
|
-
);
|
319
|
-
}
|
320
|
-
this.dialErrorsForPeer.set(peerIdStr, error);
|
321
|
-
|
322
|
-
dialAttempt++;
|
323
|
-
this.dialAttemptsForPeer.set(peerIdStr, dialAttempt);
|
324
|
-
}
|
325
|
-
}
|
326
|
-
|
327
|
-
// Always decrease the active dial count and process the dial queue
|
328
|
-
this.currentActiveParallelDialCount--;
|
329
|
-
this.processDialQueue();
|
330
|
-
|
331
|
-
// If max dial attempts reached and dialing failed, delete the peer
|
332
|
-
if (dialAttempt === this.options.maxDialAttemptsForPeer) {
|
333
|
-
try {
|
334
|
-
const error = this.dialErrorsForPeer.get(peerIdStr);
|
335
|
-
|
336
|
-
if (error) {
|
337
|
-
let errorMessage;
|
338
|
-
if (error instanceof AggregateError) {
|
339
|
-
if (!error.errors) {
|
340
|
-
log.warn(`No errors array found for AggregateError`);
|
341
|
-
} else if (error.errors.length === 0) {
|
342
|
-
log.warn(`Errors array is empty for AggregateError`);
|
343
|
-
} else {
|
344
|
-
errorMessage = JSON.stringify(error.errors[0]);
|
345
|
-
}
|
346
|
-
} else {
|
347
|
-
errorMessage = error.message;
|
348
|
-
}
|
349
|
-
|
350
|
-
log.info(
|
351
|
-
`Deleting undialable peer ${peerIdStr} from peer store. Reason: ${errorMessage}`
|
352
|
-
);
|
353
|
-
}
|
354
|
-
|
355
|
-
this.dialErrorsForPeer.delete(peerIdStr);
|
356
|
-
if (peerId) {
|
357
|
-
await this.libp2p.peerStore.delete(peerId);
|
358
|
-
}
|
359
|
-
|
360
|
-
// if it was last available peer - attempt DNS discovery
|
361
|
-
await this.attemptDnsDiscovery();
|
362
|
-
} catch (error) {
|
363
|
-
throw new Error(
|
364
|
-
`Error deleting undialable peer ${peerIdStr} from peer store - ${error}`
|
365
|
-
);
|
366
|
-
}
|
367
|
-
}
|
368
|
-
|
369
|
-
if (!connection) {
|
370
|
-
throw new Error(`Failed to dial peer ${peerDialInfo}`);
|
371
|
-
}
|
372
|
-
|
373
|
-
return connection;
|
113
|
+
public isConnected(): boolean {
|
114
|
+
return this.networkMonitor.isConnected();
|
374
115
|
}
|
375
116
|
|
376
|
-
|
377
|
-
* Dial a peer with specific protocols.
|
378
|
-
* This method is a raw proxy to the libp2p dialProtocol method.
|
379
|
-
* @param peer - The peer to connect to, either as a PeerId or multiaddr
|
380
|
-
* @param protocolCodecs - Optional array of protocol-specific codec strings to establish
|
381
|
-
* @returns A stream to the peer
|
382
|
-
*/
|
383
|
-
public async rawDialPeerWithProtocols(
|
117
|
+
public async dial(
|
384
118
|
peer: PeerId | MultiaddrInput,
|
385
119
|
protocolCodecs: string[]
|
386
120
|
): Promise<Stream> {
|
387
|
-
const
|
388
|
-
|
389
|
-
}
|
390
|
-
|
391
|
-
/**
|
392
|
-
* Internal utility to extract a PeerId or Multiaddr from a peer input.
|
393
|
-
* This is used internally by the connection manager to handle different peer input formats.
|
394
|
-
* @internal
|
395
|
-
*/
|
396
|
-
private getDialablePeerInfo(
|
397
|
-
peer: PeerId | MultiaddrInput
|
398
|
-
): PeerId | Multiaddr {
|
399
|
-
if (isPeerId(peer)) {
|
400
|
-
return peer;
|
401
|
-
} else {
|
402
|
-
// peer is of MultiaddrInput type
|
403
|
-
const ma = multiaddr(peer);
|
404
|
-
const peerIdStr = ma.getPeerId();
|
405
|
-
if (!peerIdStr) {
|
406
|
-
throw new Error("Failed to dial multiaddr: missing peer ID");
|
407
|
-
}
|
408
|
-
return ma;
|
409
|
-
}
|
410
|
-
}
|
411
|
-
|
412
|
-
private async attemptDnsDiscovery(): Promise<void> {
|
413
|
-
if (this.libp2p.getConnections().length > 0) return;
|
414
|
-
if ((await this.libp2p.peerStore.all()).length > 0) return;
|
415
|
-
|
416
|
-
log.info("Attempting to trigger DNS discovery.");
|
417
|
-
|
418
|
-
const dnsDiscovery = Object.values(this.libp2p.components.components).find(
|
419
|
-
(v: unknown) => {
|
420
|
-
if (v && v.toString) {
|
421
|
-
return v.toString().includes(DNS_DISCOVERY_TAG);
|
422
|
-
}
|
423
|
-
|
424
|
-
return false;
|
425
|
-
}
|
426
|
-
) as DiscoveryTrigger;
|
121
|
+
const ma = mapToPeerIdOrMultiaddr(peer);
|
122
|
+
log.info(`Dialing peer ${ma.toString()} with protocols ${protocolCodecs}`);
|
427
123
|
|
428
|
-
|
124
|
+
// must use libp2p directly instead of dialer because we need to dial the peer right away
|
125
|
+
const stream = await this.libp2p.dialProtocol(ma, protocolCodecs);
|
126
|
+
log.info(`Dialed peer ${ma.toString()} with protocols ${protocolCodecs}`);
|
429
127
|
|
430
|
-
|
128
|
+
return stream;
|
431
129
|
}
|
432
130
|
|
433
|
-
|
434
|
-
|
435
|
-
this.pendingPeerDialQueue.length > 0 &&
|
436
|
-
this.currentActiveParallelDialCount < this.options.maxParallelDials
|
437
|
-
) {
|
438
|
-
const peerId = this.pendingPeerDialQueue.shift();
|
439
|
-
if (!peerId) return;
|
440
|
-
this.attemptDial(peerId).catch((error) => {
|
441
|
-
log.error(error);
|
442
|
-
});
|
443
|
-
}
|
444
|
-
}
|
445
|
-
|
446
|
-
private startPeerDiscoveryListener(): void {
|
447
|
-
this.libp2p.addEventListener(
|
448
|
-
"peer:discovery",
|
449
|
-
this.onEventHandlers["peer:discovery"]
|
450
|
-
);
|
451
|
-
}
|
452
|
-
|
453
|
-
private startPeerConnectionListener(): void {
|
454
|
-
this.libp2p.addEventListener(
|
455
|
-
"peer:connect",
|
456
|
-
this.onEventHandlers["peer:connect"]
|
457
|
-
);
|
458
|
-
}
|
459
|
-
|
460
|
-
private startPeerDisconnectionListener(): void {
|
461
|
-
// TODO: ensure that these following issues are updated and confirmed
|
462
|
-
/**
|
463
|
-
* NOTE: Event is not being emitted on closing nor losing a connection.
|
464
|
-
* @see https://github.com/libp2p/js-libp2p/issues/939
|
465
|
-
* @see https://github.com/status-im/js-waku/issues/252
|
466
|
-
*
|
467
|
-
* >This event will be triggered anytime we are disconnected from another peer,
|
468
|
-
* >regardless of the circumstances of that disconnection.
|
469
|
-
* >If we happen to have multiple connections to a peer,
|
470
|
-
* >this event will **only** be triggered when the last connection is closed.
|
471
|
-
* @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100
|
472
|
-
*/
|
473
|
-
this.libp2p.addEventListener(
|
474
|
-
"peer:disconnect",
|
475
|
-
this.onEventHandlers["peer:disconnect"]
|
476
|
-
);
|
477
|
-
}
|
478
|
-
|
479
|
-
public async attemptDial(peerId: PeerId): Promise<void> {
|
480
|
-
if (!(await this.shouldDialPeer(peerId))) return;
|
481
|
-
|
482
|
-
if (this.currentActiveParallelDialCount >= this.options.maxParallelDials) {
|
483
|
-
this.pendingPeerDialQueue.push(peerId);
|
484
|
-
return;
|
485
|
-
}
|
486
|
-
|
487
|
-
await this.dialPeer(peerId);
|
488
|
-
}
|
489
|
-
|
490
|
-
private onEventHandlers = {
|
491
|
-
"peer:discovery": (evt: CustomEvent<PeerInfo>): void => {
|
492
|
-
void (async () => {
|
493
|
-
const { id: peerId } = evt.detail;
|
494
|
-
|
495
|
-
await this.dispatchDiscoveryEvent(peerId);
|
496
|
-
|
497
|
-
try {
|
498
|
-
await this.attemptDial(peerId);
|
499
|
-
} catch (error) {
|
500
|
-
log.error(`Error dialing peer ${peerId.toString()} : ${error}`);
|
501
|
-
}
|
502
|
-
})();
|
503
|
-
},
|
504
|
-
"peer:connect": (evt: CustomEvent<PeerId>): void => {
|
505
|
-
void (async () => {
|
506
|
-
log.info(`Connected to peer ${evt.detail.toString()}`);
|
507
|
-
|
508
|
-
const peerId = evt.detail;
|
509
|
-
|
510
|
-
this.keepAliveManager.start(peerId);
|
511
|
-
|
512
|
-
const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(
|
513
|
-
Tags.BOOTSTRAP
|
514
|
-
);
|
515
|
-
|
516
|
-
if (isBootstrap) {
|
517
|
-
const bootstrapConnections = this.libp2p
|
518
|
-
.getConnections()
|
519
|
-
.filter((conn) => conn.tags.includes(Tags.BOOTSTRAP));
|
520
|
-
|
521
|
-
// If we have too many bootstrap connections, drop one
|
522
|
-
if (
|
523
|
-
bootstrapConnections.length > this.options.maxBootstrapPeersAllowed
|
524
|
-
) {
|
525
|
-
await this.dropConnection(peerId);
|
526
|
-
} else {
|
527
|
-
this.dispatchEvent(
|
528
|
-
new CustomEvent<PeerId>(
|
529
|
-
EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP,
|
530
|
-
{
|
531
|
-
detail: peerId
|
532
|
-
}
|
533
|
-
)
|
534
|
-
);
|
535
|
-
}
|
536
|
-
} else {
|
537
|
-
this.dispatchEvent(
|
538
|
-
new CustomEvent<PeerId>(
|
539
|
-
EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE,
|
540
|
-
{
|
541
|
-
detail: peerId
|
542
|
-
}
|
543
|
-
)
|
544
|
-
);
|
545
|
-
}
|
546
|
-
|
547
|
-
this.setP2PNetworkConnected();
|
548
|
-
})();
|
549
|
-
},
|
550
|
-
"peer:disconnect": (evt: CustomEvent<PeerId>): void => {
|
551
|
-
void (async () => {
|
552
|
-
this.keepAliveManager.stop(evt.detail);
|
553
|
-
this.setP2PNetworkDisconnected();
|
554
|
-
})();
|
555
|
-
},
|
556
|
-
"browser:network": (): void => {
|
557
|
-
this.dispatchWakuConnectionEvent();
|
558
|
-
}
|
559
|
-
};
|
560
|
-
|
561
|
-
/**
|
562
|
-
* Checks if the peer should be dialed based on the following conditions:
|
563
|
-
* 1. If the peer is already connected, don't dial
|
564
|
-
* 2. If the peer is not part of any of the configured pubsub topics, don't dial
|
565
|
-
* 3. If the peer is not dialable based on bootstrap status, don't dial
|
566
|
-
* 4. If the peer is already has an active dial attempt, or has been dialed before, don't dial it
|
567
|
-
* @returns true if the peer should be dialed, false otherwise
|
568
|
-
*/
|
569
|
-
private async shouldDialPeer(peerId: PeerId): Promise<boolean> {
|
570
|
-
const isConnected = this.libp2p.getConnections(peerId).length > 0;
|
571
|
-
if (isConnected) {
|
572
|
-
log.warn(`Already connected to peer ${peerId.toString()}. Not dialing.`);
|
573
|
-
return false;
|
574
|
-
}
|
131
|
+
public async hangUp(peer: PeerId | MultiaddrInput): Promise<boolean> {
|
132
|
+
const peerId = mapToPeerId(peer);
|
575
133
|
|
576
|
-
|
577
|
-
|
578
|
-
|
579
|
-
|
580
|
-
log.warn(
|
581
|
-
`Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${
|
582
|
-
this.pubsubTopics
|
583
|
-
}).
|
584
|
-
Not dialing.`
|
585
|
-
);
|
586
|
-
|
587
|
-
return false;
|
588
|
-
}
|
134
|
+
try {
|
135
|
+
log.info(`Dropping connection with peer ${peerId.toString()}`);
|
136
|
+
await this.libp2p.hangUp(peerId);
|
137
|
+
log.info(`Dropped connection with peer ${peerId.toString()}`);
|
589
138
|
|
590
|
-
|
591
|
-
|
592
|
-
|
593
|
-
|
594
|
-
`Peer ${peerId.toString()} is not dialable based on bootstrap status. Not dialing.`
|
139
|
+
return true;
|
140
|
+
} catch (error) {
|
141
|
+
log.error(
|
142
|
+
`Error dropping connection with peer ${peerId.toString()} - ${error}`
|
595
143
|
);
|
596
|
-
return false;
|
597
|
-
}
|
598
144
|
|
599
|
-
const hasBeenDialed = this.dialAttemptsForPeer.has(peerId.toString());
|
600
|
-
if (hasBeenDialed) {
|
601
|
-
log.warn(
|
602
|
-
`Peer ${peerId.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`
|
603
|
-
);
|
604
145
|
return false;
|
605
146
|
}
|
606
|
-
|
607
|
-
return true;
|
608
147
|
}
|
609
148
|
|
610
|
-
|
611
|
-
|
612
|
-
* 1. If the peer is a bootstrap peer, it is only dialable if the number of current bootstrap connections is less than the max allowed.
|
613
|
-
* 2. If the peer is not a bootstrap peer
|
614
|
-
*/
|
615
|
-
private async isPeerDialableBasedOnBootstrapStatus(
|
616
|
-
peerId: PeerId
|
617
|
-
): Promise<boolean> {
|
618
|
-
const tagNames = await this.getTagNamesForPeer(peerId);
|
149
|
+
public async getConnectedPeers(codec?: string): Promise<Peer[]> {
|
150
|
+
const peerIDs = this.libp2p.getPeers();
|
619
151
|
|
620
|
-
|
152
|
+
log.info(`Getting connected peers for codec ${codec}`);
|
621
153
|
|
622
|
-
if (
|
623
|
-
|
154
|
+
if (peerIDs.length === 0) {
|
155
|
+
log.info(`No connected peers`);
|
156
|
+
return [];
|
624
157
|
}
|
625
158
|
|
626
|
-
const
|
627
|
-
.
|
628
|
-
|
629
|
-
|
630
|
-
|
631
|
-
|
632
|
-
return currentBootstrapConnections < this.options.maxBootstrapPeersAllowed;
|
633
|
-
}
|
634
|
-
|
635
|
-
private async dispatchDiscoveryEvent(peerId: PeerId): Promise<void> {
|
636
|
-
const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(
|
637
|
-
Tags.BOOTSTRAP
|
638
|
-
);
|
639
|
-
|
640
|
-
this.dispatchEvent(
|
641
|
-
new CustomEvent<PeerId>(
|
642
|
-
isBootstrap
|
643
|
-
? EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP
|
644
|
-
: EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE,
|
645
|
-
{
|
646
|
-
detail: peerId
|
159
|
+
const peers = await Promise.all(
|
160
|
+
peerIDs.map(async (id) => {
|
161
|
+
try {
|
162
|
+
return await this.libp2p.peerStore.get(id);
|
163
|
+
} catch (e) {
|
164
|
+
return null;
|
647
165
|
}
|
648
|
-
)
|
166
|
+
})
|
649
167
|
);
|
650
|
-
}
|
651
|
-
|
652
|
-
/**
|
653
|
-
* Fetches the tag names for a given peer
|
654
|
-
*/
|
655
|
-
private async getTagNamesForPeer(peerId: PeerId): Promise<string[]> {
|
656
|
-
try {
|
657
|
-
const peer = await this.libp2p.peerStore.get(peerId);
|
658
|
-
return Array.from(peer.tags.keys());
|
659
|
-
} catch (error) {
|
660
|
-
log.error(`Failed to get peer ${peerId}, error: ${error}`);
|
661
|
-
return [];
|
662
|
-
}
|
663
|
-
}
|
664
168
|
|
665
|
-
|
666
|
-
|
169
|
+
const result = peers
|
170
|
+
.filter((p) => !!p)
|
171
|
+
.filter((p) => (codec ? (p as Peer).protocols.includes(codec) : true))
|
172
|
+
.sort((left, right) => getPeerPing(left) - getPeerPing(right)) as Peer[];
|
667
173
|
|
668
|
-
|
669
|
-
return true;
|
670
|
-
}
|
174
|
+
log.info(`Found ${result.length} connected peers for codec ${codec}`);
|
671
175
|
|
672
|
-
|
176
|
+
return result;
|
177
|
+
}
|
673
178
|
|
674
|
-
|
675
|
-
|
676
|
-
|
179
|
+
public isTopicConfigured(pubsubTopic: PubsubTopic): boolean {
|
180
|
+
return this.pubsubTopics.includes(pubsubTopic);
|
181
|
+
}
|
677
182
|
|
678
|
-
|
183
|
+
public async hasShardInfo(peerId: PeerId): Promise<boolean> {
|
184
|
+
return this.shardReader.hasShardInfo(peerId);
|
679
185
|
}
|
680
186
|
|
681
|
-
public async
|
187
|
+
public async isPeerOnTopic(
|
682
188
|
peerId: PeerId,
|
683
189
|
pubsubTopic: string
|
684
190
|
): Promise<boolean> {
|
685
|
-
|
686
|
-
|
687
|
-
if (!shardInfo) {
|
688
|
-
return true;
|
689
|
-
}
|
690
|
-
|
691
|
-
const pubsubTopics = shardInfoToPubsubTopics(shardInfo);
|
692
|
-
return pubsubTopics.some((t) => t === pubsubTopic);
|
693
|
-
}
|
694
|
-
|
695
|
-
private async getPeerShardInfo(
|
696
|
-
peerId: PeerId
|
697
|
-
): Promise<ShardInfo | undefined> {
|
698
|
-
const peer = await this.libp2p.peerStore.get(peerId);
|
699
|
-
const shardInfoBytes = peer.metadata.get("shardInfo");
|
700
|
-
if (!shardInfoBytes) return undefined;
|
701
|
-
return decodeRelayShard(shardInfoBytes);
|
702
|
-
}
|
703
|
-
|
704
|
-
private startNetworkStatusListener(): void {
|
705
|
-
try {
|
706
|
-
globalThis.addEventListener(
|
707
|
-
"online",
|
708
|
-
this.onEventHandlers["browser:network"]
|
709
|
-
);
|
710
|
-
globalThis.addEventListener(
|
711
|
-
"offline",
|
712
|
-
this.onEventHandlers["browser:network"]
|
713
|
-
);
|
714
|
-
} catch (err) {
|
715
|
-
log.error(`Failed to start network listener: ${err}`);
|
716
|
-
}
|
717
|
-
}
|
718
|
-
|
719
|
-
private stopNetworkStatusListener(): void {
|
720
|
-
try {
|
721
|
-
globalThis.removeEventListener(
|
722
|
-
"online",
|
723
|
-
this.onEventHandlers["browser:network"]
|
724
|
-
);
|
725
|
-
globalThis.removeEventListener(
|
726
|
-
"offline",
|
727
|
-
this.onEventHandlers["browser:network"]
|
728
|
-
);
|
729
|
-
} catch (err) {
|
730
|
-
log.error(`Failed to stop network listener: ${err}`);
|
731
|
-
}
|
732
|
-
}
|
733
|
-
|
734
|
-
private setP2PNetworkConnected(): void {
|
735
|
-
if (!this.isP2PNetworkConnected) {
|
736
|
-
this.isP2PNetworkConnected = true;
|
737
|
-
this.dispatchWakuConnectionEvent();
|
738
|
-
}
|
739
|
-
}
|
740
|
-
|
741
|
-
private setP2PNetworkDisconnected(): void {
|
742
|
-
if (
|
743
|
-
this.isP2PNetworkConnected &&
|
744
|
-
this.libp2p.getConnections().length === 0
|
745
|
-
) {
|
746
|
-
this.isP2PNetworkConnected = false;
|
747
|
-
this.dispatchWakuConnectionEvent();
|
748
|
-
}
|
749
|
-
}
|
750
|
-
|
751
|
-
private dispatchWakuConnectionEvent(): void {
|
752
|
-
this.dispatchEvent(
|
753
|
-
new CustomEvent<boolean>(EConnectionStateEvents.CONNECTION_STATUS, {
|
754
|
-
detail: this.isConnected()
|
755
|
-
})
|
756
|
-
);
|
191
|
+
return this.shardReader.isPeerOnTopic(peerId, pubsubTopic);
|
757
192
|
}
|
758
193
|
}
|