@waku/core 0.0.33-aeb05cd.0 → 0.0.33-b7bdb60.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/base_protocol-BDjsZTsQ.js +275 -0
- package/bundle/{index-tdQNdKHx.js → index-CeEH6b9b.js} +24 -450
- package/bundle/index.js +99 -419
- package/bundle/lib/base_protocol.js +2 -2
- package/bundle/lib/message/version_0.js +2 -2
- package/bundle/{version_0-BrbNEwD-.js → version_0-BYg0O3M-.js} +451 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/dist/lib/base_protocol.d.ts +2 -3
- package/dist/lib/base_protocol.js +7 -10
- package/dist/lib/base_protocol.js.map +1 -1
- package/dist/lib/filter/index.d.ts +1 -2
- package/dist/lib/filter/index.js +1 -4
- package/dist/lib/filter/index.js.map +1 -1
- package/dist/lib/stream_manager/stream_manager.d.ts +12 -9
- package/dist/lib/stream_manager/stream_manager.js +87 -56
- package/dist/lib/stream_manager/stream_manager.js.map +1 -1
- package/dist/lib/stream_manager/utils.d.ts +1 -1
- package/dist/lib/stream_manager/utils.js +5 -17
- package/dist/lib/stream_manager/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +1 -3
- package/src/lib/base_protocol.ts +8 -22
- package/src/lib/filter/index.ts +0 -2
- package/src/lib/stream_manager/stream_manager.ts +124 -66
- package/src/lib/stream_manager/utils.ts +5 -17
- package/bundle/base_protocol-0xHh0_Hq.js +0 -334
- package/dist/lib/wait_for_remote_peer.d.ts +0 -22
- package/dist/lib/wait_for_remote_peer.js +0 -142
- package/dist/lib/wait_for_remote_peer.js.map +0 -1
- package/src/lib/wait_for_remote_peer.ts +0 -200
@@ -1,334 +0,0 @@
|
|
1
|
-
import { h as bytesToUtf8, T as Tags, L as Logger, e as pubsubTopicsToShardInfo } from './index-tdQNdKHx.js';
|
2
|
-
|
3
|
-
const decodeRelayShard = (bytes) => {
|
4
|
-
// explicitly converting to Uint8Array to avoid Buffer
|
5
|
-
// https://github.com/libp2p/js-libp2p/issues/2146
|
6
|
-
bytes = new Uint8Array(bytes);
|
7
|
-
if (bytes.length < 3)
|
8
|
-
throw new Error("Insufficient data");
|
9
|
-
const view = new DataView(bytes.buffer);
|
10
|
-
const clusterId = view.getUint16(0);
|
11
|
-
const shards = [];
|
12
|
-
if (bytes.length === 130) {
|
13
|
-
// rsv format (Bit Vector)
|
14
|
-
for (let i = 0; i < 1024; i++) {
|
15
|
-
const byteIndex = Math.floor(i / 8) + 2; // Adjusted for the 2-byte cluster field
|
16
|
-
const bitIndex = 7 - (i % 8);
|
17
|
-
if (view.getUint8(byteIndex) & (1 << bitIndex)) {
|
18
|
-
shards.push(i);
|
19
|
-
}
|
20
|
-
}
|
21
|
-
}
|
22
|
-
else {
|
23
|
-
// rs format (Index List)
|
24
|
-
const numIndices = view.getUint8(2);
|
25
|
-
for (let i = 0, offset = 3; i < numIndices; i++, offset += 2) {
|
26
|
-
if (offset + 1 >= bytes.length)
|
27
|
-
throw new Error("Unexpected end of data");
|
28
|
-
shards.push(view.getUint16(offset));
|
29
|
-
}
|
30
|
-
}
|
31
|
-
return { clusterId, shards };
|
32
|
-
};
|
33
|
-
const encodeRelayShard = (shardInfo) => {
|
34
|
-
const { clusterId, shards } = shardInfo;
|
35
|
-
const totalLength = shards.length >= 64 ? 130 : 3 + 2 * shards.length;
|
36
|
-
const buffer = new ArrayBuffer(totalLength);
|
37
|
-
const view = new DataView(buffer);
|
38
|
-
view.setUint16(0, clusterId);
|
39
|
-
if (shards.length >= 64) {
|
40
|
-
// rsv format (Bit Vector)
|
41
|
-
for (const index of shards) {
|
42
|
-
const byteIndex = Math.floor(index / 8) + 2; // Adjusted for the 2-byte cluster field
|
43
|
-
const bitIndex = 7 - (index % 8);
|
44
|
-
view.setUint8(byteIndex, view.getUint8(byteIndex) | (1 << bitIndex));
|
45
|
-
}
|
46
|
-
}
|
47
|
-
else {
|
48
|
-
// rs format (Index List)
|
49
|
-
view.setUint8(2, shards.length);
|
50
|
-
for (let i = 0, offset = 3; i < shards.length; i++, offset += 2) {
|
51
|
-
view.setUint16(offset, shards[i]);
|
52
|
-
}
|
53
|
-
}
|
54
|
-
return new Uint8Array(buffer);
|
55
|
-
};
|
56
|
-
|
57
|
-
/**
|
58
|
-
* Function to sort peers by latency from lowest to highest
|
59
|
-
* @param peerStore - The Libp2p PeerStore
|
60
|
-
* @param peers - The list of peers to choose from
|
61
|
-
* @returns Sorted array of peers by latency
|
62
|
-
*/
|
63
|
-
async function sortPeersByLatency(peerStore, peers) {
|
64
|
-
if (peers.length === 0)
|
65
|
-
return [];
|
66
|
-
const results = await Promise.all(peers.map(async (peer) => {
|
67
|
-
try {
|
68
|
-
const pingBytes = (await peerStore.get(peer.id)).metadata.get("ping");
|
69
|
-
if (!pingBytes)
|
70
|
-
return { peer, ping: Infinity };
|
71
|
-
const ping = Number(bytesToUtf8(pingBytes));
|
72
|
-
return { peer, ping };
|
73
|
-
}
|
74
|
-
catch (error) {
|
75
|
-
return { peer, ping: Infinity };
|
76
|
-
}
|
77
|
-
}));
|
78
|
-
// filter out null values
|
79
|
-
const validResults = results.filter((result) => result !== null);
|
80
|
-
return validResults
|
81
|
-
.sort((a, b) => a.ping - b.ping)
|
82
|
-
.map((result) => result.peer);
|
83
|
-
}
|
84
|
-
/**
|
85
|
-
* Returns the list of peers that supports the given protocol.
|
86
|
-
*/
|
87
|
-
async function getPeersForProtocol(peerStore, protocols) {
|
88
|
-
const peers = [];
|
89
|
-
await peerStore.forEach((peer) => {
|
90
|
-
for (let i = 0; i < protocols.length; i++) {
|
91
|
-
if (peer.protocols.includes(protocols[i])) {
|
92
|
-
peers.push(peer);
|
93
|
-
break;
|
94
|
-
}
|
95
|
-
}
|
96
|
-
});
|
97
|
-
return peers;
|
98
|
-
}
|
99
|
-
async function getConnectedPeersForProtocolAndShard(connections, peerStore, protocols, shardInfo) {
|
100
|
-
const openConnections = connections.filter((connection) => connection.status === "open");
|
101
|
-
const peerPromises = openConnections.map(async (connection) => {
|
102
|
-
const peer = await peerStore.get(connection.remotePeer);
|
103
|
-
const supportsProtocol = protocols.some((protocol) => peer.protocols.includes(protocol));
|
104
|
-
if (supportsProtocol) {
|
105
|
-
if (shardInfo) {
|
106
|
-
const encodedPeerShardInfo = peer.metadata.get("shardInfo");
|
107
|
-
const peerShardInfo = encodedPeerShardInfo && decodeRelayShard(encodedPeerShardInfo);
|
108
|
-
if (peerShardInfo && shardInfo.clusterId === peerShardInfo.clusterId) {
|
109
|
-
return peer;
|
110
|
-
}
|
111
|
-
}
|
112
|
-
else {
|
113
|
-
return peer;
|
114
|
-
}
|
115
|
-
}
|
116
|
-
return null;
|
117
|
-
});
|
118
|
-
const peersWithNulls = await Promise.all(peerPromises);
|
119
|
-
return peersWithNulls.filter((peer) => peer !== null);
|
120
|
-
}
|
121
|
-
|
122
|
-
/**
|
123
|
-
* Retrieves a list of peers based on the specified criteria:
|
124
|
-
* 1. If numPeers is 0, return all peers
|
125
|
-
* 2. Bootstrap peers are prioritized
|
126
|
-
* 3. Non-bootstrap peers are randomly selected to fill up to numPeers
|
127
|
-
*
|
128
|
-
* @param peers - The list of peers to filter from.
|
129
|
-
* @param numPeers - The total number of peers to retrieve. If 0, all peers are returned, irrespective of `maxBootstrapPeers`.
|
130
|
-
* @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
|
131
|
-
* @returns An array of peers based on the specified criteria.
|
132
|
-
*/
|
133
|
-
function filterPeersByDiscovery(peers, numPeers, maxBootstrapPeers) {
|
134
|
-
// Collect the bootstrap peers up to the specified maximum
|
135
|
-
let bootstrapPeers = peers
|
136
|
-
.filter((peer) => peer.tags.has(Tags.BOOTSTRAP))
|
137
|
-
.slice(0, maxBootstrapPeers);
|
138
|
-
// If numPeers is less than the number of bootstrap peers, adjust the bootstrapPeers array
|
139
|
-
if (numPeers > 0 && numPeers < bootstrapPeers.length) {
|
140
|
-
bootstrapPeers = bootstrapPeers.slice(0, numPeers);
|
141
|
-
}
|
142
|
-
// Collect non-bootstrap peers
|
143
|
-
const nonBootstrapPeers = peers.filter((peer) => !peer.tags.has(Tags.BOOTSTRAP));
|
144
|
-
// If numPeers is 0, return all peers
|
145
|
-
if (numPeers === 0) {
|
146
|
-
return [...bootstrapPeers, ...nonBootstrapPeers];
|
147
|
-
}
|
148
|
-
// Initialize the list of selected peers with the bootstrap peers
|
149
|
-
const selectedPeers = [...bootstrapPeers];
|
150
|
-
// Fill up to numPeers with remaining random peers if needed
|
151
|
-
while (selectedPeers.length < numPeers && nonBootstrapPeers.length > 0) {
|
152
|
-
const randomIndex = Math.floor(Math.random() * nonBootstrapPeers.length);
|
153
|
-
const randomPeer = nonBootstrapPeers.splice(randomIndex, 1)[0];
|
154
|
-
selectedPeers.push(randomPeer);
|
155
|
-
}
|
156
|
-
return selectedPeers;
|
157
|
-
}
|
158
|
-
|
159
|
-
function selectConnection(connections) {
|
160
|
-
if (!connections.length)
|
161
|
-
return;
|
162
|
-
if (connections.length === 1)
|
163
|
-
return connections[0];
|
164
|
-
let latestConnection;
|
165
|
-
connections.forEach((connection) => {
|
166
|
-
if (connection.status === "open") {
|
167
|
-
if (!latestConnection) {
|
168
|
-
latestConnection = connection;
|
169
|
-
}
|
170
|
-
else if (connection.timeline.open > latestConnection.timeline.open) {
|
171
|
-
latestConnection = connection;
|
172
|
-
}
|
173
|
-
}
|
174
|
-
});
|
175
|
-
return latestConnection;
|
176
|
-
}
|
177
|
-
|
178
|
-
const CONNECTION_TIMEOUT = 5_000;
|
179
|
-
const RETRY_BACKOFF_BASE = 1_000;
|
180
|
-
const MAX_RETRIES = 3;
|
181
|
-
class StreamManager {
|
182
|
-
multicodec;
|
183
|
-
getConnections;
|
184
|
-
addEventListener;
|
185
|
-
streamPool;
|
186
|
-
log;
|
187
|
-
constructor(multicodec, getConnections, addEventListener) {
|
188
|
-
this.multicodec = multicodec;
|
189
|
-
this.getConnections = getConnections;
|
190
|
-
this.addEventListener = addEventListener;
|
191
|
-
this.log = new Logger(`stream-manager:${multicodec}`);
|
192
|
-
this.streamPool = new Map();
|
193
|
-
this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
|
194
|
-
}
|
195
|
-
async getStream(peer) {
|
196
|
-
const peerIdStr = peer.id.toString();
|
197
|
-
const streamPromise = this.streamPool.get(peerIdStr);
|
198
|
-
if (!streamPromise) {
|
199
|
-
return this.createStream(peer);
|
200
|
-
}
|
201
|
-
this.streamPool.delete(peerIdStr);
|
202
|
-
this.prepareStream(peer);
|
203
|
-
try {
|
204
|
-
const stream = await streamPromise;
|
205
|
-
if (stream && stream.status !== "closed") {
|
206
|
-
return stream;
|
207
|
-
}
|
208
|
-
}
|
209
|
-
catch (error) {
|
210
|
-
this.log.warn(`Failed to get stream for ${peerIdStr} -- `, error);
|
211
|
-
this.log.warn("Attempting to create a new stream for the peer");
|
212
|
-
}
|
213
|
-
return this.createStream(peer);
|
214
|
-
}
|
215
|
-
async createStream(peer, retries = 0) {
|
216
|
-
const connections = this.getConnections(peer.id);
|
217
|
-
const connection = selectConnection(connections);
|
218
|
-
if (!connection) {
|
219
|
-
throw new Error("Failed to get a connection to the peer");
|
220
|
-
}
|
221
|
-
try {
|
222
|
-
return await connection.newStream(this.multicodec);
|
223
|
-
}
|
224
|
-
catch (error) {
|
225
|
-
if (retries < MAX_RETRIES) {
|
226
|
-
const backoff = RETRY_BACKOFF_BASE * Math.pow(2, retries);
|
227
|
-
await new Promise((resolve) => setTimeout(resolve, backoff));
|
228
|
-
return this.createStream(peer, retries + 1);
|
229
|
-
}
|
230
|
-
throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` + error);
|
231
|
-
}
|
232
|
-
}
|
233
|
-
prepareStream(peer) {
|
234
|
-
const timeoutPromise = new Promise((resolve) => setTimeout(resolve, CONNECTION_TIMEOUT));
|
235
|
-
const streamPromise = Promise.race([
|
236
|
-
this.createStream(peer),
|
237
|
-
timeoutPromise.then(() => {
|
238
|
-
throw new Error("Connection timeout");
|
239
|
-
})
|
240
|
-
]).catch((error) => {
|
241
|
-
this.log.error(`Failed to prepare a new stream for ${peer.id.toString()} -- `, error);
|
242
|
-
});
|
243
|
-
this.streamPool.set(peer.id.toString(), streamPromise);
|
244
|
-
}
|
245
|
-
handlePeerUpdateStreamPool = (evt) => {
|
246
|
-
const { peer } = evt.detail;
|
247
|
-
if (peer.protocols.includes(this.multicodec)) {
|
248
|
-
const isConnected = this.isConnectedTo(peer.id);
|
249
|
-
if (isConnected) {
|
250
|
-
this.log.info(`Preemptively opening a stream to ${peer.id.toString()}`);
|
251
|
-
this.prepareStream(peer);
|
252
|
-
}
|
253
|
-
else {
|
254
|
-
const peerIdStr = peer.id.toString();
|
255
|
-
this.streamPool.delete(peerIdStr);
|
256
|
-
this.log.info(`Removed pending stream for disconnected peer ${peerIdStr}`);
|
257
|
-
}
|
258
|
-
}
|
259
|
-
};
|
260
|
-
isConnectedTo(peerId) {
|
261
|
-
const connections = this.getConnections(peerId);
|
262
|
-
return connections.some((connection) => connection.status === "open");
|
263
|
-
}
|
264
|
-
}
|
265
|
-
|
266
|
-
/**
|
267
|
-
* A class with predefined helpers, to be used as a base to implement Waku
|
268
|
-
* Protocols.
|
269
|
-
*/
|
270
|
-
class BaseProtocol {
|
271
|
-
multicodec;
|
272
|
-
components;
|
273
|
-
log;
|
274
|
-
pubsubTopics;
|
275
|
-
addLibp2pEventListener;
|
276
|
-
removeLibp2pEventListener;
|
277
|
-
streamManager;
|
278
|
-
constructor(multicodec, components, log, pubsubTopics) {
|
279
|
-
this.multicodec = multicodec;
|
280
|
-
this.components = components;
|
281
|
-
this.log = log;
|
282
|
-
this.pubsubTopics = pubsubTopics;
|
283
|
-
this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
|
284
|
-
this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
|
285
|
-
this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
|
286
|
-
}
|
287
|
-
async getStream(peer) {
|
288
|
-
return this.streamManager.getStream(peer);
|
289
|
-
}
|
290
|
-
//TODO: move to SDK
|
291
|
-
/**
|
292
|
-
* Returns known peers from the address book (`libp2p.peerStore`) that support
|
293
|
-
* the class protocol. Waku may or may not be currently connected to these
|
294
|
-
* peers.
|
295
|
-
*/
|
296
|
-
async allPeers() {
|
297
|
-
return getPeersForProtocol(this.components.peerStore, [this.multicodec]);
|
298
|
-
}
|
299
|
-
async connectedPeers() {
|
300
|
-
const peers = await this.allPeers();
|
301
|
-
return peers.filter((peer) => {
|
302
|
-
const connections = this.components.connectionManager.getConnections(peer.id);
|
303
|
-
return connections.some((c) => c.streams.some((s) => s.protocol === this.multicodec));
|
304
|
-
});
|
305
|
-
}
|
306
|
-
/**
|
307
|
-
* Retrieves a list of connected peers that support the protocol. The list is sorted by latency.
|
308
|
-
*
|
309
|
-
* @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
|
310
|
-
* @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
|
311
|
-
|
312
|
-
* @returns A list of peers that support the protocol sorted by latency.
|
313
|
-
*/
|
314
|
-
async getPeers({ numPeers, maxBootstrapPeers } = {
|
315
|
-
maxBootstrapPeers: 1,
|
316
|
-
numPeers: 0
|
317
|
-
}) {
|
318
|
-
// Retrieve all connected peers that support the protocol & shard (if configured)
|
319
|
-
const connectedPeersForProtocolAndShard = await getConnectedPeersForProtocolAndShard(this.components.connectionManager.getConnections(), this.components.peerStore, [this.multicodec], pubsubTopicsToShardInfo(this.pubsubTopics));
|
320
|
-
// Filter the peers based on discovery & number of peers requested
|
321
|
-
const filteredPeers = filterPeersByDiscovery(connectedPeersForProtocolAndShard, numPeers, maxBootstrapPeers);
|
322
|
-
// Sort the peers by latency
|
323
|
-
const sortedFilteredPeers = await sortPeersByLatency(this.components.peerStore, filteredPeers);
|
324
|
-
if (sortedFilteredPeers.length === 0) {
|
325
|
-
this.log.warn("No peers found. Ensure you have a connection to the network.");
|
326
|
-
}
|
327
|
-
if (sortedFilteredPeers.length < numPeers) {
|
328
|
-
this.log.warn(`Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`);
|
329
|
-
}
|
330
|
-
return sortedFilteredPeers;
|
331
|
-
}
|
332
|
-
}
|
333
|
-
|
334
|
-
export { BaseProtocol as B, StreamManager as S, decodeRelayShard as d, encodeRelayShard as e };
|
@@ -1,22 +0,0 @@
|
|
1
|
-
import type { Waku } from "@waku/interfaces";
|
2
|
-
import { Protocols } from "@waku/interfaces";
|
3
|
-
/**
|
4
|
-
* Wait for a remote peer to be ready given the passed protocols.
|
5
|
-
* Must be used after attempting to connect to nodes, using
|
6
|
-
* {@link @waku/sdk!WakuNode.dial} or a bootstrap method with
|
7
|
-
* {@link @waku/sdk!createLightNode}.
|
8
|
-
*
|
9
|
-
* If the passed protocols is a GossipSub protocol, then it resolves only once
|
10
|
-
* a peer is in a mesh, to help ensure that other peers will send and receive
|
11
|
-
* message to us.
|
12
|
-
*
|
13
|
-
* @param waku The Waku Node
|
14
|
-
* @param protocols The protocols that need to be enabled by remote peers.
|
15
|
-
* @param timeoutMs A timeout value in milliseconds..
|
16
|
-
*
|
17
|
-
* @returns A promise that **resolves** if all desired protocols are fulfilled by
|
18
|
-
* remote nodes, **rejects** if the timeoutMs is reached.
|
19
|
-
* @throws If passing a protocol that is not mounted
|
20
|
-
* @default Wait for remote peers with protocols enabled locally and no time out is applied.
|
21
|
-
*/
|
22
|
-
export declare function waitForRemotePeer(waku: Waku, protocols?: Protocols[], timeoutMs?: number): Promise<void>;
|
@@ -1,142 +0,0 @@
|
|
1
|
-
import { Protocols } from "@waku/interfaces";
|
2
|
-
import { Logger } from "@waku/utils";
|
3
|
-
import { pEvent } from "p-event";
|
4
|
-
const log = new Logger("wait-for-remote-peer");
|
5
|
-
//TODO: move this function within the Waku class: https://github.com/waku-org/js-waku/issues/1761
|
6
|
-
/**
|
7
|
-
* Wait for a remote peer to be ready given the passed protocols.
|
8
|
-
* Must be used after attempting to connect to nodes, using
|
9
|
-
* {@link @waku/sdk!WakuNode.dial} or a bootstrap method with
|
10
|
-
* {@link @waku/sdk!createLightNode}.
|
11
|
-
*
|
12
|
-
* If the passed protocols is a GossipSub protocol, then it resolves only once
|
13
|
-
* a peer is in a mesh, to help ensure that other peers will send and receive
|
14
|
-
* message to us.
|
15
|
-
*
|
16
|
-
* @param waku The Waku Node
|
17
|
-
* @param protocols The protocols that need to be enabled by remote peers.
|
18
|
-
* @param timeoutMs A timeout value in milliseconds..
|
19
|
-
*
|
20
|
-
* @returns A promise that **resolves** if all desired protocols are fulfilled by
|
21
|
-
* remote nodes, **rejects** if the timeoutMs is reached.
|
22
|
-
* @throws If passing a protocol that is not mounted
|
23
|
-
* @default Wait for remote peers with protocols enabled locally and no time out is applied.
|
24
|
-
*/
|
25
|
-
export async function waitForRemotePeer(waku, protocols, timeoutMs) {
|
26
|
-
protocols = protocols ?? getEnabledProtocols(waku);
|
27
|
-
if (!waku.isStarted())
|
28
|
-
return Promise.reject("Waku node is not started");
|
29
|
-
const promises = [];
|
30
|
-
if (protocols.includes(Protocols.Relay)) {
|
31
|
-
if (!waku.relay)
|
32
|
-
throw new Error("Cannot wait for Relay peer: protocol not mounted");
|
33
|
-
promises.push(waitForGossipSubPeerInMesh(waku.relay));
|
34
|
-
}
|
35
|
-
if (protocols.includes(Protocols.Store)) {
|
36
|
-
if (!waku.store)
|
37
|
-
throw new Error("Cannot wait for Store peer: protocol not mounted");
|
38
|
-
promises.push(waitForConnectedPeer(waku.store.protocol, waku.libp2p.services.metadata));
|
39
|
-
}
|
40
|
-
if (protocols.includes(Protocols.LightPush)) {
|
41
|
-
if (!waku.lightPush)
|
42
|
-
throw new Error("Cannot wait for LightPush peer: protocol not mounted");
|
43
|
-
promises.push(waitForConnectedPeer(waku.lightPush.protocol, waku.libp2p.services.metadata));
|
44
|
-
}
|
45
|
-
if (protocols.includes(Protocols.Filter)) {
|
46
|
-
if (!waku.filter)
|
47
|
-
throw new Error("Cannot wait for Filter peer: protocol not mounted");
|
48
|
-
promises.push(waitForConnectedPeer(waku.filter.protocol, waku.libp2p.services.metadata));
|
49
|
-
}
|
50
|
-
if (timeoutMs) {
|
51
|
-
await rejectOnTimeout(Promise.all(promises), timeoutMs, "Timed out waiting for a remote peer.");
|
52
|
-
}
|
53
|
-
else {
|
54
|
-
await Promise.all(promises);
|
55
|
-
}
|
56
|
-
}
|
57
|
-
//TODO: move this function within protocol SDK class: https://github.com/waku-org/js-waku/issues/1761
|
58
|
-
/**
|
59
|
-
* Wait for a peer with the given protocol to be connected.
|
60
|
-
* If sharding is enabled on the node, it will also wait for the peer to be confirmed by the metadata service.
|
61
|
-
*/
|
62
|
-
async function waitForConnectedPeer(protocol, metadataService) {
|
63
|
-
const codec = protocol.multicodec;
|
64
|
-
const peers = await protocol.connectedPeers();
|
65
|
-
if (peers.length) {
|
66
|
-
if (!metadataService) {
|
67
|
-
log.info(`${codec} peer found: `, peers[0].id.toString());
|
68
|
-
return;
|
69
|
-
}
|
70
|
-
// once a peer is connected, we need to confirm the metadata handshake with at least one of those peers if sharding is enabled
|
71
|
-
try {
|
72
|
-
await Promise.any(peers.map((peer) => metadataService.confirmOrAttemptHandshake(peer.id)));
|
73
|
-
return;
|
74
|
-
}
|
75
|
-
catch (e) {
|
76
|
-
if (e.code === "ERR_CONNECTION_BEING_CLOSED")
|
77
|
-
log.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`);
|
78
|
-
log.error(`Error waiting for handshake confirmation: ${e}`);
|
79
|
-
}
|
80
|
-
}
|
81
|
-
log.info(`Waiting for ${codec} peer`);
|
82
|
-
// else we'll just wait for the next peer to connect
|
83
|
-
await new Promise((resolve) => {
|
84
|
-
const cb = (evt) => {
|
85
|
-
if (evt.detail?.protocols?.includes(codec)) {
|
86
|
-
if (metadataService) {
|
87
|
-
metadataService
|
88
|
-
.confirmOrAttemptHandshake(evt.detail.peerId)
|
89
|
-
.then(() => {
|
90
|
-
protocol.removeLibp2pEventListener("peer:identify", cb);
|
91
|
-
resolve();
|
92
|
-
})
|
93
|
-
.catch((e) => {
|
94
|
-
if (e.code === "ERR_CONNECTION_BEING_CLOSED")
|
95
|
-
log.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`);
|
96
|
-
log.error(`Error waiting for handshake confirmation: ${e}`);
|
97
|
-
});
|
98
|
-
}
|
99
|
-
else {
|
100
|
-
protocol.removeLibp2pEventListener("peer:identify", cb);
|
101
|
-
resolve();
|
102
|
-
}
|
103
|
-
}
|
104
|
-
};
|
105
|
-
protocol.addLibp2pEventListener("peer:identify", cb);
|
106
|
-
});
|
107
|
-
}
|
108
|
-
/**
|
109
|
-
* Wait for at least one peer with the given protocol to be connected and in the gossipsub
|
110
|
-
* mesh for all pubsubTopics.
|
111
|
-
*/
|
112
|
-
async function waitForGossipSubPeerInMesh(waku) {
|
113
|
-
let peers = waku.getMeshPeers();
|
114
|
-
const pubsubTopics = waku.pubsubTopics;
|
115
|
-
for (const topic of pubsubTopics) {
|
116
|
-
while (peers.length == 0) {
|
117
|
-
await pEvent(waku.gossipSub, "gossipsub:heartbeat");
|
118
|
-
peers = waku.getMeshPeers(topic);
|
119
|
-
}
|
120
|
-
}
|
121
|
-
}
|
122
|
-
const awaitTimeout = (ms, rejectReason) => new Promise((_resolve, reject) => setTimeout(() => reject(rejectReason), ms));
|
123
|
-
async function rejectOnTimeout(promise, timeoutMs, rejectReason) {
|
124
|
-
await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);
|
125
|
-
}
|
126
|
-
function getEnabledProtocols(waku) {
|
127
|
-
const protocols = [];
|
128
|
-
if (waku.relay) {
|
129
|
-
protocols.push(Protocols.Relay);
|
130
|
-
}
|
131
|
-
if (waku.filter) {
|
132
|
-
protocols.push(Protocols.Filter);
|
133
|
-
}
|
134
|
-
if (waku.store) {
|
135
|
-
protocols.push(Protocols.Store);
|
136
|
-
}
|
137
|
-
if (waku.lightPush) {
|
138
|
-
protocols.push(Protocols.LightPush);
|
139
|
-
}
|
140
|
-
return protocols;
|
141
|
-
}
|
142
|
-
//# sourceMappingURL=wait_for_remote_peer.js.map
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"wait_for_remote_peer.js","sourceRoot":"","sources":["../../src/lib/wait_for_remote_peer.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,MAAM,GAAG,GAAG,IAAI,MAAM,CAAC,sBAAsB,CAAC,CAAC;AAE/C,iGAAiG;AACjG;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,IAAU,EACV,SAAuB,EACvB,SAAkB;IAElB,SAAS,GAAG,SAAS,IAAI,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAEnD,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;QAAE,OAAO,OAAO,CAAC,MAAM,CAAC,0BAA0B,CAAC,CAAC;IAEzE,MAAM,QAAQ,GAAG,EAAE,CAAC;IAEpB,IAAI,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;QACxC,IAAI,CAAC,IAAI,CAAC,KAAK;YACb,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;QACtE,QAAQ,CAAC,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACxD,CAAC;IAED,IAAI,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;QACxC,IAAI,CAAC,IAAI,CAAC,KAAK;YACb,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;QACtE,QAAQ,CAAC,IAAI,CACX,oBAAoB,CAAC,I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