Files
zigp2p/docs/WASM_BROWSER_DESIGN.md

130 KiB

Cross-Platform Support Design Document

WASM, Browser, Mobile, and IoT

Project: zig-p2p Version: 0.1.0 Document Status: Draft Created: February 2025 Updated: February 2026


Table of Contents

  1. Overview
  2. Goals and Non-Goals
  3. Current Architecture Analysis
  4. Target Architecture
  5. Transport Abstraction Layer
  6. WebRTC Integration
  7. Event-Driven I/O Model
  8. File System Abstraction
  9. Threading Model Adaptation
  10. JavaScript Interop Layer
  11. Build System Changes
  12. Implementation Phases
  13. Testing Strategy
  14. Risk Assessment
  15. Native-Browser Interoperability
  16. Native WebRTC Implementation
  17. Mobile and IoT Platform Support
  18. Appendices

1. Overview

1.1 Purpose

This document describes the design for adding WebAssembly (WASM) and browser support to the zig-p2p library, enabling peer-to-peer communication directly in web browsers.

1.2 Background

The zig-p2p library currently targets native platforms (Linux, macOS, Windows) using POSIX sockets for network I/O. Browsers cannot use raw sockets but provide WebRTC for peer-to-peer communication. This design enables the library to work in both environments through a transport abstraction layer.

1.3 Scope

  • Transport layer abstraction (POSIX sockets vs WebRTC)
  • Event-driven I/O model for single-threaded WASM
  • File system abstraction (native fs vs IndexedDB)
  • JavaScript interoperability layer
  • Build system changes for WASM target

1.4 Executive Summary

Aspect Assessment
Feasibility High - Architecture is well-suited for abstraction
Code Reuse ~40% unchanged, ~35% needs abstraction, ~25% platform-specific
WASM-Only Effort 5-6 weeks (browser-to-browser only)
Full Interop Effort 9-12 weeks (includes native WebRTC for native↔browser)
Primary Challenge Native-browser interoperability requires WebRTC on native

Critical Note: Without native WebRTC support, native peers cannot communicate with browser peers. They use incompatible transports (UDP vs WebRTC DataChannel). See Section 15 for details.


1.5 Interoperability Matrix

Scenario Without Native WebRTC With Native WebRTC
Native ↔ Native ✅ UDP ✅ UDP
Browser ↔ Browser ✅ WebRTC ✅ WebRTC
Native ↔ Browser ❌ Incompatible ✅ WebRTC Direct

1.6 Original Executive Summary

Aspect Assessment
Feasibility High - Architecture is well-suited for abstraction
Code Reuse ~40% unchanged, ~35% needs abstraction, ~25% platform-specific
Estimated Effort 3-4 weeks (core) + 1-2 weeks (testing)
Primary Challenge Socket I/O model replacement

2. Goals and Non-Goals

2.1 Goals

  1. G1: Enable zig-p2p to run in modern web browsers via WASM
  2. G2: Maintain full compatibility with native platforms (no regression)
  3. G3: Share maximum code between native and WASM builds
  4. G4: Provide clean JavaScript API for browser integration
  5. G5: Support all core features: encrypted P2P messaging, DHT discovery, file transfer

2.2 Non-Goals

  1. NG1: Legacy browser support (IE11, older Safari) - Target ES2020+
  2. NG2: Node.js support (could be added later, but not in initial scope)
  3. NG3: WebSocket-only fallback mode (WebRTC is required)
  4. NG4: Streaming media (existing limitation, not addressed here)
  5. NG5: SharedArrayBuffer threading (complex security requirements)

2.3 Success Criteria

  • Two browser tabs can establish P2P connection and exchange messages
  • Noise encryption works identically in native and WASM
  • DHT peer discovery functions in browser environment
  • File transfer works with IndexedDB storage
  • No performance regression on native platforms
  • Unit tests pass on both native and WASM targets

3. Current Architecture Analysis

3.1 Module Dependency Graph

