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
package/src/GossipManager.js
CHANGED
|
@@ -6,419 +6,500 @@ import { environmentDetector } from './EnvironmentDetector.js';
|
|
|
6
6
|
* Ensures all peers receive messages even if not directly connected
|
|
7
7
|
*/
|
|
8
8
|
export class GossipManager extends EventEmitter {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
this.startCleanupTimer();
|
|
25
|
-
}
|
|
9
|
+
constructor(mesh, connectionManager) {
|
|
10
|
+
super();
|
|
11
|
+
this.mesh = mesh;
|
|
12
|
+
this.connectionManager = connectionManager;
|
|
13
|
+
|
|
14
|
+
// Track message history to prevent infinite loops
|
|
15
|
+
this.seenMessages = new Map(); // messageId -> { timestamp, ttl }
|
|
16
|
+
this.messageHistory = new Map(); // messageId -> message content
|
|
17
|
+
|
|
18
|
+
// Configuration
|
|
19
|
+
this.maxTTL = 10; // Maximum hops before message expires
|
|
20
|
+
this.messageExpiryTime = 5 * 60 * 1000; // 5 minutes
|
|
21
|
+
this.cleanupInterval = 60 * 1000; // 1 minute
|
|
22
|
+
this.cleanupTimer = null; // Track cleanup timer for proper cleanup
|
|
26
23
|
|
|
27
|
-
|
|
24
|
+
this.startCleanupTimer();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
28
|
* Broadcast a message to all peers in the network using gossip protocol
|
|
29
29
|
*/
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
type: 'gossip',
|
|
46
|
-
subtype: messageType,
|
|
47
|
-
content: content,
|
|
48
|
-
from: this.mesh.peerId,
|
|
49
|
-
timestamp: Date.now(),
|
|
50
|
-
ttl: this.maxTTL,
|
|
51
|
-
path: [this.mesh.peerId] // Track propagation path
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
console.log(`Broadcasting ${messageType} message: ${messageId.substring(0, 8)}... content: "${content}"`);
|
|
55
|
-
|
|
56
|
-
// Store our own message
|
|
57
|
-
this.seenMessages.set(messageId, {
|
|
58
|
-
timestamp: Date.now(),
|
|
59
|
-
ttl: this.maxTTL
|
|
60
|
-
});
|
|
61
|
-
this.messageHistory.set(messageId, message);
|
|
62
|
-
|
|
63
|
-
// Send to all connected peers
|
|
64
|
-
this.propagateMessage(message);
|
|
65
|
-
|
|
66
|
-
// Emit locally if it's a chat message
|
|
67
|
-
if (messageType === 'chat') {
|
|
68
|
-
this.emit('messageReceived', {
|
|
69
|
-
from: this.mesh.peerId,
|
|
70
|
-
content: content,
|
|
71
|
-
timestamp: message.timestamp,
|
|
72
|
-
messageId: messageId
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
return messageId;
|
|
30
|
+
broadcastMessage(content, messageType = 'chat') {
|
|
31
|
+
// Validate content
|
|
32
|
+
if (content === undefined || content === null) {
|
|
33
|
+
console.error('Cannot broadcast message with undefined/null content');
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (messageType === 'chat' && (typeof content !== 'string' || content.trim().length === 0)) {
|
|
38
|
+
console.error('Cannot broadcast empty chat message');
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (messageType === 'encrypted' && (typeof content !== 'object' || !content.encrypted)) {
|
|
43
|
+
console.error('Cannot broadcast invalid encrypted message');
|
|
44
|
+
return null;
|
|
77
45
|
}
|
|
78
46
|
|
|
79
|
-
|
|
47
|
+
const messageId = this.generateMessageId();
|
|
48
|
+
const message = {
|
|
49
|
+
id: messageId,
|
|
50
|
+
type: 'gossip',
|
|
51
|
+
subtype: messageType,
|
|
52
|
+
content,
|
|
53
|
+
from: this.mesh.peerId,
|
|
54
|
+
timestamp: Date.now(),
|
|
55
|
+
ttl: this.maxTTL,
|
|
56
|
+
path: [this.mesh.peerId] // Track propagation path
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
console.log(`Broadcasting ${messageType} message: ${messageId.substring(0, 8)}... content: "${content}"`);
|
|
60
|
+
|
|
61
|
+
// Store our own message
|
|
62
|
+
this.seenMessages.set(messageId, {
|
|
63
|
+
timestamp: Date.now(),
|
|
64
|
+
ttl: this.maxTTL
|
|
65
|
+
});
|
|
66
|
+
this.messageHistory.set(messageId, message);
|
|
67
|
+
|
|
68
|
+
// Send to all connected peers
|
|
69
|
+
this.propagateMessage(message);
|
|
70
|
+
|
|
71
|
+
// Emit locally if it's a chat or encrypted message
|
|
72
|
+
if (messageType === 'chat' || messageType === 'encrypted') {
|
|
73
|
+
this.emit('messageReceived', {
|
|
74
|
+
from: this.mesh.peerId,
|
|
75
|
+
content,
|
|
76
|
+
timestamp: message.timestamp,
|
|
77
|
+
messageId,
|
|
78
|
+
encrypted: messageType === 'encrypted'
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return messageId;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
80
86
|
* Send a direct message to a specific peer using gossip routing (DM)
|
|
81
87
|
* @param {string} targetPeerId - The destination peer's ID
|
|
82
88
|
* @param {string|object} content - The message content
|
|
89
|
+
* @param {string} subtype - Message subtype (default: 'dm')
|
|
83
90
|
* @returns {string|null} The message ID if sent, or null on error
|
|
84
91
|
*/
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
content: content,
|
|
96
|
-
from: this.mesh.peerId,
|
|
97
|
-
to: targetPeerId,
|
|
98
|
-
timestamp: Date.now(),
|
|
99
|
-
ttl: this.maxTTL,
|
|
100
|
-
path: [this.mesh.peerId]
|
|
101
|
-
};
|
|
102
|
-
// Store our own message
|
|
103
|
-
this.seenMessages.set(messageId, {
|
|
104
|
-
timestamp: Date.now(),
|
|
105
|
-
ttl: this.maxTTL
|
|
106
|
-
});
|
|
107
|
-
this.messageHistory.set(messageId, message);
|
|
108
|
-
// Route to closest peer
|
|
109
|
-
this.propagateMessage(message);
|
|
110
|
-
return messageId;
|
|
92
|
+
sendDirectMessage(targetPeerId, content, subtype = 'dm') {
|
|
93
|
+
if (!targetPeerId || typeof targetPeerId !== 'string') {
|
|
94
|
+
console.error('Invalid targetPeerId for direct message');
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Validate peer ID format (40-character hex string)
|
|
99
|
+
if (!/^[a-fA-F0-9]{40}$/.test(targetPeerId)) {
|
|
100
|
+
console.error('Invalid peer ID format for direct message:', targetPeerId);
|
|
101
|
+
return null;
|
|
111
102
|
}
|
|
112
103
|
|
|
113
|
-
|
|
104
|
+
const messageId = this.generateMessageId();
|
|
105
|
+
const message = {
|
|
106
|
+
id: messageId,
|
|
107
|
+
type: 'gossip',
|
|
108
|
+
subtype,
|
|
109
|
+
content,
|
|
110
|
+
from: this.mesh.peerId,
|
|
111
|
+
to: targetPeerId,
|
|
112
|
+
timestamp: Date.now(),
|
|
113
|
+
ttl: this.maxTTL,
|
|
114
|
+
path: [this.mesh.peerId]
|
|
115
|
+
};
|
|
116
|
+
// Store our own message
|
|
117
|
+
this.seenMessages.set(messageId, {
|
|
118
|
+
timestamp: Date.now(),
|
|
119
|
+
ttl: this.maxTTL
|
|
120
|
+
});
|
|
121
|
+
this.messageHistory.set(messageId, message);
|
|
122
|
+
// Route to closest peer
|
|
123
|
+
this.propagateMessage(message);
|
|
124
|
+
return messageId;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
114
128
|
* Handle incoming gossip message from a peer
|
|
115
129
|
*/
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
130
|
+
async handleGossipMessage(message, fromPeerId) {
|
|
131
|
+
console.log(`🔥🔥🔥 GOSSIP MESSAGE RECEIVED! From: ${fromPeerId?.substring(0, 8)}...`);
|
|
132
|
+
console.log('🔥🔥🔥 Message:', message);
|
|
133
|
+
|
|
134
|
+
const { id: messageId, ttl, from: originPeerId, subtype, content, timestamp, path, to } = message;
|
|
135
|
+
|
|
136
|
+
// Validate message structure
|
|
137
|
+
if (!messageId || !originPeerId || !subtype || content === undefined) {
|
|
138
|
+
console.error('Invalid gossip message structure:', message);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Check if we've already seen this message
|
|
143
|
+
if (this.seenMessages.has(messageId)) {
|
|
144
|
+
console.log(`Ignoring duplicate message: ${messageId.substring(0, 8)}...`);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Check TTL
|
|
149
|
+
if (ttl <= 0) {
|
|
150
|
+
console.log(`Message expired: ${messageId.substring(0, 8)}...`);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Check for loops (our peer ID in path)
|
|
155
|
+
if (path && path.includes(this.mesh.peerId)) {
|
|
156
|
+
console.log(`Preventing message loop: ${messageId.substring(0, 8)}...`);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
console.log(`Received gossip message: ${messageId.substring(0, 8)}... from ${fromPeerId.substring(0, 8)}... (TTL: ${ttl}, content: "${content}")`);
|
|
161
|
+
|
|
162
|
+
// Store message to prevent duplicates
|
|
163
|
+
this.seenMessages.set(messageId, {
|
|
164
|
+
timestamp: Date.now(),
|
|
165
|
+
ttl
|
|
166
|
+
});
|
|
167
|
+
this.messageHistory.set(messageId, message);
|
|
168
|
+
|
|
169
|
+
// Handle crypto-related messages first
|
|
170
|
+
if (this.mesh.enableCrypto && this.mesh.cryptoManager) {
|
|
171
|
+
const handled = await this._handleCryptoMessage(message, fromPeerId, originPeerId);
|
|
172
|
+
if (handled) {
|
|
173
|
+
return; // Don't propagate crypto messages further
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Handle encrypted content decryption
|
|
178
|
+
let processedContent = content;
|
|
179
|
+
let isEncrypted = false;
|
|
180
|
+
|
|
181
|
+
if (this.mesh.enableCrypto && this.mesh.cryptoManager &&
|
|
182
|
+
content && typeof content === 'object' && content.encrypted) {
|
|
183
|
+
try {
|
|
184
|
+
processedContent = await this.mesh.decryptMessage(content);
|
|
185
|
+
isEncrypted = true;
|
|
186
|
+
console.log(`🔐 Decrypted message from ${originPeerId.substring(0, 8)}...`);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
console.error('Failed to decrypt message:', error);
|
|
189
|
+
// Continue with original content
|
|
190
|
+
processedContent = content;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Emit the message locally
|
|
195
|
+
if (subtype === 'chat') {
|
|
196
|
+
// Validate chat content (handle both encrypted objects and plain strings)
|
|
197
|
+
if (isEncrypted || (typeof processedContent === 'string' && processedContent.trim().length > 0)) {
|
|
198
|
+
this.emit('messageReceived', {
|
|
199
|
+
from: originPeerId,
|
|
200
|
+
content: processedContent,
|
|
201
|
+
timestamp,
|
|
202
|
+
messageId,
|
|
203
|
+
hops: this.maxTTL - ttl,
|
|
204
|
+
direct: false, // Flag to indicate this was a gossip message
|
|
205
|
+
encrypted: isEncrypted
|
|
206
|
+
});
|
|
207
|
+
} else {
|
|
208
|
+
console.warn('Ignoring gossip chat message with invalid content:', processedContent);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
} else if (subtype === 'encrypted') {
|
|
212
|
+
// Handle encrypted broadcast messages
|
|
213
|
+
this.emit('messageReceived', {
|
|
214
|
+
from: originPeerId,
|
|
215
|
+
content: processedContent,
|
|
216
|
+
timestamp,
|
|
217
|
+
messageId,
|
|
218
|
+
hops: this.maxTTL - ttl,
|
|
219
|
+
direct: false,
|
|
220
|
+
encrypted: true
|
|
221
|
+
});
|
|
222
|
+
} else if (subtype === 'peer-announcement') {
|
|
223
|
+
this.handlePeerAnnouncement(content, originPeerId);
|
|
224
|
+
} else if (subtype === 'dm') {
|
|
225
|
+
// Direct message logic
|
|
226
|
+
if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
|
227
|
+
// This peer is the target, emit to UI
|
|
228
|
+
this.emit('messageReceived', {
|
|
229
|
+
from: originPeerId,
|
|
230
|
+
content: processedContent,
|
|
231
|
+
timestamp,
|
|
232
|
+
messageId,
|
|
233
|
+
hops: this.maxTTL - ttl,
|
|
234
|
+
direct: true, // Flag to indicate this was a direct message
|
|
235
|
+
encrypted: isEncrypted
|
|
152
236
|
});
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
timestamp: timestamp,
|
|
167
|
-
messageId: messageId,
|
|
168
|
-
hops: this.maxTTL - ttl,
|
|
169
|
-
direct: false // Flag to indicate this was a gossip message
|
|
170
|
-
});
|
|
171
|
-
} else if (subtype === 'peer-announcement') {
|
|
172
|
-
this.handlePeerAnnouncement(content, originPeerId);
|
|
173
|
-
} else if (subtype === 'dm') {
|
|
174
|
-
// Direct message logic
|
|
175
|
-
if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
|
176
|
-
// This peer is the target, emit to UI
|
|
177
|
-
this.emit('messageReceived', {
|
|
178
|
-
from: originPeerId,
|
|
179
|
-
content: content,
|
|
180
|
-
timestamp: timestamp,
|
|
181
|
-
messageId: messageId,
|
|
182
|
-
hops: this.maxTTL - ttl,
|
|
183
|
-
direct: true // Flag to indicate this was a direct message
|
|
184
|
-
});
|
|
185
|
-
// Do NOT relay further if we are the recipient
|
|
186
|
-
return;
|
|
187
|
-
} else {
|
|
188
|
-
// Not the target, relay silently (do not emit)
|
|
189
|
-
}
|
|
190
|
-
} else if (subtype === 'dht-routing') {
|
|
191
|
-
// DHT routing message - check if we're the target
|
|
192
|
-
if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
|
193
|
-
console.log(`DHT: Received routed message for us from ${originPeerId.substring(0, 8)}`);
|
|
194
|
-
// We are the target, deliver the DHT message locally
|
|
195
|
-
if (this.mesh.webDHT && content) {
|
|
196
|
-
// Simulate receiving the message from the original sender
|
|
197
|
-
this.mesh.webDHT.handleMessage(content, originPeerId);
|
|
198
|
-
}
|
|
199
|
-
// Do NOT relay further since we are the recipient
|
|
200
|
-
return;
|
|
201
|
-
} else {
|
|
202
|
-
console.log(`DHT: Routing message for ${to?.substring(0, 8)} (not us)`);
|
|
203
|
-
// Not the target, continue routing
|
|
204
|
-
}
|
|
237
|
+
// Do NOT relay further if we are the recipient
|
|
238
|
+
return;
|
|
239
|
+
} else {
|
|
240
|
+
// Not the target, relay silently (do not emit)
|
|
241
|
+
}
|
|
242
|
+
} else if (subtype === 'dht-routing') {
|
|
243
|
+
// DHT routing message - check if we're the target
|
|
244
|
+
if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
|
245
|
+
console.log(`DHT: Received routed message for us from ${originPeerId.substring(0, 8)}`);
|
|
246
|
+
// We are the target, deliver the DHT message locally
|
|
247
|
+
if (this.mesh.webDHT && content) {
|
|
248
|
+
// Simulate receiving the message from the original sender
|
|
249
|
+
this.mesh.webDHT.handleMessage(content, originPeerId);
|
|
205
250
|
}
|
|
206
|
-
//
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
this.propagateMessage(updatedMessage, fromPeerId);
|
|
251
|
+
// Do NOT relay further since we are the recipient
|
|
252
|
+
return;
|
|
253
|
+
} else {
|
|
254
|
+
console.log(`DHT: Routing message for ${to?.substring(0, 8)} (not us)`);
|
|
255
|
+
// Not the target, continue routing
|
|
256
|
+
}
|
|
214
257
|
}
|
|
258
|
+
// Propagate to other peers with decremented TTL
|
|
259
|
+
const updatedMessage = {
|
|
260
|
+
...message,
|
|
261
|
+
ttl: ttl - 1,
|
|
262
|
+
path: [...(path || []), this.mesh.peerId]
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
this.propagateMessage(updatedMessage, fromPeerId);
|
|
266
|
+
}
|
|
215
267
|
|
|
216
|
-
|
|
268
|
+
/**
|
|
217
269
|
* Handle peer announcements received via gossip
|
|
218
270
|
*/
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
271
|
+
handlePeerAnnouncement(announcementData, originPeerId) {
|
|
272
|
+
const { peerId: announcedPeerId } = announcementData;
|
|
273
|
+
|
|
274
|
+
console.log(`Gossip peer announcement: ${announcedPeerId.substring(0, 8)}... via ${originPeerId.substring(0, 8)}...`);
|
|
275
|
+
|
|
276
|
+
// Add to discovered peers if we don't know about them
|
|
277
|
+
if (!this.mesh.peerDiscovery.hasPeer(announcedPeerId) &&
|
|
226
278
|
announcedPeerId !== this.mesh.peerId) {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
this.mesh.peerDiscovery.addDiscoveredPeer(announcedPeerId);
|
|
234
|
-
}
|
|
279
|
+
this.mesh.emit('statusChanged', {
|
|
280
|
+
type: 'info',
|
|
281
|
+
message: `Discovered peer ${announcedPeerId.substring(0, 8)}... via gossip`
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
this.mesh.peerDiscovery.addDiscoveredPeer(announcedPeerId);
|
|
235
285
|
}
|
|
286
|
+
}
|
|
236
287
|
|
|
237
|
-
|
|
288
|
+
/**
|
|
238
289
|
* Broadcast peer announcement via gossip when we connect
|
|
239
290
|
*/
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
291
|
+
announcePeer(peerId = this.mesh.peerId) {
|
|
292
|
+
const announcementData = {
|
|
293
|
+
peerId,
|
|
294
|
+
timestamp: Date.now()
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
console.log(`Gossiping peer announcement for: ${peerId.substring(0, 8)}...`);
|
|
298
|
+
this.broadcastMessage(announcementData, 'peer-announcement');
|
|
299
|
+
}
|
|
249
300
|
|
|
250
|
-
|
|
301
|
+
/**
|
|
251
302
|
* Propagate message to ALL peers that can receive messages - ignore connection states!
|
|
252
303
|
*/
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
}
|
|
270
|
-
return dist;
|
|
271
|
-
}
|
|
272
|
-
let minDist = null;
|
|
273
|
-
let closestPeers = [];
|
|
274
|
-
capablePeers.forEach(peerConnection => {
|
|
275
|
-
if (peerConnection.peerId === excludePeerId || message.ttl <= 0) return;
|
|
276
|
-
const dist = xorDistance(peerConnection.peerId, targetId);
|
|
277
|
-
if (minDist === null || dist < minDist) {
|
|
278
|
-
minDist = dist;
|
|
279
|
-
closestPeers = [peerConnection];
|
|
280
|
-
} else if (dist === minDist) {
|
|
281
|
-
closestPeers.push(peerConnection);
|
|
282
|
-
}
|
|
283
|
-
});
|
|
284
|
-
if (closestPeers.length > 0) {
|
|
285
|
-
closestPeers.forEach(peer => {
|
|
286
|
-
try {
|
|
287
|
-
peer.sendMessage(message);
|
|
288
|
-
const routingType = message.subtype === 'dht-routing' ? 'DHT' : 'DM';
|
|
289
|
-
console.log(`${routingType} routed to closest peer: ${peer.peerId.substring(0, 8)}...`);
|
|
290
|
-
} catch (error) {
|
|
291
|
-
console.error(`${message.subtype} routing failed:`, error);
|
|
292
|
-
}
|
|
293
|
-
});
|
|
294
|
-
} else {
|
|
295
|
-
// Fallback: relay to all capable peers except sender
|
|
296
|
-
capablePeers.forEach(peerConnection => {
|
|
297
|
-
if (peerConnection.peerId === excludePeerId || message.ttl <= 0) return;
|
|
298
|
-
try {
|
|
299
|
-
peerConnection.sendMessage(message);
|
|
300
|
-
const routingType = message.subtype === 'dht-routing' ? 'DHT' : 'DM';
|
|
301
|
-
console.log(`${routingType} fallback relay to: ${peerConnection.peerId.substring(0, 8)}...`);
|
|
302
|
-
} catch (error) {
|
|
303
|
-
console.error(`${message.subtype} fallback relay failed:`, error);
|
|
304
|
-
}
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
return;
|
|
304
|
+
propagateMessage(message, excludePeerId = null) {
|
|
305
|
+
// DM and DHT routing: route to closest peer(s) for messages with specific targets
|
|
306
|
+
if ((message.subtype === 'dm' || message.subtype === 'dht-routing') && message.to) {
|
|
307
|
+
const targetId = message.to;
|
|
308
|
+
const allPeers = Array.from(this.connectionManager.peers.values());
|
|
309
|
+
const capablePeers = allPeers.filter(peerConnection => {
|
|
310
|
+
return peerConnection.dataChannel && peerConnection.dataChannel.readyState === 'open';
|
|
311
|
+
});
|
|
312
|
+
// Improved XOR distance for 40-char hex peer IDs
|
|
313
|
+
function xorDistance(a, b) {
|
|
314
|
+
if (!a || !b) return Number.MAX_SAFE_INTEGER;
|
|
315
|
+
let dist = 0n;
|
|
316
|
+
for (let i = 0; i < 40; i += 8) {
|
|
317
|
+
const aChunk = a.substring(i, i + 8);
|
|
318
|
+
const bChunk = b.substring(i, i + 8);
|
|
319
|
+
dist = (dist << 32n) + (BigInt('0x' + aChunk) ^ BigInt('0x' + bChunk));
|
|
308
320
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
const
|
|
328
|
-
console.log(
|
|
321
|
+
return dist;
|
|
322
|
+
}
|
|
323
|
+
let minDist = null;
|
|
324
|
+
let closestPeers = [];
|
|
325
|
+
capablePeers.forEach(peerConnection => {
|
|
326
|
+
if (peerConnection.peerId === excludePeerId || message.ttl <= 0) return;
|
|
327
|
+
const dist = xorDistance(peerConnection.peerId, targetId);
|
|
328
|
+
if (minDist === null || dist < minDist) {
|
|
329
|
+
minDist = dist;
|
|
330
|
+
closestPeers = [peerConnection];
|
|
331
|
+
} else if (dist === minDist) {
|
|
332
|
+
closestPeers.push(peerConnection);
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
if (closestPeers.length > 0) {
|
|
336
|
+
closestPeers.forEach(peer => {
|
|
337
|
+
try {
|
|
338
|
+
peer.sendMessage(message);
|
|
339
|
+
const routingType = message.subtype === 'dht-routing' ? 'DHT' : 'DM';
|
|
340
|
+
console.log(`${routingType} routed to closest peer: ${peer.peerId.substring(0, 8)}...`);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
console.error(`${message.subtype} routing failed:`, error);
|
|
343
|
+
}
|
|
329
344
|
});
|
|
330
|
-
|
|
345
|
+
} else {
|
|
346
|
+
// Fallback: relay to all capable peers except sender
|
|
331
347
|
capablePeers.forEach(peerConnection => {
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
peerConnection.sendMessage(message);
|
|
341
|
-
propagatedTo++;
|
|
342
|
-
console.log(`✅ GOSSIP SUCCESS: Sent to ${peerId.substring(0, 8)}...`);
|
|
343
|
-
} catch (error) {
|
|
344
|
-
console.error(`❌ GOSSIP FAILED: Could not send to ${peerId.substring(0, 8)}...`, error);
|
|
345
|
-
}
|
|
348
|
+
if (peerConnection.peerId === excludePeerId || message.ttl <= 0) return;
|
|
349
|
+
try {
|
|
350
|
+
peerConnection.sendMessage(message);
|
|
351
|
+
const routingType = message.subtype === 'dht-routing' ? 'DHT' : 'DM';
|
|
352
|
+
console.log(`${routingType} fallback relay to: ${peerConnection.peerId.substring(0, 8)}...`);
|
|
353
|
+
} catch (error) {
|
|
354
|
+
console.error(`${message.subtype} fallback relay failed:`, error);
|
|
355
|
+
}
|
|
346
356
|
});
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
if (propagatedTo === 0 && allPeers.length > 0) {
|
|
351
|
-
console.error(`🚨 GOSSIP FAILURE: NO PROPAGATION! ${allPeers.length} total peers, ${capablePeers.length} with data channels`);
|
|
352
|
-
}
|
|
357
|
+
}
|
|
358
|
+
return;
|
|
353
359
|
}
|
|
360
|
+
// AGGRESSIVE: Get ALL peers regardless of status - we only care if we can send a message
|
|
361
|
+
const allPeers = Array.from(this.connectionManager.peers.values());
|
|
362
|
+
const capablePeers = allPeers.filter(peerConnection => {
|
|
363
|
+
// ONLY requirement: does the peer have an open data channel?
|
|
364
|
+
return peerConnection.dataChannel &&
|
|
365
|
+
peerConnection.dataChannel.readyState === 'open';
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
let propagatedTo = 0;
|
|
369
|
+
|
|
370
|
+
console.log(`🚀 AGGRESSIVE GOSSIP: Found ${capablePeers.length}/${allPeers.length} peers with open data channels`);
|
|
371
|
+
console.log(`Message: ${message.id.substring(0, 8)}..., TTL: ${message.ttl}, Exclude: ${excludePeerId?.substring(0, 8) || 'none'}`);
|
|
372
|
+
|
|
373
|
+
// Debug: show state of ALL peers
|
|
374
|
+
allPeers.forEach(peerConnection => {
|
|
375
|
+
const status = peerConnection.getStatus();
|
|
376
|
+
const dataChannelState = peerConnection.dataChannel?.readyState || 'none';
|
|
377
|
+
const canSend = peerConnection.dataChannel && peerConnection.dataChannel.readyState === 'open';
|
|
378
|
+
const isExcluded = peerConnection.peerId === excludePeerId;
|
|
379
|
+
console.log(` ${peerConnection.peerId.substring(0, 8)}... - Status: ${status}, DataChannel: ${dataChannelState}, CanSend: ${canSend}, Excluded: ${isExcluded}`);
|
|
380
|
+
});
|
|
354
381
|
|
|
355
|
-
|
|
382
|
+
capablePeers.forEach(peerConnection => {
|
|
383
|
+
const peerId = peerConnection.peerId;
|
|
384
|
+
|
|
385
|
+
// Don't send back to sender or if TTL expired
|
|
386
|
+
if (peerId === excludePeerId || message.ttl <= 0) {
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
try {
|
|
391
|
+
peerConnection.sendMessage(message);
|
|
392
|
+
propagatedTo++;
|
|
393
|
+
console.log(`✅ GOSSIP SUCCESS: Sent to ${peerId.substring(0, 8)}...`);
|
|
394
|
+
} catch (error) {
|
|
395
|
+
console.error(`❌ GOSSIP FAILED: Could not send to ${peerId.substring(0, 8)}...`, error);
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
console.log(`🎯 GOSSIP RESULT: Propagated to ${propagatedTo}/${capablePeers.length} capable peers`);
|
|
400
|
+
|
|
401
|
+
if (propagatedTo === 0 && allPeers.length > 0) {
|
|
402
|
+
console.error(`🚨 GOSSIP FAILURE: NO PROPAGATION! ${allPeers.length} total peers, ${capablePeers.length} with data channels`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
356
407
|
* Get message statistics
|
|
357
408
|
*/
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
409
|
+
getStats() {
|
|
410
|
+
return {
|
|
411
|
+
seenMessages: this.seenMessages.size,
|
|
412
|
+
storedMessages: this.messageHistory.size,
|
|
413
|
+
maxTTL: this.maxTTL,
|
|
414
|
+
messageExpiryTime: this.messageExpiryTime
|
|
415
|
+
};
|
|
416
|
+
}
|
|
366
417
|
|
|
367
|
-
|
|
418
|
+
/**
|
|
368
419
|
* Generate unique message ID
|
|
369
420
|
*/
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
421
|
+
generateMessageId() {
|
|
422
|
+
const array = new Uint8Array(16);
|
|
423
|
+
crypto.getRandomValues(array);
|
|
424
|
+
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
425
|
+
}
|
|
375
426
|
|
|
376
|
-
|
|
427
|
+
/**
|
|
377
428
|
* Clean up expired messages
|
|
378
429
|
*/
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
if (environmentDetector.isBrowser) {
|
|
385
|
-
this.cleanupTimer = window.setInterval(() => {
|
|
386
|
-
this.cleanupExpiredMessages();
|
|
387
|
-
}, this.cleanupInterval);
|
|
388
|
-
} else {
|
|
389
|
-
this.cleanupTimer = setInterval(() => {
|
|
390
|
-
this.cleanupExpiredMessages();
|
|
391
|
-
}, this.cleanupInterval);
|
|
392
|
-
}
|
|
430
|
+
startCleanupTimer() {
|
|
431
|
+
if (this.cleanupTimer) {
|
|
432
|
+
clearInterval(this.cleanupTimer);
|
|
393
433
|
}
|
|
394
434
|
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
this.messageHistory.delete(messageId);
|
|
404
|
-
cleaned++;
|
|
405
|
-
}
|
|
406
|
-
});
|
|
407
|
-
|
|
408
|
-
if (cleaned > 0) {
|
|
409
|
-
console.log(`Cleaned up ${cleaned} expired gossip messages`);
|
|
410
|
-
}
|
|
435
|
+
if (environmentDetector.isBrowser) {
|
|
436
|
+
this.cleanupTimer = window.setInterval(() => {
|
|
437
|
+
this.cleanupExpiredMessages();
|
|
438
|
+
}, this.cleanupInterval);
|
|
439
|
+
} else {
|
|
440
|
+
this.cleanupTimer = setInterval(() => {
|
|
441
|
+
this.cleanupExpiredMessages();
|
|
442
|
+
}, this.cleanupInterval);
|
|
411
443
|
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Stop cleanup timer
|
|
448
|
+
*/
|
|
449
|
+
stopCleanupTimer() {
|
|
450
|
+
if (this.cleanupTimer) {
|
|
451
|
+
clearInterval(this.cleanupTimer);
|
|
452
|
+
this.cleanupTimer = null;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
cleanupExpiredMessages() {
|
|
457
|
+
const now = Date.now();
|
|
458
|
+
let cleaned = 0;
|
|
412
459
|
|
|
413
|
-
|
|
460
|
+
// Clean up seen messages
|
|
461
|
+
this.seenMessages.forEach((data, messageId) => {
|
|
462
|
+
if (now - data.timestamp > this.messageExpiryTime) {
|
|
463
|
+
this.seenMessages.delete(messageId);
|
|
464
|
+
this.messageHistory.delete(messageId);
|
|
465
|
+
cleaned++;
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
if (cleaned > 0) {
|
|
470
|
+
console.log(`Cleaned up ${cleaned} expired gossip messages`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
414
475
|
* Cleanup method
|
|
415
476
|
*/
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
477
|
+
cleanup() {
|
|
478
|
+
this.stopCleanupTimer();
|
|
479
|
+
this.seenMessages.clear();
|
|
480
|
+
this.messageHistory.clear();
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Handle crypto-related messages (key exchange, etc.)
|
|
485
|
+
* @private
|
|
486
|
+
*/
|
|
487
|
+
async _handleCryptoMessage(message, fromPeerId, originPeerId) {
|
|
488
|
+
const { subtype, content } = message;
|
|
489
|
+
|
|
490
|
+
// Handle key exchange messages
|
|
491
|
+
if (subtype === 'key_exchange' || subtype === 'key_exchange_response') {
|
|
492
|
+
if (content && (content.type === 'key_exchange' || content.type === 'key_exchange_response') && content.publicKey) {
|
|
493
|
+
console.log(`🔐 Received ${content.type} from peer ${originPeerId.substring(0, 8)}...`);
|
|
494
|
+
|
|
495
|
+
// Use the mesh's key exchange handler which properly handles both pub and epub keys
|
|
496
|
+
this.mesh._handleKeyExchange(content, originPeerId);
|
|
497
|
+
|
|
498
|
+
// Don't propagate key exchange messages further
|
|
499
|
+
return true; // Indicates message was handled and should not be processed further
|
|
500
|
+
}
|
|
423
501
|
}
|
|
502
|
+
|
|
503
|
+
return false; // Message was not handled by crypto processing
|
|
504
|
+
}
|
|
424
505
|
}
|