@waku/core 0.0.37-7a9850d.0 → 0.0.37-c24842a.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 +4852 -904
- package/bundle/lib/message/version_0.js +1 -1
- package/bundle/{version_0-9DPFjcJG.js → version_0-BHaZD8Qu.js} +485 -60
- package/dist/.tsbuildinfo +1 -1
- package/dist/lib/connection_manager/connection_limiter.d.ts +46 -0
- package/dist/lib/connection_manager/connection_limiter.js +177 -0
- package/dist/lib/connection_manager/connection_limiter.js.map +1 -0
- package/dist/lib/connection_manager/connection_manager.d.ts +18 -106
- package/dist/lib/connection_manager/connection_manager.js +95 -512
- package/dist/lib/connection_manager/connection_manager.js.map +1 -1
- package/dist/lib/connection_manager/dialer.d.ts +34 -0
- package/dist/lib/connection_manager/dialer.js +135 -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/dist/lib/metadata/metadata.d.ts +2 -2
- package/dist/lib/metadata/metadata.js +14 -8
- package/dist/lib/metadata/metadata.js.map +1 -1
- package/package.json +1 -1
- package/src/lib/connection_manager/connection_limiter.ts +292 -0
- package/src/lib/connection_manager/connection_manager.ts +112 -673
- package/src/lib/connection_manager/dialer.ts +192 -0
- package/src/lib/connection_manager/discovery_dialer.ts +104 -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
- package/src/lib/metadata/metadata.ts +13 -12
@@ -1,110 +1,40 @@
|
|
1
|
-
import { isPeerId, TypedEventEmitter } from "@libp2p/interface";
|
2
|
-
import { multiaddr } from "@multiformats/multiaddr";
|
3
|
-
import { DNS_DISCOVERY_TAG, EConnectionStateEvents, EPeersByDiscoveryEvents } from "@waku/interfaces";
|
4
|
-
import { Tags } from "@waku/interfaces";
|
5
|
-
import { decodeRelayShard, shardInfoToPubsubTopics } from "@waku/utils";
|
6
1
|
import { Logger } from "@waku/utils";
|
2
|
+
import { ConnectionLimiter } from "./connection_limiter.js";
|
3
|
+
import { Dialer } from "./dialer.js";
|
4
|
+
import { DiscoveryDialer } from "./discovery_dialer.js";
|
7
5
|
import { KeepAliveManager } from "./keep_alive_manager.js";
|
8
|
-
import {
|
6
|
+
import { NetworkMonitor } from "./network_monitor.js";
|
7
|
+
import { ShardReader } from "./shard_reader.js";
|
8
|
+
import { getPeerPing, mapToPeerId, mapToPeerIdOrMultiaddr } from "./utils.js";
|
9
9
|
const log = new Logger("connection-manager");
|
10
|
-
const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED =
|
11
|
-
const DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;
|
12
|
-
const DEFAULT_MAX_PARALLEL_DIALS = 3;
|
10
|
+
const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 3;
|
13
11
|
const DEFAULT_PING_KEEP_ALIVE_SEC = 5 * 60;
|
14
12
|
const DEFAULT_RELAY_KEEP_ALIVE_SEC = 5 * 60;
|
15
|
-
|
16
|
-
|
17
|
-
|
13
|
+
const DEFAULT_ENABLE_AUTO_RECOVERY = true;
|
14
|
+
const DEFAULT_MAX_CONNECTIONS = 10;
|
15
|
+
const DEFAULT_MAX_DIALING_PEERS = 3;
|
16
|
+
const DEFAULT_FAILED_DIAL_COOLDOWN_SEC = 60;
|
17
|
+
const DEFAULT_DIAL_COOLDOWN_SEC = 10;
|
18
|
+
export class ConnectionManager {
|
18
19
|
keepAliveManager;
|
20
|
+
discoveryDialer;
|
21
|
+
dialer;
|
22
|
+
shardReader;
|
23
|
+
networkMonitor;
|
24
|
+
connectionLimiter;
|
19
25
|
options;
|
20
26
|
libp2p;
|
21
|
-
dialAttemptsForPeer = new Map();
|
22
|
-
dialErrorsForPeer = new Map();
|
23
|
-
currentActiveParallelDialCount = 0;
|
24
|
-
pendingPeerDialQueue = [];
|
25
|
-
isP2PNetworkConnected = false;
|
26
|
-
isConnected() {
|
27
|
-
if (globalThis?.navigator && !globalThis?.navigator?.onLine) {
|
28
|
-
return false;
|
29
|
-
}
|
30
|
-
return this.isP2PNetworkConnected;
|
31
|
-
}
|
32
|
-
stop() {
|
33
|
-
this.keepAliveManager.stopAll();
|
34
|
-
this.libp2p.removeEventListener("peer:connect", this.onEventHandlers["peer:connect"]);
|
35
|
-
this.libp2p.removeEventListener("peer:disconnect", this.onEventHandlers["peer:disconnect"]);
|
36
|
-
this.libp2p.removeEventListener("peer:discovery", this.onEventHandlers["peer:discovery"]);
|
37
|
-
this.stopNetworkStatusListener();
|
38
|
-
}
|
39
|
-
async dropConnection(peerId) {
|
40
|
-
try {
|
41
|
-
this.keepAliveManager.stop(peerId);
|
42
|
-
await this.libp2p.hangUp(peerId);
|
43
|
-
log.info(`Dropped connection with peer ${peerId.toString()}`);
|
44
|
-
}
|
45
|
-
catch (error) {
|
46
|
-
log.error(`Error dropping connection with peer ${peerId.toString()} - ${error}`);
|
47
|
-
}
|
48
|
-
}
|
49
|
-
async getPeersByDiscovery() {
|
50
|
-
const peersDiscovered = await this.libp2p.peerStore.all();
|
51
|
-
const peersConnected = this.libp2p
|
52
|
-
.getConnections()
|
53
|
-
.map((conn) => conn.remotePeer);
|
54
|
-
const peersDiscoveredByBootstrap = [];
|
55
|
-
const peersDiscoveredByPeerExchange = [];
|
56
|
-
const peersDiscoveredByLocal = [];
|
57
|
-
const peersConnectedByBootstrap = [];
|
58
|
-
const peersConnectedByPeerExchange = [];
|
59
|
-
const peersConnectedByLocal = [];
|
60
|
-
for (const peer of peersDiscovered) {
|
61
|
-
const tags = await this.getTagNamesForPeer(peer.id);
|
62
|
-
if (tags.includes(Tags.BOOTSTRAP)) {
|
63
|
-
peersDiscoveredByBootstrap.push(peer);
|
64
|
-
}
|
65
|
-
else if (tags.includes(Tags.PEER_EXCHANGE)) {
|
66
|
-
peersDiscoveredByPeerExchange.push(peer);
|
67
|
-
}
|
68
|
-
else if (tags.includes(Tags.LOCAL)) {
|
69
|
-
peersDiscoveredByLocal.push(peer);
|
70
|
-
}
|
71
|
-
}
|
72
|
-
for (const peerId of peersConnected) {
|
73
|
-
const peer = await this.libp2p.peerStore.get(peerId);
|
74
|
-
const tags = await this.getTagNamesForPeer(peerId);
|
75
|
-
if (tags.includes(Tags.BOOTSTRAP)) {
|
76
|
-
peersConnectedByBootstrap.push(peer);
|
77
|
-
}
|
78
|
-
else if (tags.includes(Tags.PEER_EXCHANGE)) {
|
79
|
-
peersConnectedByPeerExchange.push(peer);
|
80
|
-
}
|
81
|
-
else if (tags.includes(Tags.LOCAL)) {
|
82
|
-
peersConnectedByLocal.push(peer);
|
83
|
-
}
|
84
|
-
}
|
85
|
-
return {
|
86
|
-
DISCOVERED: {
|
87
|
-
[Tags.BOOTSTRAP]: peersDiscoveredByBootstrap,
|
88
|
-
[Tags.PEER_EXCHANGE]: peersDiscoveredByPeerExchange,
|
89
|
-
[Tags.LOCAL]: peersDiscoveredByLocal
|
90
|
-
},
|
91
|
-
CONNECTED: {
|
92
|
-
[Tags.BOOTSTRAP]: peersConnectedByBootstrap,
|
93
|
-
[Tags.PEER_EXCHANGE]: peersConnectedByPeerExchange,
|
94
|
-
[Tags.LOCAL]: peersConnectedByLocal
|
95
|
-
}
|
96
|
-
};
|
97
|
-
}
|
98
27
|
constructor(options) {
|
99
|
-
super();
|
100
28
|
this.libp2p = options.libp2p;
|
101
|
-
this.pubsubTopics = options.pubsubTopics;
|
102
29
|
this.options = {
|
103
|
-
|
104
|
-
|
105
|
-
maxParallelDials: DEFAULT_MAX_PARALLEL_DIALS,
|
30
|
+
maxBootstrapPeers: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,
|
31
|
+
maxConnections: DEFAULT_MAX_CONNECTIONS,
|
106
32
|
pingKeepAlive: DEFAULT_PING_KEEP_ALIVE_SEC,
|
107
33
|
relayKeepAlive: DEFAULT_RELAY_KEEP_ALIVE_SEC,
|
34
|
+
enableAutoRecovery: DEFAULT_ENABLE_AUTO_RECOVERY,
|
35
|
+
maxDialingPeers: DEFAULT_MAX_DIALING_PEERS,
|
36
|
+
failedDialCooldown: DEFAULT_FAILED_DIAL_COOLDOWN_SEC,
|
37
|
+
dialCooldown: DEFAULT_DIAL_COOLDOWN_SEC,
|
108
38
|
...options.config
|
109
39
|
};
|
110
40
|
this.keepAliveManager = new KeepAliveManager({
|
@@ -115,17 +45,74 @@ export class ConnectionManager extends TypedEventEmitter {
|
|
115
45
|
relayKeepAlive: this.options.relayKeepAlive
|
116
46
|
}
|
117
47
|
});
|
118
|
-
this.
|
119
|
-
|
120
|
-
|
121
|
-
|
122
|
-
|
123
|
-
|
124
|
-
|
48
|
+
this.shardReader = new ShardReader({
|
49
|
+
libp2p: options.libp2p,
|
50
|
+
networkConfig: options.networkConfig
|
51
|
+
});
|
52
|
+
this.dialer = new Dialer({
|
53
|
+
libp2p: options.libp2p,
|
54
|
+
shardReader: this.shardReader,
|
55
|
+
options: this.options
|
56
|
+
});
|
57
|
+
this.discoveryDialer = new DiscoveryDialer({
|
58
|
+
libp2p: options.libp2p,
|
59
|
+
dialer: this.dialer
|
60
|
+
});
|
61
|
+
this.networkMonitor = new NetworkMonitor({
|
62
|
+
libp2p: options.libp2p,
|
63
|
+
events: options.events
|
64
|
+
});
|
65
|
+
this.connectionLimiter = new ConnectionLimiter({
|
66
|
+
libp2p: options.libp2p,
|
67
|
+
events: options.events,
|
68
|
+
networkMonitor: this.networkMonitor,
|
69
|
+
dialer: this.dialer,
|
70
|
+
options: this.options
|
71
|
+
});
|
72
|
+
}
|
73
|
+
start() {
|
74
|
+
this.dialer.start();
|
75
|
+
this.networkMonitor.start();
|
76
|
+
this.discoveryDialer.start();
|
77
|
+
this.keepAliveManager.start();
|
78
|
+
this.connectionLimiter.start();
|
79
|
+
}
|
80
|
+
stop() {
|
81
|
+
this.dialer.stop();
|
82
|
+
this.networkMonitor.stop();
|
83
|
+
this.discoveryDialer.stop();
|
84
|
+
this.keepAliveManager.stop();
|
85
|
+
this.connectionLimiter.stop();
|
86
|
+
}
|
87
|
+
isConnected() {
|
88
|
+
return this.networkMonitor.isConnected();
|
89
|
+
}
|
90
|
+
async dial(peer, protocolCodecs) {
|
91
|
+
const ma = mapToPeerIdOrMultiaddr(peer);
|
92
|
+
log.info(`Dialing peer ${ma.toString()} with protocols ${protocolCodecs}`);
|
93
|
+
// must use libp2p directly instead of dialer because we need to dial the peer right away
|
94
|
+
const stream = await this.libp2p.dialProtocol(ma, protocolCodecs);
|
95
|
+
log.info(`Dialed peer ${ma.toString()} with protocols ${protocolCodecs}`);
|
96
|
+
return stream;
|
97
|
+
}
|
98
|
+
async hangUp(peer) {
|
99
|
+
const peerId = mapToPeerId(peer);
|
100
|
+
try {
|
101
|
+
log.info(`Dropping connection with peer ${peerId.toString()}`);
|
102
|
+
await this.libp2p.hangUp(peerId);
|
103
|
+
log.info(`Dropped connection with peer ${peerId.toString()}`);
|
104
|
+
return true;
|
105
|
+
}
|
106
|
+
catch (error) {
|
107
|
+
log.error(`Error dropping connection with peer ${peerId.toString()} - ${error}`);
|
108
|
+
return false;
|
109
|
+
}
|
125
110
|
}
|
126
111
|
async getConnectedPeers(codec) {
|
127
112
|
const peerIDs = this.libp2p.getPeers();
|
113
|
+
log.info(`Getting connected peers for codec ${codec}`);
|
128
114
|
if (peerIDs.length === 0) {
|
115
|
+
log.info(`No connected peers`);
|
129
116
|
return [];
|
130
117
|
}
|
131
118
|
const peers = await Promise.all(peerIDs.map(async (id) => {
|
@@ -136,422 +123,18 @@ export class ConnectionManager extends TypedEventEmitter {
|
|
136
123
|
return null;
|
137
124
|
}
|
138
125
|
}));
|
139
|
-
|
126
|
+
const result = peers
|
140
127
|
.filter((p) => !!p)
|
141
128
|
.filter((p) => (codec ? p.protocols.includes(codec) : true))
|
142
129
|
.sort((left, right) => getPeerPing(left) - getPeerPing(right));
|
130
|
+
log.info(`Found ${result.length} connected peers for codec ${codec}`);
|
131
|
+
return result;
|
143
132
|
}
|
144
|
-
async
|
145
|
-
|
146
|
-
const dialPromises = [];
|
147
|
-
for (const peerInfo of peerInfos) {
|
148
|
-
if (this.libp2p.getConnections().find((c) => c.remotePeer === peerInfo.id))
|
149
|
-
continue;
|
150
|
-
dialPromises.push(this.attemptDial(peerInfo.id));
|
151
|
-
}
|
152
|
-
try {
|
153
|
-
await Promise.all(dialPromises);
|
154
|
-
}
|
155
|
-
catch (error) {
|
156
|
-
log.error(`Unexpected error while dialing peer store peers`, error);
|
157
|
-
}
|
158
|
-
}
|
159
|
-
async startEventListeners() {
|
160
|
-
this.startPeerDiscoveryListener();
|
161
|
-
this.startPeerConnectionListener();
|
162
|
-
this.startPeerDisconnectionListener();
|
163
|
-
this.startNetworkStatusListener();
|
164
|
-
}
|
165
|
-
/**
|
166
|
-
* Attempts to establish a connection with a peer and set up specified protocols.
|
167
|
-
* The method handles both PeerId and Multiaddr inputs, manages connection attempts,
|
168
|
-
* and maintains the connection state.
|
169
|
-
*
|
170
|
-
* The dialing process includes:
|
171
|
-
* 1. Converting input to dialable peer info
|
172
|
-
* 2. Managing parallel dial attempts
|
173
|
-
* 3. Attempting to establish protocol-specific connections
|
174
|
-
* 4. Handling connection failures and retries
|
175
|
-
* 5. Updating the peer store and connection state
|
176
|
-
*
|
177
|
-
* @param {PeerId | MultiaddrInput} peer - The peer to connect to, either as a PeerId or multiaddr
|
178
|
-
* @param {string[]} [protocolCodecs] - Optional array of protocol-specific codec strings to establish
|
179
|
-
* (e.g., for LightPush, Filter, Store protocols)
|
180
|
-
*
|
181
|
-
* @throws {Error} If the multiaddr is missing a peer ID
|
182
|
-
* @throws {Error} If the maximum dial attempts are reached and the peer cannot be dialed
|
183
|
-
* @throws {Error} If there's an error deleting an undialable peer from the peer store
|
184
|
-
*
|
185
|
-
* @example
|
186
|
-
* ```typescript
|
187
|
-
* // Dial using PeerId
|
188
|
-
* await connectionManager.dialPeer(peerId);
|
189
|
-
*
|
190
|
-
* // Dial using multiaddr with specific protocols
|
191
|
-
* await connectionManager.dialPeer(multiaddr, [
|
192
|
-
* "/vac/waku/relay/2.0.0",
|
193
|
-
* "/vac/waku/lightpush/2.0.0-beta1"
|
194
|
-
* ]);
|
195
|
-
* ```
|
196
|
-
*
|
197
|
-
* @remarks
|
198
|
-
* - The method implements exponential backoff through multiple dial attempts
|
199
|
-
* - Maintains a queue for parallel dial attempts (limited by maxParallelDials)
|
200
|
-
* - Integrates with the KeepAliveManager for connection maintenance
|
201
|
-
* - Updates the peer store and connection state after successful/failed attempts
|
202
|
-
* - If all dial attempts fail, triggers DNS discovery as a fallback
|
203
|
-
*/
|
204
|
-
async dialPeer(peer) {
|
205
|
-
let connection;
|
206
|
-
let peerId;
|
207
|
-
const peerDialInfo = this.getDialablePeerInfo(peer);
|
208
|
-
const peerIdStr = isPeerId(peerDialInfo)
|
209
|
-
? peerDialInfo.toString()
|
210
|
-
: peerDialInfo.getPeerId();
|
211
|
-
this.currentActiveParallelDialCount += 1;
|
212
|
-
let dialAttempt = 0;
|
213
|
-
while (dialAttempt < this.options.maxDialAttemptsForPeer) {
|
214
|
-
try {
|
215
|
-
log.info(`Dialing peer ${peerDialInfo} on attempt ${dialAttempt + 1}`);
|
216
|
-
connection = await this.libp2p.dial(peerDialInfo);
|
217
|
-
peerId = connection.remotePeer;
|
218
|
-
const tags = await this.getTagNamesForPeer(peerId);
|
219
|
-
// add tag to connection describing discovery mechanism
|
220
|
-
// don't add duplicate tags
|
221
|
-
this.libp2p.getConnections(peerId).forEach((conn) => {
|
222
|
-
conn.tags = Array.from(new Set([...conn.tags, ...tags]));
|
223
|
-
});
|
224
|
-
// instead of deleting the peer from the peer store, we set the dial attempt to -1
|
225
|
-
// this helps us keep track of peers that have been dialed before
|
226
|
-
this.dialAttemptsForPeer.set(peerId.toString(), -1);
|
227
|
-
// Dialing succeeded, break the loop
|
228
|
-
this.keepAliveManager.start(peerId);
|
229
|
-
break;
|
230
|
-
}
|
231
|
-
catch (error) {
|
232
|
-
if (error instanceof AggregateError) {
|
233
|
-
// Handle AggregateError
|
234
|
-
log.error(`Error dialing peer ${peerIdStr} - ${error.errors}`);
|
235
|
-
}
|
236
|
-
else {
|
237
|
-
// Handle generic error
|
238
|
-
log.error(`Error dialing peer ${peerIdStr} - ${error.message}`);
|
239
|
-
}
|
240
|
-
this.dialErrorsForPeer.set(peerIdStr, error);
|
241
|
-
dialAttempt++;
|
242
|
-
this.dialAttemptsForPeer.set(peerIdStr, dialAttempt);
|
243
|
-
}
|
244
|
-
}
|
245
|
-
// Always decrease the active dial count and process the dial queue
|
246
|
-
this.currentActiveParallelDialCount--;
|
247
|
-
this.processDialQueue();
|
248
|
-
// If max dial attempts reached and dialing failed, delete the peer
|
249
|
-
if (dialAttempt === this.options.maxDialAttemptsForPeer) {
|
250
|
-
try {
|
251
|
-
const error = this.dialErrorsForPeer.get(peerIdStr);
|
252
|
-
if (error) {
|
253
|
-
let errorMessage;
|
254
|
-
if (error instanceof AggregateError) {
|
255
|
-
if (!error.errors) {
|
256
|
-
log.warn(`No errors array found for AggregateError`);
|
257
|
-
}
|
258
|
-
else if (error.errors.length === 0) {
|
259
|
-
log.warn(`Errors array is empty for AggregateError`);
|
260
|
-
}
|
261
|
-
else {
|
262
|
-
errorMessage = JSON.stringify(error.errors[0]);
|
263
|
-
}
|
264
|
-
}
|
265
|
-
else {
|
266
|
-
errorMessage = error.message;
|
267
|
-
}
|
268
|
-
log.info(`Deleting undialable peer ${peerIdStr} from peer store. Reason: ${errorMessage}`);
|
269
|
-
}
|
270
|
-
this.dialErrorsForPeer.delete(peerIdStr);
|
271
|
-
if (peerId) {
|
272
|
-
await this.libp2p.peerStore.delete(peerId);
|
273
|
-
}
|
274
|
-
// if it was last available peer - attempt DNS discovery
|
275
|
-
await this.attemptDnsDiscovery();
|
276
|
-
}
|
277
|
-
catch (error) {
|
278
|
-
throw new Error(`Error deleting undialable peer ${peerIdStr} from peer store - ${error}`);
|
279
|
-
}
|
280
|
-
}
|
281
|
-
if (!connection) {
|
282
|
-
throw new Error(`Failed to dial peer ${peerDialInfo}`);
|
283
|
-
}
|
284
|
-
return connection;
|
285
|
-
}
|
286
|
-
/**
|
287
|
-
* Dial a peer with specific protocols.
|
288
|
-
* This method is a raw proxy to the libp2p dialProtocol method.
|
289
|
-
* @param peer - The peer to connect to, either as a PeerId or multiaddr
|
290
|
-
* @param protocolCodecs - Optional array of protocol-specific codec strings to establish
|
291
|
-
* @returns A stream to the peer
|
292
|
-
*/
|
293
|
-
async rawDialPeerWithProtocols(peer, protocolCodecs) {
|
294
|
-
const peerDialInfo = this.getDialablePeerInfo(peer);
|
295
|
-
return await this.libp2p.dialProtocol(peerDialInfo, protocolCodecs);
|
296
|
-
}
|
297
|
-
/**
|
298
|
-
* Internal utility to extract a PeerId or Multiaddr from a peer input.
|
299
|
-
* This is used internally by the connection manager to handle different peer input formats.
|
300
|
-
* @internal
|
301
|
-
*/
|
302
|
-
getDialablePeerInfo(peer) {
|
303
|
-
if (isPeerId(peer)) {
|
304
|
-
return peer;
|
305
|
-
}
|
306
|
-
else {
|
307
|
-
// peer is of MultiaddrInput type
|
308
|
-
const ma = multiaddr(peer);
|
309
|
-
const peerIdStr = ma.getPeerId();
|
310
|
-
if (!peerIdStr) {
|
311
|
-
throw new Error("Failed to dial multiaddr: missing peer ID");
|
312
|
-
}
|
313
|
-
return ma;
|
314
|
-
}
|
315
|
-
}
|
316
|
-
async attemptDnsDiscovery() {
|
317
|
-
if (this.libp2p.getConnections().length > 0)
|
318
|
-
return;
|
319
|
-
if ((await this.libp2p.peerStore.all()).length > 0)
|
320
|
-
return;
|
321
|
-
log.info("Attempting to trigger DNS discovery.");
|
322
|
-
const dnsDiscovery = Object.values(this.libp2p.components.components).find((v) => {
|
323
|
-
if (v && v.toString) {
|
324
|
-
return v.toString().includes(DNS_DISCOVERY_TAG);
|
325
|
-
}
|
326
|
-
return false;
|
327
|
-
});
|
328
|
-
if (!dnsDiscovery)
|
329
|
-
return;
|
330
|
-
await dnsDiscovery.findPeers();
|
331
|
-
}
|
332
|
-
processDialQueue() {
|
333
|
-
if (this.pendingPeerDialQueue.length > 0 &&
|
334
|
-
this.currentActiveParallelDialCount < this.options.maxParallelDials) {
|
335
|
-
const peerId = this.pendingPeerDialQueue.shift();
|
336
|
-
if (!peerId)
|
337
|
-
return;
|
338
|
-
this.attemptDial(peerId).catch((error) => {
|
339
|
-
log.error(error);
|
340
|
-
});
|
341
|
-
}
|
342
|
-
}
|
343
|
-
startPeerDiscoveryListener() {
|
344
|
-
this.libp2p.addEventListener("peer:discovery", this.onEventHandlers["peer:discovery"]);
|
133
|
+
async hasShardInfo(peerId) {
|
134
|
+
return this.shardReader.hasShardInfo(peerId);
|
345
135
|
}
|
346
|
-
|
347
|
-
this.
|
348
|
-
}
|
349
|
-
startPeerDisconnectionListener() {
|
350
|
-
// TODO: ensure that these following issues are updated and confirmed
|
351
|
-
/**
|
352
|
-
* NOTE: Event is not being emitted on closing nor losing a connection.
|
353
|
-
* @see https://github.com/libp2p/js-libp2p/issues/939
|
354
|
-
* @see https://github.com/status-im/js-waku/issues/252
|
355
|
-
*
|
356
|
-
* >This event will be triggered anytime we are disconnected from another peer,
|
357
|
-
* >regardless of the circumstances of that disconnection.
|
358
|
-
* >If we happen to have multiple connections to a peer,
|
359
|
-
* >this event will **only** be triggered when the last connection is closed.
|
360
|
-
* @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100
|
361
|
-
*/
|
362
|
-
this.libp2p.addEventListener("peer:disconnect", this.onEventHandlers["peer:disconnect"]);
|
363
|
-
}
|
364
|
-
async attemptDial(peerId) {
|
365
|
-
if (!(await this.shouldDialPeer(peerId)))
|
366
|
-
return;
|
367
|
-
if (this.currentActiveParallelDialCount >= this.options.maxParallelDials) {
|
368
|
-
this.pendingPeerDialQueue.push(peerId);
|
369
|
-
return;
|
370
|
-
}
|
371
|
-
await this.dialPeer(peerId);
|
372
|
-
}
|
373
|
-
onEventHandlers = {
|
374
|
-
"peer:discovery": (evt) => {
|
375
|
-
void (async () => {
|
376
|
-
const { id: peerId } = evt.detail;
|
377
|
-
await this.dispatchDiscoveryEvent(peerId);
|
378
|
-
try {
|
379
|
-
await this.attemptDial(peerId);
|
380
|
-
}
|
381
|
-
catch (error) {
|
382
|
-
log.error(`Error dialing peer ${peerId.toString()} : ${error}`);
|
383
|
-
}
|
384
|
-
})();
|
385
|
-
},
|
386
|
-
"peer:connect": (evt) => {
|
387
|
-
void (async () => {
|
388
|
-
log.info(`Connected to peer ${evt.detail.toString()}`);
|
389
|
-
const peerId = evt.detail;
|
390
|
-
this.keepAliveManager.start(peerId);
|
391
|
-
const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(Tags.BOOTSTRAP);
|
392
|
-
if (isBootstrap) {
|
393
|
-
const bootstrapConnections = this.libp2p
|
394
|
-
.getConnections()
|
395
|
-
.filter((conn) => conn.tags.includes(Tags.BOOTSTRAP));
|
396
|
-
// If we have too many bootstrap connections, drop one
|
397
|
-
if (bootstrapConnections.length > this.options.maxBootstrapPeersAllowed) {
|
398
|
-
await this.dropConnection(peerId);
|
399
|
-
}
|
400
|
-
else {
|
401
|
-
this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP, {
|
402
|
-
detail: peerId
|
403
|
-
}));
|
404
|
-
}
|
405
|
-
}
|
406
|
-
else {
|
407
|
-
this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE, {
|
408
|
-
detail: peerId
|
409
|
-
}));
|
410
|
-
}
|
411
|
-
this.setP2PNetworkConnected();
|
412
|
-
})();
|
413
|
-
},
|
414
|
-
"peer:disconnect": (evt) => {
|
415
|
-
void (async () => {
|
416
|
-
this.keepAliveManager.stop(evt.detail);
|
417
|
-
this.setP2PNetworkDisconnected();
|
418
|
-
})();
|
419
|
-
},
|
420
|
-
"browser:network": () => {
|
421
|
-
this.dispatchWakuConnectionEvent();
|
422
|
-
}
|
423
|
-
};
|
424
|
-
/**
|
425
|
-
* Checks if the peer should be dialed based on the following conditions:
|
426
|
-
* 1. If the peer is already connected, don't dial
|
427
|
-
* 2. If the peer is not part of any of the configured pubsub topics, don't dial
|
428
|
-
* 3. If the peer is not dialable based on bootstrap status, don't dial
|
429
|
-
* 4. If the peer is already has an active dial attempt, or has been dialed before, don't dial it
|
430
|
-
* @returns true if the peer should be dialed, false otherwise
|
431
|
-
*/
|
432
|
-
async shouldDialPeer(peerId) {
|
433
|
-
const isConnected = this.libp2p.getConnections(peerId).length > 0;
|
434
|
-
if (isConnected) {
|
435
|
-
log.warn(`Already connected to peer ${peerId.toString()}. Not dialing.`);
|
436
|
-
return false;
|
437
|
-
}
|
438
|
-
const isSameShard = await this.isPeerOnSameShard(peerId);
|
439
|
-
if (!isSameShard) {
|
440
|
-
const shardInfo = await this.getPeerShardInfo(peerId);
|
441
|
-
log.warn(`Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${this.pubsubTopics}).
|
442
|
-
Not dialing.`);
|
443
|
-
return false;
|
444
|
-
}
|
445
|
-
const isPreferredBasedOnBootstrap = await this.isPeerDialableBasedOnBootstrapStatus(peerId);
|
446
|
-
if (!isPreferredBasedOnBootstrap) {
|
447
|
-
log.warn(`Peer ${peerId.toString()} is not dialable based on bootstrap status. Not dialing.`);
|
448
|
-
return false;
|
449
|
-
}
|
450
|
-
const hasBeenDialed = this.dialAttemptsForPeer.has(peerId.toString());
|
451
|
-
if (hasBeenDialed) {
|
452
|
-
log.warn(`Peer ${peerId.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`);
|
453
|
-
return false;
|
454
|
-
}
|
455
|
-
return true;
|
456
|
-
}
|
457
|
-
/**
|
458
|
-
* Checks if the peer is dialable based on the following conditions:
|
459
|
-
* 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.
|
460
|
-
* 2. If the peer is not a bootstrap peer
|
461
|
-
*/
|
462
|
-
async isPeerDialableBasedOnBootstrapStatus(peerId) {
|
463
|
-
const tagNames = await this.getTagNamesForPeer(peerId);
|
464
|
-
const isBootstrap = tagNames.some((tagName) => tagName === Tags.BOOTSTRAP);
|
465
|
-
if (!isBootstrap) {
|
466
|
-
return true;
|
467
|
-
}
|
468
|
-
const currentBootstrapConnections = this.libp2p
|
469
|
-
.getConnections()
|
470
|
-
.filter((conn) => {
|
471
|
-
return conn.tags.find((name) => name === Tags.BOOTSTRAP);
|
472
|
-
}).length;
|
473
|
-
return currentBootstrapConnections < this.options.maxBootstrapPeersAllowed;
|
474
|
-
}
|
475
|
-
async dispatchDiscoveryEvent(peerId) {
|
476
|
-
const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(Tags.BOOTSTRAP);
|
477
|
-
this.dispatchEvent(new CustomEvent(isBootstrap
|
478
|
-
? EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP
|
479
|
-
: EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE, {
|
480
|
-
detail: peerId
|
481
|
-
}));
|
482
|
-
}
|
483
|
-
/**
|
484
|
-
* Fetches the tag names for a given peer
|
485
|
-
*/
|
486
|
-
async getTagNamesForPeer(peerId) {
|
487
|
-
try {
|
488
|
-
const peer = await this.libp2p.peerStore.get(peerId);
|
489
|
-
return Array.from(peer.tags.keys());
|
490
|
-
}
|
491
|
-
catch (error) {
|
492
|
-
log.error(`Failed to get peer ${peerId}, error: ${error}`);
|
493
|
-
return [];
|
494
|
-
}
|
495
|
-
}
|
496
|
-
async isPeerOnSameShard(peerId) {
|
497
|
-
const shardInfo = await this.getPeerShardInfo(peerId);
|
498
|
-
if (!shardInfo) {
|
499
|
-
return true;
|
500
|
-
}
|
501
|
-
const pubsubTopics = shardInfoToPubsubTopics(shardInfo);
|
502
|
-
const isTopicConfigured = pubsubTopics.some((topic) => this.pubsubTopics.includes(topic));
|
503
|
-
return isTopicConfigured;
|
504
|
-
}
|
505
|
-
async isPeerOnPubsubTopic(peerId, pubsubTopic) {
|
506
|
-
const shardInfo = await this.getPeerShardInfo(peerId);
|
507
|
-
if (!shardInfo) {
|
508
|
-
return true;
|
509
|
-
}
|
510
|
-
const pubsubTopics = shardInfoToPubsubTopics(shardInfo);
|
511
|
-
return pubsubTopics.some((t) => t === pubsubTopic);
|
512
|
-
}
|
513
|
-
async getPeerShardInfo(peerId) {
|
514
|
-
const peer = await this.libp2p.peerStore.get(peerId);
|
515
|
-
const shardInfoBytes = peer.metadata.get("shardInfo");
|
516
|
-
if (!shardInfoBytes)
|
517
|
-
return undefined;
|
518
|
-
return decodeRelayShard(shardInfoBytes);
|
519
|
-
}
|
520
|
-
startNetworkStatusListener() {
|
521
|
-
try {
|
522
|
-
globalThis.addEventListener("online", this.onEventHandlers["browser:network"]);
|
523
|
-
globalThis.addEventListener("offline", this.onEventHandlers["browser:network"]);
|
524
|
-
}
|
525
|
-
catch (err) {
|
526
|
-
log.error(`Failed to start network listener: ${err}`);
|
527
|
-
}
|
528
|
-
}
|
529
|
-
stopNetworkStatusListener() {
|
530
|
-
try {
|
531
|
-
globalThis.removeEventListener("online", this.onEventHandlers["browser:network"]);
|
532
|
-
globalThis.removeEventListener("offline", this.onEventHandlers["browser:network"]);
|
533
|
-
}
|
534
|
-
catch (err) {
|
535
|
-
log.error(`Failed to stop network listener: ${err}`);
|
536
|
-
}
|
537
|
-
}
|
538
|
-
setP2PNetworkConnected() {
|
539
|
-
if (!this.isP2PNetworkConnected) {
|
540
|
-
this.isP2PNetworkConnected = true;
|
541
|
-
this.dispatchWakuConnectionEvent();
|
542
|
-
}
|
543
|
-
}
|
544
|
-
setP2PNetworkDisconnected() {
|
545
|
-
if (this.isP2PNetworkConnected &&
|
546
|
-
this.libp2p.getConnections().length === 0) {
|
547
|
-
this.isP2PNetworkConnected = false;
|
548
|
-
this.dispatchWakuConnectionEvent();
|
549
|
-
}
|
550
|
-
}
|
551
|
-
dispatchWakuConnectionEvent() {
|
552
|
-
this.dispatchEvent(new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {
|
553
|
-
detail: this.isConnected()
|
554
|
-
}));
|
136
|
+
async isPeerOnTopic(peerId, pubsubTopic) {
|
137
|
+
return this.shardReader.isPeerOnTopic(peerId, pubsubTopic);
|
555
138
|
}
|
556
139
|
}
|
557
140
|
//# sourceMappingURL=connection_manager.js.map
|