peerpigeon 0.1.0 → 1.0.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/README.md +141 -1365
- package/cli.js +1382 -0
- package/dist/peerpigeon-browser.js +12290 -0
- package/dist/peerpigeon-browser.js.map +7 -0
- package/docs/API_DOCUMENTATION.md +1945 -0
- package/docs/BOOTSTRAP_HUBS.md +319 -0
- package/docs/CLI_README.md +371 -0
- package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
- package/docs/HUB_QUICK_REF.md +107 -0
- package/docs/HUB_SCRIPTS.md +331 -0
- package/docs/HUB_SYSTEM.md +552 -0
- package/docs/MIGRATION_COMPLETE.md +93 -0
- package/docs/NETWORK_NAMESPACES.md +212 -0
- package/docs/README.md +107 -0
- package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
- package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
- package/examples/bootstrap-hub-example.js +292 -0
- package/examples/browser/README.md +278 -0
- package/examples/browser/app.js +2426 -49
- package/examples/browser/index.html +482 -543
- package/examples/browser/minimal/README.md +55 -0
- package/examples/browser/minimal/index.html +75 -0
- package/examples/browser/minimal/minimal.js +234 -0
- package/examples/browser/styles.css +687 -1425
- package/examples/browser/test-bundle.html +35 -0
- package/examples/browser-2/index.html +30 -0
- package/examples/browser-2/package.json +21 -0
- package/examples/browser-2/src/App-simple.vue +21 -0
- package/examples/browser-2/src/App.vue +420 -0
- package/examples/browser-2/src/components/CryptoView.vue +1661 -0
- package/examples/browser-2/src/components/DHTView.vue +1281 -0
- package/examples/browser-2/src/components/DebugView.vue +1773 -0
- package/examples/browser-2/src/components/MediaView.vue +1048 -0
- package/examples/browser-2/src/components/MessagingView.vue +775 -0
- package/examples/browser-2/src/components/NetworkView.vue +930 -0
- package/examples/browser-2/src/components/StorageView.vue +1376 -0
- package/examples/browser-2/src/main.js +5 -0
- package/examples/browser-2/src/stores/peerpigeon.js +895 -0
- package/examples/browser-2/vite.config.js +6 -0
- package/examples/hub-example.js +186 -0
- package/examples/multi-hub-test.js +186 -0
- package/examples/node/README.md +2 -2
- package/examples/node/storage-test.js +141 -6
- package/examples/selective-streaming-demo.html +698 -0
- package/examples/standard-events-demo.js +126 -0
- package/package.json +33 -16
- package/server/index.js +1032 -98
- package/server/start.js +49 -0
- package/src/ConnectionManager.js +239 -225
- package/src/CryptoManager.js +147 -18
- package/src/DebugLogger.js +0 -7
- package/src/DistributedStorageManager.js +245 -205
- package/src/EnvironmentDetector.js +109 -2
- package/src/EventEmitter.js +79 -1
- package/src/EvictionManager.js +10 -9
- package/src/GossipManager.js +163 -11
- package/src/LexicalStorageInterface.js +332 -0
- package/src/PeerConnection.js +333 -310
- package/src/PeerPigeonMesh.js +577 -135
- package/src/SignalingClient.js +14 -243
- package/src/SignalingHandler.js +31 -10
- package/src/StorageManager.js +0 -39
- package/src/WebDHT-Simple.js +389 -0
- package/src/WebDHT.js +363 -1165
- package/src/browser-entry.js +40 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/crypto-test.html +0 -427
- package/examples/browser/ui-old.js +0 -1926
- package/examples/browser/ui.js +0 -3010
- package/websocket-server/README.md +0 -247
- package/websocket-server/server.js +0 -391
package/server/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// PeerPigeon WebSocket Server - Node.js module
|
|
2
|
-
import { WebSocketServer } from 'ws';
|
|
2
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
3
3
|
import { createServer } from 'http';
|
|
4
4
|
import { EventEmitter } from 'events';
|
|
5
|
+
import { URL } from 'url';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* PeerPigeon WebSocket signaling server
|
|
@@ -14,29 +15,167 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
14
15
|
this.port = options.port || 3000;
|
|
15
16
|
this.host = options.host || 'localhost';
|
|
16
17
|
this.maxConnections = options.maxConnections || 1000;
|
|
17
|
-
this.cleanupInterval = options.cleanupInterval ||
|
|
18
|
+
this.cleanupInterval = options.cleanupInterval || 30000; // 30 seconds
|
|
18
19
|
this.peerTimeout = options.peerTimeout || 300000; // 5 minutes
|
|
19
20
|
this.corsOrigin = options.corsOrigin || '*';
|
|
20
21
|
this.maxMessageSize = options.maxMessageSize || 1048576; // 1MB
|
|
22
|
+
this.maxPortRetries = options.maxPortRetries || 10; // Try up to 10 ports
|
|
23
|
+
|
|
24
|
+
// Hub configuration
|
|
25
|
+
this.isHub = options.isHub || false; // Whether this server is a hub
|
|
26
|
+
this.hubMeshNamespace = 'pigeonhub-mesh'; // Reserved namespace for hubs
|
|
27
|
+
this.bootstrapHubs = options.bootstrapHubs || []; // URIs of bootstrap hubs to connect to
|
|
28
|
+
this.autoConnect = options.autoConnect !== false; // Auto-connect to bootstrap hubs (default: true)
|
|
29
|
+
this.reconnectInterval = options.reconnectInterval || 5000; // Reconnect interval in ms
|
|
30
|
+
this.maxReconnectAttempts = options.maxReconnectAttempts || 10; // Max reconnection attempts
|
|
31
|
+
|
|
32
|
+
// Generate hub peer ID if this is a hub
|
|
33
|
+
this.hubPeerId = options.hubPeerId || (this.isHub ? this.generatePeerId() : null);
|
|
21
34
|
|
|
22
35
|
this.httpServer = null;
|
|
23
36
|
this.wss = null;
|
|
24
37
|
this.connections = new Map(); // peerId -> WebSocket
|
|
25
38
|
this.peerData = new Map(); // peerId -> peer info
|
|
39
|
+
this.networkPeers = new Map(); // networkName -> Set of peerIds
|
|
40
|
+
this.hubs = new Map(); // peerId -> hub info (for peers identified as hubs)
|
|
41
|
+
this.bootstrapConnections = new Map(); // bootstrapUri -> connection info
|
|
26
42
|
this.isRunning = false;
|
|
27
43
|
this.cleanupTimer = null;
|
|
44
|
+
this.startTime = null;
|
|
28
45
|
}
|
|
29
46
|
|
|
30
47
|
/**
|
|
31
|
-
*
|
|
48
|
+
* Validate peer ID format
|
|
32
49
|
*/
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
50
|
+
validatePeerId(peerId) {
|
|
51
|
+
return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Generate a random peer ID (40 hex characters)
|
|
56
|
+
*/
|
|
57
|
+
generatePeerId() {
|
|
58
|
+
// Generate random hex string
|
|
59
|
+
const chars = '0123456789abcdef';
|
|
60
|
+
let peerId = '';
|
|
61
|
+
for (let i = 0; i < 40; i++) {
|
|
62
|
+
peerId += chars[Math.floor(Math.random() * 16)];
|
|
63
|
+
}
|
|
64
|
+
return peerId;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Check if a peer is registered as a hub
|
|
69
|
+
*/
|
|
70
|
+
isPeerHub(peerId) {
|
|
71
|
+
return this.hubs.has(peerId);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Register a peer as a hub
|
|
76
|
+
*/
|
|
77
|
+
registerHub(peerId, hubInfo = {}) {
|
|
78
|
+
this.hubs.set(peerId, {
|
|
79
|
+
peerId,
|
|
80
|
+
registeredAt: Date.now(),
|
|
81
|
+
lastActivity: Date.now(),
|
|
82
|
+
...hubInfo
|
|
83
|
+
});
|
|
84
|
+
console.log(`🏢 Registered hub: ${peerId.substring(0, 8)}... (${this.hubs.size} total hubs)`);
|
|
85
|
+
this.emit('hubRegistered', { peerId, totalHubs: this.hubs.size });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Unregister a hub
|
|
90
|
+
*/
|
|
91
|
+
unregisterHub(peerId) {
|
|
92
|
+
if (this.hubs.delete(peerId)) {
|
|
93
|
+
console.log(`🏢 Unregistered hub: ${peerId.substring(0, 8)}... (${this.hubs.size} remaining hubs)`);
|
|
94
|
+
this.emit('hubUnregistered', { peerId, totalHubs: this.hubs.size });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Get all connected hubs
|
|
100
|
+
*/
|
|
101
|
+
getConnectedHubs(excludePeerId = null) {
|
|
102
|
+
const hubList = [];
|
|
103
|
+
for (const [peerId, hubInfo] of this.hubs) {
|
|
104
|
+
if (peerId !== excludePeerId && this.connections.has(peerId)) {
|
|
105
|
+
hubList.push({ peerId, ...hubInfo });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return hubList;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Find closest peers using XOR distance
|
|
113
|
+
*/
|
|
114
|
+
findClosestPeers(targetPeerId, allPeerIds, maxPeers = 3) {
|
|
115
|
+
if (!targetPeerId || !allPeerIds || allPeerIds.length === 0) {
|
|
116
|
+
return [];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// XOR distance calculation (simplified)
|
|
120
|
+
const distances = allPeerIds.map(peerId => {
|
|
121
|
+
let distance = 0;
|
|
122
|
+
const minLength = Math.min(targetPeerId.length, peerId.length);
|
|
123
|
+
|
|
124
|
+
for (let i = 0; i < minLength; i++) {
|
|
125
|
+
const xor = parseInt(targetPeerId[i], 16) ^ parseInt(peerId[i], 16);
|
|
126
|
+
distance += xor;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return { peerId, distance };
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// Sort by distance and return closest peers
|
|
133
|
+
distances.sort((a, b) => a.distance - b.distance);
|
|
134
|
+
return distances.slice(0, maxPeers).map(item => item.peerId);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Get active peers in a network
|
|
139
|
+
*/
|
|
140
|
+
getActivePeers(excludePeerId = null, networkName = 'global') {
|
|
141
|
+
const peers = [];
|
|
142
|
+
const stalePeers = [];
|
|
143
|
+
|
|
144
|
+
// Get peers for the specific network
|
|
145
|
+
const networkPeerSet = this.networkPeers.get(networkName);
|
|
146
|
+
if (!networkPeerSet) {
|
|
147
|
+
return peers; // No peers in this network
|
|
36
148
|
}
|
|
37
149
|
|
|
150
|
+
for (const peerId of networkPeerSet) {
|
|
151
|
+
if (peerId !== excludePeerId) {
|
|
152
|
+
const connection = this.connections.get(peerId);
|
|
153
|
+
if (connection && connection.readyState === connection.OPEN) {
|
|
154
|
+
peers.push(peerId);
|
|
155
|
+
} else {
|
|
156
|
+
// Mark stale connections for cleanup
|
|
157
|
+
stalePeers.push(peerId);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Clean up stale connections
|
|
163
|
+
stalePeers.forEach(peerId => {
|
|
164
|
+
console.log(`🧹 Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
|
|
165
|
+
this.cleanupPeer(peerId);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
return peers;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Try to start server on a specific port
|
|
173
|
+
*/
|
|
174
|
+
async tryPort(port, maxRetries = null) {
|
|
175
|
+
maxRetries = maxRetries !== null ? maxRetries : this.maxPortRetries;
|
|
176
|
+
|
|
38
177
|
return new Promise((resolve, reject) => {
|
|
39
|
-
|
|
178
|
+
const attemptPort = (currentPort, retriesLeft) => {
|
|
40
179
|
// Create HTTP server
|
|
41
180
|
this.httpServer = createServer((req, res) => {
|
|
42
181
|
// Handle CORS preflight
|
|
@@ -60,13 +199,30 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
60
199
|
status: 'healthy',
|
|
61
200
|
timestamp: new Date().toISOString(),
|
|
62
201
|
uptime: process.uptime(),
|
|
202
|
+
isHub: this.isHub,
|
|
63
203
|
connections: this.connections.size,
|
|
64
204
|
peers: this.peerData.size,
|
|
205
|
+
hubs: this.hubs.size,
|
|
206
|
+
networks: this.networkPeers.size,
|
|
65
207
|
memory: process.memoryUsage()
|
|
66
208
|
}));
|
|
67
209
|
return;
|
|
68
210
|
}
|
|
69
211
|
|
|
212
|
+
// Hubs endpoint - list connected hubs
|
|
213
|
+
if (req.url === '/hubs') {
|
|
214
|
+
res.writeHead(200, {
|
|
215
|
+
'Content-Type': 'application/json',
|
|
216
|
+
'Access-Control-Allow-Origin': this.corsOrigin
|
|
217
|
+
});
|
|
218
|
+
res.end(JSON.stringify({
|
|
219
|
+
timestamp: new Date().toISOString(),
|
|
220
|
+
totalHubs: this.hubs.size,
|
|
221
|
+
hubs: this.getConnectedHubs()
|
|
222
|
+
}));
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
70
226
|
// Default response
|
|
71
227
|
res.writeHead(200, {
|
|
72
228
|
'Content-Type': 'text/plain',
|
|
@@ -83,33 +239,97 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
83
239
|
|
|
84
240
|
this.setupWebSocketHandlers();
|
|
85
241
|
|
|
242
|
+
// Handle port in use error
|
|
243
|
+
const errorHandler = (error) => {
|
|
244
|
+
if (error.code === 'EADDRINUSE') {
|
|
245
|
+
console.log(`⚠️ Port ${currentPort} is already in use`);
|
|
246
|
+
|
|
247
|
+
// Clean up failed server
|
|
248
|
+
this.httpServer.removeAllListeners();
|
|
249
|
+
if (this.wss) {
|
|
250
|
+
this.wss.close();
|
|
251
|
+
}
|
|
252
|
+
this.httpServer = null;
|
|
253
|
+
this.wss = null;
|
|
254
|
+
|
|
255
|
+
if (retriesLeft > 0) {
|
|
256
|
+
const nextPort = currentPort + 1;
|
|
257
|
+
console.log(`🔄 Trying port ${nextPort}...`);
|
|
258
|
+
attemptPort(nextPort, retriesLeft - 1);
|
|
259
|
+
} else {
|
|
260
|
+
reject(new Error(`Failed to find available port after ${maxRetries} attempts (tried ${port}-${currentPort})`));
|
|
261
|
+
}
|
|
262
|
+
} else {
|
|
263
|
+
console.error('❌ HTTP server error:', error);
|
|
264
|
+
this.emit('error', error);
|
|
265
|
+
reject(error);
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
this.httpServer.once('error', errorHandler);
|
|
270
|
+
|
|
86
271
|
// Start HTTP server
|
|
87
|
-
this.httpServer.listen(
|
|
272
|
+
this.httpServer.listen(currentPort, this.host, () => {
|
|
273
|
+
// Remove error handler after successful start
|
|
274
|
+
this.httpServer.removeListener('error', errorHandler);
|
|
275
|
+
|
|
276
|
+
// Update port to the actual port used
|
|
277
|
+
this.port = currentPort;
|
|
88
278
|
this.isRunning = true;
|
|
279
|
+
this.startTime = Date.now();
|
|
89
280
|
this.startCleanupTimer();
|
|
90
281
|
|
|
91
|
-
|
|
282
|
+
if (currentPort !== port) {
|
|
283
|
+
console.log(`✅ Port ${port} was in use, using port ${currentPort} instead`);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const serverType = this.isHub ? '🏢 PeerPigeon Hub Server' : '🚀 PeerPigeon WebSocket Server';
|
|
287
|
+
console.log(`${serverType} started on ws://${this.host}:${this.port}`);
|
|
288
|
+
if (this.isHub) {
|
|
289
|
+
console.log(`🌐 Hub mesh namespace: ${this.hubMeshNamespace}`);
|
|
290
|
+
}
|
|
92
291
|
console.log(`📊 Max connections: ${this.maxConnections}`);
|
|
93
292
|
console.log(`🧹 Cleanup interval: ${this.cleanupInterval}ms`);
|
|
94
293
|
console.log(`⏰ Peer timeout: ${this.peerTimeout}ms`);
|
|
95
294
|
|
|
96
295
|
this.emit('started', { host: this.host, port: this.port });
|
|
97
|
-
resolve();
|
|
98
|
-
});
|
|
296
|
+
resolve({ host: this.host, port: this.port });
|
|
99
297
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
298
|
+
// Add persistent error handler after successful start
|
|
299
|
+
this.httpServer.on('error', (error) => {
|
|
300
|
+
console.error('❌ HTTP server error:', error);
|
|
301
|
+
this.emit('error', error);
|
|
302
|
+
});
|
|
104
303
|
});
|
|
304
|
+
};
|
|
105
305
|
|
|
106
|
-
|
|
107
|
-
console.error('❌ Failed to start server:', error);
|
|
108
|
-
reject(error);
|
|
109
|
-
}
|
|
306
|
+
attemptPort(port, maxRetries);
|
|
110
307
|
});
|
|
111
308
|
}
|
|
112
309
|
|
|
310
|
+
/**
|
|
311
|
+
* Start the WebSocket server
|
|
312
|
+
*/
|
|
313
|
+
async start() {
|
|
314
|
+
if (this.isRunning) {
|
|
315
|
+
throw new Error('Server is already running');
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
try {
|
|
319
|
+
const result = await this.tryPort(this.port);
|
|
320
|
+
|
|
321
|
+
// If this is a hub, connect to bootstrap hubs
|
|
322
|
+
if (this.isHub && this.autoConnect) {
|
|
323
|
+
await this.connectToBootstrapHubs();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
return result;
|
|
327
|
+
} catch (error) {
|
|
328
|
+
console.error('❌ Failed to start server:', error);
|
|
329
|
+
throw error;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
113
333
|
/**
|
|
114
334
|
* Stop the WebSocket server
|
|
115
335
|
*/
|
|
@@ -121,6 +341,11 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
121
341
|
return new Promise((resolve) => {
|
|
122
342
|
console.log('🛑 Stopping PeerPigeon WebSocket server...');
|
|
123
343
|
|
|
344
|
+
// Disconnect from bootstrap hubs if this is a hub
|
|
345
|
+
if (this.isHub) {
|
|
346
|
+
this.disconnectFromBootstrapHubs();
|
|
347
|
+
}
|
|
348
|
+
|
|
124
349
|
// Stop cleanup timer
|
|
125
350
|
if (this.cleanupTimer) {
|
|
126
351
|
clearInterval(this.cleanupTimer);
|
|
@@ -163,6 +388,367 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
163
388
|
});
|
|
164
389
|
}
|
|
165
390
|
|
|
391
|
+
/**
|
|
392
|
+
* Connect to bootstrap hubs
|
|
393
|
+
*/
|
|
394
|
+
async connectToBootstrapHubs() {
|
|
395
|
+
if (!this.isHub) {
|
|
396
|
+
console.log('⚠️ Not a hub, skipping bootstrap connections');
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// If no bootstrap hubs specified, try default port 3000
|
|
401
|
+
let bootstrapUris = this.bootstrapHubs;
|
|
402
|
+
if (!bootstrapUris || bootstrapUris.length === 0) {
|
|
403
|
+
// Don't connect to ourselves
|
|
404
|
+
const defaultPort = 3000;
|
|
405
|
+
if (this.port !== defaultPort) {
|
|
406
|
+
bootstrapUris = [`ws://${this.host}:${defaultPort}`];
|
|
407
|
+
console.log(`🔗 No bootstrap hubs specified, trying default: ws://${this.host}:${defaultPort}`);
|
|
408
|
+
} else {
|
|
409
|
+
console.log('ℹ️ No bootstrap hubs to connect to (running on default port 3000)');
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
console.log(`🔗 Connecting to ${bootstrapUris.length} bootstrap hub(s)...`);
|
|
415
|
+
|
|
416
|
+
for (const uri of bootstrapUris) {
|
|
417
|
+
try {
|
|
418
|
+
await this.connectToHub(uri);
|
|
419
|
+
} catch (error) {
|
|
420
|
+
console.error(`❌ Failed to connect to bootstrap hub ${uri}:`, error.message);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Connect to a specific hub
|
|
427
|
+
*/
|
|
428
|
+
async connectToHub(uri, attemptNumber = 0) {
|
|
429
|
+
return new Promise((resolve, reject) => {
|
|
430
|
+
try {
|
|
431
|
+
// Parse URI to check if it's our own server
|
|
432
|
+
const url = new URL(uri);
|
|
433
|
+
const hubPort = parseInt(url.port) || 3000;
|
|
434
|
+
const hubHost = url.hostname;
|
|
435
|
+
|
|
436
|
+
// Don't connect to ourselves
|
|
437
|
+
if (hubHost === this.host && hubPort === this.port) {
|
|
438
|
+
console.log(`⚠️ Skipping self-connection to ${uri}`);
|
|
439
|
+
resolve();
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const wsUrl = `${uri}?peerId=${this.hubPeerId}`;
|
|
444
|
+
console.log(`🔗 Connecting to hub: ${uri} (attempt ${attemptNumber + 1})`);
|
|
445
|
+
|
|
446
|
+
const ws = new WebSocket(wsUrl);
|
|
447
|
+
|
|
448
|
+
const connectionInfo = {
|
|
449
|
+
uri,
|
|
450
|
+
ws,
|
|
451
|
+
connected: false,
|
|
452
|
+
attemptNumber,
|
|
453
|
+
lastAttempt: Date.now(),
|
|
454
|
+
reconnectTimer: null
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
this.bootstrapConnections.set(uri, connectionInfo);
|
|
458
|
+
|
|
459
|
+
ws.on('open', () => {
|
|
460
|
+
console.log(`✅ Connected to bootstrap hub: ${uri}`);
|
|
461
|
+
connectionInfo.connected = true;
|
|
462
|
+
connectionInfo.attemptNumber = 0; // Reset attempt counter on success
|
|
463
|
+
|
|
464
|
+
// Announce this hub on the hub mesh
|
|
465
|
+
this.announceToHub(ws);
|
|
466
|
+
|
|
467
|
+
this.emit('bootstrapConnected', { uri });
|
|
468
|
+
resolve();
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
ws.on('message', (data) => {
|
|
472
|
+
try {
|
|
473
|
+
const message = JSON.parse(data.toString());
|
|
474
|
+
this.handleBootstrapMessage(uri, message);
|
|
475
|
+
} catch (error) {
|
|
476
|
+
console.error(`❌ Error handling message from ${uri}:`, error);
|
|
477
|
+
}
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
ws.on('close', (code, reason) => {
|
|
481
|
+
console.log(`🔌 Disconnected from bootstrap hub ${uri} (${code}: ${reason})`)
|
|
482
|
+
connectionInfo.connected = false;
|
|
483
|
+
|
|
484
|
+
this.emit('bootstrapDisconnected', { uri, code, reason });
|
|
485
|
+
|
|
486
|
+
// Attempt to reconnect
|
|
487
|
+
if (this.isRunning && attemptNumber < this.maxReconnectAttempts) {
|
|
488
|
+
connectionInfo.reconnectTimer = setTimeout(() => {
|
|
489
|
+
console.log(`🔄 Reconnecting to ${uri}...`);
|
|
490
|
+
this.connectToHub(uri, attemptNumber + 1);
|
|
491
|
+
}, this.reconnectInterval);
|
|
492
|
+
} else if (attemptNumber >= this.maxReconnectAttempts) {
|
|
493
|
+
console.log(`❌ Max reconnection attempts reached for ${uri}`);
|
|
494
|
+
this.bootstrapConnections.delete(uri);
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
ws.on('error', (error) => {
|
|
499
|
+
console.error(`❌ WebSocket error for ${uri}:`, error.message);
|
|
500
|
+
|
|
501
|
+
// Only reject on first attempt, otherwise we'll retry
|
|
502
|
+
if (attemptNumber === 0) {
|
|
503
|
+
this.bootstrapConnections.delete(uri);
|
|
504
|
+
reject(error);
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
} catch (error) {
|
|
509
|
+
console.error(`❌ Failed to create connection to ${uri}:`, error);
|
|
510
|
+
reject(error);
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Announce this hub to a bootstrap hub
|
|
517
|
+
*/
|
|
518
|
+
announceToHub(ws) {
|
|
519
|
+
const announcement = {
|
|
520
|
+
type: 'announce',
|
|
521
|
+
networkName: this.hubMeshNamespace,
|
|
522
|
+
data: {
|
|
523
|
+
isHub: true,
|
|
524
|
+
port: this.port,
|
|
525
|
+
host: this.host,
|
|
526
|
+
capabilities: ['signaling', 'relay'],
|
|
527
|
+
timestamp: Date.now()
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
ws.send(JSON.stringify(announcement));
|
|
532
|
+
console.log(`📢 Announced to bootstrap hub on ${this.hubMeshNamespace}`);
|
|
533
|
+
|
|
534
|
+
// Announce all existing local peers to the bootstrap hub
|
|
535
|
+
this.announceLocalPeersToHub(ws);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Announce all local (non-hub) peers to a bootstrap hub
|
|
540
|
+
*/
|
|
541
|
+
announceLocalPeersToHub(ws) {
|
|
542
|
+
let totalAnnounced = 0;
|
|
543
|
+
|
|
544
|
+
// Iterate through all networks and announce their peers
|
|
545
|
+
for (const [networkName, peerSet] of this.networkPeers) {
|
|
546
|
+
// Skip the hub mesh namespace
|
|
547
|
+
if (networkName === this.hubMeshNamespace) {
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
for (const peerId of peerSet) {
|
|
552
|
+
const peerData = this.peerData.get(peerId);
|
|
553
|
+
|
|
554
|
+
// Skip hubs, only announce regular peers
|
|
555
|
+
if (peerData?.isHub) {
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// Skip if not connected or not announced
|
|
560
|
+
const connection = this.connections.get(peerId);
|
|
561
|
+
if (!connection || connection.readyState !== WebSocket.OPEN || !peerData?.announced) {
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// Send peer-discovered message to bootstrap hub
|
|
566
|
+
const peerAnnouncement = {
|
|
567
|
+
type: 'peer-discovered',
|
|
568
|
+
data: {
|
|
569
|
+
peerId,
|
|
570
|
+
isHub: false,
|
|
571
|
+
...peerData.data
|
|
572
|
+
},
|
|
573
|
+
networkName: networkName,
|
|
574
|
+
fromPeerId: 'system',
|
|
575
|
+
timestamp: Date.now()
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
try {
|
|
579
|
+
ws.send(JSON.stringify(peerAnnouncement));
|
|
580
|
+
totalAnnounced++;
|
|
581
|
+
} catch (error) {
|
|
582
|
+
console.error(`❌ Error announcing peer ${peerId.substring(0, 8)}... to bootstrap:`, error.message);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
if (totalAnnounced > 0) {
|
|
588
|
+
console.log(`📡 Announced ${totalAnnounced} local peer(s) to bootstrap hub`);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Send all local peers to a connected hub (via peerId)
|
|
594
|
+
*/
|
|
595
|
+
sendLocalPeersToHub(hubPeerId) {
|
|
596
|
+
const hubConnection = this.connections.get(hubPeerId);
|
|
597
|
+
if (!hubConnection || hubConnection.readyState !== WebSocket.OPEN) {
|
|
598
|
+
console.log(`⚠️ Cannot send peers to hub ${hubPeerId.substring(0, 8)}... - not connected`);
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
let totalSent = 0;
|
|
603
|
+
|
|
604
|
+
// Iterate through all networks and send their peers
|
|
605
|
+
for (const [networkName, peerSet] of this.networkPeers) {
|
|
606
|
+
// Skip the hub mesh namespace
|
|
607
|
+
if (networkName === this.hubMeshNamespace) {
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
for (const peerId of peerSet) {
|
|
612
|
+
const peerData = this.peerData.get(peerId);
|
|
613
|
+
|
|
614
|
+
// Skip hubs, only send regular peers
|
|
615
|
+
if (peerData?.isHub) {
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// Skip if not connected or not announced
|
|
620
|
+
const connection = this.connections.get(peerId);
|
|
621
|
+
if (!connection || connection.readyState !== WebSocket.OPEN || !peerData?.announced) {
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Send peer-discovered message to the hub
|
|
626
|
+
const peerAnnouncement = {
|
|
627
|
+
type: 'peer-discovered',
|
|
628
|
+
data: {
|
|
629
|
+
peerId,
|
|
630
|
+
isHub: false,
|
|
631
|
+
...peerData.data
|
|
632
|
+
},
|
|
633
|
+
networkName: networkName,
|
|
634
|
+
fromPeerId: 'system',
|
|
635
|
+
targetPeerId: hubPeerId,
|
|
636
|
+
timestamp: Date.now()
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
try {
|
|
640
|
+
this.sendToConnection(hubConnection, peerAnnouncement);
|
|
641
|
+
totalSent++;
|
|
642
|
+
} catch (error) {
|
|
643
|
+
console.error(`❌ Error sending peer ${peerId.substring(0, 8)}... to hub:`, error.message);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
if (totalSent > 0) {
|
|
649
|
+
console.log(`📡 Sent ${totalSent} local peer(s) to hub ${hubPeerId.substring(0, 8)}...`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Handle messages from bootstrap hubs
|
|
655
|
+
*/
|
|
656
|
+
handleBootstrapMessage(uri, message) {
|
|
657
|
+
const { type, data, fromPeerId, targetPeerId, networkName } = message;
|
|
658
|
+
|
|
659
|
+
switch (type) {
|
|
660
|
+
case 'connected':
|
|
661
|
+
console.log(`✅ Bootstrap hub acknowledged connection: ${uri}`);
|
|
662
|
+
break;
|
|
663
|
+
|
|
664
|
+
case 'peer-discovered':
|
|
665
|
+
if (data?.isHub) {
|
|
666
|
+
console.log(`🏢 Discovered hub via bootstrap: ${data.peerId?.substring(0, 8)}...`);
|
|
667
|
+
this.emit('hubDiscovered', { peerId: data.peerId, via: uri, data });
|
|
668
|
+
} else if (data?.peerId) {
|
|
669
|
+
// Regular peer discovered on another hub - notify our local peers in same network
|
|
670
|
+
const discoveredPeerId = data.peerId;
|
|
671
|
+
const discoveredNetwork = networkName || 'global';
|
|
672
|
+
|
|
673
|
+
console.log(`📥 Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
|
|
674
|
+
|
|
675
|
+
// Forward to all our local peers in the same network
|
|
676
|
+
const localPeers = this.getActivePeers(null, discoveredNetwork);
|
|
677
|
+
localPeers.forEach(localPeerId => {
|
|
678
|
+
const localConnection = this.connections.get(localPeerId);
|
|
679
|
+
if (localConnection) {
|
|
680
|
+
this.sendToConnection(localConnection, {
|
|
681
|
+
type: 'peer-discovered',
|
|
682
|
+
data,
|
|
683
|
+
networkName: discoveredNetwork,
|
|
684
|
+
fromPeerId: 'system',
|
|
685
|
+
targetPeerId: localPeerId,
|
|
686
|
+
timestamp: Date.now()
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
break;
|
|
692
|
+
|
|
693
|
+
case 'peer-disconnected':
|
|
694
|
+
if (data?.isHub) {
|
|
695
|
+
console.log(`🏢 Hub disconnected: ${data.peerId?.substring(0, 8)}...`);
|
|
696
|
+
}
|
|
697
|
+
break;
|
|
698
|
+
|
|
699
|
+
case 'offer':
|
|
700
|
+
case 'answer':
|
|
701
|
+
case 'ice-candidate':
|
|
702
|
+
// Check if target peer is on this hub
|
|
703
|
+
if (targetPeerId) {
|
|
704
|
+
const targetConnection = this.connections.get(targetPeerId);
|
|
705
|
+
if (targetConnection && targetConnection.readyState === WebSocket.OPEN) {
|
|
706
|
+
// Forward to local peer
|
|
707
|
+
console.log(`📥 Received ${type} from ${fromPeerId?.substring(0, 8)}... for local peer ${targetPeerId.substring(0, 8)}...`);
|
|
708
|
+
this.sendToConnection(targetConnection, message);
|
|
709
|
+
} else {
|
|
710
|
+
// Not our peer, relay to other bootstrap hubs
|
|
711
|
+
console.log(`🔄 Relaying ${type} from ${fromPeerId?.substring(0, 8)}... for ${targetPeerId.substring(0, 8)}... (not local)`);
|
|
712
|
+
for (const [otherUri, connInfo] of this.bootstrapConnections) {
|
|
713
|
+
if (otherUri !== uri && connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
|
|
714
|
+
connInfo.ws.send(JSON.stringify(message));
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
} else {
|
|
719
|
+
console.log(`⚠️ Received ${type} without targetPeerId via ${uri}`);
|
|
720
|
+
}
|
|
721
|
+
this.emit('bootstrapSignaling', { type, data, fromPeerId, targetPeerId, uri });
|
|
722
|
+
break;
|
|
723
|
+
|
|
724
|
+
case 'pong':
|
|
725
|
+
// Heartbeat response
|
|
726
|
+
break;
|
|
727
|
+
|
|
728
|
+
default:
|
|
729
|
+
console.log(`📨 Received ${type} from bootstrap hub ${uri}`);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Disconnect from all bootstrap hubs
|
|
735
|
+
*/
|
|
736
|
+
disconnectFromBootstrapHubs() {
|
|
737
|
+
console.log(`🔌 Disconnecting from ${this.bootstrapConnections.size} bootstrap hub(s)...`);
|
|
738
|
+
|
|
739
|
+
for (const [uri, info] of this.bootstrapConnections) {
|
|
740
|
+
if (info.reconnectTimer) {
|
|
741
|
+
clearTimeout(info.reconnectTimer);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
if (info.ws && info.ws.readyState === WebSocket.OPEN) {
|
|
745
|
+
info.ws.close(1000, 'Hub shutting down');
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
this.bootstrapConnections.clear();
|
|
750
|
+
}
|
|
751
|
+
|
|
166
752
|
/**
|
|
167
753
|
* Setup WebSocket connection handlers
|
|
168
754
|
*/
|
|
@@ -172,12 +758,26 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
172
758
|
const peerId = url.searchParams.get('peerId');
|
|
173
759
|
|
|
174
760
|
// Validate peer ID
|
|
175
|
-
if (!peerId ||
|
|
761
|
+
if (!peerId || !this.validatePeerId(peerId)) {
|
|
176
762
|
console.log('❌ Invalid peer ID, closing connection');
|
|
177
763
|
ws.close(1008, 'Invalid peerId format');
|
|
178
764
|
return;
|
|
179
765
|
}
|
|
180
766
|
|
|
767
|
+
// Check if peerId is already connected
|
|
768
|
+
if (this.connections.has(peerId)) {
|
|
769
|
+
const existingConnection = this.connections.get(peerId);
|
|
770
|
+
if (existingConnection.readyState === existingConnection.OPEN) {
|
|
771
|
+
console.log(`⚠️ Peer ${peerId.substring(0, 8)}... already connected, closing duplicate`);
|
|
772
|
+
ws.close(1008, 'Peer already connected');
|
|
773
|
+
return;
|
|
774
|
+
} else {
|
|
775
|
+
// Clean up stale connection
|
|
776
|
+
console.log(`🔄 Replacing stale connection for ${peerId.substring(0, 8)}...`);
|
|
777
|
+
this.cleanupPeer(peerId);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
181
781
|
// Check connection limit
|
|
182
782
|
if (this.connections.size >= this.maxConnections) {
|
|
183
783
|
console.log('❌ Maximum connections reached, closing connection');
|
|
@@ -191,9 +791,13 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
191
791
|
peerId,
|
|
192
792
|
connectedAt: Date.now(),
|
|
193
793
|
lastActivity: Date.now(),
|
|
194
|
-
remoteAddress: req.socket.remoteAddress
|
|
794
|
+
remoteAddress: req.socket.remoteAddress,
|
|
795
|
+
connected: true
|
|
195
796
|
});
|
|
196
797
|
|
|
798
|
+
// Set up connection metadata
|
|
799
|
+
ws.connectedAt = Date.now();
|
|
800
|
+
|
|
197
801
|
console.log(`✅ Peer connected: ${peerId.substring(0, 8)}... (${this.connections.size} total)`);
|
|
198
802
|
this.emit('peerConnected', { peerId, totalConnections: this.connections.size });
|
|
199
803
|
|
|
@@ -250,20 +854,37 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
250
854
|
return;
|
|
251
855
|
}
|
|
252
856
|
|
|
857
|
+
const { type, data: messageData, targetPeerId, networkName, fromPeerId: originalFromPeerId } = message;
|
|
858
|
+
|
|
253
859
|
// Log message type
|
|
254
|
-
console.log(`📨
|
|
860
|
+
console.log(`📨 Received ${type} from ${peerId.substring(0, 8)}... in network: ${networkName || 'global'}`);
|
|
861
|
+
|
|
862
|
+
// Preserve the original fromPeerId if it exists (for relayed messages from other hubs)
|
|
863
|
+
// Otherwise use the peerId of the connection
|
|
864
|
+
const responseMessage = {
|
|
865
|
+
type,
|
|
866
|
+
data: messageData,
|
|
867
|
+
fromPeerId: originalFromPeerId || peerId,
|
|
868
|
+
targetPeerId,
|
|
869
|
+
networkName: networkName || 'global',
|
|
870
|
+
timestamp: Date.now()
|
|
871
|
+
};
|
|
255
872
|
|
|
256
|
-
switch (
|
|
873
|
+
switch (type) {
|
|
257
874
|
case 'announce':
|
|
258
|
-
this.handleAnnounce(peerId, message);
|
|
875
|
+
this.handleAnnounce(peerId, message, responseMessage);
|
|
259
876
|
break;
|
|
260
877
|
case 'goodbye':
|
|
261
|
-
this.handleGoodbye(peerId, message);
|
|
878
|
+
this.handleGoodbye(peerId, message, responseMessage);
|
|
262
879
|
break;
|
|
263
880
|
case 'offer':
|
|
264
881
|
case 'answer':
|
|
265
882
|
case 'ice-candidate':
|
|
266
|
-
this.handleSignaling(peerId, message);
|
|
883
|
+
this.handleSignaling(peerId, message, responseMessage);
|
|
884
|
+
break;
|
|
885
|
+
case 'peer-discovered':
|
|
886
|
+
// Handle peer discovery from other hubs
|
|
887
|
+
this.handlePeerDiscovered(peerId, message);
|
|
267
888
|
break;
|
|
268
889
|
case 'ping':
|
|
269
890
|
this.handlePing(peerId, message);
|
|
@@ -272,85 +893,255 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
272
893
|
this.handleCleanup(peerId, message);
|
|
273
894
|
break;
|
|
274
895
|
default:
|
|
275
|
-
console.log(
|
|
896
|
+
console.log(`⚠️ Ignoring non-signaling message type '${type}' - peers should route their own messages`);
|
|
897
|
+
const connection = this.connections.get(peerId);
|
|
898
|
+
if (connection && connection.readyState === WebSocket.OPEN) {
|
|
899
|
+
this.sendToConnection(connection, {
|
|
900
|
+
type: 'error',
|
|
901
|
+
error: `Signaling server does not route '${type}' messages. Use WebRTC data channels for peer-to-peer communication.`,
|
|
902
|
+
timestamp: Date.now()
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
break;
|
|
276
906
|
}
|
|
277
907
|
}
|
|
278
908
|
|
|
279
909
|
/**
|
|
280
910
|
* Handle peer announcement
|
|
281
911
|
*/
|
|
282
|
-
handleAnnounce(peerId, message) {
|
|
283
|
-
|
|
912
|
+
handleAnnounce(peerId, message, responseMessage) {
|
|
913
|
+
// Extract network name from the message
|
|
914
|
+
const peerNetworkName = message.networkName || 'global';
|
|
915
|
+
|
|
916
|
+
// Detect if this peer is a hub
|
|
917
|
+
const isHub = message.data?.isHub === true || peerNetworkName === this.hubMeshNamespace;
|
|
918
|
+
|
|
919
|
+
if (isHub) {
|
|
920
|
+
console.log(`📢 Hub announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
|
|
921
|
+
} else {
|
|
922
|
+
console.log(`📢 Peer announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
|
|
923
|
+
}
|
|
284
924
|
|
|
285
|
-
// Update peer data
|
|
925
|
+
// Update peer data with network information
|
|
286
926
|
const peerInfo = this.peerData.get(peerId);
|
|
287
927
|
if (peerInfo) {
|
|
288
928
|
peerInfo.announced = true;
|
|
289
929
|
peerInfo.announcedAt = Date.now();
|
|
930
|
+
peerInfo.networkName = peerNetworkName;
|
|
931
|
+
peerInfo.data = message.data;
|
|
932
|
+
peerInfo.isHub = isHub;
|
|
290
933
|
}
|
|
291
934
|
|
|
292
|
-
//
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
935
|
+
// Register as hub if applicable
|
|
936
|
+
if (isHub) {
|
|
937
|
+
this.registerHub(peerId, {
|
|
938
|
+
networkName: peerNetworkName,
|
|
939
|
+
data: message.data,
|
|
940
|
+
connectedAt: peerInfo?.connectedAt || Date.now()
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
// When a new hub announces itself, send it all our local peers
|
|
944
|
+
if (this.isHub) {
|
|
945
|
+
console.log(`📡 New hub connected, sending our local peers to ${peerId.substring(0, 8)}...`);
|
|
946
|
+
this.sendLocalPeersToHub(peerId);
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// Add peer to network tracking
|
|
951
|
+
if (!this.networkPeers.has(peerNetworkName)) {
|
|
952
|
+
this.networkPeers.set(peerNetworkName, new Set());
|
|
953
|
+
}
|
|
954
|
+
this.networkPeers.get(peerNetworkName).add(peerId);
|
|
955
|
+
|
|
956
|
+
// If this is a hub, broadcast this peer to ALL other connected hubs (both bootstrap and incoming)
|
|
957
|
+
if (this.isHub && !isHub) {
|
|
958
|
+
const connectedHubs = [];
|
|
959
|
+
|
|
960
|
+
// 1. Add outgoing bootstrap connections
|
|
961
|
+
for (const [uri, connInfo] of this.bootstrapConnections) {
|
|
962
|
+
if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
|
|
963
|
+
connectedHubs.push({ type: 'bootstrap', ws: connInfo.ws, id: uri });
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// 2. Add incoming hub connections (hubs that connected to us)
|
|
968
|
+
for (const [hubPeerId, hubInfo] of this.hubs) {
|
|
969
|
+
// Skip self and the announcing hub
|
|
970
|
+
if (hubPeerId === this.hubPeerId || hubPeerId === peerId) {
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
const hubConnection = this.connections.get(hubPeerId);
|
|
974
|
+
if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
|
|
975
|
+
connectedHubs.push({ type: 'incoming', ws: hubConnection, id: hubPeerId });
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
if (connectedHubs.length > 0) {
|
|
980
|
+
console.log(`📡 Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} connected hub(s)`);
|
|
981
|
+
const peerAnnouncement = {
|
|
982
|
+
type: 'peer-discovered',
|
|
983
|
+
data: {
|
|
984
|
+
peerId,
|
|
985
|
+
isHub: false,
|
|
986
|
+
...message.data
|
|
987
|
+
},
|
|
988
|
+
networkName: peerNetworkName,
|
|
989
|
+
fromPeerId: 'system',
|
|
990
|
+
timestamp: Date.now()
|
|
991
|
+
};
|
|
992
|
+
|
|
993
|
+
for (const hub of connectedHubs) {
|
|
994
|
+
try {
|
|
995
|
+
if (hub.type === 'bootstrap') {
|
|
996
|
+
hub.ws.send(JSON.stringify(peerAnnouncement));
|
|
997
|
+
} else {
|
|
998
|
+
this.sendToConnection(hub.ws, peerAnnouncement);
|
|
999
|
+
}
|
|
1000
|
+
} catch (error) {
|
|
1001
|
+
console.error(`❌ Error broadcasting to hub ${hub.id}:`, error.message);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Get active peers in the same network
|
|
1008
|
+
const activePeers = this.getActivePeers(peerId, peerNetworkName);
|
|
1009
|
+
|
|
1010
|
+
// Validate peers
|
|
1011
|
+
const validatedPeers = [];
|
|
1012
|
+
for (const otherPeerId of activePeers) {
|
|
1013
|
+
const connection = this.connections.get(otherPeerId);
|
|
1014
|
+
if (connection && connection.readyState === connection.OPEN) {
|
|
1015
|
+
validatedPeers.push(otherPeerId);
|
|
1016
|
+
} else {
|
|
1017
|
+
console.log(`🧹 Found dead connection during announce: ${otherPeerId.substring(0, 8)}...`);
|
|
1018
|
+
this.cleanupPeer(otherPeerId);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
const hubType = isHub ? 'hub' : 'peer';
|
|
1023
|
+
console.log(`📢 Announcing ${hubType} ${peerId.substring(0, 8)}... to ${validatedPeers.length} validated peers in network: ${peerNetworkName}`);
|
|
1024
|
+
|
|
1025
|
+
// Send peer-discovered messages to validated peers only
|
|
1026
|
+
validatedPeers.forEach(otherPeerId => {
|
|
1027
|
+
const otherPeerData = this.peerData.get(otherPeerId);
|
|
1028
|
+
this.sendToConnection(this.connections.get(otherPeerId), {
|
|
1029
|
+
type: 'peer-discovered',
|
|
1030
|
+
data: {
|
|
1031
|
+
peerId,
|
|
1032
|
+
isHub,
|
|
1033
|
+
...message.data
|
|
1034
|
+
},
|
|
1035
|
+
networkName: peerNetworkName,
|
|
1036
|
+
fromPeerId: 'system',
|
|
1037
|
+
targetPeerId: otherPeerId,
|
|
1038
|
+
timestamp: Date.now()
|
|
1039
|
+
});
|
|
1040
|
+
});
|
|
1041
|
+
|
|
1042
|
+
// Send existing validated peers to the new peer (include their hub status)
|
|
1043
|
+
const newPeerConnection = this.connections.get(peerId);
|
|
1044
|
+
validatedPeers.forEach(existingPeerId => {
|
|
1045
|
+
const existingPeerData = this.peerData.get(existingPeerId);
|
|
1046
|
+
this.sendToConnection(newPeerConnection, {
|
|
1047
|
+
type: 'peer-discovered',
|
|
1048
|
+
data: {
|
|
1049
|
+
peerId: existingPeerId,
|
|
1050
|
+
isHub: existingPeerData?.isHub || false,
|
|
1051
|
+
...existingPeerData?.data
|
|
1052
|
+
},
|
|
1053
|
+
networkName: peerNetworkName,
|
|
1054
|
+
fromPeerId: 'system',
|
|
1055
|
+
targetPeerId: peerId,
|
|
1056
|
+
timestamp: Date.now()
|
|
1057
|
+
});
|
|
302
1058
|
});
|
|
303
1059
|
|
|
304
|
-
this.emit('peerAnnounced', { peerId });
|
|
1060
|
+
this.emit('peerAnnounced', { peerId, networkName: peerNetworkName, isHub });
|
|
305
1061
|
}
|
|
306
1062
|
|
|
307
1063
|
/**
|
|
308
1064
|
* Handle peer goodbye
|
|
309
1065
|
*/
|
|
310
|
-
handleGoodbye(peerId, message) {
|
|
1066
|
+
handleGoodbye(peerId, message, responseMessage) {
|
|
311
1067
|
console.log(`👋 Peer goodbye: ${peerId.substring(0, 8)}...`);
|
|
312
1068
|
|
|
313
|
-
//
|
|
314
|
-
this.
|
|
315
|
-
|
|
316
|
-
data: {
|
|
317
|
-
peerId,
|
|
318
|
-
reason: message.data?.reason || 'goodbye',
|
|
319
|
-
timestamp: Date.now()
|
|
320
|
-
},
|
|
321
|
-
fromPeerId: 'system',
|
|
322
|
-
timestamp: Date.now()
|
|
323
|
-
});
|
|
324
|
-
|
|
1069
|
+
// Broadcast to closest peers before removing peer data
|
|
1070
|
+
this.broadcastToClosestPeers(peerId, responseMessage);
|
|
1071
|
+
|
|
325
1072
|
// Remove peer
|
|
326
|
-
this.
|
|
1073
|
+
this.cleanupPeer(peerId);
|
|
327
1074
|
this.emit('peerGoodbye', { peerId });
|
|
328
1075
|
}
|
|
329
1076
|
|
|
330
1077
|
/**
|
|
331
1078
|
* Handle WebRTC signaling messages
|
|
332
1079
|
*/
|
|
333
|
-
handleSignaling(peerId, message) {
|
|
1080
|
+
handleSignaling(peerId, message, responseMessage) {
|
|
334
1081
|
const targetPeerId = message.targetPeerId;
|
|
1082
|
+
const networkName = message.networkName || 'global';
|
|
1083
|
+
|
|
1084
|
+
console.log(`🔍 SIGNALING DEBUG: Received ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId?.substring(0, 8)}... in network '${networkName}'`);
|
|
1085
|
+
|
|
335
1086
|
if (!targetPeerId) {
|
|
336
1087
|
console.log(`❌ No target peer ID in signaling message from ${peerId.substring(0, 8)}...`);
|
|
337
1088
|
return;
|
|
338
1089
|
}
|
|
339
1090
|
|
|
340
1091
|
const targetConnection = this.connections.get(targetPeerId);
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
1092
|
+
|
|
1093
|
+
// Only validate network if target peer is local (we have their data)
|
|
1094
|
+
if (targetConnection) {
|
|
1095
|
+
const targetPeerData = this.peerData.get(targetPeerId);
|
|
1096
|
+
const targetNetwork = targetPeerData?.networkName || 'global';
|
|
1097
|
+
|
|
1098
|
+
if (networkName !== targetNetwork) {
|
|
1099
|
+
console.log(`🚫 Blocking ${message.type} from ${peerId.substring(0, 8)}... (network: ${networkName}) to ${targetPeerId.substring(0, 8)}... (network: ${targetNetwork}) - different networks`);
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
// Target is local - forward directly
|
|
1104
|
+
console.log(`✅ Forwarding ${message.type} to LOCAL peer ${targetPeerId.substring(0, 8)}...`);
|
|
1105
|
+
this.sendToConnection(targetConnection, responseMessage);
|
|
1106
|
+
} else {
|
|
1107
|
+
// Target peer not on this hub - relay to other hubs
|
|
1108
|
+
console.log(`🔄 Target peer ${targetPeerId.substring(0, 8)}... NOT LOCAL, relaying to other hubs (network: ${networkName})`);
|
|
1109
|
+
|
|
1110
|
+
let relayed = false;
|
|
1111
|
+
|
|
1112
|
+
// First try relaying through bootstrap hubs (if we're not the bootstrap)
|
|
1113
|
+
if (this.bootstrapConnections.size > 0) {
|
|
1114
|
+
console.log(`� Relaying ${message.type} through ${this.bootstrapConnections.size} bootstrap connection(s)`);
|
|
1115
|
+
|
|
1116
|
+
for (const [uri, connInfo] of this.bootstrapConnections) {
|
|
1117
|
+
if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
|
|
1118
|
+
connInfo.ws.send(JSON.stringify(responseMessage));
|
|
1119
|
+
console.log(`✅ Relayed ${message.type} to bootstrap hub ${uri}`);
|
|
1120
|
+
relayed = true;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// If we're the bootstrap hub (or bootstrap relay failed), forward to all connected hubs
|
|
1126
|
+
if (this.hubs.size > 0) {
|
|
1127
|
+
console.log(`� Forwarding ${message.type} to ${this.hubs.size} connected hub(s)`);
|
|
1128
|
+
|
|
1129
|
+
for (const [hubPeerId, hubInfo] of this.hubs) {
|
|
1130
|
+
const hubConnection = this.connections.get(hubPeerId);
|
|
1131
|
+
if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
|
|
1132
|
+
hubConnection.send(JSON.stringify(responseMessage));
|
|
1133
|
+
console.log(`✅ Forwarded ${message.type} to hub ${hubPeerId.substring(0, 8)}...`);
|
|
1134
|
+
relayed = true;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
if (!relayed) {
|
|
1140
|
+
console.log(`❌ FAILED TO RELAY: No hubs available for ${targetPeerId.substring(0, 8)}... (network: ${networkName})`);
|
|
1141
|
+
console.log(` - Bootstrap connections: ${this.bootstrapConnections.size}`);
|
|
1142
|
+
console.log(` - Connected hubs: ${this.hubs.size}`);
|
|
1143
|
+
}
|
|
344
1144
|
}
|
|
345
|
-
|
|
346
|
-
// Forward signaling message to target peer
|
|
347
|
-
this.sendToConnection(targetConnection, {
|
|
348
|
-
...message,
|
|
349
|
-
fromPeerId: peerId,
|
|
350
|
-
timestamp: Date.now()
|
|
351
|
-
});
|
|
352
|
-
|
|
353
|
-
console.log(`🔄 Forwarded ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId.substring(0, 8)}...`);
|
|
354
1145
|
}
|
|
355
1146
|
|
|
356
1147
|
/**
|
|
@@ -378,6 +1169,59 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
378
1169
|
// This is just for logging purposes
|
|
379
1170
|
}
|
|
380
1171
|
|
|
1172
|
+
/**
|
|
1173
|
+
* Handle peer discovery messages from other hubs
|
|
1174
|
+
*/
|
|
1175
|
+
handlePeerDiscovered(fromHubPeerId, message) {
|
|
1176
|
+
const { data: messageData, networkName } = message;
|
|
1177
|
+
const discoveredPeerId = messageData?.peerId;
|
|
1178
|
+
|
|
1179
|
+
if (!discoveredPeerId || !networkName) {
|
|
1180
|
+
console.log(`⚠️ Invalid peer-discovered message from ${fromHubPeerId.substring(0, 8)}...`);
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
// Check if sender is a hub
|
|
1185
|
+
const senderPeerData = this.peerData.get(fromHubPeerId);
|
|
1186
|
+
const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
|
|
1187
|
+
|
|
1188
|
+
if (!isFromHub) {
|
|
1189
|
+
console.log(`⚠️ Received peer-discovered from non-hub peer ${fromHubPeerId.substring(0, 8)}... - ignoring`);
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
console.log(`🔍 Received peer discovery from hub ${fromHubPeerId.substring(0, 8)}... - Peer ${discoveredPeerId.substring(0, 8)}... in network '${networkName}'`);
|
|
1194
|
+
|
|
1195
|
+
// Forward to all local CLIENT peers in the same network (exclude hubs)
|
|
1196
|
+
const localPeers = this.networkPeers.get(networkName);
|
|
1197
|
+
if (localPeers && localPeers.size > 0) {
|
|
1198
|
+
let forwardedCount = 0;
|
|
1199
|
+
for (const localPeerId of localPeers) {
|
|
1200
|
+
// Skip hubs - only forward to client peers
|
|
1201
|
+
const localPeerData = this.peerData.get(localPeerId);
|
|
1202
|
+
if (localPeerData?.isHub) {
|
|
1203
|
+
continue;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
const ws = this.connections.get(localPeerId);
|
|
1207
|
+
if (ws && ws.readyState === ws.OPEN) {
|
|
1208
|
+
ws.send(JSON.stringify({
|
|
1209
|
+
type: 'peer-discovered',
|
|
1210
|
+
data: messageData,
|
|
1211
|
+
networkName,
|
|
1212
|
+
fromPeerId: 'system',
|
|
1213
|
+
targetPeerId: localPeerId,
|
|
1214
|
+
timestamp: Date.now()
|
|
1215
|
+
}));
|
|
1216
|
+
forwardedCount++;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
console.log(`✅ Forwarded peer-discovered to ${forwardedCount} local peer(s) in network '${networkName}'`);
|
|
1220
|
+
} else {
|
|
1221
|
+
console.log(`ℹ️ No local peers in network '${networkName}' to forward to`);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
|
|
381
1225
|
/**
|
|
382
1226
|
* Handle peer disconnection
|
|
383
1227
|
*/
|
|
@@ -397,17 +1241,67 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
397
1241
|
});
|
|
398
1242
|
|
|
399
1243
|
// Remove peer
|
|
400
|
-
this.
|
|
1244
|
+
this.cleanupPeer(peerId);
|
|
401
1245
|
this.emit('peerDisconnected', { peerId, code, reason, totalConnections: this.connections.size });
|
|
402
1246
|
}
|
|
403
1247
|
|
|
404
1248
|
/**
|
|
405
|
-
* Remove peer from server
|
|
1249
|
+
* Remove peer from server with network cleanup
|
|
406
1250
|
*/
|
|
407
|
-
|
|
1251
|
+
cleanupPeer(peerId) {
|
|
1252
|
+
const wasConnected = this.connections.has(peerId);
|
|
1253
|
+
const peerInfo = this.peerData.get(peerId);
|
|
1254
|
+
const isHub = peerInfo?.isHub || false;
|
|
1255
|
+
|
|
408
1256
|
this.connections.delete(peerId);
|
|
409
1257
|
this.peerData.delete(peerId);
|
|
410
|
-
|
|
1258
|
+
|
|
1259
|
+
// Unregister hub if applicable
|
|
1260
|
+
if (isHub) {
|
|
1261
|
+
this.unregisterHub(peerId);
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
// Remove from network tracking
|
|
1265
|
+
if (peerInfo && peerInfo.networkName) {
|
|
1266
|
+
const networkPeerSet = this.networkPeers.get(peerInfo.networkName);
|
|
1267
|
+
if (networkPeerSet) {
|
|
1268
|
+
networkPeerSet.delete(peerId);
|
|
1269
|
+
// Clean up empty network sets
|
|
1270
|
+
if (networkPeerSet.size === 0) {
|
|
1271
|
+
this.networkPeers.delete(peerInfo.networkName);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
if (wasConnected) {
|
|
1277
|
+
const peerType = isHub ? 'hub' : 'peer';
|
|
1278
|
+
console.log(`🧹 Cleaned up ${peerType}: ${peerId.substring(0, 8)}... from network: ${peerInfo?.networkName || 'unknown'}`);
|
|
1279
|
+
|
|
1280
|
+
// Notify other peers in the same network about disconnection
|
|
1281
|
+
if (peerInfo && peerInfo.networkName) {
|
|
1282
|
+
const activePeers = this.getActivePeers(null, peerInfo.networkName);
|
|
1283
|
+
activePeers.forEach(otherPeerId => {
|
|
1284
|
+
this.sendToConnection(this.connections.get(otherPeerId), {
|
|
1285
|
+
type: 'peer-disconnected',
|
|
1286
|
+
data: {
|
|
1287
|
+
peerId,
|
|
1288
|
+
isHub
|
|
1289
|
+
},
|
|
1290
|
+
networkName: peerInfo.networkName,
|
|
1291
|
+
fromPeerId: 'system',
|
|
1292
|
+
targetPeerId: otherPeerId,
|
|
1293
|
+
timestamp: Date.now()
|
|
1294
|
+
});
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
/**
|
|
1301
|
+
* Remove peer from server (backwards compatibility)
|
|
1302
|
+
*/
|
|
1303
|
+
removePeer(peerId) {
|
|
1304
|
+
this.cleanupPeer(peerId);
|
|
411
1305
|
}
|
|
412
1306
|
|
|
413
1307
|
/**
|
|
@@ -445,6 +1339,22 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
445
1339
|
return sentCount;
|
|
446
1340
|
}
|
|
447
1341
|
|
|
1342
|
+
/**
|
|
1343
|
+
* Broadcast message to closest peers in same network
|
|
1344
|
+
*/
|
|
1345
|
+
broadcastToClosestPeers(fromPeerId, message, maxPeers = 5) {
|
|
1346
|
+
const peerInfo = this.peerData.get(fromPeerId);
|
|
1347
|
+
const networkName = peerInfo?.networkName || 'global';
|
|
1348
|
+
const activePeers = this.getActivePeers(fromPeerId, networkName);
|
|
1349
|
+
const closestPeers = this.findClosestPeers(fromPeerId, activePeers, maxPeers);
|
|
1350
|
+
|
|
1351
|
+
console.log(`Broadcasting from ${fromPeerId.substring(0, 8)}... to ${closestPeers.length} closest peers in network: ${networkName}`);
|
|
1352
|
+
|
|
1353
|
+
closestPeers.forEach(peerId => {
|
|
1354
|
+
this.sendToConnection(this.connections.get(peerId), message);
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
|
|
448
1358
|
/**
|
|
449
1359
|
* Start cleanup timer
|
|
450
1360
|
*/
|
|
@@ -458,33 +1368,17 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
458
1368
|
* Perform cleanup of inactive connections
|
|
459
1369
|
*/
|
|
460
1370
|
performCleanup() {
|
|
461
|
-
const
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
for (const [
|
|
465
|
-
|
|
466
|
-
console.log(`🧹 Cleaning up inactive peer: ${peerId.substring(0, 8)}...`);
|
|
467
|
-
|
|
468
|
-
const connection = this.connections.get(peerId);
|
|
469
|
-
if (connection) {
|
|
470
|
-
try {
|
|
471
|
-
connection.close(1000, 'Inactive timeout');
|
|
472
|
-
} catch (error) {
|
|
473
|
-
console.error(`Error closing inactive connection for ${peerId}:`, error);
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
disconnectedPeers.push(peerId);
|
|
478
|
-
}
|
|
1371
|
+
const totalConnections = this.connections.size;
|
|
1372
|
+
|
|
1373
|
+
// Clean up all networks
|
|
1374
|
+
for (const [networkName] of this.networkPeers) {
|
|
1375
|
+
this.getActivePeers(null, networkName); // This will clean up stale connections
|
|
479
1376
|
}
|
|
1377
|
+
|
|
1378
|
+
const cleanedUp = totalConnections - this.connections.size;
|
|
480
1379
|
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
this.removePeer(peerId);
|
|
484
|
-
});
|
|
485
|
-
|
|
486
|
-
if (disconnectedPeers.length > 0) {
|
|
487
|
-
console.log(`🧹 Cleaned up ${disconnectedPeers.length} inactive peers`);
|
|
1380
|
+
if (cleanedUp > 0) {
|
|
1381
|
+
console.log(`🧹 Periodic cleanup: removed ${cleanedUp} stale connections, ${this.connections.size} active across ${this.networkPeers.size} networks`);
|
|
488
1382
|
}
|
|
489
1383
|
}
|
|
490
1384
|
|
|
@@ -492,17 +1386,57 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
492
1386
|
* Get server statistics
|
|
493
1387
|
*/
|
|
494
1388
|
getStats() {
|
|
1389
|
+
const bootstrapStats = {
|
|
1390
|
+
total: this.bootstrapConnections.size,
|
|
1391
|
+
connected: 0
|
|
1392
|
+
};
|
|
1393
|
+
|
|
1394
|
+
for (const [, info] of this.bootstrapConnections) {
|
|
1395
|
+
if (info.connected) {
|
|
1396
|
+
bootstrapStats.connected++;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
|
|
495
1400
|
return {
|
|
496
1401
|
isRunning: this.isRunning,
|
|
1402
|
+
isHub: this.isHub,
|
|
1403
|
+
hubPeerId: this.hubPeerId,
|
|
497
1404
|
connections: this.connections.size,
|
|
498
1405
|
peers: this.peerData.size,
|
|
1406
|
+
hubs: this.hubs.size,
|
|
1407
|
+
networks: this.networkPeers.size,
|
|
1408
|
+
bootstrapHubs: bootstrapStats,
|
|
499
1409
|
maxConnections: this.maxConnections,
|
|
500
|
-
uptime: this.isRunning ? Date.now() - this.startTime : 0,
|
|
1410
|
+
uptime: this.isRunning && this.startTime ? Date.now() - this.startTime : 0,
|
|
501
1411
|
host: this.host,
|
|
502
1412
|
port: this.port
|
|
503
1413
|
};
|
|
504
1414
|
}
|
|
505
1415
|
|
|
1416
|
+
/**
|
|
1417
|
+
* Get hub statistics
|
|
1418
|
+
*/
|
|
1419
|
+
getHubStats() {
|
|
1420
|
+
const connectedHubs = this.getConnectedHubs();
|
|
1421
|
+
const bootstrapHubsInfo = [];
|
|
1422
|
+
|
|
1423
|
+
for (const [uri, info] of this.bootstrapConnections) {
|
|
1424
|
+
bootstrapHubsInfo.push({
|
|
1425
|
+
uri,
|
|
1426
|
+
connected: info.connected,
|
|
1427
|
+
lastAttempt: info.lastAttempt,
|
|
1428
|
+
attemptNumber: info.attemptNumber
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
return {
|
|
1433
|
+
totalHubs: this.hubs.size,
|
|
1434
|
+
connectedHubs: connectedHubs.length,
|
|
1435
|
+
hubs: connectedHubs,
|
|
1436
|
+
bootstrapHubs: bootstrapHubsInfo
|
|
1437
|
+
};
|
|
1438
|
+
}
|
|
1439
|
+
|
|
506
1440
|
/**
|
|
507
1441
|
* Get list of connected peers
|
|
508
1442
|
*/
|