peerpigeon 0.0.5 ā 0.0.7
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 +190 -12
- package/examples/browser/app.js +40 -40
- package/examples/browser/crypto-test.html +427 -0
- package/examples/browser/index.html +161 -0
- package/examples/browser/styles.css +216 -0
- package/examples/browser/ui-old.js +1704 -1708
- package/examples/browser/ui.js +2226 -1692
- package/examples/nativescript/README.md +73 -0
- package/examples/nativescript/app.js +152 -0
- package/examples/nativescript/package.json +27 -0
- package/examples/node/test-crypto-media.js +137 -0
- package/examples/node/test-crypto.js +146 -0
- package/examples/node/test-node.js +114 -115
- package/package.json +16 -13
- package/src/CleanupManager.js +154 -154
- package/src/ConnectionManager.js +772 -753
- package/src/CryptoManager.js +612 -0
- package/src/EnvironmentDetector.js +457 -384
- package/src/EventEmitter.js +19 -19
- package/src/EvictionManager.js +211 -211
- package/src/GossipManager.js +447 -366
- package/src/MediaManager.js +216 -214
- package/src/MeshOptimizer.js +165 -166
- package/src/PeerConnection.js +847 -941
- package/src/PeerDiscovery.js +255 -259
- package/src/PeerPigeonMesh.js +1100 -721
- package/src/SignalingClient.js +517 -518
- package/src/SignalingHandler.js +295 -295
- package/src/StorageManager.js +118 -104
- package/src/TimerUtils.js +29 -29
- package/src/WebDHT.js +1123 -948
- package/websocket-server/server.js +360 -362
|
@@ -4,7 +4,7 @@ import { URL } from 'url';
|
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Local WebSocket Server for PeerPigeon Development
|
|
7
|
-
*
|
|
7
|
+
*
|
|
8
8
|
* This server provides WebSocket signaling functionality
|
|
9
9
|
* for local development and testing of the PeerPigeon mesh network.
|
|
10
10
|
*/
|
|
@@ -14,147 +14,143 @@ const HOST = process.env.HOST || 'localhost';
|
|
|
14
14
|
|
|
15
15
|
// In-memory storage for connections and peer data
|
|
16
16
|
const connections = new Map(); // peerId -> WebSocket connection
|
|
17
|
-
const peerData = new Map();
|
|
17
|
+
const peerData = new Map(); // peerId -> { peerId, timestamp, data }
|
|
18
18
|
|
|
19
19
|
// Utility functions
|
|
20
|
-
function generateId() {
|
|
21
|
-
return Date.now().toString(36) + Math.random().toString(36).substr(2);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
20
|
function validatePeerId(peerId) {
|
|
25
|
-
|
|
21
|
+
return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
|
|
26
22
|
}
|
|
27
23
|
|
|
28
24
|
function findClosestPeers(targetPeerId, allPeerIds, maxPeers = 3) {
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
if (!targetPeerId || !allPeerIds || allPeerIds.length === 0) {
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// XOR distance calculation (simplified)
|
|
30
|
+
const distances = allPeerIds.map(peerId => {
|
|
31
|
+
let distance = 0;
|
|
32
|
+
const minLength = Math.min(targetPeerId.length, peerId.length);
|
|
33
|
+
|
|
34
|
+
for (let i = 0; i < minLength; i++) {
|
|
35
|
+
const xor = parseInt(targetPeerId[i], 16) ^ parseInt(peerId[i], 16);
|
|
36
|
+
distance += xor;
|
|
31
37
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const xor = parseInt(targetPeerId[i], 16) ^ parseInt(peerId[i], 16);
|
|
40
|
-
distance += xor;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
return { peerId, distance };
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
// Sort by distance and return closest peers
|
|
47
|
-
distances.sort((a, b) => a.distance - b.distance);
|
|
48
|
-
return distances.slice(0, maxPeers).map(item => item.peerId);
|
|
38
|
+
|
|
39
|
+
return { peerId, distance };
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// Sort by distance and return closest peers
|
|
43
|
+
distances.sort((a, b) => a.distance - b.distance);
|
|
44
|
+
return distances.slice(0, maxPeers).map(item => item.peerId);
|
|
49
45
|
}
|
|
50
46
|
|
|
51
47
|
function getActivePeers(excludePeerId = null) {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
48
|
+
const peers = [];
|
|
49
|
+
const stalePeers = [];
|
|
50
|
+
|
|
51
|
+
for (const [peerId, connection] of connections) {
|
|
52
|
+
if (peerId !== excludePeerId) {
|
|
53
|
+
if (connection.readyState === WebSocket.OPEN && isConnectionAlive(connection)) {
|
|
54
|
+
peers.push(peerId);
|
|
55
|
+
} else {
|
|
56
|
+
// Mark stale connections for cleanup
|
|
57
|
+
stalePeers.push(peerId);
|
|
58
|
+
}
|
|
64
59
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Clean up stale connections
|
|
63
|
+
stalePeers.forEach(peerId => {
|
|
64
|
+
console.log(`š§¹ Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
|
|
65
|
+
connections.delete(peerId);
|
|
66
|
+
peerData.delete(peerId);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
return peers;
|
|
74
70
|
}
|
|
75
71
|
|
|
76
72
|
function isConnectionAlive(connection) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
73
|
+
if (!connection || connection.readyState !== WebSocket.OPEN) {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Check if we've received a recent pong or if this is a fresh connection
|
|
78
|
+
const now = Date.now();
|
|
79
|
+
const lastPong = connection.lastPong || connection.connectedAt || now;
|
|
80
|
+
const timeSinceLastPong = now - lastPong;
|
|
81
|
+
|
|
82
|
+
// Consider connection dead if no pong for more than 12 minutes (since we ping every 9 minutes)
|
|
83
|
+
return timeSinceLastPong < 720000; // 12 minutes
|
|
88
84
|
}
|
|
89
85
|
|
|
90
86
|
function pingConnection(peerId, connection) {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
}
|
|
87
|
+
if (connection.readyState === WebSocket.OPEN) {
|
|
88
|
+
try {
|
|
89
|
+
connection.ping();
|
|
90
|
+
return true;
|
|
91
|
+
} catch (error) {
|
|
92
|
+
console.log(`š Failed to ping ${peerId.substring(0, 8)}...:`, error.message);
|
|
93
|
+
cleanupPeer(peerId);
|
|
94
|
+
return false;
|
|
100
95
|
}
|
|
101
|
-
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
102
98
|
}
|
|
103
99
|
|
|
104
100
|
function sendToConnection(peerId, data) {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
} else if (connection && (connection.readyState === WebSocket.CLOSED || connection.readyState === WebSocket.CLOSING)) {
|
|
117
|
-
// Clean up closed connection
|
|
118
|
-
cleanupPeer(peerId);
|
|
101
|
+
const connection = connections.get(peerId);
|
|
102
|
+
if (connection && connection.readyState === WebSocket.OPEN) {
|
|
103
|
+
try {
|
|
104
|
+
connection.send(JSON.stringify(data));
|
|
105
|
+
return true;
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error(`Error sending to ${peerId}:`, error);
|
|
108
|
+
// Clean up failed connection
|
|
109
|
+
cleanupPeer(peerId);
|
|
110
|
+
return false;
|
|
119
111
|
}
|
|
120
|
-
|
|
112
|
+
} else if (connection && (connection.readyState === WebSocket.CLOSED || connection.readyState === WebSocket.CLOSING)) {
|
|
113
|
+
// Clean up closed connection
|
|
114
|
+
cleanupPeer(peerId);
|
|
115
|
+
}
|
|
116
|
+
return false;
|
|
121
117
|
}
|
|
122
118
|
|
|
123
119
|
function cleanupPeer(peerId) {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
120
|
+
const wasConnected = connections.has(peerId);
|
|
121
|
+
connections.delete(peerId);
|
|
122
|
+
peerData.delete(peerId);
|
|
123
|
+
|
|
124
|
+
if (wasConnected) {
|
|
125
|
+
console.log(`š§¹ Cleaned up peer: ${peerId.substring(0, 8)}...`);
|
|
126
|
+
|
|
127
|
+
// Notify other peers about disconnection
|
|
128
|
+
const activePeers = getActivePeers();
|
|
129
|
+
activePeers.forEach(otherPeerId => {
|
|
130
|
+
sendToConnection(otherPeerId, {
|
|
131
|
+
type: 'peer-disconnected',
|
|
132
|
+
data: { peerId },
|
|
133
|
+
fromPeerId: 'system',
|
|
134
|
+
targetPeerId: otherPeerId,
|
|
135
|
+
timestamp: Date.now()
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
}
|
|
143
139
|
}
|
|
144
140
|
|
|
145
141
|
function broadcastToClosestPeers(fromPeerId, message, maxPeers = 5) {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
142
|
+
const activePeers = getActivePeers(fromPeerId);
|
|
143
|
+
const closestPeers = findClosestPeers(fromPeerId, activePeers, maxPeers);
|
|
144
|
+
|
|
145
|
+
console.log(`Broadcasting from ${fromPeerId} to ${closestPeers.length} closest peers`);
|
|
146
|
+
|
|
147
|
+
closestPeers.forEach(peerId => {
|
|
148
|
+
sendToConnection(peerId, message);
|
|
149
|
+
});
|
|
154
150
|
}
|
|
155
151
|
|
|
156
152
|
function sendToSpecificPeer(targetPeerId, message) {
|
|
157
|
-
|
|
153
|
+
return sendToConnection(targetPeerId, message);
|
|
158
154
|
}
|
|
159
155
|
|
|
160
156
|
// Create HTTP server
|
|
@@ -163,302 +159,304 @@ const server = createServer();
|
|
|
163
159
|
// Create WebSocket server
|
|
164
160
|
const wss = new WebSocketServer({ server });
|
|
165
161
|
|
|
166
|
-
console.log(
|
|
162
|
+
console.log('š Starting PeerPigeon WebSocket server...');
|
|
167
163
|
|
|
168
164
|
// Periodic cleanup of stale connections
|
|
169
165
|
setInterval(() => {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
166
|
+
const totalConnections = connections.size;
|
|
167
|
+
getActivePeers(); // This will clean up stale connections
|
|
168
|
+
const cleanedUp = totalConnections - connections.size;
|
|
169
|
+
|
|
170
|
+
if (cleanedUp > 0) {
|
|
171
|
+
console.log(`š§¹ Periodic cleanup: removed ${cleanedUp} stale connections, ${connections.size} active`);
|
|
172
|
+
}
|
|
177
173
|
}, 30000); // Clean up every 30 seconds
|
|
178
174
|
|
|
179
175
|
// DHT-based heartbeat ping every 9 minutes (540 seconds)
|
|
180
176
|
// Use DHT logic to select a SINGLE peer to do the pinging instead of server pinging all
|
|
181
177
|
setInterval(() => {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
}
|
|
178
|
+
const activePeers = Array.from(connections.keys());
|
|
179
|
+
|
|
180
|
+
if (activePeers.length === 0) {
|
|
181
|
+
console.log('š No peers to ping');
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Use XOR distance to select the peer closest to a deterministic target
|
|
186
|
+
// This ensures the same peer is consistently selected across intervals
|
|
187
|
+
const pingTarget = '0000000000000000000000000000000000000000'; // Deterministic target for ping selection
|
|
188
|
+
const selectedPeer = selectPeerForPing(pingTarget, activePeers);
|
|
189
|
+
|
|
190
|
+
if (selectedPeer) {
|
|
191
|
+
const connection = connections.get(selectedPeer);
|
|
192
|
+
console.log(`š DHT-selected peer ${selectedPeer.substring(0, 8)}... for heartbeat ping (${activePeers.length} total peers)`);
|
|
193
|
+
|
|
194
|
+
if (!pingConnection(selectedPeer, connection)) {
|
|
195
|
+
console.log(`š§¹ DHT-selected peer ${selectedPeer.substring(0, 8)}... failed ping, cleaned up`);
|
|
201
196
|
}
|
|
197
|
+
}
|
|
202
198
|
}, 540000); // Ping every 9 minutes (540 seconds)
|
|
203
199
|
|
|
204
200
|
// DHT-based peer selection for ping duty
|
|
205
201
|
function selectPeerForPing(target, peerIds) {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
}
|
|
202
|
+
if (!peerIds || peerIds.length === 0) return null;
|
|
203
|
+
|
|
204
|
+
// Use XOR distance to find the peer closest to the target
|
|
205
|
+
let closestPeer = null;
|
|
206
|
+
let closestDistance = Infinity;
|
|
207
|
+
|
|
208
|
+
for (const peerId of peerIds) {
|
|
209
|
+
const distance = calculateXORDistance(target, peerId);
|
|
210
|
+
if (distance < closestDistance) {
|
|
211
|
+
closestDistance = distance;
|
|
212
|
+
closestPeer = peerId;
|
|
218
213
|
}
|
|
219
|
-
|
|
220
|
-
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return closestPeer;
|
|
221
217
|
}
|
|
222
218
|
|
|
223
219
|
// XOR distance calculation for DHT peer selection
|
|
224
220
|
function calculateXORDistance(id1, id2) {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
221
|
+
let distance = 0;
|
|
222
|
+
const minLength = Math.min(id1.length, id2.length);
|
|
223
|
+
|
|
224
|
+
for (let i = 0; i < minLength; i++) {
|
|
225
|
+
const xor = parseInt(id1[i], 16) ^ parseInt(id2[i], 16);
|
|
226
|
+
distance += xor;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return distance;
|
|
234
230
|
}
|
|
235
231
|
|
|
236
232
|
wss.on('connection', (ws, req) => {
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
}
|
|
233
|
+
let peerId = null;
|
|
234
|
+
|
|
235
|
+
// Extract peerId from query parameters
|
|
236
|
+
const url = new URL(req.url, `http://${req.headers.host}`);
|
|
237
|
+
const queryPeerId = url.searchParams.get('peerId');
|
|
238
|
+
|
|
239
|
+
if (!queryPeerId || !validatePeerId(queryPeerId)) {
|
|
240
|
+
console.log(`ā Invalid peerId: ${queryPeerId}`);
|
|
241
|
+
ws.close(1008, 'Invalid peerId');
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
peerId = queryPeerId;
|
|
246
|
+
|
|
247
|
+
// Check if peerId is already connected
|
|
248
|
+
if (connections.has(peerId)) {
|
|
249
|
+
const existingConnection = connections.get(peerId);
|
|
250
|
+
if (existingConnection.readyState === WebSocket.OPEN) {
|
|
251
|
+
console.log(`ā ļø Peer ${peerId.substring(0, 8)}... already connected, closing duplicate`);
|
|
252
|
+
ws.close(1008, 'Peer already connected');
|
|
253
|
+
return;
|
|
254
|
+
} else {
|
|
255
|
+
// Clean up stale connection
|
|
256
|
+
console.log(`š Replacing stale connection for ${peerId.substring(0, 8)}...`);
|
|
257
|
+
cleanupPeer(peerId);
|
|
263
258
|
}
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Store connection
|
|
262
|
+
connections.set(peerId, ws);
|
|
263
|
+
peerData.set(peerId, {
|
|
264
|
+
peerId,
|
|
265
|
+
timestamp: Date.now(),
|
|
266
|
+
connected: true
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
// Set up connection metadata
|
|
270
|
+
ws.connectedAt = Date.now();
|
|
271
|
+
ws.lastPong = Date.now();
|
|
272
|
+
|
|
273
|
+
// Set up pong handler for heartbeat
|
|
274
|
+
ws.on('pong', () => {
|
|
275
275
|
ws.lastPong = Date.now();
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
console.log(`ā
Peer ${peerId.substring(0, 8)}... connected (${connections.size} total)`);
|
|
279
|
+
|
|
280
|
+
// Send connection confirmation
|
|
281
|
+
ws.send(JSON.stringify({
|
|
282
|
+
type: 'connected',
|
|
283
|
+
peerId,
|
|
284
|
+
timestamp: Date.now()
|
|
285
|
+
}));
|
|
286
|
+
|
|
287
|
+
// Handle incoming messages
|
|
288
|
+
ws.on('message', (data) => {
|
|
289
|
+
try {
|
|
290
|
+
const message = JSON.parse(data);
|
|
291
|
+
const { type, data: messageData, targetPeerId, maxPeers } = message;
|
|
292
|
+
|
|
293
|
+
console.log(`šØ Received ${type} from ${peerId.substring(0, 8)}...`);
|
|
294
|
+
|
|
295
|
+
const responseMessage = {
|
|
296
|
+
type,
|
|
297
|
+
data: messageData,
|
|
298
|
+
fromPeerId: peerId,
|
|
299
|
+
targetPeerId,
|
|
288
300
|
timestamp: Date.now()
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
data: messageData,
|
|
324
|
-
connected: true
|
|
325
|
-
});
|
|
326
|
-
|
|
327
|
-
// Get active peers with immediate validation
|
|
328
|
-
const activePeers = getActivePeers(peerId);
|
|
329
|
-
|
|
330
|
-
// Double-check each active peer with a quick ping test
|
|
331
|
-
const validatedPeers = [];
|
|
332
|
-
for (const otherPeerId of activePeers) {
|
|
333
|
-
const connection = connections.get(otherPeerId);
|
|
334
|
-
if (connection && isConnectionAlive(connection)) {
|
|
335
|
-
validatedPeers.push(otherPeerId);
|
|
336
|
-
} else {
|
|
337
|
-
console.log(`ļæ½ Found dead connection during announce: ${otherPeerId.substring(0, 8)}...`);
|
|
338
|
-
cleanupPeer(otherPeerId);
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
console.log(`ļæ½š¢ Announcing ${peerId.substring(0, 8)}... to ${validatedPeers.length} validated peers`);
|
|
343
|
-
|
|
344
|
-
// Send peer-discovered messages to validated peers only
|
|
345
|
-
validatedPeers.forEach(otherPeerId => {
|
|
346
|
-
sendToConnection(otherPeerId, {
|
|
347
|
-
type: 'peer-discovered',
|
|
348
|
-
data: { peerId, ...messageData },
|
|
349
|
-
fromPeerId: 'system',
|
|
350
|
-
targetPeerId: otherPeerId,
|
|
351
|
-
timestamp: Date.now()
|
|
352
|
-
});
|
|
353
|
-
});
|
|
354
|
-
|
|
355
|
-
// Send existing validated peers to the new peer
|
|
356
|
-
validatedPeers.forEach(existingPeerId => {
|
|
357
|
-
const existingPeerData = peerData.get(existingPeerId);
|
|
358
|
-
ws.send(JSON.stringify({
|
|
359
|
-
type: 'peer-discovered',
|
|
360
|
-
data: { peerId: existingPeerId, ...existingPeerData?.data },
|
|
361
|
-
fromPeerId: 'system',
|
|
362
|
-
targetPeerId: peerId,
|
|
363
|
-
timestamp: Date.now()
|
|
364
|
-
}));
|
|
365
|
-
});
|
|
366
|
-
break;
|
|
367
|
-
|
|
368
|
-
case 'goodbye':
|
|
369
|
-
// Handle peer disconnect
|
|
370
|
-
peerData.delete(peerId);
|
|
371
|
-
broadcastToClosestPeers(peerId, responseMessage);
|
|
372
|
-
break;
|
|
373
|
-
|
|
374
|
-
case 'offer':
|
|
375
|
-
case 'answer':
|
|
376
|
-
case 'ice-candidate':
|
|
377
|
-
// Handle WebRTC signaling
|
|
378
|
-
if (targetPeerId) {
|
|
379
|
-
const success = sendToSpecificPeer(targetPeerId, responseMessage);
|
|
380
|
-
if (!success) {
|
|
381
|
-
console.log(`ā ļø Failed to send ${type} to ${targetPeerId.substring(0, 8)}... (peer not found)`);
|
|
382
|
-
}
|
|
383
|
-
} else {
|
|
384
|
-
console.log(`ā ļø ${type} message missing targetPeerId`);
|
|
385
|
-
}
|
|
386
|
-
break;
|
|
387
|
-
|
|
388
|
-
default:
|
|
389
|
-
// Handle generic messages
|
|
390
|
-
if (targetPeerId) {
|
|
391
|
-
sendToSpecificPeer(targetPeerId, responseMessage);
|
|
392
|
-
} else {
|
|
393
|
-
broadcastToClosestPeers(peerId, responseMessage, maxPeers || 10);
|
|
394
|
-
}
|
|
395
|
-
break;
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
// Handle different message types
|
|
304
|
+
switch (type) {
|
|
305
|
+
case 'ping':
|
|
306
|
+
// Respond with pong
|
|
307
|
+
ws.send(JSON.stringify({
|
|
308
|
+
type: 'pong',
|
|
309
|
+
timestamp: Date.now(),
|
|
310
|
+
originalTimestamp: messageData?.timestamp
|
|
311
|
+
}));
|
|
312
|
+
break;
|
|
313
|
+
|
|
314
|
+
case 'announce': {
|
|
315
|
+
// Handle peer announcement
|
|
316
|
+
peerData.set(peerId, {
|
|
317
|
+
peerId,
|
|
318
|
+
timestamp: Date.now(),
|
|
319
|
+
data: messageData,
|
|
320
|
+
connected: true
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// Get active peers with immediate validation
|
|
324
|
+
const activePeers = getActivePeers(peerId);
|
|
325
|
+
|
|
326
|
+
// Double-check each active peer with a quick ping test
|
|
327
|
+
const validatedPeers = [];
|
|
328
|
+
for (const otherPeerId of activePeers) {
|
|
329
|
+
const connection = connections.get(otherPeerId);
|
|
330
|
+
if (connection && isConnectionAlive(connection)) {
|
|
331
|
+
validatedPeers.push(otherPeerId);
|
|
332
|
+
} else {
|
|
333
|
+
console.log(`ļæ½ Found dead connection during announce: ${otherPeerId.substring(0, 8)}...`);
|
|
334
|
+
cleanupPeer(otherPeerId);
|
|
396
335
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
console.log(`ļæ½š¢ Announcing ${peerId.substring(0, 8)}... to ${validatedPeers.length} validated peers`);
|
|
339
|
+
|
|
340
|
+
// Send peer-discovered messages to validated peers only
|
|
341
|
+
validatedPeers.forEach(otherPeerId => {
|
|
342
|
+
sendToConnection(otherPeerId, {
|
|
343
|
+
type: 'peer-discovered',
|
|
344
|
+
data: { peerId, ...messageData },
|
|
345
|
+
fromPeerId: 'system',
|
|
346
|
+
targetPeerId: otherPeerId,
|
|
347
|
+
timestamp: Date.now()
|
|
348
|
+
});
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
// Send existing validated peers to the new peer
|
|
352
|
+
validatedPeers.forEach(existingPeerId => {
|
|
353
|
+
const existingPeerData = peerData.get(existingPeerId);
|
|
400
354
|
ws.send(JSON.stringify({
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
355
|
+
type: 'peer-discovered',
|
|
356
|
+
data: { peerId: existingPeerId, ...existingPeerData?.data },
|
|
357
|
+
fromPeerId: 'system',
|
|
358
|
+
targetPeerId: peerId,
|
|
359
|
+
timestamp: Date.now()
|
|
404
360
|
}));
|
|
361
|
+
});
|
|
362
|
+
break;
|
|
405
363
|
}
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
if (peerId) {
|
|
413
|
-
cleanupPeer(peerId);
|
|
364
|
+
|
|
365
|
+
case 'goodbye': {
|
|
366
|
+
// Handle peer disconnect
|
|
367
|
+
peerData.delete(peerId);
|
|
368
|
+
broadcastToClosestPeers(peerId, responseMessage);
|
|
369
|
+
break;
|
|
414
370
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
371
|
+
|
|
372
|
+
case 'offer':
|
|
373
|
+
case 'answer':
|
|
374
|
+
case 'ice-candidate': {
|
|
375
|
+
// Handle WebRTC signaling
|
|
376
|
+
if (targetPeerId) {
|
|
377
|
+
const success = sendToSpecificPeer(targetPeerId, responseMessage);
|
|
378
|
+
if (!success) {
|
|
379
|
+
console.log(`ā ļø Failed to send ${type} to ${targetPeerId.substring(0, 8)}... (peer not found)`);
|
|
380
|
+
}
|
|
381
|
+
} else {
|
|
382
|
+
console.log(`ā ļø ${type} message missing targetPeerId`);
|
|
383
|
+
}
|
|
384
|
+
break;
|
|
426
385
|
}
|
|
427
|
-
|
|
386
|
+
|
|
387
|
+
default:
|
|
388
|
+
// Handle generic messages
|
|
389
|
+
if (targetPeerId) {
|
|
390
|
+
sendToSpecificPeer(targetPeerId, responseMessage);
|
|
391
|
+
} else {
|
|
392
|
+
broadcastToClosestPeers(peerId, responseMessage, maxPeers || 10);
|
|
393
|
+
}
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
} catch (error) {
|
|
397
|
+
console.error(`ā Error handling message from ${peerId?.substring(0, 8)}...:`, error);
|
|
398
|
+
ws.send(JSON.stringify({
|
|
399
|
+
type: 'error',
|
|
400
|
+
error: 'Invalid message format',
|
|
401
|
+
timestamp: Date.now()
|
|
402
|
+
}));
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
// Handle connection close
|
|
407
|
+
ws.on('close', (code, reason) => {
|
|
408
|
+
console.log(`š Peer ${peerId?.substring(0, 8)}... disconnected (${code}: ${reason})`);
|
|
409
|
+
|
|
410
|
+
if (peerId) {
|
|
411
|
+
cleanupPeer(peerId);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
console.log(`š Active connections: ${connections.size}`);
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
// Handle connection errors
|
|
418
|
+
ws.on('error', (error) => {
|
|
419
|
+
console.error(`ā WebSocket error for ${peerId?.substring(0, 8)}...:`, error);
|
|
420
|
+
|
|
421
|
+
// Clean up errored connection
|
|
422
|
+
if (peerId && (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING)) {
|
|
423
|
+
cleanupPeer(peerId);
|
|
424
|
+
}
|
|
425
|
+
});
|
|
428
426
|
});
|
|
429
427
|
|
|
430
428
|
// Start server
|
|
431
429
|
server.listen(PORT, HOST, () => {
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
430
|
+
console.log(`š PeerPigeon WebSocket server running on ws://${HOST}:${PORT}`);
|
|
431
|
+
console.log('š Usage: Connect with ?peerId=<40-char-hex-id>');
|
|
432
|
+
console.log('š Ready to handle peer connections...');
|
|
435
433
|
});
|
|
436
434
|
|
|
437
435
|
// Handle graceful shutdown
|
|
438
436
|
process.on('SIGINT', () => {
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
437
|
+
console.log('\nš Shutting down WebSocket server...');
|
|
438
|
+
|
|
439
|
+
// Close all connections
|
|
440
|
+
for (const [, connection] of connections) {
|
|
441
|
+
connection.close(1001, 'Server shutting down');
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Close server
|
|
445
|
+
server.close(() => {
|
|
446
|
+
console.log('ā
WebSocket server closed');
|
|
447
|
+
process.exit(0);
|
|
448
|
+
});
|
|
451
449
|
});
|
|
452
450
|
|
|
453
451
|
// Error handling
|
|
454
452
|
process.on('uncaughtException', (error) => {
|
|
455
|
-
|
|
456
|
-
|
|
453
|
+
console.error('ā Uncaught Exception:', error);
|
|
454
|
+
process.exit(1);
|
|
457
455
|
});
|
|
458
456
|
|
|
459
457
|
process.on('unhandledRejection', (reason, promise) => {
|
|
460
|
-
|
|
461
|
-
|
|
458
|
+
console.error('ā Unhandled Rejection at:', promise, 'reason:', reason);
|
|
459
|
+
process.exit(1);
|
|
462
460
|
});
|
|
463
461
|
|
|
464
462
|
// Export for programmatic use
|