┌─────────────────────────────────────────────────────────────────┐
│                        Application Layer                        │
│                    (examples/, user code)                       │
└─────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────┐
│                          P2P Layer                              │
│                      (src/p2p/*.zig)                            │
│              Lifecycle, Config, Stats, Types                    │
└─────────────────────────────────────────────────────────────────┘
                                 │
                 ┌───────────────┼───────────────┐
                 ▼               ▼               ▼
┌─────────────────────┐ ┌─────────────────┐ ┌─────────────────────┐
│   Network Layer     │ │  Protocol Layer │ │    Files Layer      │
│ (src/network/*.zig) │ │(src/protocol/*) │ │  (src/files/*.zig)  │
│                     │ │                 │ │                     │
│ • NetworkManager    │ │ • Message       │ │ • FileManager       │
│ • Discovery         │ │ • Handler       │ │ • Download/Upload   │
│ • DHT/Routing       │ │ • Router        │ │ • PiecePipeline     │
│ • NAT Traversal     │ │ • Crypto        │ │ • Verification      │
│ • SecureConnection  │ │                 │ │                     │
└─────────────────────┘ └─────────────────┘ └─────────────────────┘
         │                      │                     │
         ▼                      ▼                     ▼
┌─────────────────────────────────────────────────────────────────┐
│                         Core Layer                              │
│                      (src/core/*.zig)                           │
│        Socket, Address, Buffer, Limits, RateLimiter, Error      │
└─────────────────────────────────────────────────────────────────┘
         │                                            │
         ▼                                            ▼
┌─────────────────────┐                    ┌─────────────────────┐
│    Noise Layer      │                    │   OS/Platform       │
│  (src/noise/*.zig)  │                    │                     │
│                     │                    │ • POSIX Sockets     │
│ • Handshake         │                    │ • File System       │
│ • Cipher            │                    │ • Threading         │
│ • DH (X25519)       │                    │ • Time/Random       │
│ • Hash (BLAKE2b)    │                    │                     │
└─────────────────────┘                    └─────────────────────┘
        ✓                                           ✗
   WASM-Ready                               Needs Abstraction

3.2 WASM Compatibility by Layer

Layer Files WASM Status Notes
Noise 7 files ✅ Ready Pure crypto, generic I/O interfaces
Protocol 5 files ✅ Ready Pure data structures
Core 10 files ⚠️ Mixed Socket/Address need abstraction
Network 12 files ⚠️ Mixed NetworkManager needs event model
Files 11 files ⚠️ Mixed Has mock_fs foundation
P2P 5 files ⚠️ Minor Lifecycle needs adaptation

3.3 Platform Dependencies Inventory

3.3.1 POSIX Socket Operations (src/core/socket.zig)

// 23 POSIX syscalls identified:
posix.socket()      // Line 168 - Socket creation
posix.bind()        // Line 384 - Address binding
posix.listen()      // Line 417 - TCP listen
posix.accept()      // Line 439 - Accept connections
posix.connect()     // Line 506 - Initiate connection
posix.send()        // Line 524 - Send data
posix.sendto()      // Line 551 - UDP send
posix.recv()        // Line 568 - Receive data
posix.recvfrom()    // Line 594 - UDP receive
posix.close()       // Line 637 - Close socket
posix.fcntl()       // Lines 318, 331 - Non-blocking mode
posix.poll()        // Lines 726, 738 - I/O readiness
posix.setsockopt()  // Lines 208-230 - Socket options
posix.getsockopt()  // Lines 656-661 - Query options

3.3.2 Threading Operations

// Found in 36 files:
std.Thread.Mutex      // Synchronization primitive
std.Thread.spawn()    // Thread creation (11 files)
std.Thread.sleep()    // Blocking wait
std.atomic.Value      // Atomic operations (WASM-compatible)

3.3.3 File System Operations

// Found in 11 files:
std.fs.File           // File handle
std.fs.openFile()     // Open file
posix.read()          // Direct read
posix.write()         // Direct write
posix.mmap()          // Memory mapping (not in WASM)

4. Target Architecture

4.1 Dual-Target Build

                    ┌─────────────────┐
                    │   zig-p2p API   │
                    │   (Unchanged)   │
                    └────────┬────────┘
                             │
              ┌──────────────┴──────────────┐
              │                             │
              ▼                             ▼
    ┌─────────────────┐           ┌─────────────────┐
    │  Native Build   │           │   WASM Build    │
    │  (zig build)    │           │ (zig build-lib) │
    └────────┬────────┘           └────────┬────────┘
             │                             │
             ▼                             ▼
    ┌─────────────────┐           ┌─────────────────┐
    │ POSIXTransport  │           │ WebRTCTransport │
    │ NativeFileSystem│           │ IndexedDBFS     │
    │ std.Thread      │           │ EventQueue      │
    └─────────────────┘           └─────────────────┘

4.2 Abstraction Layers

┌─────────────────────────────────────────────────────────────────┐
│                     Platform-Agnostic Code                      │
│                                                                 │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐            │
│  │  Noise   │ │ Protocol │ │   DHT    │ │  Piece   │            │
│  │ Protocol │ │ Messages │ │ Routing  │ │ Selector │            │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘            │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Abstraction Interfaces                     │
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │
│  │  Transport   │  │  FileSystem  │  │  Scheduler   │           │
│  │  Interface   │  │  Interface   │  │  Interface   │           │
│  └──────────────┘  └──────────────┘  └──────────────┘           │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
                              │
              ┌───────────────┴───────────────┐
              │                               │
              ▼                               ▼
┌─────────────────────────┐     ┌─────────────────────────┐
│    Native Platform      │     │    WASM Platform        │
│                         │     │                         │
│  ┌─────────────────┐    │     │  ┌─────────────────┐    │
│  │ POSIXTransport  │    │     │  │ WebRTCTransport │    │
│  └─────────────────┘    │     │  └─────────────────┘    │
│  ┌─────────────────┐    │     │  ┌─────────────────┐    │
│  │  NativeFS       │    │     │  │  IndexedDBFS    │    │
│  └─────────────────┘    │     │  └─────────────────┘    │
│  ┌─────────────────┐    │     │  ┌─────────────────┐    │
│  │  ThreadPool     │    │     │  │  EventQueue     │    │
│  └─────────────────┘    │     │  └─────────────────┘    │
│                         │     │                         │
└─────────────────────────┘     └─────────────────────────┘

5. Transport Abstraction Layer

5.1 Transport Interface Definition

File: src/core/transport.zig (new file)

const std = @import("std");

/// Transport-agnostic connection interface
pub const Transport = struct {
    ptr: *anyopaque,
    vtable: *const VTable,

    pub const VTable = struct {
        /// Send data to the transport. Returns bytes sent or error.
        send: *const fn (ptr: *anyopaque, data: []const u8) Error!usize,

        /// Receive data from the transport. Returns bytes received or error.
        /// May return 0 if no data available (non-blocking).
        receive: *const fn (ptr: *anyopaque, buffer: []u8) Error!usize,

        /// Close the transport connection.
        close: *const fn (ptr: *anyopaque) void,

        /// Check if transport can accept more data without blocking.
        canSend: *const fn (ptr: *anyopaque) bool,

        /// Check if transport has data available to read.
        canReceive: *const fn (ptr: *anyopaque) bool,

        /// Get remote peer identifier.
        getRemoteId: *const fn (ptr: *anyopaque) ?PeerId,

        /// Get transport state.
        getState: *const fn (ptr: *anyopaque) State,
    };

    pub const State = enum {
        connecting,
        connected,
        disconnecting,
        disconnected,
        failed,
    };

    pub const Error = error{
        ConnectionFailed,
        ConnectionClosed,
        ConnectionTimeout,
        WouldBlock,
        BufferFull,
        InvalidState,
        TransportError,
    };

    // Convenience methods delegating to vtable
    pub fn send(self: Transport, data: []const u8) Error!usize {
        return self.vtable.send(self.ptr, data);
    }

    pub fn receive(self: Transport, buffer: []u8) Error!usize {
        return self.vtable.receive(self.ptr, buffer);
    }

    pub fn close(self: Transport) void {
        self.vtable.close(self.ptr);
    }

    pub fn canSend(self: Transport) bool {
        return self.vtable.canSend(self.ptr);
    }

    pub fn canReceive(self: Transport) bool {
        return self.vtable.canReceive(self.ptr);
    }
};

/// Transport factory for creating connections
pub const TransportFactory = struct {
    ptr: *anyopaque,
    vtable: *const VTable,

    pub const VTable = struct {
        /// Create outbound connection to address.
        connect: *const fn (
            ptr: *anyopaque,
            address: []const u8,
            callback: ConnectCallback,
        ) Error!void,

        /// Start listening for inbound connections.
        listen: *const fn (
            ptr: *anyopaque,
            address: []const u8,
            callback: AcceptCallback,
        ) Error!void,

        /// Stop listening.
        stopListening: *const fn (ptr: *anyopaque) void,
    };

    pub const ConnectCallback = *const fn (
        result: Error!Transport,
        context: ?*anyopaque,
    ) void;

    pub const AcceptCallback = *const fn (
        transport: Transport,
        context: ?*anyopaque,
    ) void;
};

5.2 POSIX Transport Implementation

File: src/platform/posix_transport.zig

const std = @import("std");
const posix = std.posix;
const Transport = @import("../core/transport.zig").Transport;

pub const POSIXTransport = struct {
    fd: posix.fd_t,
    state: Transport.State,
    remote_addr: ?std.net.Address,
    allocator: std.mem.Allocator,

    // Non-blocking I/O state
    send_buffer: std.ArrayList(u8),
    recv_buffer: std.ArrayList(u8),

    pub fn init(allocator: std.mem.Allocator) !*POSIXTransport {
        const self = try allocator.create(POSIXTransport);
        self.* = .{
            .fd = -1,
            .state = .disconnected,
            .remote_addr = null,
            .allocator = allocator,
            .send_buffer = std.ArrayList(u8).init(allocator),
            .recv_buffer = std.ArrayList(u8).init(allocator),
        };
        return self;
    }

    pub fn transport(self: *POSIXTransport) Transport {
        return .{
            .ptr = self,
            .vtable = &vtable,
        };
    }

    const vtable = Transport.VTable{
        .send = send,
        .receive = receive,
        .close = close,
        .canSend = canSend,
        .canReceive = canReceive,
        .getRemoteId = getRemoteId,
        .getState = getState,
    };

    fn send(ptr: *anyopaque, data: []const u8) Transport.Error!usize {
        const self: *POSIXTransport = @ptrCast(@alignCast(ptr));
        if (self.state != .connected) return error.InvalidState;

        const result = posix.send(self.fd, data, 0) catch |err| {
            return switch (err) {
                error.WouldBlock => error.WouldBlock,
                error.ConnectionResetByPeer => error.ConnectionClosed,
                else => error.TransportError,
            };
        };
        return result;
    }

    fn receive(ptr: *anyopaque, buffer: []u8) Transport.Error!usize {
        const self: *POSIXTransport = @ptrCast(@alignCast(ptr));
        if (self.state != .connected) return error.InvalidState;

        const result = posix.recv(self.fd, buffer, 0) catch |err| {
            return switch (err) {
                error.WouldBlock => error.WouldBlock,
                error.ConnectionResetByPeer => error.ConnectionClosed,
                else => error.TransportError,
            };
        };
        if (result == 0) return error.ConnectionClosed;
        return result;
    }

    fn close(ptr: *anyopaque) void {
        const self: *POSIXTransport = @ptrCast(@alignCast(ptr));
        if (self.fd != -1) {
            posix.close(self.fd);
            self.fd = -1;
        }
        self.state = .disconnected;
    }

    fn canSend(ptr: *anyopaque) bool {
        const self: *POSIXTransport = @ptrCast(@alignCast(ptr));
        if (self.fd == -1) return false;

        var fds = [_]posix.pollfd{.{
            .fd = self.fd,
            .events = posix.POLL.OUT,
            .revents = 0,
        }};
        const result = posix.poll(&fds, 0) catch return false;
        return result > 0 and (fds[0].revents & posix.POLL.OUT) != 0;
    }

    fn canReceive(ptr: *anyopaque) bool {
        const self: *POSIXTransport = @ptrCast(@alignCast(ptr));
        if (self.fd == -1) return false;

        var fds = [_]posix.pollfd{.{
            .fd = self.fd,
            .events = posix.POLL.IN,
            .revents = 0,
        }};
        const result = posix.poll(&fds, 0) catch return false;
        return result > 0 and (fds[0].revents & posix.POLL.IN) != 0;
    }

    fn getRemoteId(ptr: *anyopaque) ?PeerId {
        const self: *POSIXTransport = @ptrCast(@alignCast(ptr));
        _ = self;
        // Derive from connection or return stored ID
        return null;
    }

    fn getState(ptr: *anyopaque) Transport.State {
        const self: *POSIXTransport = @ptrCast(@alignCast(ptr));
        return self.state;
    }
};

5.3 WebRTC Transport Implementation

File: src/platform/webrtc_transport.zig

const std = @import("std");
const Transport = @import("../core/transport.zig").Transport;

/// WebRTC Data Channel transport for WASM/browser environment.
/// Communicates with JavaScript via imported functions.
pub const WebRTCTransport = struct {
    channel_id: u32,
    state: Transport.State,
    allocator: std.mem.Allocator,

    // Buffers for async I/O
    recv_queue: std.ArrayList([]u8),
    send_pending: usize,

    // JavaScript interop functions (imported)
    extern "webrtc" fn js_send(channel_id: u32, data: [*]const u8, len: usize) i32;
    extern "webrtc" fn js_close(channel_id: u32) void;
    extern "webrtc" fn js_get_state(channel_id: u32) u32;
    extern "webrtc" fn js_can_send(channel_id: u32) bool;
    extern "webrtc" fn js_recv_available(channel_id: u32) usize;
    extern "webrtc" fn js_recv(channel_id: u32, buffer: [*]u8, len: usize) i32;

    pub fn init(allocator: std.mem.Allocator, channel_id: u32) !*WebRTCTransport {
        const self = try allocator.create(WebRTCTransport);
        self.* = .{
            .channel_id = channel_id,
            .state = .connecting,
            .allocator = allocator,
            .recv_queue = std.ArrayList([]u8).init(allocator),
            .send_pending = 0,
        };
        return self;
    }

    pub fn transport(self: *WebRTCTransport) Transport {
        return .{
            .ptr = self,
            .vtable = &vtable,
        };
    }

    const vtable = Transport.VTable{
        .send = send,
        .receive = receive,
        .close = close,
        .canSend = canSend,
        .canReceive = canReceive,
        .getRemoteId = getRemoteId,
        .getState = getState,
    };

    fn send(ptr: *anyopaque, data: []const u8) Transport.Error!usize {
        const self: *WebRTCTransport = @ptrCast(@alignCast(ptr));

        const result = js_send(self.channel_id, data.ptr, data.len);
        if (result < 0) {
            return switch (result) {
                -1 => error.WouldBlock,
                -2 => error.BufferFull,
                -3 => error.ConnectionClosed,
                else => error.TransportError,
            };
        }
        return @intCast(result);
    }

    fn receive(ptr: *anyopaque, buffer: []u8) Transport.Error!usize {
        const self: *WebRTCTransport = @ptrCast(@alignCast(ptr));

        const result = js_recv(self.channel_id, buffer.ptr, buffer.len);
        if (result < 0) {
            return switch (result) {
                -1 => error.WouldBlock,
                -3 => error.ConnectionClosed,
                else => error.TransportError,
            };
        }
        return @intCast(result);
    }

    fn close(ptr: *anyopaque) void {
        const self: *WebRTCTransport = @ptrCast(@alignCast(ptr));
        js_close(self.channel_id);
        self.state = .disconnected;
    }

    fn canSend(ptr: *anyopaque) bool {
        const self: *WebRTCTransport = @ptrCast(@alignCast(ptr));
        return js_can_send(self.channel_id);
    }

    fn canReceive(ptr: *anyopaque) bool {
        const self: *WebRTCTransport = @ptrCast(@alignCast(ptr));
        return js_recv_available(self.channel_id) > 0;
    }

    fn getRemoteId(ptr: *anyopaque) ?PeerId {
        _ = ptr;
        return null; // Managed by JS layer
    }

    fn getState(ptr: *anyopaque) Transport.State {
        const self: *WebRTCTransport = @ptrCast(@alignCast(ptr));
        const js_state = js_get_state(self.channel_id);
        return switch (js_state) {
            0 => .connecting,
            1 => .connected,
            2 => .disconnecting,
            3 => .disconnected,
            else => .failed,
        };
    }
};

6. WebRTC Integration

6.1 WebRTC Architecture Overview

┌─────────────────────────────────────────────────────────────────┐
│                         Browser A                               │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐          │
│  │  WASM P2P   │◄──►│   JS Glue   │◄──►│  WebRTC     │          │
│  │   Library   │    │   Layer     │    │ DataChannel │          │
│  └─────────────┘    └─────────────┘    └──────┬──────┘          │
└───────────────────────────────────────────────│─────────────────┘
                                                │
                                                │ P2P (after signaling)
                                                │
┌───────────────────────────────────────────────│────────────────┐
│                         Browser B             │                │
│  ┌─────────────┐    ┌─────────────┐    ┌──────▼──────┐         │
│  │  WASM P2P   │◄──►│   JS Glue   │◄──►│  WebRTC     │         │
│  │   Library   │    │   Layer     │    │ DataChannel │         │
│  └─────────────┘    └─────────────┘    └─────────────┘         │
└────────────────────────────────────────────────────────────────┘
                              ▲
                              │ Signaling (one-time)
                              ▼
                    ┌─────────────────┐
                    │ Signaling Server│
                    │  (WebSocket)    │
                    └─────────────────┘

6.2 Signaling Protocol

WebRTC requires a signaling server to exchange connection metadata (SDP offers/answers and ICE candidates). Once connected, communication is peer-to-peer.

Note (Feb 2026): For native↔native connections, MWP (Mutual Witness Protocol) now provides infrastructure-free peer discovery and hole punching via DHT. For browser↔anything connections, WebRTC signaling is still required because browsers cannot use raw UDP. However, the DHT could serve as the signaling transport — native peers already connected via MWP could relay SDP offers/answers for browser peers through the DHT, potentially eliminating the need for a separate WebSocket signaling server.

6.2.1 Signaling Message Types

interface SignalingMessage {
    type: 'offer' | 'answer' | 'ice-candidate' | 'peer-id';
    from: string;      // Sender peer ID
    to: string;        // Target peer ID
    payload: any;      // SDP or ICE candidate
}

6.2.2 Connection Flow

Browser A                   Signaling Server                   Browser B
    │                             │                                │
    │  1. Register(peerIdA)       │                                │
    │────────────────────────────►│                                │
    │                             │                                │
    │                             │  2. Register(peerIdB)          │
    │                             │◄───────────────────────────────│
    │                             │                                │
    │  3. Offer(to: peerIdB)      │                                │
    │────────────────────────────►│                                │
    │                             │  4. Forward Offer              │
    │                             │───────────────────────────────►│
    │                             │                                │
    │                             │  5. Answer(to: peerIdA)        │
    │                             │◄───────────────────────────────│
    │  6. Forward Answer          │                                │
    │◄────────────────────────────│                                │
    │                             │                                │
    │  7. ICE Candidates ◄───────►│◄───────────────────────────────│
    │                             │                                │
    │                      P2P DataChannel Established             │
    │◄────────────────────────────────────────────────────────────►│

6.3 JavaScript Glue Layer

File: wasm/js/webrtc-transport.js

/**
 * WebRTC transport bridge for zig-p2p WASM module.
 * Manages WebRTC connections and exposes them to WASM.
 */
class WebRTCTransportManager {
    constructor(wasmInstance, signalingUrl) {
        this.wasm = wasmInstance;
        this.channels = new Map();  // channel_id -> RTCDataChannel
        this.nextChannelId = 1;
        this.recvBuffers = new Map(); // channel_id -> ArrayBuffer[]

        // Connect to signaling server
        this.signaling = new WebSocket(signalingUrl);
        this.signaling.onmessage = (e) => this.handleSignaling(JSON.parse(e.data));

        this.peerConnections = new Map(); // peerId -> RTCPeerConnection
    }

    /**
     * Create outbound connection to peer.
     * Called from WASM via imported function.
     */
    async connect(peerId) {
        const pc = new RTCPeerConnection({
            iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
        });

        const channel = pc.createDataChannel('p2p', {
            ordered: false,  // UDP-like for performance
            maxRetransmits: 0
        });

        const channelId = this.registerChannel(channel);

        // Create and send offer
        const offer = await pc.createOffer();
        await pc.setLocalDescription(offer);

        this.signaling.send(JSON.stringify({
            type: 'offer',
            to: peerId,
            payload: offer
        }));

        // Handle ICE candidates
        pc.onicecandidate = (e) => {
            if (e.candidate) {
                this.signaling.send(JSON.stringify({
                    type: 'ice-candidate',
                    to: peerId,
                    payload: e.candidate
                }));
            }
        };

        this.peerConnections.set(peerId, pc);
        return channelId;
    }

    /**
     * Register a data channel and return its ID.
     */
    registerChannel(channel) {
        const id = this.nextChannelId++;
        this.channels.set(id, channel);
        this.recvBuffers.set(id, []);

        channel.onmessage = (e) => {
            this.recvBuffers.get(id).push(new Uint8Array(e.data));
            // Notify WASM that data is available
            this.wasm.exports.on_data_available(id);
        };

        channel.onclose = () => {
            // Notify WASM of disconnection
            this.wasm.exports.on_channel_closed(id);
        };

        return id;
    }

    // Functions exported to WASM
    getImports() {
        return {
            webrtc: {
                js_send: (channelId, dataPtr, len) => {
                    const channel = this.channels.get(channelId);
                    if (!channel || channel.readyState !== 'open') return -3;
                    if (channel.bufferedAmount > 16 * 1024 * 1024) return -2;

                    const data = new Uint8Array(
                        this.wasm.exports.memory.buffer,
                        dataPtr,
                        len
                    );
                    channel.send(data);
                    return len;
                },

                js_recv: (channelId, bufferPtr, maxLen) => {
                    const queue = this.recvBuffers.get(channelId);
                    if (!queue || queue.length === 0) return -1;

                    const data = queue.shift();
                    const copyLen = Math.min(data.length, maxLen);
                    const target = new Uint8Array(
                        this.wasm.exports.memory.buffer,
                        bufferPtr,
                        copyLen
                    );
                    target.set(data.subarray(0, copyLen));
                    return copyLen;
                },

                js_close: (channelId) => {
                    const channel = this.channels.get(channelId);
                    if (channel) channel.close();
                    this.channels.delete(channelId);
                    this.recvBuffers.delete(channelId);
                },

                js_get_state: (channelId) => {
                    const channel = this.channels.get(channelId);
                    if (!channel) return 3; // disconnected
                    switch (channel.readyState) {
                        case 'connecting': return 0;
                        case 'open': return 1;
                        case 'closing': return 2;
                        case 'closed': return 3;
                        default: return 4;
                    }
                },

                js_can_send: (channelId) => {
                    const channel = this.channels.get(channelId);
                    return channel &&
                           channel.readyState === 'open' &&
                           channel.bufferedAmount < 1024 * 1024;
                },

                js_recv_available: (channelId) => {
                    const queue = this.recvBuffers.get(channelId);
                    if (!queue) return 0;
                    return queue.reduce((sum, buf) => sum + buf.length, 0);
                }
            }
        };
    }
}

6.4 Data Channel Configuration

// Recommended settings for P2P messaging
const dataChannelConfig = {
    ordered: false,        // Don't wait for packet ordering (UDP-like)
    maxRetransmits: 3,     // Limited retries for reliability
    // OR
    maxPacketLifeTime: 1000, // Max 1 second retry window
};

// For file transfer (needs reliability)
const reliableChannelConfig = {
    ordered: true,         // Maintain order
    // No maxRetransmits = unlimited (TCP-like)
};

7. Event-Driven I/O Model

7.1 Problem Statement

The current implementation uses blocking I/O patterns:

// Current: Blocking retry loop (src/network/network_manager.zig:690-753)
while (header_sent < 4 and retries < max_retries) {
    const n = socket.send(header[header_sent..]) catch |err| {
        if (err == Error.ConnectionTimeout) {
            std.Thread.sleep(retry_delay_ms * ns_per_ms);  // BLOCKS!
            retries += 1;
            continue;
        }
        return err;
    };
    header_sent += n;
}

WASM cannot:

  • Block the main thread (only one thread exists)
  • Use Thread.sleep()
  • Wait on poll() or select()

7.2 Event Queue Design

File: src/platform/event_queue.zig

const std = @import("std");

pub const Event = union(enum) {
    /// Data available to read from transport
    transport_readable: struct {
        transport_id: u32,
    },

    /// Transport can accept more data
    transport_writable: struct {
        transport_id: u32,
    },

    /// Transport state changed
    transport_state: struct {
        transport_id: u32,
        new_state: Transport.State,
    },

    /// Timer fired
    timer: struct {
        timer_id: u32,
        context: ?*anyopaque,
    },

    /// File I/O completed
    file_io_complete: struct {
        operation_id: u32,
        result: anyerror!usize,
    },
};

pub const EventQueue = struct {
    allocator: std.mem.Allocator,
    events: std.ArrayList(Event),
    handlers: std.AutoHashMap(u32, EventHandler),

    pub const EventHandler = struct {
        callback: *const fn (event: Event, context: ?*anyopaque) void,
        context: ?*anyopaque,
    };

    pub fn init(allocator: std.mem.Allocator) EventQueue {
        return .{
            .allocator = allocator,
            .events = std.ArrayList(Event).init(allocator),
            .handlers = std.AutoHashMap(u32, EventHandler).init(allocator),
        };
    }

    /// Push event to queue (called from JS callbacks)
    pub fn push(self: *EventQueue, event: Event) !void {
        try self.events.append(event);
    }

    /// Process all pending events (called from main loop)
    pub fn processAll(self: *EventQueue) void {
        while (self.events.items.len > 0) {
            const event = self.events.orderedRemove(0);
            self.dispatch(event);
        }
    }

    /// Process up to N events (for cooperative multitasking)
    pub fn processN(self: *EventQueue, max_events: usize) usize {
        var processed: usize = 0;
        while (processed < max_events and self.events.items.len > 0) {
            const event = self.events.orderedRemove(0);
            self.dispatch(event);
            processed += 1;
        }
        return processed;
    }

    fn dispatch(self: *EventQueue, event: Event) void {
        const id = switch (event) {
            .transport_readable => |e| e.transport_id,
            .transport_writable => |e| e.transport_id,
            .transport_state => |e| e.transport_id,
            .timer => |e| e.timer_id,
            .file_io_complete => |e| e.operation_id,
        };

        if (self.handlers.get(id)) |handler| {
            handler.callback(event, handler.context);
        }
    }
};

7.3 Refactored Network Manager

// New: Event-driven send (no blocking)
pub fn queueSend(self: *NetworkManager, peer_id: PeerId, data: []const u8) !void {
    const conn = self.connections.get(peer_id) orelse return error.ConnectionNotFound;

    // Queue data for sending
    try conn.send_queue.append(self.allocator, .{
        .data = try self.allocator.dupe(u8, data),
        .offset = 0,
    });

    // Try to send immediately if possible
    self.drainSendQueue(peer_id);
}

pub fn drainSendQueue(self: *NetworkManager, peer_id: PeerId) void {
    const conn = self.connections.get(peer_id) orelse return;

    while (conn.send_queue.items.len > 0) {
        const entry = &conn.send_queue.items[0];
        const remaining = entry.data[entry.offset..];

        const sent = conn.transport.send(remaining) catch |err| {
            if (err == error.WouldBlock) {
                // Will retry when transport becomes writable
                return;
            }
            // Handle other errors
            self.handleSendError(peer_id, err);
            return;
        };

        entry.offset += sent;
        if (entry.offset >= entry.data.len) {
            // Entry complete, remove from queue
            self.allocator.free(entry.data);
            _ = conn.send_queue.orderedRemove(0);
        }
    }
}

// Called when transport signals writable
pub fn onTransportWritable(self: *NetworkManager, transport_id: u32) void {
    if (self.transport_to_peer.get(transport_id)) |peer_id| {
        self.drainSendQueue(peer_id);
    }
}

7.4 Main Loop Comparison

// Native: Can use blocking poll()
pub fn runNative(self: *P2P) !void {
    while (self.running) {
        // Block until I/O ready or timeout
        const ready = try posix.poll(self.poll_fds, 100);
        if (ready > 0) {
            self.processIO();
        }
        self.processTasks();
    }
}

// WASM: Must be non-blocking, called from JS event loop
pub fn runWasm(self: *P2P) void {
    // Process available events (non-blocking)
    _ = self.event_queue.processN(100);

    // Drain send queues
    for (self.connections.keys()) |peer_id| {
        self.network_manager.drainSendQueue(peer_id);
    }

    // Process pending tasks
    self.processTasks();

    // Return control to JS - will be called again via requestAnimationFrame
}

// Exported for JS to call
export fn wasm_tick() void {
    global_p2p.runWasm();
}

8. File System Abstraction

8.1 FileSystem Interface

File: src/platform/filesystem.zig

const std = @import("std");

pub const FileSystem = struct {
    ptr: *anyopaque,
    vtable: *const VTable,

    pub const VTable = struct {
        open: *const fn (
            ptr: *anyopaque,
            path: []const u8,
            flags: OpenFlags,
        ) Error!FileHandle,

        read: *const fn (
            ptr: *anyopaque,
            handle: FileHandle,
            buffer: []u8,
        ) Error!usize,

        write: *const fn (
            ptr: *anyopaque,
            handle: FileHandle,
            data: []const u8,
        ) Error!usize,

        close: *const fn (ptr: *anyopaque, handle: FileHandle) void,

        stat: *const fn (ptr: *anyopaque, path: []const u8) Error!Stat,

        delete: *const fn (ptr: *anyopaque, path: []const u8) Error!void,
    };

    pub const OpenFlags = struct {
        read: bool = true,
        write: bool = false,
        create: bool = false,
        truncate: bool = false,
    };

    pub const Stat = struct {
        size: u64,
        is_directory: bool,
        modified_time: i64,
    };

    pub const FileHandle = u32;

    pub const Error = error{
        FileNotFound,
        PermissionDenied,
        DiskFull,
        IOError,
        InvalidHandle,
    };
};

8.2 IndexedDB Implementation

File: src/platform/indexeddb_fs.zig

const std = @import("std");
const FileSystem = @import("filesystem.zig").FileSystem;

pub const IndexedDBFS = struct {
    allocator: std.mem.Allocator,
    next_handle: u32,
    open_files: std.AutoHashMap(u32, OpenFile),

    const OpenFile = struct {
        path: []const u8,
        position: u64,
        flags: FileSystem.OpenFlags,
    };

    // JavaScript interop
    extern "indexeddb" fn js_file_exists(path: [*]const u8, len: usize) bool;
    extern "indexeddb" fn js_file_size(path: [*]const u8, len: usize) i64;
    extern "indexeddb" fn js_file_read(
        path: [*]const u8,
        path_len: usize,
        offset: u64,
        buffer: [*]u8,
        buffer_len: usize,
    ) i32;
    extern "indexeddb" fn js_file_write(
        path: [*]const u8,
        path_len: usize,
        offset: u64,
        data: [*]const u8,
        data_len: usize,
    ) i32;
    extern "indexeddb" fn js_file_delete(path: [*]const u8, len: usize) bool;

    pub fn init(allocator: std.mem.Allocator) IndexedDBFS {
        return .{
            .allocator = allocator,
            .next_handle = 1,
            .open_files = std.AutoHashMap(u32, OpenFile).init(allocator),
        };
    }

    pub fn filesystem(self: *IndexedDBFS) FileSystem {
        return .{
            .ptr = self,
            .vtable = &vtable,
        };
    }

    const vtable = FileSystem.VTable{
        .open = open,
        .read = read,
        .write = write,
        .close = close,
        .stat = stat,
        .delete = delete,
    };

    fn open(ptr: *anyopaque, path: []const u8, flags: FileSystem.OpenFlags) FileSystem.Error!FileSystem.FileHandle {
        const self: *IndexedDBFS = @ptrCast(@alignCast(ptr));

        if (!flags.create and !js_file_exists(path.ptr, path.len)) {
            return error.FileNotFound;
        }

        const handle = self.next_handle;
        self.next_handle += 1;

        try self.open_files.put(handle, .{
            .path = try self.allocator.dupe(u8, path),
            .position = 0,
            .flags = flags,
        });

        return handle;
    }

    fn read(ptr: *anyopaque, handle: FileSystem.FileHandle, buffer: []u8) FileSystem.Error!usize {
        const self: *IndexedDBFS = @ptrCast(@alignCast(ptr));

        const file = self.open_files.getPtr(handle) orelse return error.InvalidHandle;

        const result = js_file_read(
            file.path.ptr,
            file.path.len,
            file.position,
            buffer.ptr,
            buffer.len,
        );

        if (result < 0) return error.IOError;

        file.position += @intCast(result);
        return @intCast(result);
    }

    fn write(ptr: *anyopaque, handle: FileSystem.FileHandle, data: []const u8) FileSystem.Error!usize {
        const self: *IndexedDBFS = @ptrCast(@alignCast(ptr));

        const file = self.open_files.getPtr(handle) orelse return error.InvalidHandle;

        if (!file.flags.write) return error.PermissionDenied;

        const result = js_file_write(
            file.path.ptr,
            file.path.len,
            file.position,
            data.ptr,
            data.len,
        );

        if (result < 0) return error.IOError;

        file.position += @intCast(result);
        return @intCast(result);
    }

    fn close(ptr: *anyopaque, handle: FileSystem.FileHandle) void {
        const self: *IndexedDBFS = @ptrCast(@alignCast(ptr));

        if (self.open_files.fetchRemove(handle)) |entry| {
            self.allocator.free(entry.value.path);
        }
    }

    fn stat(ptr: *anyopaque, path: []const u8) FileSystem.Error!FileSystem.Stat {
        _ = ptr;

        if (!js_file_exists(path.ptr, path.len)) {
            return error.FileNotFound;
        }

        const size = js_file_size(path.ptr, path.len);
        if (size < 0) return error.IOError;

        return .{
            .size = @intCast(size),
            .is_directory = false,  // IndexedDB doesn't have directories
            .modified_time = 0,     // Could add this to JS layer
        };
    }

    fn delete(ptr: *anyopaque, path: []const u8) FileSystem.Error!void {
        _ = ptr;

        if (!js_file_delete(path.ptr, path.len)) {
            return error.IOError;
        }
    }
};

8.3 JavaScript IndexedDB Layer

File: wasm/js/indexeddb-fs.js

/**
 * IndexedDB-based file system for WASM.
 * Stores files as blobs with path-based keys.
 */
class IndexedDBFileSystem {
    constructor(dbName = 'zig-p2p-files') {
        this.dbName = dbName;
        this.db = null;
        this.storeName = 'files';
    }

    async init() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(this.dbName, 1);

            request.onerror = () => reject(request.error);
            request.onsuccess = () => {
                this.db = request.result;
                resolve();
            };

            request.onupgradeneeded = (event) => {
                const db = event.target.result;
                if (!db.objectStoreNames.contains(this.storeName)) {
                    db.createObjectStore(this.storeName);
                }
            };
        });
    }

    getImports(wasmMemory) {
        return {
            indexeddb: {
                js_file_exists: (pathPtr, pathLen) => {
                    const path = this.readString(wasmMemory, pathPtr, pathLen);
                    return this.fileExistsSync(path);
                },

                js_file_size: (pathPtr, pathLen) => {
                    const path = this.readString(wasmMemory, pathPtr, pathLen);
                    return this.getFileSizeSync(path);
                },

                js_file_read: (pathPtr, pathLen, offset, bufferPtr, bufferLen) => {
                    const path = this.readString(wasmMemory, pathPtr, pathLen);
                    return this.readFileSync(
                        path,
                        offset,
                        new Uint8Array(wasmMemory.buffer, bufferPtr, bufferLen)
                    );
                },

                js_file_write: (pathPtr, pathLen, offset, dataPtr, dataLen) => {
                    const path = this.readString(wasmMemory, pathPtr, pathLen);
                    const data = new Uint8Array(wasmMemory.buffer, dataPtr, dataLen);
                    return this.writeFileSync(path, offset, data);
                },

                js_file_delete: (pathPtr, pathLen) => {
                    const path = this.readString(wasmMemory, pathPtr, pathLen);
                    return this.deleteFileSync(path);
                }
            }
        };
    }

    readString(memory, ptr, len) {
        const bytes = new Uint8Array(memory.buffer, ptr, len);
        return new TextDecoder().decode(bytes);
    }

    // Synchronous wrappers using SharedArrayBuffer + Atomics
    // OR async wrappers with callback model
    // Implementation depends on browser support

    async readFile(path, offset, length) {
        return new Promise((resolve, reject) => {
            const tx = this.db.transaction(this.storeName, 'readonly');
            const store = tx.objectStore(this.storeName);
            const request = store.get(path);

            request.onsuccess = () => {
                const blob = request.result;
                if (!blob) {
                    resolve(null);
                    return;
                }

                const slice = blob.slice(offset, offset + length);
                slice.arrayBuffer().then(buffer => {
                    resolve(new Uint8Array(buffer));
                });
            };

            request.onerror = () => reject(request.error);
        });
    }

    async writeFile(path, offset, data) {
        // Read existing blob (if any), modify, write back
        const existing = await this.readFullFile(path);

        let newData;
        if (existing) {
            newData = new Uint8Array(Math.max(existing.length, offset + data.length));
            newData.set(existing);
            newData.set(data, offset);
        } else {
            newData = new Uint8Array(offset + data.length);
            newData.set(data, offset);
        }

        return new Promise((resolve, reject) => {
            const tx = this.db.transaction(this.storeName, 'readwrite');
            const store = tx.objectStore(this.storeName);
            const blob = new Blob([newData]);
            const request = store.put(blob, path);

            request.onsuccess = () => resolve(data.length);
            request.onerror = () => reject(request.error);
        });
    }
}

9. Threading Model Adaptation

9.1 Current Threading Usage

Pattern Files WASM Strategy
std.Thread.Mutex 36 files No-op in single-threaded WASM
std.Thread.spawn() 11 files Event queue + callbacks
std.Thread.sleep() 5 files Remove (use timers instead)
std.atomic.Value 12 files Keep (works in WASM)

9.2 Mutex Abstraction

File: src/platform/sync.zig

const std = @import("std");
const builtin = @import("builtin");

pub const Mutex = if (builtin.target.isWasm())
    WasmMutex
else
    std.Thread.Mutex;

/// No-op mutex for single-threaded WASM.
/// Optionally validates lock ordering in debug builds.
pub const WasmMutex = struct {
    locked: bool = false,
    lock_order: ?u32 = null,

    pub fn lock(self: *WasmMutex) void {
        if (builtin.mode == .Debug) {
            if (self.locked) {
                @panic("WasmMutex: recursive lock detected");
            }
            self.locked = true;
        }
    }

    pub fn unlock(self: *WasmMutex) void {
        if (builtin.mode == .Debug) {
            if (!self.locked) {
                @panic("WasmMutex: unlock without lock");
            }
            self.locked = false;
        }
    }

    pub fn tryLock(self: *WasmMutex) bool {
        if (builtin.mode == .Debug) {
            if (self.locked) return false;
            self.locked = true;
        }
        return true;
    }
};

9.3 Task Queue for Background Work

File: src/platform/task_queue.zig

const std = @import("std");

/// Cooperative task queue for WASM.
/// Replaces thread pools with chunked execution.
pub const TaskQueue = struct {
    allocator: std.mem.Allocator,
    tasks: std.ArrayList(Task),
    current_task: ?*Task = null,

    pub const Task = struct {
        func: *const fn (context: *anyopaque, budget: usize) Status,
        context: *anyopaque,
        priority: Priority,
    };

    pub const Priority = enum { high, normal, low };

    pub const Status = enum {
        complete,    // Task finished
        yield,       // Task yielded, continue later
        blocked,     // Task waiting on external event
    };

    pub fn init(allocator: std.mem.Allocator) TaskQueue {
        return .{
            .allocator = allocator,
            .tasks = std.ArrayList(Task).init(allocator),
        };
    }

    /// Add task to queue
    pub fn schedule(self: *TaskQueue, task: Task) !void {
        try self.tasks.append(task);
    }

    /// Run tasks for up to `budget` iterations.
    /// Returns number of completed tasks.
    pub fn run(self: *TaskQueue, budget: usize) usize {
        var remaining = budget;
        var completed: usize = 0;

        while (remaining > 0 and self.tasks.items.len > 0) {
            const task = &self.tasks.items[0];
            const chunk = @min(remaining, 100); // Max 100 iterations per task

            const status = task.func(task.context, chunk);
            remaining -= chunk;

            switch (status) {
                .complete => {
                    _ = self.tasks.orderedRemove(0);
                    completed += 1;
                },
                .yield => {
                    // Move to end of queue for fairness
                    const t = self.tasks.orderedRemove(0);
                    self.tasks.append(t) catch {};
                },
                .blocked => {
                    // Move to end, will be re-checked later
                    const t = self.tasks.orderedRemove(0);
                    self.tasks.append(t) catch {};
                },
            }
        }

        return completed;
    }
};

9.4 Verification Pool Adaptation

// Native: Thread pool for parallel verification
pub const NativeVerificationPool = struct {
    threads: []std.Thread,
    queue: std.atomic.Queue(VerifyTask),

    pub fn verify(self: *NativeVerificationPool, data: []const u8, expected: [32]u8) void {
        self.queue.push(.{ .data = data, .expected = expected });
        // Threads pick up work automatically
    }
};

// WASM: Chunked single-threaded verification
pub const WasmVerificationPool = struct {
    task_queue: *TaskQueue,

    pub fn verify(self: *WasmVerificationPool, data: []const u8, expected: [32]u8) !void {
        try self.task_queue.schedule(.{
            .func = verifyChunked,
            .context = // ...
            .priority = .normal,
        });
    }

    fn verifyChunked(context: *anyopaque, budget: usize) TaskQueue.Status {
        const state: *VerifyState = @ptrCast(@alignCast(context));

        // Process `budget` chunks of 64KB each
        const chunk_size = 64 * 1024;
        var processed: usize = 0;

        while (processed < budget and state.offset < state.data.len) {
            const end = @min(state.offset + chunk_size, state.data.len);
            state.hasher.update(state.data[state.offset..end]);
            state.offset = end;
            processed += 1;
        }

        if (state.offset >= state.data.len) {
            const hash = state.hasher.final();
            state.callback(std.mem.eql(u8, &hash, &state.expected));
            return .complete;
        }

        return .yield;
    }
};

10. JavaScript Interop Layer

10.1 WASM Module Interface

File: wasm/js/zig-p2p.js

/**
 * Main entry point for zig-p2p in browser.
 */
class ZigP2P {
    constructor() {
        this.wasm = null;
        this.webrtc = null;
        this.fs = null;
        this.eventCallbacks = new Map();
    }

    /**
     * Initialize the P2P library.
     * @param {Object} config - Configuration options
     * @param {string} config.signalingUrl - WebSocket URL for signaling
     * @param {string} [config.wasmUrl] - URL to WASM file
     */
    async init(config) {
        // Initialize subsystems
        this.fs = new IndexedDBFileSystem();
        await this.fs.init();

        // Load WASM module
        const wasmUrl = config.wasmUrl || '/zig-p2p.wasm';
        const response = await fetch(wasmUrl);
        const wasmBytes = await response.arrayBuffer();

        // Combine all imports
        const imports = {
            ...this.getEnvImports(),
            ...this.fs.getImports(null), // Will update with memory later
        };

        const { instance } = await WebAssembly.instantiate(wasmBytes, imports);
        this.wasm = instance;

        // Initialize WebRTC with WASM instance
        this.webrtc = new WebRTCTransportManager(instance, config.signalingUrl);

        // Add WebRTC imports
        Object.assign(imports, this.webrtc.getImports());

        // Initialize WASM P2P library
        this.wasm.exports.p2p_init();

        // Start event loop
        this.startEventLoop();
    }

    getEnvImports() {
        return {
            env: {
                // Logging
                js_log: (level, msgPtr, msgLen) => {
                    const msg = this.readString(msgPtr, msgLen);
                    const levels = ['debug', 'info', 'warn', 'error'];
                    console[levels[level] || 'log'](msg);
                },

                // Time
                js_timestamp_ms: () => Date.now(),
                js_performance_now: () => performance.now(),

                // Random
                js_random_bytes: (bufferPtr, len) => {
                    const buffer = new Uint8Array(
                        this.wasm.exports.memory.buffer,
                        bufferPtr,
                        len
                    );
                    crypto.getRandomValues(buffer);
                },

                // Timers
                js_set_timeout: (callbackId, delayMs) => {
                    setTimeout(() => {
                        this.wasm.exports.on_timer(callbackId);
                    }, delayMs);
                },
            }
        };
    }

    startEventLoop() {
        const tick = () => {
            this.wasm.exports.wasm_tick();
            requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
    }

    // Public API

    /**
     * Connect to a peer.
     * @param {string} peerId - Target peer ID
     * @returns {Promise<void>}
     */
    async connect(peerId) {
        return new Promise((resolve, reject) => {
            const callbackId = this.registerCallback((success) => {
                if (success) resolve();
                else reject(new Error('Connection failed'));
            });

            const peerIdBytes = new TextEncoder().encode(peerId);
            // Copy to WASM memory and call
            const ptr = this.allocString(peerId);
            this.wasm.exports.p2p_connect(ptr, peerIdBytes.length, callbackId);
        });
    }

    /**
     * Send message to peer.
     * @param {string} peerId - Target peer ID
     * @param {Uint8Array} data - Message data
     */
    send(peerId, data) {
        const peerPtr = this.allocString(peerId);
        const dataPtr = this.allocBytes(data);
        this.wasm.exports.p2p_send(peerPtr, peerId.length, dataPtr, data.length);
    }

    /**
     * Register callback for incoming messages.
     * @param {Function} callback - Called with (peerId, data)
     */
    onMessage(callback) {
        this.eventCallbacks.set('message', callback);
    }

    /**
     * Register callback for peer connections.
     * @param {Function} callback - Called with (peerId)
     */
    onPeerConnected(callback) {
        this.eventCallbacks.set('peer_connected', callback);
    }

    // Memory management helpers

    readString(ptr, len) {
        const bytes = new Uint8Array(this.wasm.exports.memory.buffer, ptr, len);
        return new TextDecoder().decode(bytes);
    }

    allocString(str) {
        const bytes = new TextEncoder().encode(str);
        return this.allocBytes(bytes);
    }

    allocBytes(data) {
        const ptr = this.wasm.exports.alloc(data.length);
        const target = new Uint8Array(this.wasm.exports.memory.buffer, ptr, data.length);
        target.set(data);
        return ptr;
    }
}

// Export for use
window.ZigP2P = ZigP2P;
export { ZigP2P };

10.2 WASM Exports

// Exports from WASM module (src/wasm/exports.zig)

const std = @import("std");
const P2P = @import("../p2p/p2p.zig").P2P;

var global_allocator: std.heap.WasmAllocator = .{};
var global_p2p: ?*P2P = null;

/// Initialize P2P library
export fn p2p_init() void {
    global_p2p = P2P.init(.{
        // WASM-specific config
    }, global_allocator.allocator()) catch null;
}

/// Connect to peer
export fn p2p_connect(peer_id_ptr: [*]const u8, peer_id_len: usize, callback_id: u32) void {
    const peer_id = peer_id_ptr[0..peer_id_len];
    if (global_p2p) |p2p| {
        p2p.connect(peer_id, callback_id) catch {};
    }
}

/// Send message
export fn p2p_send(
    peer_id_ptr: [*]const u8,
    peer_id_len: usize,
    data_ptr: [*]const u8,
    data_len: usize,
) void {
    const peer_id = peer_id_ptr[0..peer_id_len];
    const data = data_ptr[0..data_len];
    if (global_p2p) |p2p| {
        p2p.send(peer_id, data) catch {};
    }
}

/// Main tick function (called from JS event loop)
export fn wasm_tick() void {
    if (global_p2p) |p2p| {
        p2p.runWasm();
    }
}

/// Allocate memory (for JS to copy data into)
export fn alloc(len: usize) ?[*]u8 {
    const slice = global_allocator.allocator().alloc(u8, len) catch return null;
    return slice.ptr;
}

/// Free memory
export fn free(ptr: [*]u8, len: usize) void {
    global_allocator.allocator().free(ptr[0..len]);
}

/// Called from JS when timer fires
export fn on_timer(callback_id: u32) void {
    if (global_p2p) |p2p| {
        p2p.handleTimer(callback_id);
    }
}

/// Called from JS when data available on channel
export fn on_data_available(channel_id: u32) void {
    if (global_p2p) |p2p| {
        p2p.handleDataAvailable(channel_id);
    }
}

/// Called from JS when channel closed
export fn on_channel_closed(channel_id: u32) void {
    if (global_p2p) |p2p| {
        p2p.handleChannelClosed(channel_id);
    }
}

11. Build System Changes

11.1 Build Configuration

File: build.zig (additions)

const std = @import("std");

pub fn build(b: *std.Build) void {
    // Existing native build...

    // WASM build
    const wasm_target = b.resolveTargetQuery(.{
        .cpu_arch = .wasm32,
        .os_tag = .freestanding,
        .abi = .none,
    });

    const wasm_lib = b.addExecutable(.{
        .name = "zig-p2p",
        .root_source_file = b.path("src/wasm/main.zig"),
        .target = wasm_target,
        .optimize = .ReleaseFast,
    });

    // Export required functions
    wasm_lib.export_symbol_names = &.{
        "p2p_init",
        "p2p_connect",
        "p2p_send",
        "wasm_tick",
        "alloc",
        "free",
        "on_timer",
        "on_data_available",
        "on_channel_closed",
    };

    // Don't include standard library start files
    wasm_lib.entry = .disabled;

    // Build step
    const wasm_step = b.step("wasm", "Build WASM library");
    wasm_step.dependOn(&b.addInstallArtifact(wasm_lib, .{}).step);

    // Copy JS files
    const copy_js = b.addInstallDirectory(.{
        .source_dir = b.path("wasm/js"),
        .install_dir = .prefix,
        .install_subdir = "wasm",
    });
    wasm_step.dependOn(&copy_js.step);
}

11.2 Conditional Compilation

const builtin = @import("builtin");

pub const platform = if (builtin.target.isWasm())
    @import("platform/wasm.zig")
else
    @import("platform/native.zig");

// Usage in code:
const Transport = platform.Transport;
const FileSystem = platform.FileSystem;
const Mutex = platform.Mutex;

11.3 Directory Structure

zig-p2p/
├── src/
│   ├── core/
│   │   ├── transport.zig      # Transport interface
│   │   ├── socket.zig         # (Native only)
│   │   └── ...
│   ├── platform/
│   │   ├── native.zig         # Native platform exports
│   │   ├── wasm.zig           # WASM platform exports
│   │   ├── posix_transport.zig
│   │   ├── webrtc_transport.zig
│   │   ├── native_fs.zig
│   │   ├── indexeddb_fs.zig
│   │   ├── sync.zig           # Mutex abstraction
│   │   ├── event_queue.zig
│   │   └── task_queue.zig
│   ├── wasm/
│   │   ├── main.zig           # WASM entry point
│   │   └── exports.zig        # Exported functions
│   └── ...
├── wasm/
│   └── js/
│       ├── zig-p2p.js         # Main JS interface
│       ├── webrtc-transport.js
│       └── indexeddb-fs.js
└── build.zig

12. Implementation Phases

Phase 1: Transport Abstraction (Week 1-2)

Goal: Create transport interface, implement POSIX backend, verify no regression.

Task Est. Owner Status
Define Transport interface 2d - [ ]
Implement POSIXTransport 2d - [ ]
Update Socket to use Transport 3d - [ ]
Update NetworkManager 2d - [ ]
Run existing tests 1d - [ ]

Deliverable: Native build works with new abstraction layer.

Phase 2: Event-Driven I/O (Week 2-3)

Goal: Replace blocking I/O with event-driven model.

Task Est. Owner Status
Implement EventQueue 1d - [ ]
Refactor send to async queue 2d - [ ]
Refactor receive to callbacks 2d - [ ]
Remove Thread.sleep usage 1d - [ ]
Add TaskQueue for background work 1d - [ ]

Deliverable: Native build uses event-driven I/O model.

Phase 3: WebRTC Transport (Week 3-4)

Goal: Implement browser transport layer.

Task Est. Owner Status
Implement WebRTCTransport 2d - [ ]
Create JS WebRTC glue layer 2d - [ ]
Implement signaling protocol 2d - [ ]
Basic connection test 1d - [ ]

Deliverable: Two browser tabs can establish P2P connection.

Phase 4: File System & Threading (Week 4)

Goal: Complete platform abstraction.

Task Est. Owner Status
Implement IndexedDBFS 2d - [ ]
Implement WASM Mutex 0.5d - [ ]
Adapt VerificationPool 1d - [ ]
Adapt PiecePipeline 1d - [ ]

Deliverable: File transfer works in browser.

Phase 5: Native WebRTC Support (Week 5-8)

Goal: Enable native peers to communicate with browser peers.

Task Est. Owner Status
Integrate libdatachannel build 3d - [ ]
Write Zig C bindings 5d - [ ]
Implement WebRTCTransport (native) 5d - [ ]
Implement WebRTC Direct protocol 5d - [ ]
Native-browser connection tests 3d - [ ]
Certificate/identity management 2d - [ ]

Deliverable: Native peer can establish P2P connection with browser peer.

Note: This phase is required for native↔browser interoperability. Without it, native and browser peers cannot communicate directly.

Phase 6: Integration & Polish (Week 9-10)

Goal: End-to-end testing, documentation.

Task Est. Owner Status
End-to-end browser tests 2d - [ ]
Native↔browser integration tests 2d - [ ]
Cross-browser testing 1d - [ ]
Performance profiling 1d - [ ]
Documentation 2d - [ ]

Deliverable: Production-ready WASM build with full interoperability.

Timeline Summary

Week 1-2:   Transport Abstraction
Week 2-3:   Event-Driven I/O
Week 3-4:   WASM WebRTC Transport
Week 4-5:   File System & Threading
Week 5-8:   Native WebRTC (libdatachannel)  ← NEW
Week 9-10:  Integration & Polish

Total: 10-12 weeks for full interoperability
       (5-6 weeks for browser-only, no native↔browser)

13. Testing Strategy

13.1 Test Matrix

Test Type Native WASM (Node) WASM (Browser)
Unit tests ✓ ✓ -
Integration ✓ ✓ ✓
End-to-end ✓ - ✓
Performance ✓ - ✓

13.2 Unit Tests

// Platform-agnostic tests run on both targets
test "Transport interface compliance" {
    const transport = try platform.createTestTransport();
    defer transport.close();

    try transport.send("hello");
    const received = try transport.receive(buffer);
    try testing.expectEqualStrings("hello", received);
}

13.3 Integration Tests (Browser)

// Playwright test
test('two peers can exchange messages', async ({ browser }) => {
    const pageA = await browser.newPage();
    const pageB = await browser.newPage();

    await pageA.goto('/test.html');
    await pageB.goto('/test.html');

    // Initialize P2P
    await pageA.evaluate(() => window.p2p.init({ signalingUrl: 'ws://localhost:8080' }));
    await pageB.evaluate(() => window.p2p.init({ signalingUrl: 'ws://localhost:8080' }));

    // Get peer IDs
    const idA = await pageA.evaluate(() => window.p2p.getLocalId());
    const idB = await pageB.evaluate(() => window.p2p.getLocalId());

    // Connect and send message
    await pageA.evaluate((id) => window.p2p.connect(id), idB);
    await pageA.evaluate((id) => window.p2p.send(id, 'hello'), idB);

    // Verify receipt
    const received = await pageB.evaluate(() =>
        new Promise(resolve => window.p2p.onMessage((_, data) => resolve(data)))
    );
    expect(received).toBe('hello');
});

13.4 Performance Benchmarks

Metric Measured (Native) Target (WASM)
Multi-peer throughput 497 MB/s (10 peers, localhost) 10+ MB/s
Swarm throughput 130 MB/s (9 peers, 25GB) 5+ MB/s
Connection setup <50ms (UDP), ~200ms est. (WebRTC) <500ms
Message latency <5ms <20ms
Memory per conn ~131KB (Noise buffers) ~131KB

14. Risk Assessment

14.1 Technical Risks

Risk Probability Impact Mitigation
WebRTC browser inconsistencies Medium Medium Test on Chrome, Firefox, Safari; use adapter.js
IndexedDB performance Low Medium Batch writes, use Blob storage
WASM memory limits Medium High Chunk large operations, streaming
Signaling server dependency High Medium Provide reference implementation
Noise handshake timing Low Low Crypto is pure Zig, no timing issues
libdatachannel integration Medium High Start integration early, have fallback plan
Native↔browser interop Medium High Extensive cross-platform testing

14.2 Project Risks

Risk Probability Impact Mitigation
Scope creep Medium High Strict phase boundaries
Native regression Low High Comprehensive test suite
Browser API changes Low Medium Version pinning, polyfills
libdatachannel API changes Low Medium Pin to specific version
TLS library conflicts Medium Medium Document supported configurations

14.3 Contingency Plans

  1. WebRTC issues: Fall back to WebSocket relay mode (not P2P, but functional)
  2. Performance issues: Reduce feature set in WASM build
  3. Browser compatibility: Minimum viable: Chrome only for v1
  4. libdatachannel issues: Fall back to relay server for native↔browser
  5. Native WebRTC too complex: Ship browser-only first, add native WebRTC later

15. Native-Browser Interoperability

15.1 The Problem

Native zig-p2p peers use UDP sockets. Browser peers use WebRTC DataChannels. These are fundamentally incompatible transports:

┌─────────────────┐                      ┌─────────────────┐
│  Native Peer    │         ???          │  Browser Peer   │
│                 │       Cannot         │                 │
│  UDP Socket     │◄─────Connect────────►│  WebRTC         │
│  (port 9000)    │                      │  DataChannel    │
└─────────────────┘                      └─────────────────┘
      ▲                                         ▲
      │                                         │
   POSIX                                    Browser API
   send()/recv()                            RTCDataChannel

A UDP packet cannot reach a WebRTC DataChannel directly. The protocols, framing, and connection establishment are entirely different.

15.2 How libp2p Solves This

libp2p requires native nodes to also implement WebRTC:

┌─────────────────┐                      ┌─────────────────┐
│  Native Peer    │      WebRTC          │  Browser Peer   │
│                 │◄────────────────────►│                 │
│  UDP + WebRTC   │      DataChannel     │  WebRTC         │
│  (both!)        │                      │  DataChannel    │
└─────────────────┘                      └─────────────────┘

They use WebRTC Direct which:

  • Doesn't require a signaling server for browser-to-server connections
  • Browser derives SDP offer from server's multiaddress (contains certificate hash)
  • Uses DTLS + Noise for security
  • Implementations: go-libp2p-webrtc-direct, rust-libp2p webrtc

15.3 Solutions for zig-p2p

Add WebRTC transport to native builds:

// Native peer configuration
const config = P2PConfig{
    .transports = .{
        .udp = true,      // For native-to-native (fast, existing)
        .webrtc = true,   // For browser connections (new)
    },
};

Pros:

  • True P2P between all peer types
  • No relay servers needed
  • Same protocol on both sides

Cons:

  • Significant implementation effort (see Section 16)
  • Adds binary size (~200KB)
  • External dependency (libdatachannel or similar)

Option B: Relay/Bridge Server

┌────────────┐      UDP       ┌────────────┐     WebRTC     ┌────────────┐
│   Native   │◄──────────────►│   Bridge   │◄──────────────►│  Browser   │
│   Peer     │                │   Server   │                │   Peer     │
└────────────┘                └────────────┘                └────────────┘

Pros:

  • Simpler initial implementation
  • No changes to native code

Cons:

  • Not true P2P (all traffic through bridge)
  • Single point of failure
  • Higher latency
  • Bandwidth costs for relay operator

WASM peers only communicate with other WASM peers. Separate networks.

Pros:

  • Simplest implementation

Cons:

  • Defeats the purpose of unified library
  • Two separate, incompatible networks

15.4 Recommendation

Implement Option A (Native WebRTC) for true interoperability. This is what libp2p does, and it's the only way to achieve genuine cross-platform P2P.

The additional effort (4-6 weeks) is justified by the significant increase in utility.


16. Native WebRTC via libdatachannel C Bindings

16.1 Strategy: Use C Bindings, Don't Reimplement

Decision (Feb 2026): Bind to libdatachannel's C API via Zig's @cImport.

WebRTC Data Channels require SCTP (~30K lines), DTLS (~10K lines), ICE (~5K lines), and SDP parsing. Reimplementing this is 6-10 months of work with high risk of subtle protocol bugs. Instead, we use libdatachannel — a lightweight, actively maintained C++ library with a clean C API — and call it directly from Zig.

┌─────────────────────────────────────────────────────────────┐
│                    zig-p2p Application                      │
├─────────────────────────────────────────────────────────────┤
│           Transport Abstraction (Section 5)                 │
│     ┌──────────────────┐    ┌──────────────────┐            │
│     │  POSIXTransport  │    │ WebRTCTransport  │            │
│     │  (native↔native) │    │ (native↔browser) │            │
│     │  UDP/TCP sockets │    │  @cImport rtc.h  │            │
│     └──────────────────┘    └────────┬─────────┘            │
├──────────────────────────────────────┼──────────────────────┤
│              Zig C Interop           │                      │
│              @cImport("rtc/rtc.h")   │                      │
├──────────────────────────────────────┼──────────────────────┤
│              libdatachannel          │                      │
│     ┌──────────┬──────────┬──────────┘                      │
│     │ libjuice │ usrsctp  │  GnuTLS/mbedTLS                 │
│     │  (ICE)   │  (SCTP)  │  (DTLS)                         │
│     └──────────┴──────────┴─────────────────────────────────┤
│              UDP Socket (already in zig-p2p)                │
└─────────────────────────────────────────────────────────────┘

16.2 Why libdatachannel

Criteria libdatachannel Alternatives
Language C++ with clean C API (rtc.h) Pion (Go, can't link), webrtc-rs (Rust, complex ABI)
Scope DataChannels only (what we need) Google's libwebrtc includes media (~10MB)
Size ~15K-20K lines, ~200KB binary libwebrtc: millions of lines, ~10MB
Dependencies libjuice + usrsctp + TLS lib Self-contained with sub-libraries
TLS Backend Choice: GnuTLS, mbedTLS, or OpenSSL Most lock you into OpenSSL
License MPL 2.0 (permissive, compatible) Varies
C API Complete, stable, callback-based Most require C++ or FFI wrappers
Platforms Linux, macOS, Windows, Android, iOS, FreeBSD Good cross-platform
Maintenance Active (Paul-Louis Ageneau) Varies
Zig interop @cImport works directly Rust/Go require complex bridging

16.3 libdatachannel C API Surface (What We Actually Use)

The full API has ~80 functions but we only need the DataChannel subset:

16.3.1 Lifecycle

// Global init/cleanup (call once)
void rtcPreload(void);                                   // Optional preload
void rtcCleanup(void);                                   // Cleanup at shutdown
void rtcInitLogger(rtcLogLevel level, rtcLogCallbackFunc cb);  // Wire to core.log

// PeerConnection lifecycle
int  rtcCreatePeerConnection(const rtcConfiguration *config);  // Returns pc ID
int  rtcClosePeerConnection(int pc);
int  rtcDeletePeerConnection(int pc);

// DataChannel lifecycle
int  rtcCreateDataChannel(int pc, const char *label);           // Returns dc ID
int  rtcCreateDataChannelEx(int pc, const char *label, const rtcDataChannelInit *init);
int  rtcDeleteDataChannel(int dc);
int  rtcClose(int id);        // Close any channel/track/ws
int  rtcDelete(int id);       // Delete any channel/track/ws

16.3.2 Signaling (SDP/ICE Exchange)

// SDP exchange
int  rtcSetLocalDescription(int pc, const char *type);         // "offer" or "answer"
int  rtcSetRemoteDescription(int pc, const char *sdp, const char *type);
int  rtcGetLocalDescription(int pc, char *buffer, int size);   // Get generated SDP
int  rtcGetRemoteDescription(int pc, char *buffer, int size);

// ICE candidates
int  rtcAddRemoteCandidate(int pc, const char *cand, const char *mid);
int  rtcGetLocalAddress(int pc, char *buffer, int size);
int  rtcGetRemoteAddress(int pc, char *buffer, int size);

16.3.3 Data Transfer

// Send/receive
int  rtcSendMessage(int id, const char *data, int size);       // Returns bytes or error
int  rtcReceiveMessage(int id, char *buffer, int *size);       // Non-blocking receive

// State query
bool rtcIsOpen(int id);
bool rtcIsClosed(int id);
int  rtcMaxMessageSize(int id);
int  rtcGetBufferedAmount(int id);
int  rtcGetAvailableAmount(int id);

16.3.4 Callbacks (Critical for Zig Integration)

// User data pointer (how we pass Zig context to C callbacks)
void  rtcSetUserPointer(int id, void *ptr);
void *rtcGetUserPointer(int id);

// Connection state callbacks
int rtcSetLocalDescriptionCallback(int pc, rtcDescriptionCallbackFunc cb);
int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb);
int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb);
int rtcSetIceStateChangeCallback(int pc, rtcIceStateChangeCallbackFunc cb);
int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb);

// DataChannel callbacks
int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb);
int rtcSetOpenCallback(int id, rtcOpenCallbackFunc cb);
int rtcSetClosedCallback(int id, rtcClosedCallbackFunc cb);
int rtcSetErrorCallback(int id, rtcErrorCallbackFunc cb);
int rtcSetMessageCallback(int id, rtcMessageCallbackFunc cb);

// Flow control
int rtcSetBufferedAmountLowThreshold(int id, int amount);
int rtcSetBufferedAmountLowCallback(int id, rtcBufferedAmountLowCallbackFunc cb);
int rtcSetAvailableCallback(int id, rtcAvailableCallbackFunc cb);

16.3.5 Configuration Structures

typedef struct {
    const char **iceServers;         // STUN/TURN server URLs
    int iceServersCount;
    const char *proxyServer;         // Optional SOCKS5 proxy
    const char *bindAddress;         // Local bind address
    rtcCertificateType certificateType;  // Default, ECDSA, or RSA
    rtcTransportPolicy iceTransportPolicy;  // All or Relay
    bool enableIceTcp;               // ICE over TCP
    bool enableIceUdpMux;            // Multiplex ICE on single port
    bool disableAutoNegotiation;     // Manual SDP control
    bool forceMediaTransport;        // Force DTLS even without media
    uint16_t portRangeBegin;         // Port range for allocation
    uint16_t portRangeEnd;
    int mtu;                         // Max transmission unit
    int maxMessageSize;              // Max DataChannel message size
} rtcConfiguration;

typedef struct {
    bool unordered;                  // false = TCP-like, true = UDP-like
    bool unreliable;                 // false = reliable, true = unreliable
    unsigned int maxPacketLifeTime;  // Max ms for retransmit (if unreliable)
    unsigned int maxRetransmits;     // Max retransmit count (if unreliable)
} rtcReliability;

typedef struct {
    rtcReliability reliability;
    const char *protocol;            // Sub-protocol
    bool negotiated;                 // Pre-negotiated channel
    bool manualStream;               // Manual stream ID assignment
    uint16_t stream;                 // Stream ID (if manual)
} rtcDataChannelInit;

16.4 Zig Binding Implementation

16.4.1 C Import and Type Mapping

File: src/platform/webrtc_native.zig

const std = @import("std");
const Transport = @import("../core/transport.zig").Transport;

const rtc = @cImport({
    @cInclude("rtc/rtc.h");
});

/// Maps libdatachannel integer IDs to Zig-managed state.
/// libdatachannel uses integer handles (like file descriptors) for
/// PeerConnections and DataChannels. We track them in a HashMap.
const ChannelState = struct {
    dc_id: c_int,                      // libdatachannel DataChannel ID
    pc_id: c_int,                      // libdatachannel PeerConnection ID
    state: Transport.State,
    recv_queue: std.fifo.LinearFifo(u8, .Dynamic),  // Incoming data buffer
    allocator: std.mem.Allocator,

    // Signaling data (captured by callbacks, consumed by poll loop)
    local_sdp: ?[]const u8 = null,
    local_candidates: std.ArrayList([]const u8),
    gathering_complete: bool = false,
};

16.4.2 Callback Bridge (C → Zig)

The trickiest part: libdatachannel callbacks are C function pointers with a void *ptr user data. We use rtcSetUserPointer to stash a pointer to our Zig struct, then recover it in each callback.

/// Called by libdatachannel when local SDP description is generated.
/// This is a C-ABI callback — must be `callconv(.c)`.
fn onLocalDescription(pc: c_int, sdp: [*c]const u8, sdp_type: [*c]const u8, ptr: ?*anyopaque) callconv(.c) void {
    _ = sdp_type;
    const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return));

    // Copy SDP into Zig-managed memory (libdatachannel frees its copy after callback returns)
    const sdp_slice = std.mem.span(sdp);
    state.local_sdp = state.allocator.dupe(u8, sdp_slice) catch return;
}

/// Called when a local ICE candidate is generated.
fn onLocalCandidate(pc: c_int, cand: [*c]const u8, mid: [*c]const u8, ptr: ?*anyopaque) callconv(.c) void {
    _ = mid;
    const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return));

    const cand_slice = std.mem.span(cand);
    const duped = state.allocator.dupe(u8, cand_slice) catch return;
    state.local_candidates.append(duped) catch {
        state.allocator.free(duped);
    };
}

/// Called when PeerConnection state changes.
fn onStateChange(pc: c_int, rtc_state: rtc.rtcState, ptr: ?*anyopaque) callconv(.c) void {
    const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
    state.state = switch (rtc_state) {
        rtc.RTC_NEW, rtc.RTC_CONNECTING => .connecting,
        rtc.RTC_CONNECTED => .connected,
        rtc.RTC_DISCONNECTED, rtc.RTC_CLOSED => .disconnected,
        rtc.RTC_FAILED => .failed,
        else => .failed,
    };
}

/// Called when ICE gathering state changes.
fn onGatheringStateChange(pc: c_int, rtc_state: rtc.rtcGatheringState, ptr: ?*anyopaque) callconv(.c) void {
    const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
    if (rtc_state == rtc.RTC_GATHERING_COMPLETE) {
        state.gathering_complete = true;
    }
}

/// Called when a DataChannel message arrives.
fn onMessage(id: c_int, message: [*c]const u8, size: c_int, ptr: ?*anyopaque) callconv(.c) void {
    const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
    if (size < 0) return;  // size < 0 means string message (not binary)

    const data = message[0..@intCast(size)];
    state.recv_queue.write(data) catch return;  // Drop if buffer full
}

/// Called when DataChannel opens.
fn onOpen(id: c_int, ptr: ?*anyopaque) callconv(.c) void {
    const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
    state.state = .connected;
}

/// Called when DataChannel closes.
fn onClosed(id: c_int, ptr: ?*anyopaque) callconv(.c) void {
    const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
    state.state = .disconnected;
}

16.4.3 WebRTCTransport (Native) — Full Implementation

pub const NativeWebRTCTransport = struct {
    channels: std.AutoHashMap(u32, *ChannelState),
    allocator: std.mem.Allocator,
    next_id: u32 = 1,
    ice_servers: []const []const u8,

    pub fn init(allocator: std.mem.Allocator, ice_servers: []const []const u8) NativeWebRTCTransport {
        // Initialize libdatachannel (once, globally)
        rtc.rtcInitLogger(rtc.RTC_LOG_WARNING, logCallback);

        return .{
            .channels = std.AutoHashMap(u32, *ChannelState).init(allocator),
            .allocator = allocator,
            .ice_servers = ice_servers,
        };
    }

    pub fn deinit(self: *NativeWebRTCTransport) void {
        var it = self.channels.valueIterator();
        while (it.next()) |state_ptr| {
            const state = state_ptr.*;
            rtc.rtcDeleteDataChannel(state.dc_id);
            rtc.rtcDeletePeerConnection(state.pc_id);
            state.recv_queue.deinit();
            state.local_candidates.deinit();
            if (state.local_sdp) |sdp| self.allocator.free(sdp);
            self.allocator.destroy(state);
        }
        self.channels.deinit();
        rtc.rtcCleanup();
    }

    /// Create an outbound WebRTC connection (as offerer).
    /// Returns a channel ID. The caller must exchange SDP/ICE via signaling.
    pub fn createOffer(self: *NativeWebRTCTransport) !struct { channel_id: u32, state: *ChannelState } {
        // Build config with ICE servers
        var ice_server_ptrs: [8][*c]const u8 = undefined;
        const count = @min(self.ice_servers.len, 8);
        for (0..count) |i| {
            ice_server_ptrs[i] = self.ice_servers[i].ptr;
        }

        var config = std.mem.zeroes(rtc.rtcConfiguration);
        config.iceServers = &ice_server_ptrs;
        config.iceServersCount = @intCast(count);

        // Create PeerConnection
        const pc = rtc.rtcCreatePeerConnection(&config);
        if (pc < 0) return error.TransportError;

        // Allocate Zig state
        const state = try self.allocator.create(ChannelState);
        state.* = .{
            .dc_id = -1,
            .pc_id = pc,
            .state = .connecting,
            .recv_queue = std.fifo.LinearFifo(u8, .Dynamic).init(self.allocator),
            .allocator = self.allocator,
            .local_candidates = std.ArrayList([]const u8).init(self.allocator),
        };

        // Wire callbacks with user pointer
        rtc.rtcSetUserPointer(pc, state);
        _ = rtc.rtcSetLocalDescriptionCallback(pc, onLocalDescription);
        _ = rtc.rtcSetLocalCandidateCallback(pc, onLocalCandidate);
        _ = rtc.rtcSetStateChangeCallback(pc, onStateChange);
        _ = rtc.rtcSetGatheringStateChangeCallback(pc, onGatheringStateChange);

        // Create DataChannel (triggers SDP offer generation)
        const dc_init = rtc.rtcDataChannelInit{
            .reliability = .{
                .unordered = false,  // Reliable, ordered (TCP-like)
                .unreliable = false,
                .maxPacketLifeTime = 0,
                .maxRetransmits = 0,
            },
            .protocol = "zig-p2p",
            .negotiated = false,
            .manualStream = false,
            .stream = 0,
        };

        const dc = rtc.rtcCreateDataChannelEx(pc, "p2p-data", &dc_init);
        if (dc < 0) {
            rtc.rtcDeletePeerConnection(pc);
            self.allocator.destroy(state);
            return error.TransportError;
        }
        state.dc_id = dc;

        // Wire DataChannel callbacks
        rtc.rtcSetUserPointer(dc, state);
        _ = rtc.rtcSetOpenCallback(dc, onOpen);
        _ = rtc.rtcSetClosedCallback(dc, onClosed);
        _ = rtc.rtcSetMessageCallback(dc, onMessage);

        const channel_id = self.next_id;
        self.next_id += 1;
        try self.channels.put(channel_id, state);

        return .{ .channel_id = channel_id, .state = state };
    }

    /// Accept an inbound WebRTC connection (as answerer).
    /// Called when we receive an SDP offer via signaling.
    pub fn acceptOffer(self: *NativeWebRTCTransport, remote_sdp: []const u8) !struct { channel_id: u32, state: *ChannelState } {
        var config = std.mem.zeroes(rtc.rtcConfiguration);
        // ... (same ICE server setup as createOffer)

        const pc = rtc.rtcCreatePeerConnection(&config);
        if (pc < 0) return error.TransportError;

        const state = try self.allocator.create(ChannelState);
        state.* = .{
            .dc_id = -1,
            .pc_id = pc,
            .state = .connecting,
            .recv_queue = std.fifo.LinearFifo(u8, .Dynamic).init(self.allocator),
            .allocator = self.allocator,
            .local_candidates = std.ArrayList([]const u8).init(self.allocator),
        };

        rtc.rtcSetUserPointer(pc, state);
        _ = rtc.rtcSetLocalDescriptionCallback(pc, onLocalDescription);
        _ = rtc.rtcSetLocalCandidateCallback(pc, onLocalCandidate);
        _ = rtc.rtcSetStateChangeCallback(pc, onStateChange);
        _ = rtc.rtcSetGatheringStateChangeCallback(pc, onGatheringStateChange);

        // Callback to capture incoming DataChannel from remote
        _ = rtc.rtcSetDataChannelCallback(pc, struct {
            fn callback(pc_id: c_int, dc: c_int, ptr: ?*anyopaque) callconv(.c) void {
                const s: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
                s.dc_id = dc;
                rtc.rtcSetUserPointer(dc, s);
                _ = rtc.rtcSetOpenCallback(dc, onOpen);
                _ = rtc.rtcSetClosedCallback(dc, onClosed);
                _ = rtc.rtcSetMessageCallback(dc, onMessage);
            }
        }.callback);

        // Apply remote offer (triggers answer generation)
        const sdp_z = try self.allocator.dupeZ(u8, remote_sdp);
        defer self.allocator.free(sdp_z);
        if (rtc.rtcSetRemoteDescription(pc, sdp_z.ptr, "offer") < 0) {
            rtc.rtcDeletePeerConnection(pc);
            self.allocator.destroy(state);
            return error.TransportError;
        }

        const channel_id = self.next_id;
        self.next_id += 1;
        try self.channels.put(channel_id, state);

        return .{ .channel_id = channel_id, .state = state };
    }

    /// Add remote ICE candidate (received via signaling).
    pub fn addRemoteCandidate(self: *NativeWebRTCTransport, channel_id: u32, candidate: []const u8) !void {
        const state = self.channels.get(channel_id) orelse return error.InvalidState;
        const cand_z = try self.allocator.dupeZ(u8, candidate);
        defer self.allocator.free(cand_z);
        _ = rtc.rtcAddRemoteCandidate(state.pc_id, cand_z.ptr, "0");
    }

    /// Conform to Transport interface — send data on DataChannel.
    pub fn send(self: *NativeWebRTCTransport, channel_id: u32, data: []const u8) Transport.Error!usize {
        const state = self.channels.get(channel_id) orelse return error.InvalidState;
        if (state.state != .connected) return error.InvalidState;

        const result = rtc.rtcSendMessage(state.dc_id, data.ptr, @intCast(data.len));
        if (result < 0) {
            return switch (result) {
                -1 => error.ConnectionClosed,
                else => error.TransportError,
            };
        }
        return data.len;
    }

    /// Conform to Transport interface — receive data from DataChannel.
    pub fn receive(self: *NativeWebRTCTransport, channel_id: u32, buffer: []u8) Transport.Error!usize {
        const state = self.channels.get(channel_id) orelse return error.InvalidState;
        const n = state.recv_queue.read(buffer);
        if (n == 0) return error.WouldBlock;
        return n;
    }

    /// Get local SDP (after offer/answer generation).
    pub fn getLocalSdp(self: *NativeWebRTCTransport, channel_id: u32) ?[]const u8 {
        const state = self.channels.get(channel_id) orelse return null;
        return state.local_sdp;
    }

    /// Get pending local ICE candidates.
    pub fn drainLocalCandidates(self: *NativeWebRTCTransport, channel_id: u32) ?[][]const u8 {
        const state = self.channels.get(channel_id) orelse return null;
        if (state.local_candidates.items.len == 0) return null;
        const items = state.local_candidates.toOwnedSlice() catch return null;
        return items;
    }

    fn logCallback(level: rtc.rtcLogLevel, message: [*c]const u8) callconv(.c) void {
        const msg = std.mem.span(message);
        switch (level) {
            rtc.RTC_LOG_ERROR => core.log.err("{s}", .{msg}),
            rtc.RTC_LOG_WARNING => core.log.warn("{s}", .{msg}),
            rtc.RTC_LOG_INFO => core.log.info("{s}", .{msg}),
            else => core.log.debug("{s}", .{msg}),
        }
    }
};

16.5 Signaling via DHT (No Separate Server)

Key insight: We already have a DHT with dhtStore/dhtFindValue. We can use it as the signaling transport for WebRTC, eliminating the need for a separate WebSocket signaling server.

16.5.1 Signaling Flow Using DHT

Native Peer (Alice)                    DHT Network                    Browser Peer (Bob)
      │                                    │                                 │
      │  1. dhtStore(meeting_point,        │                                 │
      │     {type:"offer", sdp:...})       │                                 │
      │───────────────────────────────────►│                                 │
      │                                    │                                 │
      │                                    │  2. dhtFindValue(meeting_point) │
      │                                    │◄────────────────────────────────│
      │                                    │                                 │
      │                                    │  3. Return offer                │
      │                                    │────────────────────────────────►│
      │                                    │                                 │
      │                                    │  4. dhtStore(meeting_point,     │
      │                                    │     {type:"answer", sdp:...})   │
      │                                    │◄────────────────────────────────│
      │                                    │                                 │
      │  5. dhtFindValue(meeting_point)    │                                 │
      │───────────────────────────────────►│                                 │
      │                                    │                                 │
      │  6. Return answer                  │                                 │
      │◄───────────────────────────────────│                                 │
      │                                    │                                 │
      │        7. WebRTC DataChannel established (P2P direct)                │
      │◄────────────────────────────────────────────────────────────────────►│

16.5.2 Meeting Point Computation

Reuse the same MWP meeting point derivation — deterministic from both peers' public keys:

/// Compute DHT key for WebRTC signaling between two peers.
/// Same as MWP: SHA-256(sorted(pubkey_a, pubkey_b)).
fn computeSignalingKey(pubkey_a: [32]u8, pubkey_b: [32]u8) [32]u8 {
    var hasher = std.crypto.hash.sha2.Sha256.init(.{});
    // Sort keys for order-independence
    if (std.mem.order(u8, &pubkey_a, &pubkey_b) == .lt) {
        hasher.update(&pubkey_a);
        hasher.update(&pubkey_b);
    } else {
        hasher.update(&pubkey_b);
        hasher.update(&pubkey_a);
    }
    return hasher.finalResult();
}

16.5.3 Signaling Message Format

const SignalingMessage = struct {
    msg_type: enum { offer, answer, ice_candidate },
    from_pubkey: [32]u8,
    sdp: ?[]const u8,          // For offer/answer
    candidate: ?[]const u8,    // For ICE candidate
    timestamp: i64,
    signature: [64]u8,         // Ed25519 signature over message
};

This approach means:

  • No WebSocket signaling server needed
  • SDP exchange happens through the same DHT used for peer discovery
  • ICE candidates trickle through DHT publications
  • MWP meeting point computation is reused
  • Ed25519 signatures prevent spoofing

16.5.4 Fallback: WebSocket Signaling Server

For environments where DHT is unavailable (e.g., first browser peer with no native bootstrap):

// Minimal signaling server — ~30 lines
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const peers = new Map();

wss.on('connection', (ws) => {
    ws.on('message', (data) => {
        const msg = JSON.parse(data);
        if (msg.type === 'register') {
            peers.set(msg.peerId, ws);
            ws.peerId = msg.peerId;
        } else if (msg.to && peers.has(msg.to)) {
            msg.from = ws.peerId;
            peers.get(msg.to).send(JSON.stringify(msg));
        }
    });
    ws.on('close', () => { if (ws.peerId) peers.delete(ws.peerId); });
});

16.6 Build System Integration

16.6.1 Option A: System Library (Simplest)

// build.zig — link against system-installed libdatachannel
if (options.enable_webrtc) {
    exe.linkSystemLibrary("datachannel");
    exe.linkLibC();
    exe.addIncludePath(.{ .cwd_relative = "/usr/local/include" }); // or pkg-config
}

Install on macOS: brew install libdatachannel Install on Linux: apt install libdatachannel-dev or build from source.

// build.zig — build libdatachannel from source as a Zig build step
const webrtc_dep = b.dependency("libdatachannel", .{
    .target = target,
    .optimize = optimize,
});

// libdatachannel's build.zig.zon would wrap its CMake build
exe.linkLibrary(webrtc_dep.artifact("datachannel"));
exe.linkLibC();
// build.zig.zon
.dependencies = .{
    .libdatachannel = .{
        .url = "https://github.com/user/libdatachannel-zig-pkg/archive/v0.21.0.tar.gz",
        .hash = "...",
    },
},

16.6.3 Option C: Compile C Sources Directly (Most Control)

Since libdatachannel uses CMake, we'd create a Zig build wrapper:

// build.zig — compile libdatachannel C/C++ sources directly
const libdc = b.addStaticLibrary(.{
    .name = "datachannel",
    .target = target,
    .optimize = optimize,
});

// Add libjuice sources (ICE)
libdc.addCSourceFiles(.{
    .root = b.path("deps/libjuice/src"),
    .files = &.{ "agent.c", "conn.c", "ice.c", "stun.c", "turn.c", "udp.c", ... },
    .flags = &.{ "-std=c11", "-DJUICE_STATIC" },
});

// Add usrsctp sources (SCTP)
libdc.addCSourceFiles(.{
    .root = b.path("deps/usrsctp/usrsctplib"),
    .files = &.{ "netinet/sctp_asconf.c", "netinet/sctp_auth.c", ... },
    .flags = &.{ "-std=c11", "-DSCTP_SIMPLE_ALLOCATOR" },
});

// Add libdatachannel C++ sources
libdc.addCSourceFiles(.{
    .root = b.path("deps/libdatachannel/src"),
    .files = &.{ "peerconnection.cpp", "datachannel.cpp", "capi.cpp", ... },
    .flags = &.{ "-std=c++17", "-fno-exceptions" },
});

// Link TLS backend
if (target.os_tag == .macos) {
    libdc.linkFramework("Security");  // Use Apple's TLS
} else {
    libdc.linkSystemLibrary("gnutls"); // Or mbedtls
}

exe.linkLibrary(libdc);

Recommendation: Start with Option A (system library) for development, move to Option C for release builds.

16.6.4 Conditional Compilation

// src/platform/native.zig
const builtin = @import("builtin");

pub const Transport = @import("../core/transport.zig").Transport;

pub const has_webrtc = @hasDecl(@This(), "webrtc_native");

// Only import WebRTC when built with -Denable-webrtc=true
pub const webrtc_native = if (builtin.os.tag != .freestanding)
    @import("webrtc_native.zig")
else
    void;
// P2P config
pub const P2PConfig = struct {
    // ... existing fields ...
    transports: struct {
        udp: bool = true,       // Native-to-native (default)
        tcp: bool = true,       // Native-to-native
        webrtc: bool = false,   // For browser interop (opt-in)
    } = .{},
};

16.7 Security: Noise Over WebRTC DataChannel

WebRTC already provides DTLS encryption, but we layer Noise on top for two reasons:

  1. Uniform identity model: Same Ed25519 keys authenticate all connections (UDP and WebRTC)
  2. Wire envelope compatibility: Same replay protection applies to all transports
┌──────────────────────────────────────────┐
│     zig-p2p wire envelope                │  Same format for all transports
│  [app_id][salt][timestamp][payload]      │
├──────────────────────────────────────────┤
│     Noise_XX encryption                  │  Same Ed25519 identity keys
├──────────────────────────────────────────┤
│     WebRTC DataChannel (SCTP)            │  Reliable delivery
├──────────────────────────────────────────┤
│     DTLS 1.2 (libdatachannel)            │  Transport encryption (redundant but free)
├──────────────────────────────────────────┤
│     ICE + STUN (libjuice)                │  NAT traversal
├──────────────────────────────────────────┤
│     UDP                                  │
└──────────────────────────────────────────┘

The Noise layer runs identically whether the underlying transport is UDP socket or WebRTC DataChannel — this is the whole point of the Transport abstraction in Section 5.

16.8 Implementation Plan

Phase 5a: Build System + Raw Bindings (3 days)

Task Details
Install libdatachannel Homebrew/apt, verify C headers accessible
Create src/platform/webrtc_native.zig @cImport("rtc/rtc.h"), verify types compile
Add build flag -Denable-webrtc=true conditional in build.zig
Smoke test Call rtcPreload() + rtcCleanup() from Zig, verify linking

Deliverable: zig build -Denable-webrtc=true compiles and links.

Phase 5b: Callback Bridge + Transport Impl (1 week)

Task Details
Implement C→Zig callbacks All 8 callbacks with callconv(.c) and user pointer recovery
Implement NativeWebRTCTransport createOffer(), acceptOffer(), send(), receive()
Unit test: loopback Two NativeWebRTCTransport instances, exchange SDP in-memory, send/receive data
Conform to Transport vtable Wire into existing Transport interface from Section 5

Deliverable: Two native peers connect via WebRTC DataChannel on localhost.

Phase 5c: Signaling via DHT (1 week)

Task Details
Define SignalingMessage format Serialization, Ed25519 signing
Implement DHT-based signaling dhtStore/dhtFindValue for SDP exchange
Reuse MWP meeting point Same computeSignalingKey() derivation
ICE candidate trickle via DHT Periodic dhtStore of new candidates
Integration test Native peer creates offer, stores in DHT, second peer finds and answers

Deliverable: Two native peers establish WebRTC connection using DHT for signaling.

Phase 5d: Browser↔Native Testing (1 week)

Task Details
WASM peer creates offer via JS WebRTC Browser-side, existing code from Section 6
Native peer accepts via libdatachannel Cross-transport connection
Noise handshake over DataChannel Verify same identity/auth as UDP connections
File transfer over WebRTC Piece-based transfer works through DataChannel
Fallback WebSocket signaling For first-boot browser with no DHT peers

Deliverable: Browser tab connects to native peer and transfers a file.

Phase 5e: Integration + Polish (1 week)

Task Details
Auto-transport selection Native-to-native: UDP. Native-to-browser: WebRTC.
Connection upgrade If peer supports both, prefer UDP
Error handling Timeouts, ICE failures, TURN fallback
Memory cleanup Verify no leaks (libdatachannel cleanup + Zig dealloc)
CI: add -Denable-webrtc build Ensure it doesn't break non-WebRTC builds

Deliverable: Production-ready WebRTC transport, opt-in via build flag.

16.9 What We Don't Need From libdatachannel

The library has ~80 C API functions. We use ~25 of them. Explicitly excluded:

Feature Why Skip
Media tracks (rtcAddTrack, packetizers) No audio/video streaming — data channels only
WebSocket client/server (rtcCreateWebSocket) We have our own signaling via DHT
SCTP settings tuning (rtcSetSctpSettings) Defaults are fine for data channels
Track interceptors, RTP timestamps Media-only features

This keeps the integration surface small and the mental model simple.

16.10 Risk Assessment

Risk Probability Impact Mitigation
libdatachannel C API breaks between versions Low Medium Pin to specific release, vendored build
Callback threading: libdatachannel calls from internal thread Medium High Callbacks push to thread-safe queue, consumed in update()
TLS library conflicts with Zig's stdlib crypto Low Low libdatachannel TLS is isolated to DTLS layer
Binary size increase Low Low ~200KB — acceptable
Build complexity on CI Medium Medium Start with system library, document install steps

16.11 Updated Timeline Summary

Phase Duration Cumulative
1. Transport Abstraction 2 weeks 2 weeks
2. Event-Driven I/O 1.5 weeks 3.5 weeks
3. WASM WebRTC Transport (browser) 1.5 weeks 5 weeks
4. File System & Threading 1 week 6 weeks
5. Native WebRTC (libdatachannel C bindings) 4 weeks 10 weeks
6. Integration & Polish 2 weeks 12 weeks

Total with full interoperability: 10-12 weeks Browser-only (no native↔browser): 6 weeks


17. Mobile and IoT Platform Support

17.1 Overview

With native WebRTC support via libdatachannel, zig-p2p achieves universal interoperability across all platforms - desktop, mobile, IoT, and browsers can all communicate seamlessly.

17.2 Platform Support Matrix

Zig Cross-Compilation Targets

Platform Target Triple Zig Support zig-p2p Status
Linux x86_64 x86_64-linux-gnu Tier 1 ✅ Ready
Linux ARM64 aarch64-linux-gnu Tier 1 ✅ Ready
Linux ARM32 arm-linux-gnueabihf Tier 2 ✅ Ready
macOS x86_64 x86_64-macos Tier 1 ✅ Ready
macOS ARM64 aarch64-macos Tier 1 ✅ Ready
Windows x86_64 x86_64-windows-gnu Tier 1 ✅ Ready
Android ARM64 aarch64-linux-android Tier 2 ✅ Ready
Android ARM32 arm-linux-androideabi Tier 2 ✅ Ready
iOS ARM64 aarch64-ios Tier 3 ⚠️ Needs Testing
FreeBSD x86_64-freebsd Tier 2 ✅ Ready
WASM wasm32-freestanding Tier 2 🔧 This Document

libdatachannel Platform Support

Platform Official Support Build Method
Linux (all archs) ✅ Yes Native or cross-compile
Android ✅ Yes NDK + provided scripts
iOS ✅ Yes Xcode + provided scripts
macOS ✅ Yes Native or Homebrew
Windows ✅ Yes MSVC or MinGW
FreeBSD ✅ Yes Ports collection

17.3 Universal Interoperability Diagram

With native WebRTC implemented, all platforms can communicate:

                         ┌──────────────────────────────────┐
                         │      Web Browsers (Any)          │
                         │   Chrome / Firefox / Safari      │
                         │         Edge / Opera             │
                         └───────────────┬──────────────────┘
                                         │
                                    WebRTC DataChannel
                                         │
     ┌───────────────────────────────────┼───────────────────────────────────┐
     │                                   │                                   │
     ▼                                   ▼                                   ▼
┌─────────────┐                   ┌─────────────┐                   ┌─────────────┐
│   Desktop   │                   │   Mobile    │                   │    IoT      │
│             │                   │             │                   │             │
│ • Linux     │◄─────────────────►│ • Android   │◄─────────────────►│ • Rasp Pi   │
│ • macOS     │   WebRTC or UDP   │ • iOS       │   WebRTC or UDP   │ • ARM SBCs  │
│ • Windows   │                   │ • Tablets   │                   │ • Gateways  │
│             │                   │             │                   │             │
└──────┬──────┘                   └──────┬──────┘                   └──────┬──────┘
       │                                 │                                 │
       │                                 │                                 │
       └─────────────────────────────────┴─────────────────────────────────┘
                                         │
                            UDP (Native-to-Native, fastest)

17.4 Communication Paths

From To Transport Options Latency
Browser Browser WebRTC ~50-100ms
Browser Android/iOS WebRTC ~50-100ms
Browser Desktop WebRTC ~20-50ms
Browser IoT (RPi) WebRTC ~50-150ms
Android iOS WebRTC or UDP ~20-50ms
Android Desktop WebRTC or UDP ~10-30ms
Desktop Desktop UDP ~1-10ms
Desktop IoT UDP ~1-10ms
IoT IoT UDP ~1-10ms

Key insight: Native-to-native connections can use UDP for lowest latency, while browser connections require WebRTC. The library automatically negotiates the best transport.

17.5 Mobile Platform Details

17.5.1 Android

Build Command:

# Cross-compile zig-p2p for Android
zig build -Dtarget=aarch64-linux-android -Doptimize=ReleaseFast

# With libdatachannel (requires Android NDK)
# See build scripts in libdatachannel/scripts/build_openssl_android.sh

Integration Options:

  1. JNI Bindings (Recommended)

    // Java/Kotlin wrapper
    public class ZigP2P {
        static { System.loadLibrary("zig-p2p"); }
    
        public native void init(P2PConfig config);
        public native void connect(String peerId);
        public native void send(String peerId, byte[] data);
        public native void setMessageCallback(MessageCallback cb);
    }
    
  2. Flutter Plugin

    • Use dart:ffi to call native library
    • Single codebase for Android + iOS

Android-Specific Considerations:

Concern Solution
Background networking Use ForegroundService for persistent connections
Battery optimization Implement exponential backoff, reduce keepalive frequency
Network changes Listen to ConnectivityManager broadcasts
Permissions INTERNET, ACCESS_NETWORK_STATE

17.5.2 iOS

Build Command:

# Cross-compile for iOS
zig build -Dtarget=aarch64-ios -Doptimize=ReleaseFast

# Create universal binary (if needed)
lipo -create zig-out/lib/libzig-p2p-arm64.a zig-out/lib/libzig-p2p-x64.a \
     -output libzig-p2p-universal.a

Integration Options:

  1. Swift/Objective-C Bridge

    // Swift wrapper using C interop
    import ZigP2P
    
    class P2PManager {
        func connect(peerId: String) {
            p2p_connect(peerId.cString(using: .utf8))
        }
    }
    
  2. React Native Module

    • Native module wrapping the Zig library
    • Shared JS code between platforms

iOS-Specific Considerations:

Concern Solution
Background execution Limited to ~30 seconds; use Background Tasks API
VoIP Push For persistent connections, register as VoIP app
App Transport Security WebRTC uses DTLS, compliant with ATS
App Store Review Document network usage, privacy policy

17.6 IoT Platform Details

17.6.1 Raspberry Pi / ARM Linux

Build Command:

# For Raspberry Pi 4 (64-bit)
zig build -Dtarget=aarch64-linux-musl -Doptimize=ReleaseSmall

# For Raspberry Pi Zero/older (32-bit)
zig build -Dtarget=arm-linux-musleabihf -Doptimize=ReleaseSmall

# Check binary size
ls -lh zig-out/bin/zig-p2p
# Expected: ~1.5-2.5 MB

Deployment:

# Copy to device
scp zig-out/bin/zig-p2p pi@raspberrypi:/usr/local/bin/

# Run as service
sudo systemctl enable zig-p2p
sudo systemctl start zig-p2p

17.6.2 Resource Constraints

Resource zig-p2p Requirement Typical IoT Device
RAM ~131KB per connection 256MB-1GB
Storage ~5MB binary 4GB+ SD card
CPU Single core OK ARM Cortex-A
Network UDP/WebRTC WiFi/Ethernet

Memory-Constrained Configuration:

const config = P2PConfig{
    .max_connections = 10,        // Limit connections
    .memory_budget_mb = 64,       // Cap memory usage
    .enable_file_transfer = false, // Disable if not needed
    .piece_size = 256 * 1024,     // Smaller pieces
};

17.6.3 Power-Aware Mode (Future Enhancement)

const PowerMode = enum {
    always_on,      // Full connectivity, higher power
    balanced,       // Reduce keepalives, wake on activity
    low_power,      // Disconnect when idle, periodic sync
};

const config = P2PConfig{
    .power_mode = .balanced,
    .keepalive_interval_ms = 30_000,  // 30s instead of 5s
    .idle_disconnect_ms = 300_000,    // Disconnect after 5min idle
};

17.7 Unsupported Platforms

Platform Reason Alternative
ESP32 (bare metal) No OS, no POSIX sockets Use ESP-IDF with custom port
Arduino Too resource constrained Use as sensor, relay via gateway
FreeRTOS (raw) No POSIX compatibility Needs lwIP socket wrapper
Zephyr RTOS Different socket API Possible future port

For bare-metal microcontrollers, the recommended pattern is:

┌─────────────┐        Serial/BLE        ┌──────────────┐       P2P        ┌─────────────┐
│   ESP32     │◄────────────────────────►│  RPi Gateway │◄────────────────►│   Cloud     │
│  (sensors)  │                          │  (zig-p2p)   │                  │  (zig-p2p)  │
└─────────────┘                          └──────────────┘                  └─────────────┘

17.8 Build System Integration

17.8.1 Multi-Target Build Script

// build.zig additions for mobile/IoT
const mobile_targets = [_]std.Target.Query{
    .{ .cpu_arch = .aarch64, .os_tag = .linux, .abi = .android },
    .{ .cpu_arch = .aarch64, .os_tag = .ios, .abi = .none },
    .{ .cpu_arch = .aarch64, .os_tag = .linux, .abi = .musl },  // RPi
    .{ .cpu_arch = .arm, .os_tag = .linux, .abi = .musleabihf }, // RPi Zero
};

const mobile_step = b.step("mobile", "Build for all mobile/IoT targets");

for (mobile_targets) |target_query| {
    const resolved = b.resolveTargetQuery(target_query);
    const lib = b.addStaticLibrary(.{
        .name = "zig-p2p",
        .root_source_file = b.path("src/lib.zig"),
        .target = resolved,
        .optimize = .ReleaseSmall,
    });
    mobile_step.dependOn(&b.addInstallArtifact(lib, .{}).step);
}

17.8.2 Conditional libdatachannel Linking

// Link libdatachannel only when WebRTC is enabled
if (options.enable_webrtc) {
    const target = exe.root_module.resolved_target.?.result;

    if (target.os.tag == .android) {
        exe.addLibraryPath(.{ .cwd_relative = "deps/libdatachannel/android/lib" });
    } else if (target.os.tag == .ios) {
        exe.addLibraryPath(.{ .cwd_relative = "deps/libdatachannel/ios/lib" });
    } else {
        exe.linkSystemLibrary("datachannel");
    }

    exe.linkLibC();
}

17.9 Testing Strategy for Mobile/IoT

17.9.1 Test Matrix

Test Desktop Android iOS RPi Browser
Unit tests ✅ ✅ ✅ ✅ -
Integration ✅ ✅ ✅ ✅ ✅
Cross-platform P2P ✅ ✅ ✅ ✅ ✅
Battery impact - ✅ ✅ - -
Network transitions - ✅ ✅ - -

17.9.2 CI/CD for Mobile

# GitHub Actions example
jobs:
  build-android:
    runs-on: ubuntu-latest
    steps:
      - uses: goto-bus-stop/setup-zig@v2
      - name: Build Android ARM64
        run: zig build -Dtarget=aarch64-linux-android

  build-ios:
    runs-on: macos-latest
    steps:
      - uses: goto-bus-stop/setup-zig@v2
      - name: Build iOS ARM64
        run: zig build -Dtarget=aarch64-ios

  test-interop:
    needs: [build-android, build-ios]
    runs-on: ubuntu-latest
    steps:
      - name: Start browser peer (Playwright)
      - name: Start Android emulator peer
      - name: Verify cross-platform messaging

17.10 Mobile/IoT Implementation Phase

Additional Phase for Mobile Support:

Task Duration Dependencies
Android JNI bindings 1 week Core library complete
iOS Swift bridge 1 week Core library complete
Cross-compile CI setup 3 days -
Mobile integration tests 1 week JNI + Swift done
Power-aware mode 1 week Optional
Total 4-5 weeks After core phases

18. Appendices

A. Browser API Reference

API Spec Browser Support
WebRTC W3C Chrome 56+, Firefox 44+, Safari 11+
IndexedDB W3C All modern browsers
WebSocket RFC 6455 All modern browsers
WASM W3C Chrome 57+, Firefox 52+, Safari 11+

B. WebRTC Protocol References

Protocol RFC/Spec Purpose
WebRTC Data Channels RFC 8831 Data channel architecture
SCTP RFC 4960 Stream Control Transmission Protocol
DTLS 1.2 RFC 6347 Datagram TLS
ICE RFC 8445 Interactive Connectivity Establishment
STUN RFC 5389 Session Traversal Utilities for NAT
TURN RFC 5766 Relay server protocol
SDP RFC 8866 Session Description Protocol

C. Native WebRTC Libraries

Library Language License Size Notes
libdatachannel C++ MPL 2.0 ~200KB Recommended - lightweight, C API
libjuice C MPL 2.0 ~50KB ICE only, same author
Pion Go MIT N/A Cannot link from Zig
webrtc-rs Rust MIT ~500KB Could use via C ABI
libwebrtc C++ BSD ~10MB Google's impl, very large

D. Signaling Server Reference Implementation

A minimal signaling server is provided in examples/signaling-server/:

// Simple WebSocket signaling server
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const peers = new Map();

wss.on('connection', (ws) => {
    ws.on('message', (data) => {
        const msg = JSON.parse(data);

        if (msg.type === 'register') {
            peers.set(msg.peerId, ws);
            ws.peerId = msg.peerId;
        } else if (msg.to && peers.has(msg.to)) {
            msg.from = ws.peerId;
            peers.get(msg.to).send(JSON.stringify(msg));
        }
    });

    ws.on('close', () => {
        if (ws.peerId) peers.delete(ws.peerId);
    });
});

E. Glossary

Term Definition
DataChannel WebRTC API for arbitrary data transfer
DCEP Data Channel Establishment Protocol
DTLS Datagram Transport Layer Security - TLS over UDP
ICE Interactive Connectivity Establishment - NAT traversal protocol
IndexedDB Browser API for client-side storage
libdatachannel Lightweight C++ WebRTC library (recommended for native WebRTC)
SCTP Stream Control Transmission Protocol - reliable streams over UDP
SDP Session Description Protocol - WebRTC connection metadata
Signaling Exchange of connection metadata before P2P link
STUN Session Traversal Utilities for NAT
Transport Abstract interface for sending/receiving bytes
TURN Traversal Using Relays around NAT - relay fallback
WASM WebAssembly - portable binary format
WebRTC Direct WebRTC connection without signaling server (server has known address)

Document version: 1.3 Last updated: February 2026

Revision History

Version Date Changes
1.0 Feb 2025 Initial design document
1.1 Feb 2025 Added native-browser interoperability analysis (Sections 15-16), WebRTC implementation options, updated timeline
1.2 Feb 2026 Added Mobile and IoT platform support (Section 17), universal interoperability matrix, build system integration for cross-platform targets
1.3 Feb 2026 Major Section 16 rewrite: detailed libdatachannel C binding plan with full API surface, Zig callback bridge implementation, DHT-based signaling (no separate server), build system options, Noise-over-WebRTC security model. Updated benchmarks with measured values. Fixed memory per connection (64KB → 131KB). Added MWP note to signaling section.