peerpigeon 0.0.1
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/LICENSE +21 -0
- package/README.md +1187 -0
- package/examples/browser/app-dht-disabled.js +42 -0
- package/examples/browser/app.js +51 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/index-dht-disabled.html +123 -0
- package/examples/browser/index.html +340 -0
- package/examples/browser/styles.css +1288 -0
- package/examples/browser/ui-clean.js +0 -0
- package/examples/browser/ui.js +1930 -0
- package/index.js +8 -0
- package/package.json +70 -0
- package/server/index.js +515 -0
- package/src/CleanupManager.js +181 -0
- package/src/ConnectionManager.js +841 -0
- package/src/EventEmitter.js +27 -0
- package/src/EvictionManager.js +257 -0
- package/src/GossipManager.js +416 -0
- package/src/MediaManager.js +225 -0
- package/src/MeshOptimizer.js +181 -0
- package/src/PeerConnection.js +831 -0
- package/src/PeerDiscovery.js +297 -0
- package/src/PeerPigeonMesh.js +703 -0
- package/src/SignalingClient.js +536 -0
- package/src/SignalingHandler.js +325 -0
- package/src/StorageManager.js +88 -0
- package/src/TimerUtils.js +46 -0
- package/src/WebDHT.js +1099 -0
- package/websocket-server/README.md +257 -0
- package/websocket-server/memory-leak-test.js +193 -0
- package/websocket-server/node_modules/.package-lock.json +29 -0
- package/websocket-server/node_modules/ws/LICENSE +20 -0
- package/websocket-server/node_modules/ws/README.md +548 -0
- package/websocket-server/node_modules/ws/browser.js +8 -0
- package/websocket-server/node_modules/ws/index.js +13 -0
- package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
- package/websocket-server/node_modules/ws/lib/constants.js +18 -0
- package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
- package/websocket-server/node_modules/ws/lib/extension.js +203 -0
- package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
- package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
- package/websocket-server/node_modules/ws/lib/sender.js +602 -0
- package/websocket-server/node_modules/ws/lib/stream.js +161 -0
- package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
- package/websocket-server/node_modules/ws/lib/validation.js +152 -0
- package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
- package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
- package/websocket-server/node_modules/ws/package.json +69 -0
- package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
- package/websocket-server/package-lock.json +39 -0
- package/websocket-server/server.js +298 -0
- package/websocket-server/test.js +133 -0
package/README.md
ADDED
|
@@ -0,0 +1,1187 @@
|
|
|
1
|
+
# PeerPigeon <img src="examples/browser/assets/images/favicon.png" alt="PeerPigeon Logo" width="32" height="32" align="right">
|
|
2
|
+
|
|
3
|
+
**A WebRTC-based peer-to-peer mesh networking library with intelligent routing, gossip protocol messaging, and automated peer management.**
|
|
4
|
+
|
|
5
|
+
[](https://badge.fury.io/js/peerpigeon)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
|
|
8
|
+
> **π Viewing Diagrams**: This README contains Mermaid diagrams. For proper visualization in VS Code, install the [Markdown Preview Mermaid Support](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-mermaid) extension.
|
|
9
|
+
|
|
10
|
+
## π Features
|
|
11
|
+
|
|
12
|
+
- **πΈοΈ True Mesh Networking**: Gossip protocol ensures messages reach all peers, not just direct connections
|
|
13
|
+
- **π XOR Distance Routing**: Kademlia-inspired peer selection for optimal network topology
|
|
14
|
+
- **π§ Smart Eviction Strategy**: Automatically replaces distant peers with closer ones to optimize mesh topology
|
|
15
|
+
- **π Auto-Discovery**: Seamlessly connects to peers as they join the network
|
|
16
|
+
- **β‘ WebSocket Signaling**: Real-time bidirectional communication for optimal performance
|
|
17
|
+
- **οΏ½οΈ Distributed Hash Table (WebDHT)**: Store and retrieve data across the mesh with automatic replication
|
|
18
|
+
- **π₯ Media Streaming**: Built-in support for audio/video streaming between peers
|
|
19
|
+
- **π¬ Messaging System**: Direct messages and broadcast gossip protocol messaging
|
|
20
|
+
- **π§ Modular Architecture**: Clean separation of concerns with event-driven components
|
|
21
|
+
- **π° Cost-Optimized**: XOR-based routing reduces signaling server costs by ~95%
|
|
22
|
+
- **π‘οΈ Memory Safe**: Comprehensive cleanup prevents memory leaks in long-running applications
|
|
23
|
+
|
|
24
|
+
## ποΈ Architecture Overview
|
|
25
|
+
|
|
26
|
+
```mermaid
|
|
27
|
+
graph TB
|
|
28
|
+
subgraph Browser[Browser Environment]
|
|
29
|
+
UI[User Interface] --> App[PeerPigeonMesh]
|
|
30
|
+
|
|
31
|
+
App --> SC[SignalingClient]
|
|
32
|
+
App --> PD[PeerDiscovery]
|
|
33
|
+
App --> CM[ConnectionManager]
|
|
34
|
+
App --> EM[EvictionManager]
|
|
35
|
+
App --> GM[GossipManager]
|
|
36
|
+
App --> MO[MeshOptimizer]
|
|
37
|
+
|
|
38
|
+
CM --> PC1[PeerConnection A]
|
|
39
|
+
CM --> PC2[PeerConnection B]
|
|
40
|
+
CM --> PC3[PeerConnection ...]
|
|
41
|
+
|
|
42
|
+
GM --> PC1
|
|
43
|
+
GM --> PC2
|
|
44
|
+
GM --> PC3
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
subgraph Network[Network Layer]
|
|
48
|
+
PC1 -.->|WebRTC Data Channel| PA[Peer A]
|
|
49
|
+
PC2 -.->|WebRTC Data Channel| PB[Peer B]
|
|
50
|
+
PC3 -.->|WebRTC Data Channel| PC[Peer ...]
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
subgraph Signaling[Signaling Infrastructure]
|
|
54
|
+
SC -->|HTTP/WebSocket| SS[Signaling Server]
|
|
55
|
+
SS --> DB[(Message Storage)]
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
style App fill:#e1f5fe,color:#000000
|
|
59
|
+
style GM fill:#e8f5e8,color:#000000
|
|
60
|
+
style EM fill:#fff3e0,color:#000000
|
|
61
|
+
style PD fill:#fce4ec,color:#000000
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
> **Note**: If diagrams don't display, install the [Markdown Preview Mermaid Support](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-mermaid) extension in VS Code.
|
|
65
|
+
|
|
66
|
+
## π Quick Start
|
|
67
|
+
|
|
68
|
+
### Installation
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
# Install PeerPigeon from npm
|
|
72
|
+
npm install peerpigeon
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Basic Setup
|
|
76
|
+
|
|
77
|
+
```javascript
|
|
78
|
+
import { PeerPigeonMesh } from 'peerpigeon';
|
|
79
|
+
|
|
80
|
+
// Create mesh instance
|
|
81
|
+
const mesh = new PeerPigeonMesh({
|
|
82
|
+
enableWebDHT: true, // Enable distributed hash table (default: true)
|
|
83
|
+
peerId: 'custom-peer-id' // Optional: provide custom peer ID
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// Initialize and connect
|
|
87
|
+
await mesh.init();
|
|
88
|
+
await mesh.connect('ws://localhost:3000'); // Your signaling server URL
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Starting a WebSocket Server
|
|
92
|
+
|
|
93
|
+
#### Option 1: Programmatic Server Setup (Recommended)
|
|
94
|
+
|
|
95
|
+
```javascript
|
|
96
|
+
import { PeerPigeonServer } from 'peerpigeon';
|
|
97
|
+
|
|
98
|
+
// Create and start the server
|
|
99
|
+
const server = new PeerPigeonServer({
|
|
100
|
+
port: 3000,
|
|
101
|
+
host: 'localhost',
|
|
102
|
+
maxConnections: 1000,
|
|
103
|
+
cleanupInterval: 60000, // 1 minute
|
|
104
|
+
peerTimeout: 300000 // 5 minutes
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// Start the server
|
|
108
|
+
await server.start();
|
|
109
|
+
|
|
110
|
+
// Listen for events
|
|
111
|
+
server.on('peerConnected', ({ peerId, totalConnections }) => {
|
|
112
|
+
console.log(`Peer ${peerId} connected. Total: ${totalConnections}`);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
server.on('peerDisconnected', ({ peerId, totalConnections }) => {
|
|
116
|
+
console.log(`Peer ${peerId} disconnected. Total: ${totalConnections}`);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// Graceful shutdown
|
|
120
|
+
process.on('SIGINT', async () => {
|
|
121
|
+
await server.stop();
|
|
122
|
+
process.exit(0);
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
#### Option 2: Standalone Server
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
# Run the standalone server (from npm package)
|
|
130
|
+
npm start
|
|
131
|
+
|
|
132
|
+
# Or run directly with custom configuration
|
|
133
|
+
PORT=8080 HOST=0.0.0.0 npm start
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Messaging Examples
|
|
137
|
+
|
|
138
|
+
```javascript
|
|
139
|
+
// Send a broadcast message to all peers
|
|
140
|
+
const messageId = mesh.sendMessage('Hello, mesh network!');
|
|
141
|
+
|
|
142
|
+
// Send a direct message to a specific peer
|
|
143
|
+
const directMessageId = mesh.sendDirectMessage('target-peer-id', 'Private message');
|
|
144
|
+
|
|
145
|
+
// Listen for incoming messages
|
|
146
|
+
mesh.addEventListener('messageReceived', (data) => {
|
|
147
|
+
console.log(`Message from ${data.from}: ${data.content}`);
|
|
148
|
+
console.log(`Direct message: ${data.direct}`);
|
|
149
|
+
});
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### WebDHT (Distributed Hash Table) Examples
|
|
153
|
+
|
|
154
|
+
```javascript
|
|
155
|
+
// Store data in the distributed hash table
|
|
156
|
+
await mesh.dhtPut('user-settings', { theme: 'dark', language: 'en' });
|
|
157
|
+
|
|
158
|
+
// Retrieve data from the DHT
|
|
159
|
+
const settings = await mesh.dhtGet('user-settings');
|
|
160
|
+
|
|
161
|
+
// Subscribe to changes
|
|
162
|
+
await mesh.dhtSubscribe('shared-counter');
|
|
163
|
+
mesh.addEventListener('dhtValueChanged', (data) => {
|
|
164
|
+
console.log(`Key ${data.key} changed to:`, data.newValue);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// Update a value and notify subscribers
|
|
168
|
+
await mesh.dhtUpdate('shared-counter', 42);
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Media Streaming Examples
|
|
172
|
+
|
|
173
|
+
```javascript
|
|
174
|
+
// Start local video stream
|
|
175
|
+
const stream = await mesh.startMedia({ video: true, audio: true });
|
|
176
|
+
|
|
177
|
+
// Toggle media
|
|
178
|
+
mesh.toggleVideo(); // Enable/disable video
|
|
179
|
+
mesh.toggleAudio(); // Enable/disable audio
|
|
180
|
+
|
|
181
|
+
// Get media devices
|
|
182
|
+
const devices = await mesh.enumerateMediaDevices();
|
|
183
|
+
console.log('Available cameras:', devices.cameras);
|
|
184
|
+
console.log('Available microphones:', devices.microphones);
|
|
185
|
+
|
|
186
|
+
// Listen for remote streams
|
|
187
|
+
mesh.addEventListener('remoteStream', (data) => {
|
|
188
|
+
const { peerId, stream } = data;
|
|
189
|
+
const videoElement = document.createElement('video');
|
|
190
|
+
videoElement.srcObject = stream;
|
|
191
|
+
videoElement.play();
|
|
192
|
+
});
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### Event Handling Examples
|
|
196
|
+
|
|
197
|
+
```javascript
|
|
198
|
+
// Connection events
|
|
199
|
+
mesh.addEventListener('connected', () => {
|
|
200
|
+
console.log('Connected to signaling server');
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
mesh.addEventListener('peerConnected', (data) => {
|
|
204
|
+
console.log(`Peer connected: ${data.peerId}`);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
mesh.addEventListener('peerDisconnected', (data) => {
|
|
208
|
+
console.log(`Peer disconnected: ${data.peerId}, reason: ${data.reason}`);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// Status monitoring
|
|
212
|
+
mesh.addEventListener('statusChanged', (data) => {
|
|
213
|
+
console.log(`Status: ${data.type} - ${data.message}`);
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### Configuration Examples
|
|
218
|
+
|
|
219
|
+
```javascript
|
|
220
|
+
// Adjust mesh topology
|
|
221
|
+
mesh.setMaxPeers(5); // Maximum peer connections
|
|
222
|
+
mesh.setMinPeers(2); // Minimum peer connections
|
|
223
|
+
mesh.setXorRouting(true); // Enable XOR-based routing
|
|
224
|
+
mesh.setEvictionStrategy(true); // Enable smart peer eviction
|
|
225
|
+
|
|
226
|
+
// Get current status
|
|
227
|
+
const status = mesh.getStatus();
|
|
228
|
+
console.log('Connected peers:', status.connectedCount);
|
|
229
|
+
console.log('Discovered peers:', status.discoveredCount);
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
### Local Development Server
|
|
233
|
+
|
|
234
|
+
**Option 1: Using npm package (Recommended)**
|
|
235
|
+
```bash
|
|
236
|
+
# Install PeerPigeon globally or in your project
|
|
237
|
+
npm install peerpigeon
|
|
238
|
+
|
|
239
|
+
# Start the signaling server
|
|
240
|
+
npm start
|
|
241
|
+
|
|
242
|
+
# Or with custom configuration
|
|
243
|
+
PORT=8080 HOST=0.0.0.0 npm start
|
|
244
|
+
|
|
245
|
+
# Serve the browser examples using the built-in server
|
|
246
|
+
npm run dev
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
**Option 2: From source (for development)**
|
|
250
|
+
```bash
|
|
251
|
+
# Clone the repository
|
|
252
|
+
git clone https://github.com/draeder/peerpigeon.git
|
|
253
|
+
cd peerpigeon
|
|
254
|
+
|
|
255
|
+
# Start the WebSocket signaling server
|
|
256
|
+
npm start
|
|
257
|
+
|
|
258
|
+
# Serve the browser examples
|
|
259
|
+
npm run dev
|
|
260
|
+
```
|
|
261
|
+
# Navigate to http://localhost:8080/examples/browser/
|
|
262
|
+
|
|
263
|
+
# Test with query parameters
|
|
264
|
+
# http://localhost:8080/examples/browser/?api=ws://localhost:3000
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## π System Flow Diagrams
|
|
268
|
+
|
|
269
|
+
### Peer Discovery & Connection Flow
|
|
270
|
+
|
|
271
|
+
```mermaid
|
|
272
|
+
sequenceDiagram
|
|
273
|
+
participant A as Peer A
|
|
274
|
+
participant B as Peer B
|
|
275
|
+
participant C as Peer C
|
|
276
|
+
participant S as Signaling Server
|
|
277
|
+
|
|
278
|
+
Note over A,C: Network Formation
|
|
279
|
+
A->>S: announce (peerId, timestamp)
|
|
280
|
+
B->>S: announce (peerId, timestamp)
|
|
281
|
+
C->>S: announce (peerId, timestamp)
|
|
282
|
+
|
|
283
|
+
S->>A: peer-discovered (B, C)
|
|
284
|
+
S->>B: peer-discovered (A, C)
|
|
285
|
+
S->>C: peer-discovered (A, B)
|
|
286
|
+
|
|
287
|
+
Note over A,C: Smart Connection Logic
|
|
288
|
+
A->>A: shouldInitiate(B)? (A > B lexicographically)
|
|
289
|
+
A->>B: WebRTC offer (if true)
|
|
290
|
+
B->>A: WebRTC answer
|
|
291
|
+
|
|
292
|
+
A->>B: ICE candidate
|
|
293
|
+
B->>A: ICE candidate
|
|
294
|
+
Note over A,B: β
WebRTC Data Channel Ready
|
|
295
|
+
|
|
296
|
+
Note over A,C: Topology Optimization
|
|
297
|
+
C->>A: connection request
|
|
298
|
+
A->>A: at capacity? should evict?
|
|
299
|
+
A->>B: eviction notice (if applicable)
|
|
300
|
+
Note over A,C: β
Connection established
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
### Gossip Protocol Message Flow
|
|
304
|
+
|
|
305
|
+
```mermaid
|
|
306
|
+
flowchart TD
|
|
307
|
+
Send[User sends message] --> CreateMsg["Create gossip message<br/>with ID, TTL=10"]
|
|
308
|
+
CreateMsg --> StoreLocal["Store in seen messages<br/>to prevent loops"]
|
|
309
|
+
StoreLocal --> EmitLocal[Emit to local UI]
|
|
310
|
+
EmitLocal --> Broadcast[Send to all connected peers]
|
|
311
|
+
|
|
312
|
+
Receive[Receive gossip message] --> CheckSeen{Already seen this message?}
|
|
313
|
+
CheckSeen -->|Yes| Drop[Drop message]
|
|
314
|
+
CheckSeen -->|No| CheckTTL{TTL > 0?}
|
|
315
|
+
CheckTTL -->|No| Drop
|
|
316
|
+
CheckTTL -->|Yes| CheckLoop{Sender in our path?}
|
|
317
|
+
CheckLoop -->|Yes| Drop
|
|
318
|
+
CheckLoop -->|No| Process[Process message]
|
|
319
|
+
|
|
320
|
+
Process --> StoreSeen[Store in seen messages]
|
|
321
|
+
StoreSeen --> EmitReceived[Emit to local UI]
|
|
322
|
+
EmitReceived --> DecrementTTL["TTL--, add to path"]
|
|
323
|
+
DecrementTTL --> Propagate["Forward to other peers<br/>except sender"]
|
|
324
|
+
|
|
325
|
+
Propagate --> End[Message delivered]
|
|
326
|
+
Drop --> End
|
|
327
|
+
|
|
328
|
+
style Send fill:#e8f5e8,color:#000000
|
|
329
|
+
style Receive fill:#e1f5fe,color:#000000
|
|
330
|
+
style Drop fill:#ffebee,color:#000000
|
|
331
|
+
style End fill:#f3e5f5,color:#000000
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
### Peer Connection & Isolation Prevention
|
|
335
|
+
|
|
336
|
+
```mermaid
|
|
337
|
+
flowchart TD
|
|
338
|
+
Discover[Peer Discovered] --> ShouldInit{Should we initiate connection?}
|
|
339
|
+
|
|
340
|
+
ShouldInit --> CheckLex["Lexicographic rule:<br/>our ID > target ID?"]
|
|
341
|
+
CheckLex -->|Yes| Connect[Initiate Connection]
|
|
342
|
+
CheckLex -->|No| CheckIsolation{Are we isolated?}
|
|
343
|
+
|
|
344
|
+
CheckIsolation -->|No connections| IsolationOverride["Override lexicographic rule<br/>to prevent isolation"]
|
|
345
|
+
CheckIsolation -->|Has connections| Wait[Wait for peer to initiate to us]
|
|
346
|
+
|
|
347
|
+
IsolationOverride --> NaturalInitiator{Can initiate to natural targets?}
|
|
348
|
+
NaturalInitiator -->|Yes| ConnectNatural["Connect to peer where<br/>we're natural initiator"]
|
|
349
|
+
NaturalInitiator -->|No| ConnectClosest["Connect to closest peer<br/>by XOR distance"]
|
|
350
|
+
|
|
351
|
+
ConnectNatural --> Connect
|
|
352
|
+
ConnectClosest --> Connect
|
|
353
|
+
|
|
354
|
+
Connect --> WebRTC["WebRTC Handshake<br/>via signaling server"]
|
|
355
|
+
WebRTC --> Success{Connection successful?}
|
|
356
|
+
|
|
357
|
+
Success -->|Yes| CheckCapacity{At peer capacity?}
|
|
358
|
+
Success -->|No| RetryLater["Retry with<br/>exponential backoff"]
|
|
359
|
+
|
|
360
|
+
CheckCapacity -->|No| Maintain[Maintain connection]
|
|
361
|
+
CheckCapacity -->|Yes| ConsiderEviction["Should evict<br/>existing peer?"]
|
|
362
|
+
|
|
363
|
+
ConsiderEviction -->|No| Maintain
|
|
364
|
+
ConsiderEviction -->|Yes| EvictFarthest["Evict farthest peer<br/>by XOR distance"]
|
|
365
|
+
|
|
366
|
+
EvictFarthest --> Maintain
|
|
367
|
+
Wait --> End[End]
|
|
368
|
+
RetryLater --> End
|
|
369
|
+
Maintain --> End
|
|
370
|
+
|
|
371
|
+
style Discover fill:#e1f5fe,color:#000000
|
|
372
|
+
style IsolationOverride fill:#fff3e0,color:#000000
|
|
373
|
+
style EvictFarthest fill:#ffebee,color:#000000
|
|
374
|
+
style Maintain fill:#e8f5e8,color:#000000
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### Smart Eviction Strategy
|
|
378
|
+
|
|
379
|
+
```mermaid
|
|
380
|
+
flowchart TD
|
|
381
|
+
NewPeer[Incoming Connection Request] --> AtCapacity{At maximum peer capacity?}
|
|
382
|
+
|
|
383
|
+
AtCapacity -->|No| Accept[Accept Connection]
|
|
384
|
+
AtCapacity -->|Yes| CalcDistance["Calculate XOR distance<br/>from our peer ID"]
|
|
385
|
+
|
|
386
|
+
CalcDistance --> FindFarthest["Find currently farthest<br/>connected peer"]
|
|
387
|
+
FindFarthest --> Compare["New peer closer<br/>than farthest peer?"]
|
|
388
|
+
|
|
389
|
+
Compare -->|No| Reject["Reject connection<br/>not worth evicting for"]
|
|
390
|
+
Compare -->|Yes| SendEviction["Send eviction notice<br/>to farthest peer"]
|
|
391
|
+
|
|
392
|
+
SendEviction --> DisconnectFarthest[Disconnect farthest peer]
|
|
393
|
+
DisconnectFarthest --> AcceptNew[Accept new peer connection]
|
|
394
|
+
|
|
395
|
+
AcceptNew --> OptimalTopology["Maintain optimal<br/>mesh topology"]
|
|
396
|
+
|
|
397
|
+
Accept --> End[Connection Complete]
|
|
398
|
+
Reject --> End
|
|
399
|
+
OptimalTopology --> End
|
|
400
|
+
|
|
401
|
+
style NewPeer fill:#e1f5fe,color:#000000
|
|
402
|
+
style SendEviction fill:#fff3e0,color:#000000
|
|
403
|
+
style DisconnectFarthest fill:#ffebee,color:#000000
|
|
404
|
+
style AcceptNew fill:#e8f5e8,color:#000000
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
## οΏ½ API Reference
|
|
408
|
+
|
|
409
|
+
### PeerPigeonServer Class
|
|
410
|
+
|
|
411
|
+
When importing the server class, you can create and configure it programmatically:
|
|
412
|
+
|
|
413
|
+
```javascript
|
|
414
|
+
import { PeerPigeonServer } from 'peerpigeon';
|
|
415
|
+
|
|
416
|
+
const server = new PeerPigeonServer(options);
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
#### Constructor Options
|
|
420
|
+
|
|
421
|
+
- **`port`** (number) - Server port (default: 3000)
|
|
422
|
+
- **`host`** (string) - Server host (default: 'localhost')
|
|
423
|
+
- **`maxConnections`** (number) - Maximum concurrent connections (default: 1000)
|
|
424
|
+
- **`cleanupInterval`** (number) - Cleanup interval in ms (default: 60000)
|
|
425
|
+
- **`peerTimeout`** (number) - Peer timeout in ms (default: 300000)
|
|
426
|
+
- **`corsOrigin`** (string) - CORS origin (default: '*')
|
|
427
|
+
- **`maxMessageSize`** (number) - Max message size in bytes (default: 1MB)
|
|
428
|
+
|
|
429
|
+
#### Methods
|
|
430
|
+
|
|
431
|
+
- **`await server.start()`** - Start the server
|
|
432
|
+
- **`await server.stop()`** - Stop the server
|
|
433
|
+
- **`server.getStats()`** - Get server statistics
|
|
434
|
+
- **`server.getPeers()`** - Get list of connected peers
|
|
435
|
+
|
|
436
|
+
#### Events
|
|
437
|
+
|
|
438
|
+
- **`started`** - Server started
|
|
439
|
+
- **`stopped`** - Server stopped
|
|
440
|
+
- **`peerConnected`** - Peer connected
|
|
441
|
+
- **`peerDisconnected`** - Peer disconnected
|
|
442
|
+
- **`peerAnnounced`** - Peer announced
|
|
443
|
+
- **`peerGoodbye`** - Peer said goodbye
|
|
444
|
+
- **`error`** - Server error
|
|
445
|
+
|
|
446
|
+
#### Example: Custom Server Configuration
|
|
447
|
+
|
|
448
|
+
```javascript
|
|
449
|
+
import { PeerPigeonServer } from 'peerpigeon';
|
|
450
|
+
|
|
451
|
+
const server = new PeerPigeonServer({
|
|
452
|
+
port: 8080,
|
|
453
|
+
maxConnections: 500,
|
|
454
|
+
cleanupInterval: 30000
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
server.on('peerConnected', ({ peerId, totalConnections }) => {
|
|
458
|
+
console.log(`New peer: ${peerId}, Total: ${totalConnections}`);
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
await server.start();
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
### Client Library Exports
|
|
465
|
+
|
|
466
|
+
```javascript
|
|
467
|
+
import { PeerPigeonMesh, PeerPigeonServer } from 'peerpigeon';
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
- **`PeerPigeonMesh`** - Main mesh networking class (browser)
|
|
471
|
+
- **`PeerPigeonServer`** - WebSocket signaling server class (Node.js)
|
|
472
|
+
- **`PeerConnection`** - WebRTC peer connection wrapper
|
|
473
|
+
- **`SignalingClient`** - WebSocket signaling client
|
|
474
|
+
- **`WebDHT`** - Distributed hash table implementation
|
|
475
|
+
|
|
476
|
+
## οΏ½π Core Components
|
|
477
|
+
|
|
478
|
+
### PeerPigeonMesh
|
|
479
|
+
Central coordinator that manages all mesh networking functionality and orchestrates the component interactions.
|
|
480
|
+
|
|
481
|
+
```javascript
|
|
482
|
+
const mesh = new PeerPigeonMesh();
|
|
483
|
+
await mesh.init();
|
|
484
|
+
await mesh.connect('wss://your-signaling-server.com');
|
|
485
|
+
|
|
486
|
+
// Send message to entire network via gossip protocol
|
|
487
|
+
const messageId = mesh.sendMessage('Hello mesh network!');
|
|
488
|
+
|
|
489
|
+
// Get network status
|
|
490
|
+
const status = mesh.getStatus();
|
|
491
|
+
console.log(`Connected to ${status.connectedCount}/${status.maxPeers} peers`);
|
|
492
|
+
|
|
493
|
+
// Configure mesh behavior
|
|
494
|
+
mesh.setMaxPeers(10);
|
|
495
|
+
mesh.setAutoDiscovery(true);
|
|
496
|
+
mesh.setEvictionStrategy(true);
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
### PeerDiscovery
|
|
500
|
+
Manages peer discovery and implements smart connection logic with isolation prevention.
|
|
501
|
+
|
|
502
|
+
**Key Features:**
|
|
503
|
+
- **Lexicographic connection rule** prevents connection race conditions
|
|
504
|
+
- **Isolation override** ensures peers with no connections can still connect
|
|
505
|
+
- **XOR distance sorting** prioritizes closer peers for optimal topology
|
|
506
|
+
- **Connection attempt tracking** prevents duplicate connection attempts
|
|
507
|
+
|
|
508
|
+
```javascript
|
|
509
|
+
// Example of isolation override logic
|
|
510
|
+
if (currentConnectionCount === 0 && discoveredPeers.length > 0) {
|
|
511
|
+
// Override lexicographic rule to prevent isolation
|
|
512
|
+
// Priority: natural initiators > closest peer by XOR distance
|
|
513
|
+
}
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
### ConnectionManager
|
|
517
|
+
Manages WebRTC peer connections, handles signaling, and routes messages to appropriate handlers.
|
|
518
|
+
|
|
519
|
+
**Responsibilities:**
|
|
520
|
+
- WebRTC connection establishment and management
|
|
521
|
+
- Message routing to GossipManager and EvictionManager
|
|
522
|
+
- Connection state tracking and cleanup
|
|
523
|
+
- Retry logic with exponential backoff
|
|
524
|
+
- Race condition prevention
|
|
525
|
+
|
|
526
|
+
### GossipManager
|
|
527
|
+
Implements gossip protocol for reliable message propagation across the entire mesh network.
|
|
528
|
+
|
|
529
|
+
**Protocol Features:**
|
|
530
|
+
- **TTL (Time To Live)**: Messages expire after 10 hops to prevent infinite loops
|
|
531
|
+
- **Seen message tracking**: Prevents duplicate message processing
|
|
532
|
+
- **Path tracking**: Detects and prevents routing loops
|
|
533
|
+
- **Broadcast guarantee**: Messages reach all peers, not just direct connections
|
|
534
|
+
|
|
535
|
+
```javascript
|
|
536
|
+
// Gossip message structure
|
|
537
|
+
{
|
|
538
|
+
id: 'unique-message-id',
|
|
539
|
+
type: 'gossip',
|
|
540
|
+
subtype: 'chat',
|
|
541
|
+
content: 'Hello network!',
|
|
542
|
+
from: 'sender-peer-id',
|
|
543
|
+
timestamp: Date.now(),
|
|
544
|
+
ttl: 10,
|
|
545
|
+
path: ['sender-peer-id', 'relay-peer-id', ...]
|
|
546
|
+
}
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
### EvictionManager
|
|
550
|
+
Implements smart peer eviction for optimal mesh topology using XOR distance calculations.
|
|
551
|
+
|
|
552
|
+
**Eviction Strategy:**
|
|
553
|
+
- Only evicts when at maximum peer capacity
|
|
554
|
+
- Calculates XOR distances to determine peer relationships
|
|
555
|
+
- Evicts farthest peer when a closer one wants to connect
|
|
556
|
+
- Sends eviction notices before disconnecting peers
|
|
557
|
+
- No cooldown periods - focuses purely on topology optimization
|
|
558
|
+
|
|
559
|
+
### MeshOptimizer
|
|
560
|
+
Handles periodic mesh optimization and provides debugging utilities.
|
|
561
|
+
|
|
562
|
+
**Optimization Features:**
|
|
563
|
+
- Periodic connectivity analysis
|
|
564
|
+
- Force connection to all discovered peers (for testing)
|
|
565
|
+
- Mesh topology evaluation and recommendations
|
|
566
|
+
|
|
567
|
+
## βοΈ Configuration & API
|
|
568
|
+
|
|
569
|
+
The PeerPigeonMesh API provides methods for configuration, network management, messaging, and debugging. It is designed to be intuitive and event-driven.
|
|
570
|
+
|
|
571
|
+
### Initialization & Connection
|
|
572
|
+
Methods to initialize the mesh and manage the connection to the signaling server.
|
|
573
|
+
|
|
574
|
+
```javascript
|
|
575
|
+
// Initialize the mesh with a new, cryptographically secure peer ID.
|
|
576
|
+
// This must be called before any other method.
|
|
577
|
+
await mesh.init();
|
|
578
|
+
|
|
579
|
+
// Connect to the signaling server to join the mesh network.
|
|
580
|
+
await mesh.connect(signalingUrl);
|
|
581
|
+
|
|
582
|
+
// Disconnect from the signaling server and all connected peers.
|
|
583
|
+
mesh.disconnect();
|
|
584
|
+
```
|
|
585
|
+
|
|
586
|
+
### Configuration
|
|
587
|
+
Configure the behavior of the mesh network. These setters can be called at any time.
|
|
588
|
+
|
|
589
|
+
```javascript
|
|
590
|
+
// Set the maximum number of concurrent peer connections.
|
|
591
|
+
// Default: 3, Min: 1, Max: 50
|
|
592
|
+
mesh.setMaxPeers(10);
|
|
593
|
+
|
|
594
|
+
// Set the minimum number of connections to maintain for network health.
|
|
595
|
+
// Default: 2, Min: 0, Max: 49
|
|
596
|
+
mesh.setMinPeers(2);
|
|
597
|
+
|
|
598
|
+
// Enable or disable automatic connection to newly discovered peers.
|
|
599
|
+
// Default: true
|
|
600
|
+
mesh.setAutoDiscovery(true);
|
|
601
|
+
|
|
602
|
+
// Enable or disable the smart eviction strategy to optimize topology.
|
|
603
|
+
// Default: true
|
|
604
|
+
mesh.setEvictionStrategy(true);
|
|
605
|
+
|
|
606
|
+
// Enable or disable XOR distance-based routing for peer selection.
|
|
607
|
+
// Default: true
|
|
608
|
+
mesh.setXorRouting(true);
|
|
609
|
+
|
|
610
|
+
// Enable or disable the WebDHT (Distributed Hash Table) functionality.
|
|
611
|
+
// When disabled, all DHT methods will throw errors with helpful messages.
|
|
612
|
+
// Default: true (enabled)
|
|
613
|
+
// Can only be set during initialization in constructor options
|
|
614
|
+
const mesh = new PeerPigeonMesh({ enableWebDHT: false }); // Disable DHT
|
|
615
|
+
|
|
616
|
+
// Set the signaling connection type. Currently only 'websocket' is supported.
|
|
617
|
+
// Default: 'websocket'
|
|
618
|
+
mesh.setConnectionType('websocket');
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
### Network & Peer Information
|
|
622
|
+
Retrieve information about the network state and connected peers.
|
|
623
|
+
|
|
624
|
+
```javascript
|
|
625
|
+
// Get a comprehensive status object with the current state of the mesh.
|
|
626
|
+
// See "Status Object Structure" below for details.
|
|
627
|
+
const status = mesh.getStatus();
|
|
628
|
+
|
|
629
|
+
// Get the number of currently connected peers.
|
|
630
|
+
const count = mesh.getConnectedPeerCount();
|
|
631
|
+
|
|
632
|
+
// Get an array of peer IDs for all connected peers.
|
|
633
|
+
const peers = mesh.getPeers();
|
|
634
|
+
|
|
635
|
+
// Get an array of peer IDs for all discovered but not-yet-connected peers.
|
|
636
|
+
const discovered = mesh.getDiscoveredPeers();
|
|
637
|
+
|
|
638
|
+
// Check if the mesh can accept new incoming connections (i.e., not at maxPeers).
|
|
639
|
+
const canAccept = mesh.canAcceptMorePeers();
|
|
640
|
+
|
|
641
|
+
// Check if a peer is currently connected.
|
|
642
|
+
const isConnected = mesh.hasPeer(peerId);
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
### Messaging
|
|
646
|
+
Send messages to other peers in the network.
|
|
647
|
+
|
|
648
|
+
```javascript
|
|
649
|
+
// Broadcast a message to the entire mesh network using the gossip protocol.
|
|
650
|
+
// Returns a unique ID for the message.
|
|
651
|
+
const messageId = mesh.sendMessage(content);
|
|
652
|
+
```
|
|
653
|
+
|
|
654
|
+
### Manual Peer Management
|
|
655
|
+
Manually control connections to specific peers.
|
|
656
|
+
```
|
|
657
|
+
|
|
658
|
+
### Event System
|
|
659
|
+
|
|
660
|
+
```javascript
|
|
661
|
+
// === Connection Events ===
|
|
662
|
+
mesh.addEventListener('peerConnected', (event) => {
|
|
663
|
+
console.log(`β
Peer connected: ${event.peerId.substring(0, 8)}...`);
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
mesh.addEventListener('peerDisconnected', (event) => {
|
|
667
|
+
console.log(`β Peer disconnected: ${event.peerId.substring(0, 8)}... (${event.reason})`);
|
|
668
|
+
});
|
|
669
|
+
|
|
670
|
+
mesh.addEventListener('peerDiscovered', (event) => {
|
|
671
|
+
console.log(`π Peer discovered: ${event.peerId.substring(0, 8)}...`);
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
// === Messaging Events ===
|
|
675
|
+
mesh.addEventListener('messageReceived', (event) => {
|
|
676
|
+
console.log(`π¬ Message from ${event.from.substring(0, 8)}...: "${event.content}"`);
|
|
677
|
+
console.log(` Direct: ${event.direct}, Hops: ${event.hops || 0}`);
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
// === Network Events ===
|
|
681
|
+
mesh.addEventListener('peerEvicted', (event) => {
|
|
682
|
+
console.log(`π Peer evicted: ${event.peerId.substring(0, 8)}... (${event.reason})`);
|
|
683
|
+
});
|
|
684
|
+
|
|
685
|
+
mesh.addEventListener('statusChanged', (event) => {
|
|
686
|
+
console.log(`π Status: ${event.type} - ${event.message}`);
|
|
687
|
+
});
|
|
688
|
+
|
|
689
|
+
mesh.addEventListener('peersUpdated', () => {
|
|
690
|
+
console.log(`π Peer list updated - Connected: ${mesh.getConnectedPeerCount()}`);
|
|
691
|
+
});
|
|
692
|
+
```
|
|
693
|
+
|
|
694
|
+
### Status Object Structure
|
|
695
|
+
|
|
696
|
+
```javascript
|
|
697
|
+
const status = mesh.getStatus();
|
|
698
|
+
// Returns:
|
|
699
|
+
{
|
|
700
|
+
peerId: "abc123...", // Our peer ID
|
|
701
|
+
connected: true, // Connected to signaling server
|
|
702
|
+
connectedCount: 3, // Number of connected peers
|
|
703
|
+
discoveredCount: 5, // Number of discovered peers
|
|
704
|
+
maxPeers: 10, // Maximum peer limit
|
|
705
|
+
minPeers: 2, // Minimum peer target
|
|
706
|
+
autoDiscovery: true, // Auto-discovery enabled
|
|
707
|
+
evictionStrategy: true, // Smart eviction enabled
|
|
708
|
+
xorRouting: true, // XOR-based routing enabled
|
|
709
|
+
connectionType: "websocket", // Current signaling method
|
|
710
|
+
signalingUrl: "wss://...", // Signaling server URL
|
|
711
|
+
uptime: 120000 // Milliseconds since connection
|
|
712
|
+
}
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
## π Network Topology & XOR Routing
|
|
716
|
+
|
|
717
|
+
### XOR Distance Calculation
|
|
718
|
+
|
|
719
|
+
PeerPigeon uses XOR distance (inspired by Kademlia DHT) to determine peer relationships:
|
|
720
|
+
|
|
721
|
+
```javascript
|
|
722
|
+
// Example XOR distance calculation
|
|
723
|
+
function calculateXorDistance(peerId1, peerId2) {
|
|
724
|
+
let distance = 0n;
|
|
725
|
+
for (let i = 0; i < Math.min(peerId1.length, peerId2.length); i += 2) {
|
|
726
|
+
const byte1 = parseInt(peerId1.substr(i, 2), 16);
|
|
727
|
+
const byte2 = parseInt(peerId2.substr(i, 2), 16);
|
|
728
|
+
const xor = byte1 ^ byte2;
|
|
729
|
+
distance = (distance << 8n) | BigInt(xor);
|
|
730
|
+
}
|
|
731
|
+
return distance;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// Peer A: 0x1234abcd...
|
|
735
|
+
// Peer B: 0x1345cdef...
|
|
736
|
+
// XOR: 0x0071661e... (smaller = closer)
|
|
737
|
+
```
|
|
738
|
+
|
|
739
|
+
### Topology Example
|
|
740
|
+
|
|
741
|
+
```mermaid
|
|
742
|
+
graph TB
|
|
743
|
+
subgraph MeshNetwork[Mesh Network with XOR Distance Optimization]
|
|
744
|
+
A[Peer A: 0x1234...]
|
|
745
|
+
B[Peer B: 0x1345...]
|
|
746
|
+
C[Peer C: 0x5678...]
|
|
747
|
+
D[Peer D: 0x9ABC...]
|
|
748
|
+
E[Peer E: 0x9BCD...]
|
|
749
|
+
end
|
|
750
|
+
|
|
751
|
+
A -->|Direct connection XOR small| B
|
|
752
|
+
A -->|Direct connection XOR medium| C
|
|
753
|
+
A -.->|Would connect if capacity| D
|
|
754
|
+
|
|
755
|
+
B -->|Direct connection XOR small| A
|
|
756
|
+
B -->|Direct connection XOR large| C
|
|
757
|
+
|
|
758
|
+
C -->|Direct connection XOR medium| A
|
|
759
|
+
C -->|Direct connection XOR large| B
|
|
760
|
+
C -.->|Would evict B for| D
|
|
761
|
+
|
|
762
|
+
D -.->|Very close XOR distance| E
|
|
763
|
+
D -->|Would connect to| C
|
|
764
|
+
|
|
765
|
+
E -.->|Very close XOR distance| D
|
|
766
|
+
E -->|Would evict distant peer to connect to D| D
|
|
767
|
+
|
|
768
|
+
style A fill:#e1f5fe,color:#000000
|
|
769
|
+
style B fill:#e8f5e8,color:#000000
|
|
770
|
+
style C fill:#fff3e0,color:#000000
|
|
771
|
+
style D fill:#fce4ec,color:#000000
|
|
772
|
+
style E fill:#f3e5f5,color:#000000
|
|
773
|
+
```
|
|
774
|
+
|
|
775
|
+
### XOR Distance Benefits
|
|
776
|
+
|
|
777
|
+
1. **Optimal Peer Selection**: Peers with smaller XOR distances are preferred for connections
|
|
778
|
+
2. **Efficient Message Routing**: Gossip protocol naturally routes through relevant connections
|
|
779
|
+
3. **Scalable Discovery**: New peers only notify the closest existing peers, reducing overhead
|
|
780
|
+
4. **Network Resilience**: Multiple paths through the mesh ensure message delivery
|
|
781
|
+
5. **Cost Optimization**: Reduces signaling server load by ~95% through smart peer targeting
|
|
782
|
+
|
|
783
|
+
### Isolation Prevention
|
|
784
|
+
|
|
785
|
+
The isolation prevention mechanism ensures network connectivity:
|
|
786
|
+
|
|
787
|
+
```javascript
|
|
788
|
+
// Isolation override logic in PeerDiscovery
|
|
789
|
+
if (currentConnectionCount === 0 && discoveredPeers.length > 0) {
|
|
790
|
+
// Step 1: Try to connect to peers where we're the natural initiator
|
|
791
|
+
const naturalInitiators = discoveredPeers.filter(peerId => this.peerId > peerId);
|
|
792
|
+
|
|
793
|
+
if (naturalInitiators.length > 0) {
|
|
794
|
+
// Connect to natural targets first
|
|
795
|
+
return naturalInitiators.includes(targetPeerId);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// Step 2: If no natural targets, connect to closest peer by XOR distance
|
|
799
|
+
const sortedByDistance = discoveredPeers.sort((a, b) => {
|
|
800
|
+
const distA = calculateXorDistance(this.peerId, a);
|
|
801
|
+
const distB = calculateXorDistance(this.peerId, b);
|
|
802
|
+
return distA < distB ? -1 : 1;
|
|
803
|
+
});
|
|
804
|
+
|
|
805
|
+
return sortedByDistance[0] === targetPeerId;
|
|
806
|
+
}
|
|
807
|
+
```
|
|
808
|
+
|
|
809
|
+
## π WebSocket Signaling
|
|
810
|
+
|
|
811
|
+
PeerPigeon uses WebSocket signaling for real-time, bidirectional communication:
|
|
812
|
+
|
|
813
|
+
### WebSocket Signaling - Real-time Communication
|
|
814
|
+
- **Real-time delivery**: Instant bidirectional message delivery
|
|
815
|
+
- **Cost-efficient**: Persistent connections reduce connection overhead
|
|
816
|
+
- **Modern browsers**: Chrome, Firefox, Safari, Edge with full support
|
|
817
|
+
- **Use case**: Production applications requiring real-time performance
|
|
818
|
+
|
|
819
|
+
```javascript
|
|
820
|
+
// WebSocket signaling is used by default
|
|
821
|
+
const mesh = new PeerPigeonMesh();
|
|
822
|
+
await mesh.connect('wss://your-websocket-server.com');
|
|
823
|
+
|
|
824
|
+
// WebSocket connection automatically handles:
|
|
825
|
+
// - Real-time peer discovery notifications
|
|
826
|
+
// - WebRTC signaling message delivery
|
|
827
|
+
// - Bidirectional communication
|
|
828
|
+
// - Connection state management
|
|
829
|
+
```
|
|
830
|
+
|
|
831
|
+
### WebSocket Protocol Messages
|
|
832
|
+
|
|
833
|
+
The WebSocket signaling supports these message types:
|
|
834
|
+
|
|
835
|
+
| Message Type | Purpose | Data Structure |
|
|
836
|
+
|--------------|---------|----------------|
|
|
837
|
+
| `announce` | Peer joins network | `{peerId, timestamp}` |
|
|
838
|
+
| `goodbye` | Peer leaves network | `{peerId, timestamp}` |
|
|
839
|
+
| `offer` | WebRTC connection offer | `{type: 'offer', data: RTCSessionDescription, targetPeerId}` |
|
|
840
|
+
| `answer` | WebRTC connection answer | `{type: 'answer', data: RTCSessionDescription, targetPeerId}` |
|
|
841
|
+
| `ice-candidate` | ICE candidate exchange | `{type: 'ice-candidate', data: RTCIceCandidate, targetPeerId}` |
|
|
842
|
+
| `cleanup` | Remove processed messages | `{type: 'cleanup', reason}` |
|
|
843
|
+
|
|
844
|
+
## π Deployment Options
|
|
845
|
+
|
|
846
|
+
### Option 1: Custom Signaling Server
|
|
847
|
+
|
|
848
|
+
Implement your own signaling server with these required endpoints:
|
|
849
|
+
|
|
850
|
+
```typescript
|
|
851
|
+
// Required endpoints for custom signaling server
|
|
852
|
+
|
|
853
|
+
// WebSocket connection endpoint
|
|
854
|
+
wss://your-server.com/signaling?peerId={peerId}
|
|
855
|
+
|
|
856
|
+
// WebSocket message format for all signaling messages:
|
|
857
|
+
{
|
|
858
|
+
"type": "offer|answer|ice-candidate|announce|goodbye|ping",
|
|
859
|
+
"data": "message-specific-data",
|
|
860
|
+
"fromPeerId": "sender-peer-id",
|
|
861
|
+
"targetPeerId": "recipient-peer-id", // optional for broadcasts
|
|
862
|
+
"timestamp": 1234567890
|
|
863
|
+
}
|
|
864
|
+
```
|
|
865
|
+
|
|
866
|
+
### Option 2: Development/Testing Setup
|
|
867
|
+
|
|
868
|
+
For local development and testing:
|
|
869
|
+
|
|
870
|
+
```bash
|
|
871
|
+
For local development and testing:
|
|
872
|
+
|
|
873
|
+
```bash
|
|
874
|
+
# Serve with npm (preferred)
|
|
875
|
+
npm run dev
|
|
876
|
+
|
|
877
|
+
# Or with Node.js http-server
|
|
878
|
+
npm install -g http-server
|
|
879
|
+
http-server -p 8080
|
|
880
|
+
```
|
|
881
|
+
|
|
882
|
+
# Use query parameters to pre-configure signaling
|
|
883
|
+
open "http://localhost:8080/examples/browser/?api=wss://your-signaling-server.com/dev"
|
|
884
|
+
```
|
|
885
|
+
|
|
886
|
+
**Development Features:**
|
|
887
|
+
- Browser debugging tools integration
|
|
888
|
+
- Console logging with peer ID prefixes
|
|
889
|
+
- Global mesh access via `window.peerPigeonMesh`
|
|
890
|
+
- Force connection utilities for testing
|
|
891
|
+
- Real-time peer discovery and connection monitoring
|
|
892
|
+
|
|
893
|
+
## π Browser Compatibility & Requirements
|
|
894
|
+
|
|
895
|
+
### Required Browser Features
|
|
896
|
+
- **WebRTC**: RTCPeerConnection and RTCDataChannel support
|
|
897
|
+
- **ES6 Modules**: Dynamic imports and module syntax
|
|
898
|
+
- **Crypto API**: For cryptographically secure peer ID generation
|
|
899
|
+
- **WebSocket API**: For real-time signaling communication
|
|
900
|
+
|
|
901
|
+
### Supported Browsers & Versions
|
|
902
|
+
|
|
903
|
+
| Browser | Minimum Version | WebRTC Support | WebSocket Support | Status |
|
|
904
|
+
|---------|----------------|----------------|-------------------|---------|
|
|
905
|
+
| **Chrome** | 80+ | β
Full | β
Yes | **Recommended** |
|
|
906
|
+
| **Firefox** | 75+ | β
Full | β
Yes | **Recommended** |
|
|
907
|
+
| **Safari** | 14+ | β
Full | β
Yes | **Supported** |
|
|
908
|
+
| **Edge** | 80+ | β
Full | β
Yes | **Supported** |
|
|
909
|
+
| **Mobile Chrome** | 80+ | β
Full | β
Yes | **Supported** |
|
|
910
|
+
| **Mobile Safari** | 14+ | β
Full | β
Yes | **Supported** |
|
|
911
|
+
|
|
912
|
+
### Feature Detection
|
|
913
|
+
|
|
914
|
+
PeerPigeon automatically detects browser capabilities:
|
|
915
|
+
|
|
916
|
+
```javascript
|
|
917
|
+
// Automatic capability detection
|
|
918
|
+
const mesh = new PeerPigeonMesh();
|
|
919
|
+
await mesh.init(); // Detects WebRTC, WebSocket support
|
|
920
|
+
|
|
921
|
+
// Check detected capabilities
|
|
922
|
+
const status = mesh.getStatus();
|
|
923
|
+
console.log('Connection type:', status.connectionType); // 'websocket'
|
|
924
|
+
console.log('WebRTC support:', mesh.hasWebRTCSupport());
|
|
925
|
+
console.log('WebSocket support:', mesh.hasWebSocketSupport());
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
## β‘ Performance & Scalability
|
|
929
|
+
|
|
930
|
+
### Network Efficiency
|
|
931
|
+
- **Gossip TTL**: Messages expire after 10 hops to prevent network flooding
|
|
932
|
+
- **XOR Routing**: Only relevant peers receive discovery notifications (~95% reduction)
|
|
933
|
+
- **Connection Limits**: Configurable peer limits prevent resource exhaustion
|
|
934
|
+
- **Smart Eviction**: Maintains optimal topology without unnecessary reconnections
|
|
935
|
+
|
|
936
|
+
### Performance Metrics
|
|
937
|
+
Based on testing with browser networks:
|
|
938
|
+
|
|
939
|
+
| Network Size | Avg Connection Time | Message Delivery | Memory Usage |
|
|
940
|
+
|--------------|-------------------|------------------|--------------|
|
|
941
|
+
| 2-5 peers | < 2 seconds | 100% success | ~5MB per peer |
|
|
942
|
+
| 6-10 peers | 2-4 seconds | 99.8% success | ~8MB per peer |
|
|
943
|
+
| 11-15 peers | 3-6 seconds | 99.5% success | ~12MB per peer |
|
|
944
|
+
|
|
945
|
+
### Best Practices for Performance
|
|
946
|
+
|
|
947
|
+
1. **Optimal Peer Limits**
|
|
948
|
+
```javascript
|
|
949
|
+
// For most applications
|
|
950
|
+
mesh.setMaxPeers(8); // Sweet spot for connectivity vs resources
|
|
951
|
+
mesh.setMinPeers(3); // Ensures network resilience
|
|
952
|
+
```
|
|
953
|
+
|
|
954
|
+
2. **Enable All Optimizations**
|
|
955
|
+
```javascript
|
|
956
|
+
mesh.setEvictionStrategy(true); // Maintains optimal topology
|
|
957
|
+
mesh.setXorRouting(true); // Reduces signaling overhead
|
|
958
|
+
mesh.setAutoDiscovery(true); // Handles connections automatically
|
|
959
|
+
```
|
|
960
|
+
|
|
961
|
+
3. **Monitor Connection Health**
|
|
962
|
+
```javascript
|
|
963
|
+
mesh.addEventListener('statusChanged', (event) => {
|
|
964
|
+
if (event.type === 'warning') {
|
|
965
|
+
console.warn('Network issue:', event.message);
|
|
966
|
+
// Implement reconnection logic
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
```
|
|
970
|
+
|
|
971
|
+
## π Security Considerations
|
|
972
|
+
|
|
973
|
+
### Built-in Security Features
|
|
974
|
+
- **Peer ID Generation**: Uses `crypto.getRandomValues()` for cryptographically secure peer IDs
|
|
975
|
+
- **WebRTC Encryption**: Built-in DTLS encryption for all peer-to-peer communication
|
|
976
|
+
- **Input Validation**: All peer IDs and messages are validated before processing
|
|
977
|
+
- **Message Limits**: TTL and size limits prevent abuse and resource exhaustion
|
|
978
|
+
|
|
979
|
+
### Deployment Security
|
|
980
|
+
|
|
981
|
+
#### Signaling Server Security
|
|
982
|
+
```bash
|
|
983
|
+
# Always use HTTPS/WSS for signaling endpoints
|
|
984
|
+
https://your-signaling-server.com/signaling # β
Secure
|
|
985
|
+
http://your-signaling-server.com/signaling # β Insecure
|
|
986
|
+
|
|
987
|
+
# Implement rate limiting
|
|
988
|
+
POST /signaling
|
|
989
|
+
X-Rate-Limit: 100 requests per minute per IP
|
|
990
|
+
```
|
|
991
|
+
|
|
992
|
+
### Security Best Practices
|
|
993
|
+
|
|
994
|
+
1. **Validate All Inputs**
|
|
995
|
+
```javascript
|
|
996
|
+
// PeerPigeon automatically validates:
|
|
997
|
+
// - Peer ID format (hexadecimal, correct length)
|
|
998
|
+
// - Message content (type, size limits)
|
|
999
|
+
// - WebRTC message structure
|
|
1000
|
+
```
|
|
1001
|
+
|
|
1002
|
+
2. **Implement Application-Level Security**
|
|
1003
|
+
```javascript
|
|
1004
|
+
// Add your own message authentication
|
|
1005
|
+
mesh.addEventListener('messageReceived', (event) => {
|
|
1006
|
+
if (!validateMessageSignature(event.content, event.from)) {
|
|
1007
|
+
console.warn('Ignoring message with invalid signature');
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
// Process trusted message
|
|
1011
|
+
});
|
|
1012
|
+
```
|
|
1013
|
+
|
|
1014
|
+
3. **Monitor for Abuse**
|
|
1015
|
+
```javascript
|
|
1016
|
+
// Track message frequency per peer
|
|
1017
|
+
const messageRates = new Map();
|
|
1018
|
+
mesh.addEventListener('messageReceived', (event) => {
|
|
1019
|
+
const rate = trackMessageRate(event.from);
|
|
1020
|
+
if (rate > MAX_MESSAGES_PER_MINUTE) {
|
|
1021
|
+
mesh.disconnectPeer(event.from, 'rate limit exceeded');
|
|
1022
|
+
}
|
|
1023
|
+
});
|
|
1024
|
+
```
|
|
1025
|
+
|
|
1026
|
+
## π οΈ Development & Debugging
|
|
1027
|
+
|
|
1028
|
+
### Running Tests
|
|
1029
|
+
|
|
1030
|
+
```bash
|
|
1031
|
+
# Install development dependencies
|
|
1032
|
+
npm install
|
|
1033
|
+
|
|
1034
|
+
# Start local development server
|
|
1035
|
+
npm run dev
|
|
1036
|
+
# or
|
|
1037
|
+
npx http-server -p 8080
|
|
1038
|
+
|
|
1039
|
+
# Open multiple browser tabs for testing
|
|
1040
|
+
open http://localhost:8080/examples/browser/
|
|
1041
|
+
open http://localhost:8080/examples/browser/
|
|
1042
|
+
open http://localhost:8080/examples/browser/
|
|
1043
|
+
```
|
|
1044
|
+
|
|
1045
|
+
### Debugging Tools
|
|
1046
|
+
|
|
1047
|
+
#### Built-in Debugging
|
|
1048
|
+
```javascript
|
|
1049
|
+
// Global mesh access in browser
|
|
1050
|
+
window.peerPigeonMesh.getStatus(); // Network status
|
|
1051
|
+
window.peerPigeonMesh.getPeers(); // Connected peers
|
|
1052
|
+
window.peerPigeonMesh.getDiscoveredPeers(); // Discovered peers
|
|
1053
|
+
window.peerPigeonMesh.debugConnectivity(); // Detailed connectivity info
|
|
1054
|
+
|
|
1055
|
+
// Force connections for testing
|
|
1056
|
+
window.peerPigeonMesh.forceConnectToAllPeers();
|
|
1057
|
+
|
|
1058
|
+
// Component access
|
|
1059
|
+
window.peerPigeonSignaling; // SignalingClient instance
|
|
1060
|
+
window.getPeerPigeonState(); // Complete application state
|
|
1061
|
+
```
|
|
1062
|
+
|
|
1063
|
+
#### Browser Developer Tools
|
|
1064
|
+
1. **Console Logs**: Detailed connection and message flow with peer ID prefixes
|
|
1065
|
+
2. **Network Tab**: Monitor signaling server communication patterns
|
|
1066
|
+
3. **WebRTC Internals**: Chrome's `chrome://webrtc-internals/` for connection debugging
|
|
1067
|
+
4. **Application Tab**: LocalStorage inspection for persistent state
|
|
1068
|
+
|
|
1069
|
+
#### Debugging Common Issues
|
|
1070
|
+
|
|
1071
|
+
**Connection Problems:**
|
|
1072
|
+
```javascript
|
|
1073
|
+
// Check connection prerequisites
|
|
1074
|
+
console.log('Signaling connected:', mesh.getStatus().connected);
|
|
1075
|
+
console.log('Discovered peers:', mesh.getDiscoveredPeers().length);
|
|
1076
|
+
console.log('Connection attempts:', mesh.getConnectionAttempts());
|
|
1077
|
+
|
|
1078
|
+
// Force retry connections
|
|
1079
|
+
mesh.getDiscoveredPeers().forEach(peer => {
|
|
1080
|
+
if (!mesh.hasPeer(peer.peerId)) {
|
|
1081
|
+
mesh.connectToPeer(peer.peerId);
|
|
1082
|
+
}
|
|
1083
|
+
});
|
|
1084
|
+
```
|
|
1085
|
+
|
|
1086
|
+
**Message Delivery Issues:**
|
|
1087
|
+
```javascript
|
|
1088
|
+
// Check gossip protocol state
|
|
1089
|
+
mesh.addEventListener('messageReceived', (event) => {
|
|
1090
|
+
console.log('Message path:', event.path);
|
|
1091
|
+
console.log('TTL remaining:', event.ttl);
|
|
1092
|
+
console.log('Seen messages:', mesh.gossipManager.seenMessages.size);
|
|
1093
|
+
});
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
### Testing Scenarios
|
|
1097
|
+
|
|
1098
|
+
#### Multi-Tab Testing
|
|
1099
|
+
```bash
|
|
1100
|
+
# Open 3-5 browser tabs
|
|
1101
|
+
for i in {1..5}; do
|
|
1102
|
+
open "http://localhost:8080/examples/browser/?debug=true&tab=$i"
|
|
1103
|
+
done
|
|
1104
|
+
```
|
|
1105
|
+
|
|
1106
|
+
#### Network Partition Testing
|
|
1107
|
+
```javascript
|
|
1108
|
+
// Simulate network partition
|
|
1109
|
+
mesh.disconnectPeer(specificPeerId, 'testing partition');
|
|
1110
|
+
|
|
1111
|
+
// Wait and observe reconnection behavior
|
|
1112
|
+
setTimeout(() => {
|
|
1113
|
+
console.log('Network recovered, connections:', mesh.getConnectedPeerCount());
|
|
1114
|
+
}, 10000);
|
|
1115
|
+
```
|
|
1116
|
+
|
|
1117
|
+
#### Load Testing
|
|
1118
|
+
```javascript
|
|
1119
|
+
// Send messages rapidly to test gossip protocol
|
|
1120
|
+
setInterval(() => {
|
|
1121
|
+
mesh.sendMessage(`Load test message ${Date.now()}`);
|
|
1122
|
+
}, 1000);
|
|
1123
|
+
```
|
|
1124
|
+
|
|
1125
|
+
## π€ Contributing
|
|
1126
|
+
|
|
1127
|
+
We welcome contributions! Here's how to get started:
|
|
1128
|
+
|
|
1129
|
+
### Development Setup
|
|
1130
|
+
```bash
|
|
1131
|
+
# Fork and clone the repository
|
|
1132
|
+
git clone https://github.com/your-username/pigon.git
|
|
1133
|
+
cd pigon
|
|
1134
|
+
|
|
1135
|
+
# Create a feature branch
|
|
1136
|
+
git checkout -b feature/amazing-improvement
|
|
1137
|
+
|
|
1138
|
+
# Make your changes and test thoroughly
|
|
1139
|
+
npm run dev
|
|
1140
|
+
# Test with multiple browser instances
|
|
1141
|
+
|
|
1142
|
+
# Commit with descriptive messages
|
|
1143
|
+
git commit -m "Add isolation prevention to peer discovery
|
|
1144
|
+
|
|
1145
|
+
- Implements lexicographic override when peer has no connections
|
|
1146
|
+
- Prioritizes natural initiators over XOR distance
|
|
1147
|
+
- Prevents permanent isolation in small networks
|
|
1148
|
+
- Adds comprehensive logging for debugging"
|
|
1149
|
+
|
|
1150
|
+
# Push and create pull request
|
|
1151
|
+
git push origin feature/amazing-improvement
|
|
1152
|
+
```
|
|
1153
|
+
|
|
1154
|
+
### Contribution Guidelines
|
|
1155
|
+
|
|
1156
|
+
1. **Test with Multiple Peers**: Always test changes with 3-5 browser instances
|
|
1157
|
+
2. **Maintain Backward Compatibility**: Don't break existing API contracts
|
|
1158
|
+
3. **Add Comprehensive Logging**: Use consistent peer ID prefixes in logs
|
|
1159
|
+
4. **Update Documentation**: Include code examples and explanations
|
|
1160
|
+
5. **Follow Code Style**: Use consistent formatting and naming conventions
|
|
1161
|
+
|
|
1162
|
+
### Areas for Contribution
|
|
1163
|
+
- **Performance Optimization**: Improve connection speed and memory usage
|
|
1164
|
+
- **Security Enhancements**: Add message authentication and rate limiting
|
|
1165
|
+
- **Testing Framework**: Automated testing for mesh network scenarios
|
|
1166
|
+
- **Mobile Optimization**: Improve performance on mobile browsers
|
|
1167
|
+
- **Documentation**: Examples, tutorials, and API improvements
|
|
1168
|
+
|
|
1169
|
+
## π License
|
|
1170
|
+
|
|
1171
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
1172
|
+
|
|
1173
|
+
## π Acknowledgments
|
|
1174
|
+
|
|
1175
|
+
- **Kademlia DHT**: Inspired the XOR distance routing algorithm ([Paper](https://pdos.csail.mit.edu/~petar/papers/maymounkov-kademlia-lncs.pdf))
|
|
1176
|
+
- **WebRTC Community**: For providing the foundation of peer-to-peer communication
|
|
1177
|
+
- **Gossip Protocols**: Epidemic algorithms research for reliable message propagation
|
|
1178
|
+
- **Open Source Community**: For feedback, testing, and continuous improvement
|
|
1179
|
+
|
|
1180
|
+
---
|
|
1181
|
+
|
|
1182
|
+
**Quick Links:**
|
|
1183
|
+
- [Live Demo](http://localhost:8080/examples/browser/) (after starting local server)
|
|
1184
|
+
- [API Documentation](docs/API.md)
|
|
1185
|
+
- [Deployment Guide](docs/DEPLOYMENT.md)
|
|
1186
|
+
- [GitHub Issues](https://github.com/danrayadev/pigon/issues)
|
|
1187
|
+
- [Contributing Guidelines](CONTRIBUTING.md)
|