Skip to content

feat(edge-net): Replace simulated P2P with real WebRTC implementation #101

@ruvnet

Description

@ruvnet

Summary

Replace the current simulated peer-to-peer networking in the Edge-Net join system with a real WebRTC implementation for production-ready distributed compute coordination.

Current State

The current implementation in examples/edge-net/pkg/join.js and join.html uses simulated P2P:

// join.html:428 - Simulated peer discovery
function announceToNetwork() {
    peerCount = Math.floor(Math.random() * 5) + 1;  // ❌ Simulated
    document.getElementById('stat-peers').textContent = peerCount;
    
    // Simulate peer discovery
    setInterval(() => {
        const delta = Math.random() > 0.5 ? 1 : -1;
        peerCount = Math.max(1, peerCount + delta);  // ❌ Random fluctuation
    }, 10000);
}

Proposed Implementation

1. WebRTC Data Channels for P2P Communication

class WebRTCPeerManager {
    constructor(identity) {
        this.identity = identity;
        this.peers = new Map();
        this.dataChannels = new Map();
        this.iceServers = [
            { urls: 'stun:stun.l.google.com:19302' },
            { urls: 'stun:stun1.l.google.com:19302' }
        ];
    }

    async createOffer(peerId) {
        const pc = new RTCPeerConnection({ iceServers: this.iceServers });
        const dc = pc.createDataChannel('edge-net', { ordered: true });
        
        dc.onopen = () => this.onChannelOpen(peerId, dc);
        dc.onmessage = (e) => this.onMessage(peerId, e.data);
        
        const offer = await pc.createOffer();
        await pc.setLocalDescription(offer);
        
        this.peers.set(peerId, pc);
        return offer;
    }

    async handleAnswer(peerId, answer) {
        const pc = this.peers.get(peerId);
        await pc.setRemoteDescription(new RTCSessionDescription(answer));
    }
}

2. Signaling Server Options

Option Pros Cons
WebSocket Relay Simple, low latency Centralized
Gun.js Decentralized, no server Higher latency
LibP2P Full P2P stack Complex, larger bundle
Hyperswarm DHT-based discovery Node.js focused

Recommendation: Start with WebSocket signaling + Gun.js fallback for resilience.

3. QDAG Synchronization Protocol

// Sync contributions via WebRTC data channels
async syncQDAG(peer) {
    // Request peer's latest contributions
    peer.send(JSON.stringify({
        type: 'qdag_sync_request',
        since: this.lastSyncTimestamp
    }));
}

onQDAGSync(peerId, contributions) {
    for (const contrib of contributions) {
        // Verify signature before accepting
        if (this.verifyContribution(contrib)) {
            this.qdag.addContribution(contrib);
        }
    }
}

4. NAT Traversal with TURN Fallback

const iceServers = [
    { urls: 'stun:stun.l.google.com:19302' },
    { urls: 'stun:stun.cloudflare.com:3478' },
    {
        urls: 'turn:turn.edge-net.io:3478',
        username: 'edge-net',
        credential: process.env.TURN_SECRET
    }
];

Files to Modify

File Changes
pkg/join.js Add WebRTCPeerManager class
pkg/join.html Add WebRTC browser implementation
pkg/network.js Integrate WebRTC with QDAG sync
pkg/networks.js Add network-specific signaling
relay/server.js Add WebSocket signaling server

Tasks

  • Implement WebRTCPeerManager class
  • Add ICE candidate handling
  • Create WebSocket signaling server
  • Add Gun.js fallback for decentralized signaling
  • Implement QDAG sync over data channels
  • Add connection quality monitoring
  • Handle peer disconnection/reconnection
  • Add TURN server configuration
  • Write integration tests
  • Benchmark latency vs simulated P2P
  • Update documentation

Acceptance Criteria

  1. Real peer discovery - Nodes actually discover and connect to each other
  2. Data channel communication - Messages sent via WebRTC, not simulated
  3. QDAG synchronization - Contributions sync across peers in real-time
  4. NAT traversal - Works behind NATs with STUN/TURN
  5. Graceful degradation - Falls back to relay if P2P fails
  6. < 100ms latency - Peer-to-peer message latency under 100ms

Performance Targets

Metric Target Current (Simulated)
Peer discovery < 2s N/A (fake)
Message latency < 100ms N/A (local)
Connection success > 95% 100% (fake)
Reconnection time < 5s N/A

References

Labels

enhancement, p2p, webrtc, edge-net

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions