peerpigeon 0.0.3 โ 0.0.5
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/examples/browser/app.js +1 -0
- package/examples/browser/ui-old.js +1930 -0
- package/package.json +1 -1
- package/src/ConnectionManager.js +5 -1
- package/src/MediaManager.js +23 -0
- package/src/PeerConnection.js +217 -31
- package/src/SignalingHandler.js +5 -1
- package/websocket-server/server.js +189 -22
package/package.json
CHANGED
package/src/ConnectionManager.js
CHANGED
|
@@ -116,7 +116,11 @@ export class ConnectionManager extends EventEmitter {
|
|
|
116
116
|
|
|
117
117
|
// Get current media stream if available
|
|
118
118
|
const localStream = this.mesh.mediaManager.localStream;
|
|
119
|
-
const options = {
|
|
119
|
+
const options = {
|
|
120
|
+
localStream,
|
|
121
|
+
enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
|
|
122
|
+
enableVideo: hasMedia && localStream.getVideoTracks().length > 0
|
|
123
|
+
};
|
|
120
124
|
|
|
121
125
|
const peerConnection = new PeerConnection(targetPeerId, true, options);
|
|
122
126
|
|
package/src/MediaManager.js
CHANGED
|
@@ -111,6 +111,9 @@ export class MediaManager extends EventEmitter {
|
|
|
111
111
|
this.isVideoEnabled = video;
|
|
112
112
|
this.isAudioEnabled = audio;
|
|
113
113
|
|
|
114
|
+
// Mark stream as local origin to prevent confusion with remote streams
|
|
115
|
+
this.markStreamAsLocal(this.localStream);
|
|
116
|
+
|
|
114
117
|
console.log('Local media stream started:', {
|
|
115
118
|
video: this.isVideoEnabled,
|
|
116
119
|
audio: this.isAudioEnabled,
|
|
@@ -236,4 +239,24 @@ export class MediaManager extends EventEmitter {
|
|
|
236
239
|
return {};
|
|
237
240
|
}
|
|
238
241
|
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Mark stream as local origin to prevent confusion with remote streams
|
|
245
|
+
*/
|
|
246
|
+
markStreamAsLocal(stream) {
|
|
247
|
+
if (!stream) return;
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
Object.defineProperty(stream, '_peerPigeonOrigin', {
|
|
251
|
+
value: 'local',
|
|
252
|
+
writable: false,
|
|
253
|
+
enumerable: false,
|
|
254
|
+
configurable: false
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
console.log(`๐ Stream ${stream.id} marked as local origin in MediaManager`);
|
|
258
|
+
} catch (error) {
|
|
259
|
+
console.warn('Could not mark stream as local origin:', error);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
239
262
|
}
|
package/src/PeerConnection.js
CHANGED
|
@@ -22,6 +22,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
22
22
|
this.remoteStream = null;
|
|
23
23
|
this.enableVideo = options.enableVideo || false;
|
|
24
24
|
this.enableAudio = options.enableAudio || false;
|
|
25
|
+
this.audioTransceiver = null;
|
|
26
|
+
this.videoTransceiver = null;
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
/**
|
|
@@ -51,24 +53,35 @@ export class PeerConnection extends EventEmitter {
|
|
|
51
53
|
|
|
52
54
|
this.setupConnectionHandlers();
|
|
53
55
|
|
|
54
|
-
//
|
|
55
|
-
// This
|
|
56
|
-
|
|
56
|
+
// Only pre-allocate transceivers if media is actually intended to be used
|
|
57
|
+
// This prevents unnecessary WebRTC negotiations for data-only connections
|
|
58
|
+
const hasLocalMedia = this.localStream && (this.localStream.getAudioTracks().length > 0 || this.localStream.getVideoTracks().length > 0);
|
|
59
|
+
const intendToUseMedia = this.enableVideo || this.enableAudio || hasLocalMedia;
|
|
57
60
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
61
|
+
if (intendToUseMedia) {
|
|
62
|
+
console.log('๐ Pre-allocating transceivers for stable media negotiation');
|
|
63
|
+
|
|
64
|
+
// Add audio transceiver only if audio is enabled or present
|
|
65
|
+
if (this.enableAudio || (this.localStream && this.localStream.getAudioTracks().length > 0)) {
|
|
66
|
+
this.audioTransceiver = this.connection.addTransceiver('audio', {
|
|
67
|
+
direction: 'recvonly'
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Add video transceiver only if video is enabled or present
|
|
72
|
+
if (this.enableVideo || (this.localStream && this.localStream.getVideoTracks().length > 0)) {
|
|
73
|
+
this.videoTransceiver = this.connection.addTransceiver('video', {
|
|
74
|
+
direction: 'recvonly'
|
|
75
|
+
});
|
|
76
|
+
}
|
|
67
77
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
78
|
+
// Add local media stream if provided
|
|
79
|
+
if (this.localStream) {
|
|
80
|
+
console.log('Adding local stream tracks to existing transceivers');
|
|
81
|
+
await this.setLocalStreamToTransceivers(this.localStream);
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
console.log('๐ก Creating data-only connection (no media transceivers)');
|
|
72
85
|
}
|
|
73
86
|
|
|
74
87
|
if (this.isInitiator) {
|
|
@@ -107,12 +120,9 @@ export class PeerConnection extends EventEmitter {
|
|
|
107
120
|
|
|
108
121
|
console.log(`๐ต Track received: kind=${track.kind}, id=${track.id}, enabled=${track.enabled}, readyState=${track.readyState}`);
|
|
109
122
|
|
|
110
|
-
// CRITICAL:
|
|
111
|
-
if (this.
|
|
112
|
-
|
|
113
|
-
console.error('Local stream ID:', this.localStream.id);
|
|
114
|
-
console.error('Received stream ID:', stream.id);
|
|
115
|
-
return; // Don't process our own stream as remote
|
|
123
|
+
// CRITICAL: Enhanced loopback detection and stream validation
|
|
124
|
+
if (!this.validateRemoteStream(stream, track)) {
|
|
125
|
+
return; // Don't process invalid or looped back streams
|
|
116
126
|
}
|
|
117
127
|
|
|
118
128
|
if (stream) {
|
|
@@ -123,18 +133,12 @@ export class PeerConnection extends EventEmitter {
|
|
|
123
133
|
console.log(`๐ต Remote stream tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
|
|
124
134
|
console.log(`๐ต Remote stream ID: ${stream.id} (vs local: ${this.localStream?.id || 'none'})`);
|
|
125
135
|
|
|
136
|
+
// Mark stream as genuinely remote to prevent future confusion
|
|
137
|
+
this.markStreamAsRemote(stream);
|
|
138
|
+
|
|
126
139
|
audioTracks.forEach((audioTrack, index) => {
|
|
127
140
|
console.log(`๐ต Audio track ${index}: enabled=${audioTrack.enabled}, readyState=${audioTrack.readyState}, muted=${audioTrack.muted}, id=${audioTrack.id}`);
|
|
128
141
|
|
|
129
|
-
// Check if this track ID matches any of our local tracks
|
|
130
|
-
if (this.localStream) {
|
|
131
|
-
const localAudioTracks = this.localStream.getAudioTracks();
|
|
132
|
-
const isOwnTrack = localAudioTracks.some(localTrack => localTrack.id === audioTrack.id);
|
|
133
|
-
if (isOwnTrack) {
|
|
134
|
-
console.error('โ LOOPBACK: This audio track is our own local track!');
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
142
|
// Add audio data monitoring
|
|
139
143
|
this.setupAudioDataMonitoring(audioTrack, index);
|
|
140
144
|
});
|
|
@@ -410,6 +414,185 @@ export class PeerConnection extends EventEmitter {
|
|
|
410
414
|
return false;
|
|
411
415
|
}
|
|
412
416
|
|
|
417
|
+
/**
|
|
418
|
+
* Enhanced validation to ensure received stream is genuinely remote
|
|
419
|
+
*/
|
|
420
|
+
validateRemoteStream(stream, track) {
|
|
421
|
+
// Check 1: Stream ID collision (basic loopback detection)
|
|
422
|
+
if (this.localStream && stream.id === this.localStream.id) {
|
|
423
|
+
console.error('โ LOOPBACK DETECTED: Received our own local stream as remote!');
|
|
424
|
+
console.error('Local stream ID:', this.localStream.id);
|
|
425
|
+
console.error('Received stream ID:', stream.id);
|
|
426
|
+
return false;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Check 2: Track ID collision (more granular loopback detection)
|
|
430
|
+
if (this.localStream) {
|
|
431
|
+
const localTracks = this.localStream.getTracks();
|
|
432
|
+
const isOwnTrack = localTracks.some(localTrack => localTrack.id === track.id);
|
|
433
|
+
if (isOwnTrack) {
|
|
434
|
+
console.error('โ TRACK LOOPBACK: This track is our own local track!');
|
|
435
|
+
console.error('Local track ID:', track.id);
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Check 3: Verify track comes from remote peer transceiver
|
|
441
|
+
if (this.connection) {
|
|
442
|
+
const transceivers = this.connection.getTransceivers();
|
|
443
|
+
const sourceTransceiver = transceivers.find(t => t.receiver.track === track);
|
|
444
|
+
if (!sourceTransceiver) {
|
|
445
|
+
console.warn('โ ๏ธ Track not found in any transceiver - may be invalid');
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Ensure this is a receiving transceiver (not sending our own track back)
|
|
450
|
+
if (sourceTransceiver.direction === 'sendonly') {
|
|
451
|
+
console.error('โ Invalid direction: Receiving track from sendonly transceiver');
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Check 4: Verify stream hasn't been marked as local origin
|
|
457
|
+
if (stream._peerPigeonOrigin === 'local') {
|
|
458
|
+
console.error('โ Stream marked as local origin - preventing synchronization loop');
|
|
459
|
+
return false;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
console.log('โ
Remote stream validation passed for peer', this.peerId.substring(0, 8));
|
|
463
|
+
return true;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Mark a stream as genuinely remote to prevent future confusion
|
|
468
|
+
*/
|
|
469
|
+
markStreamAsRemote(stream) {
|
|
470
|
+
// Add internal marker to prevent future misidentification
|
|
471
|
+
Object.defineProperty(stream, '_peerPigeonOrigin', {
|
|
472
|
+
value: 'remote',
|
|
473
|
+
writable: false,
|
|
474
|
+
enumerable: false,
|
|
475
|
+
configurable: false
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
Object.defineProperty(stream, '_peerPigeonSourcePeerId', {
|
|
479
|
+
value: this.peerId,
|
|
480
|
+
writable: false,
|
|
481
|
+
enumerable: false,
|
|
482
|
+
configurable: false
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
console.log(`๐ Stream ${stream.id} marked as remote from peer ${this.peerId.substring(0, 8)}`);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Mark local stream to prevent it from being treated as remote
|
|
490
|
+
*/
|
|
491
|
+
markStreamAsLocal(stream) {
|
|
492
|
+
if (!stream) return;
|
|
493
|
+
|
|
494
|
+
Object.defineProperty(stream, '_peerPigeonOrigin', {
|
|
495
|
+
value: 'local',
|
|
496
|
+
writable: false,
|
|
497
|
+
enumerable: false,
|
|
498
|
+
configurable: false
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
console.log(`๐ Stream ${stream.id} marked as local origin`);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
async createOffer() {
|
|
505
|
+
const offer = await this.connection.createOffer();
|
|
506
|
+
await this.connection.setLocalDescription(offer);
|
|
507
|
+
return offer;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async handleOffer(offer) {
|
|
511
|
+
// Check if we're in the right state to handle an offer
|
|
512
|
+
if (this.connection.signalingState !== 'stable') {
|
|
513
|
+
console.log(`Cannot handle offer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: stable)`);
|
|
514
|
+
throw new Error(`Cannot handle offer in state: ${this.connection.signalingState}`);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
await this.connection.setRemoteDescription(offer);
|
|
518
|
+
this.remoteDescriptionSet = true;
|
|
519
|
+
await this.processPendingIceCandidates();
|
|
520
|
+
|
|
521
|
+
const answer = await this.connection.createAnswer();
|
|
522
|
+
await this.connection.setLocalDescription(answer);
|
|
523
|
+
return answer;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async handleAnswer(answer) {
|
|
527
|
+
// Check if we're in the right state to handle an answer
|
|
528
|
+
if (this.connection.signalingState !== 'have-local-offer') {
|
|
529
|
+
console.log(`Cannot handle answer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: have-local-offer)`);
|
|
530
|
+
|
|
531
|
+
// If we're already stable, the connection might already be established
|
|
532
|
+
if (this.connection.signalingState === 'stable') {
|
|
533
|
+
console.log('Connection already stable, answer not needed');
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
throw new Error(`Cannot handle answer in state: ${this.connection.signalingState}`);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
await this.connection.setRemoteDescription(answer);
|
|
541
|
+
this.remoteDescriptionSet = true;
|
|
542
|
+
await this.processPendingIceCandidates();
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
async handleIceCandidate(candidate) {
|
|
546
|
+
console.log(`๐ง Received ICE candidate for ${this.peerId.substring(0, 8)}...`, {
|
|
547
|
+
type: candidate.type,
|
|
548
|
+
protocol: candidate.protocol
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
if (!this.remoteDescriptionSet) {
|
|
552
|
+
console.log(`๐ง Buffering ICE candidate for ${this.peerId.substring(0, 8)}... (remote description not set yet)`);
|
|
553
|
+
this.pendingIceCandidates.push(candidate);
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
try {
|
|
558
|
+
await this.connection.addIceCandidate(candidate);
|
|
559
|
+
console.log(`๐ง Successfully added ICE candidate for ${this.peerId.substring(0, 8)}...`);
|
|
560
|
+
} catch (error) {
|
|
561
|
+
console.error(`๐ง Failed to add ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
async processPendingIceCandidates() {
|
|
566
|
+
if (this.pendingIceCandidates.length > 0) {
|
|
567
|
+
console.log(`๐ง Processing ${this.pendingIceCandidates.length} buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
|
|
568
|
+
|
|
569
|
+
for (const candidate of this.pendingIceCandidates) {
|
|
570
|
+
try {
|
|
571
|
+
await this.connection.addIceCandidate(candidate);
|
|
572
|
+
console.log(`๐ง Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
|
|
573
|
+
} catch (error) {
|
|
574
|
+
console.error(`๐ง Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
this.pendingIceCandidates = [];
|
|
579
|
+
console.log(`๐ง Finished processing buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
sendMessage(message) {
|
|
584
|
+
if (this.dataChannel && this.dataChannel.readyState === 'open') {
|
|
585
|
+
try {
|
|
586
|
+
this.dataChannel.send(JSON.stringify(message));
|
|
587
|
+
return true;
|
|
588
|
+
} catch (error) {
|
|
589
|
+
console.error(`Failed to send message to ${this.peerId}:`, error);
|
|
590
|
+
return false;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return false;
|
|
594
|
+
}
|
|
595
|
+
|
|
413
596
|
/**
|
|
414
597
|
* Add or replace local media stream
|
|
415
598
|
*/
|
|
@@ -436,6 +619,9 @@ export class PeerConnection extends EventEmitter {
|
|
|
436
619
|
const audioTracks = stream.getAudioTracks();
|
|
437
620
|
const videoTracks = stream.getVideoTracks();
|
|
438
621
|
|
|
622
|
+
// Mark stream as local origin to prevent loopback
|
|
623
|
+
this.markStreamAsLocal(stream);
|
|
624
|
+
|
|
439
625
|
// Handle audio track using stored reference
|
|
440
626
|
if (this.audioTransceiver) {
|
|
441
627
|
if (audioTracks.length > 0) {
|
package/src/SignalingHandler.js
CHANGED
|
@@ -191,7 +191,11 @@ export class SignalingHandler extends EventEmitter {
|
|
|
191
191
|
// Get current media stream if available
|
|
192
192
|
const localStream = this.mesh.mediaManager.localStream;
|
|
193
193
|
const hasMedia = localStream !== null;
|
|
194
|
-
const options = {
|
|
194
|
+
const options = {
|
|
195
|
+
localStream,
|
|
196
|
+
enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
|
|
197
|
+
enableVideo: hasMedia && localStream.getVideoTracks().length > 0
|
|
198
|
+
};
|
|
195
199
|
|
|
196
200
|
console.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
|
|
197
201
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { WebSocketServer } from 'ws';
|
|
1
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
2
2
|
import { createServer } from 'http';
|
|
3
3
|
import { URL } from 'url';
|
|
4
4
|
|
|
@@ -50,14 +50,57 @@ function findClosestPeers(targetPeerId, allPeerIds, maxPeers = 3) {
|
|
|
50
50
|
|
|
51
51
|
function getActivePeers(excludePeerId = null) {
|
|
52
52
|
const peers = [];
|
|
53
|
+
const stalePeers = [];
|
|
54
|
+
|
|
53
55
|
for (const [peerId, connection] of connections) {
|
|
54
|
-
if (peerId !== excludePeerId
|
|
55
|
-
|
|
56
|
+
if (peerId !== excludePeerId) {
|
|
57
|
+
if (connection.readyState === WebSocket.OPEN && isConnectionAlive(connection)) {
|
|
58
|
+
peers.push(peerId);
|
|
59
|
+
} else {
|
|
60
|
+
// Mark stale connections for cleanup
|
|
61
|
+
stalePeers.push(peerId);
|
|
62
|
+
}
|
|
56
63
|
}
|
|
57
64
|
}
|
|
65
|
+
|
|
66
|
+
// Clean up stale connections
|
|
67
|
+
stalePeers.forEach(peerId => {
|
|
68
|
+
console.log(`๐งน Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
|
|
69
|
+
connections.delete(peerId);
|
|
70
|
+
peerData.delete(peerId);
|
|
71
|
+
});
|
|
72
|
+
|
|
58
73
|
return peers;
|
|
59
74
|
}
|
|
60
75
|
|
|
76
|
+
function isConnectionAlive(connection) {
|
|
77
|
+
if (!connection || connection.readyState !== WebSocket.OPEN) {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Check if we've received a recent pong or if this is a fresh connection
|
|
82
|
+
const now = Date.now();
|
|
83
|
+
const lastPong = connection.lastPong || connection.connectedAt || now;
|
|
84
|
+
const timeSinceLastPong = now - lastPong;
|
|
85
|
+
|
|
86
|
+
// Consider connection dead if no pong for more than 12 minutes (since we ping every 9 minutes)
|
|
87
|
+
return timeSinceLastPong < 720000; // 12 minutes
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function pingConnection(peerId, connection) {
|
|
91
|
+
if (connection.readyState === WebSocket.OPEN) {
|
|
92
|
+
try {
|
|
93
|
+
connection.ping();
|
|
94
|
+
return true;
|
|
95
|
+
} catch (error) {
|
|
96
|
+
console.log(`๐ Failed to ping ${peerId.substring(0, 8)}...:`, error.message);
|
|
97
|
+
cleanupPeer(peerId);
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
|
|
61
104
|
function sendToConnection(peerId, data) {
|
|
62
105
|
const connection = connections.get(peerId);
|
|
63
106
|
if (connection && connection.readyState === WebSocket.OPEN) {
|
|
@@ -66,12 +109,39 @@ function sendToConnection(peerId, data) {
|
|
|
66
109
|
return true;
|
|
67
110
|
} catch (error) {
|
|
68
111
|
console.error(`Error sending to ${peerId}:`, error);
|
|
112
|
+
// Clean up failed connection
|
|
113
|
+
cleanupPeer(peerId);
|
|
69
114
|
return false;
|
|
70
115
|
}
|
|
116
|
+
} else if (connection && (connection.readyState === WebSocket.CLOSED || connection.readyState === WebSocket.CLOSING)) {
|
|
117
|
+
// Clean up closed connection
|
|
118
|
+
cleanupPeer(peerId);
|
|
71
119
|
}
|
|
72
120
|
return false;
|
|
73
121
|
}
|
|
74
122
|
|
|
123
|
+
function cleanupPeer(peerId) {
|
|
124
|
+
const wasConnected = connections.has(peerId);
|
|
125
|
+
connections.delete(peerId);
|
|
126
|
+
peerData.delete(peerId);
|
|
127
|
+
|
|
128
|
+
if (wasConnected) {
|
|
129
|
+
console.log(`๐งน Cleaned up peer: ${peerId.substring(0, 8)}...`);
|
|
130
|
+
|
|
131
|
+
// Notify other peers about disconnection
|
|
132
|
+
const activePeers = getActivePeers();
|
|
133
|
+
activePeers.forEach(otherPeerId => {
|
|
134
|
+
sendToConnection(otherPeerId, {
|
|
135
|
+
type: 'peer-disconnected',
|
|
136
|
+
data: { peerId },
|
|
137
|
+
fromPeerId: 'system',
|
|
138
|
+
targetPeerId: otherPeerId,
|
|
139
|
+
timestamp: Date.now()
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
75
145
|
function broadcastToClosestPeers(fromPeerId, message, maxPeers = 5) {
|
|
76
146
|
const activePeers = getActivePeers(fromPeerId);
|
|
77
147
|
const closestPeers = findClosestPeers(fromPeerId, activePeers, maxPeers);
|
|
@@ -95,6 +165,74 @@ const wss = new WebSocketServer({ server });
|
|
|
95
165
|
|
|
96
166
|
console.log(`๐ Starting PeerPigeon WebSocket server...`);
|
|
97
167
|
|
|
168
|
+
// Periodic cleanup of stale connections
|
|
169
|
+
setInterval(() => {
|
|
170
|
+
const totalConnections = connections.size;
|
|
171
|
+
const activePeers = getActivePeers(); // This will clean up stale connections
|
|
172
|
+
const cleanedUp = totalConnections - connections.size;
|
|
173
|
+
|
|
174
|
+
if (cleanedUp > 0) {
|
|
175
|
+
console.log(`๐งน Periodic cleanup: removed ${cleanedUp} stale connections, ${connections.size} active`);
|
|
176
|
+
}
|
|
177
|
+
}, 30000); // Clean up every 30 seconds
|
|
178
|
+
|
|
179
|
+
// DHT-based heartbeat ping every 9 minutes (540 seconds)
|
|
180
|
+
// Use DHT logic to select a SINGLE peer to do the pinging instead of server pinging all
|
|
181
|
+
setInterval(() => {
|
|
182
|
+
const activePeers = Array.from(connections.keys());
|
|
183
|
+
|
|
184
|
+
if (activePeers.length === 0) {
|
|
185
|
+
console.log(`๐ No peers to ping`);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Use XOR distance to select the peer closest to a deterministic target
|
|
190
|
+
// This ensures the same peer is consistently selected across intervals
|
|
191
|
+
const pingTarget = '0000000000000000000000000000000000000000'; // Deterministic target for ping selection
|
|
192
|
+
const selectedPeer = selectPeerForPing(pingTarget, activePeers);
|
|
193
|
+
|
|
194
|
+
if (selectedPeer) {
|
|
195
|
+
const connection = connections.get(selectedPeer);
|
|
196
|
+
console.log(`๐ DHT-selected peer ${selectedPeer.substring(0, 8)}... for heartbeat ping (${activePeers.length} total peers)`);
|
|
197
|
+
|
|
198
|
+
if (!pingConnection(selectedPeer, connection)) {
|
|
199
|
+
console.log(`๐งน DHT-selected peer ${selectedPeer.substring(0, 8)}... failed ping, cleaned up`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}, 540000); // Ping every 9 minutes (540 seconds)
|
|
203
|
+
|
|
204
|
+
// DHT-based peer selection for ping duty
|
|
205
|
+
function selectPeerForPing(target, peerIds) {
|
|
206
|
+
if (!peerIds || peerIds.length === 0) return null;
|
|
207
|
+
|
|
208
|
+
// Use XOR distance to find the peer closest to the target
|
|
209
|
+
let closestPeer = null;
|
|
210
|
+
let closestDistance = Infinity;
|
|
211
|
+
|
|
212
|
+
for (const peerId of peerIds) {
|
|
213
|
+
const distance = calculateXORDistance(target, peerId);
|
|
214
|
+
if (distance < closestDistance) {
|
|
215
|
+
closestDistance = distance;
|
|
216
|
+
closestPeer = peerId;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return closestPeer;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// XOR distance calculation for DHT peer selection
|
|
224
|
+
function calculateXORDistance(id1, id2) {
|
|
225
|
+
let distance = 0;
|
|
226
|
+
const minLength = Math.min(id1.length, id2.length);
|
|
227
|
+
|
|
228
|
+
for (let i = 0; i < minLength; i++) {
|
|
229
|
+
const xor = parseInt(id1[i], 16) ^ parseInt(id2[i], 16);
|
|
230
|
+
distance += xor;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return distance;
|
|
234
|
+
}
|
|
235
|
+
|
|
98
236
|
wss.on('connection', (ws, req) => {
|
|
99
237
|
let peerId = null;
|
|
100
238
|
|
|
@@ -110,6 +248,20 @@ wss.on('connection', (ws, req) => {
|
|
|
110
248
|
|
|
111
249
|
peerId = queryPeerId;
|
|
112
250
|
|
|
251
|
+
// Check if peerId is already connected
|
|
252
|
+
if (connections.has(peerId)) {
|
|
253
|
+
const existingConnection = connections.get(peerId);
|
|
254
|
+
if (existingConnection.readyState === WebSocket.OPEN) {
|
|
255
|
+
console.log(`โ ๏ธ Peer ${peerId.substring(0, 8)}... already connected, closing duplicate`);
|
|
256
|
+
ws.close(1008, 'Peer already connected');
|
|
257
|
+
return;
|
|
258
|
+
} else {
|
|
259
|
+
// Clean up stale connection
|
|
260
|
+
console.log(`๐ Replacing stale connection for ${peerId.substring(0, 8)}...`);
|
|
261
|
+
cleanupPeer(peerId);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
113
265
|
// Store connection
|
|
114
266
|
connections.set(peerId, ws);
|
|
115
267
|
peerData.set(peerId, {
|
|
@@ -118,6 +270,15 @@ wss.on('connection', (ws, req) => {
|
|
|
118
270
|
connected: true
|
|
119
271
|
});
|
|
120
272
|
|
|
273
|
+
// Set up connection metadata
|
|
274
|
+
ws.connectedAt = Date.now();
|
|
275
|
+
ws.lastPong = Date.now();
|
|
276
|
+
|
|
277
|
+
// Set up pong handler for heartbeat
|
|
278
|
+
ws.on('pong', () => {
|
|
279
|
+
ws.lastPong = Date.now();
|
|
280
|
+
});
|
|
281
|
+
|
|
121
282
|
console.log(`โ
Peer ${peerId.substring(0, 8)}... connected (${connections.size} total)`);
|
|
122
283
|
|
|
123
284
|
// Send connection confirmation
|
|
@@ -163,11 +324,25 @@ wss.on('connection', (ws, req) => {
|
|
|
163
324
|
connected: true
|
|
164
325
|
});
|
|
165
326
|
|
|
327
|
+
// Get active peers with immediate validation
|
|
166
328
|
const activePeers = getActivePeers(peerId);
|
|
167
|
-
console.log(`๐ข Announcing ${peerId.substring(0, 8)}... to ${activePeers.length} peers`);
|
|
168
329
|
|
|
169
|
-
//
|
|
170
|
-
|
|
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 => {
|
|
171
346
|
sendToConnection(otherPeerId, {
|
|
172
347
|
type: 'peer-discovered',
|
|
173
348
|
data: { peerId, ...messageData },
|
|
@@ -177,8 +352,8 @@ wss.on('connection', (ws, req) => {
|
|
|
177
352
|
});
|
|
178
353
|
});
|
|
179
354
|
|
|
180
|
-
// Send existing peers to the new peer
|
|
181
|
-
|
|
355
|
+
// Send existing validated peers to the new peer
|
|
356
|
+
validatedPeers.forEach(existingPeerId => {
|
|
182
357
|
const existingPeerData = peerData.get(existingPeerId);
|
|
183
358
|
ws.send(JSON.stringify({
|
|
184
359
|
type: 'peer-discovered',
|
|
@@ -235,20 +410,7 @@ wss.on('connection', (ws, req) => {
|
|
|
235
410
|
console.log(`๐ Peer ${peerId?.substring(0, 8)}... disconnected (${code}: ${reason})`);
|
|
236
411
|
|
|
237
412
|
if (peerId) {
|
|
238
|
-
|
|
239
|
-
peerData.delete(peerId);
|
|
240
|
-
|
|
241
|
-
// Notify other peers
|
|
242
|
-
const activePeers = getActivePeers();
|
|
243
|
-
activePeers.forEach(otherPeerId => {
|
|
244
|
-
sendToConnection(otherPeerId, {
|
|
245
|
-
type: 'peer-disconnected',
|
|
246
|
-
data: { peerId },
|
|
247
|
-
fromPeerId: 'system',
|
|
248
|
-
targetPeerId: otherPeerId,
|
|
249
|
-
timestamp: Date.now()
|
|
250
|
-
});
|
|
251
|
-
});
|
|
413
|
+
cleanupPeer(peerId);
|
|
252
414
|
}
|
|
253
415
|
|
|
254
416
|
console.log(`๐ Active connections: ${connections.size}`);
|
|
@@ -257,6 +419,11 @@ wss.on('connection', (ws, req) => {
|
|
|
257
419
|
// Handle connection errors
|
|
258
420
|
ws.on('error', (error) => {
|
|
259
421
|
console.error(`โ WebSocket error for ${peerId?.substring(0, 8)}...:`, error);
|
|
422
|
+
|
|
423
|
+
// Clean up errored connection
|
|
424
|
+
if (peerId && (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING)) {
|
|
425
|
+
cleanupPeer(peerId);
|
|
426
|
+
}
|
|
260
427
|
});
|
|
261
428
|
});
|
|
262
429
|
|