Files
zigp2p/docs/WASM_BROWSER_DESIGN.md
2026-02-06 21:03:59 -03:00

102 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.

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 Target (Native) Target (WASM)
Connection setup <50ms <200ms
Message latency <5ms <20ms
Throughput 100+ MB/s 10+ MB/s
Memory per conn 64KB 128KB

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 Implementation

16.1 WebRTC Protocol Stack

WebRTC Data Channels require implementing multiple complex protocols:

┌─────────────────────────────────────────┐
│         Data Channel (DCEP)             │  Simple message framing
├─────────────────────────────────────────┤
│              SCTP                       │  Reliable streams over UDP
├─────────────────────────────────────────┤  (congestion control, ordering)
│              DTLS 1.2/1.3               │  TLS over UDP
├─────────────────────────────────────────┤  (encryption, authentication)
│           ICE + STUN + TURN             │  NAT traversal
├─────────────────────────────────────────┤  (connectivity establishment)
│              UDP                        │  ← Already implemented
└─────────────────────────────────────────┘

16.2 Component Complexity Analysis

Component Purpose Complexity Est. Lines From-Scratch Time
SCTP Reliable data streams, congestion control Very High 8,000-15,000 2-3 months
DTLS 1.2 TLS handshake over UDP High 5,000-10,000 1-2 months
ICE NAT traversal, connectivity checks High 3,000-5,000 3-4 weeks
STUN Public IP discovery Medium 1,000-2,000 1-2 weeks
TURN Relay fallback Medium 2,000-3,000 2-3 weeks
SDP Session description parsing Medium 1,000-2,000 1 week
DCEP Data channel setup Low ~500 2-3 days

16.3 The Hard Parts

SCTP (Hardest)

  • Must run in userspace over DTLS (not kernel SCTP)
  • Complex congestion control algorithms
  • Partial reliability extensions for WebRTC
  • Multi-stream multiplexing
  • Reference: usrsctp is ~30,000 lines of C

DTLS

  • Full TLS 1.2 handshake adapted for unreliable UDP
  • Retransmission, fragmentation, reordering of handshake messages
  • Must integrate with ICE (consent freshness checks)
  • Certificate handling and cipher suite negotiation

ICE Timing

  • Consent freshness requires STUN keepalives every few seconds
  • Browser will close connection if consent expires
  • Tight integration between ICE and DTLS layers required

16.4 Reference Implementation Sizes

Project Language Scope Approx Size Notes
Pion Go Full WebRTC ~50,000+ lines Multiple repos
libdatachannel C++ Data channels ~15,000-20,000 lines Lightweight
webrtc-rs Rust Full WebRTC ~40,000+ lines Feature-rich
usrsctp C SCTP only ~30,000 lines Used by Chrome
libjuice C ICE only ~5,000 lines Same author as libdatachannel

16.5 Implementation Options

Effort: 4-6 weeks

// Zig bindings for libdatachannel C API
const rtc = @cImport({
    @cInclude("rtc/rtc.h");
});

pub const WebRTCTransport = struct {
    peer_connection: rtc.rtcPeerConnection,
    data_channel: rtc.rtcDataChannel,

    pub fn connect(self: *WebRTCTransport, remote_sdp: []const u8) !void {
        rtc.rtcSetRemoteDescription(self.peer_connection, remote_sdp.ptr);
    }

    pub fn send(self: *WebRTCTransport, data: []const u8) !usize {
        return rtc.rtcSendMessage(self.data_channel, data.ptr, data.len);
    }
};

Pros:

  • Mature, tested implementation
  • Small footprint (~200KB binary increase)
  • C API is clean for Zig interop
  • Maintained by active developer
  • MPL 2.0 license

Cons:

  • External C++ dependency
  • Requires OpenSSL/GnuTLS/mbedTLS for crypto

Timeline:

Task Duration
Build system integration 3 days
Zig C bindings 1 week
Transport implementation 1 week
WebRTC Direct protocol 1 week
Integration & testing 1-2 weeks
Total 4-6 weeks

Option 2: Port libjuice to Zig + Bind usrsctp

Effort: 4-6 months

Port the ICE layer (libjuice) to pure Zig, bind usrsctp for SCTP:

// Pure Zig ICE implementation (ported from libjuice)
pub const IceAgent = struct {
    local_candidates: std.ArrayList(Candidate),
    remote_candidates: std.ArrayList(Candidate),
    selected_pair: ?CandidatePair,

    pub fn gatherCandidates(self: *IceAgent) !void {
        // STUN binding requests to discover public IP
        try self.gatherHostCandidates();
        try self.gatherServerReflexiveCandidates();
    }
};

Pros:

  • Partial pure Zig (ICE layer)
  • Good learning experience
  • More control over ICE behavior

Cons:

  • Still depends on usrsctp (C)
  • DTLS still needs external library
  • Significant effort for marginal benefit

Option 3: Full From-Scratch Implementation

Effort: 6-10 months (1 person full-time)

Write everything in pure Zig:

Component Lines Time
SCTP 8,000-15,000 2-3 months
DTLS 1.2 5,000-10,000 1-2 months
ICE 3,000-5,000 1 month
STUN 1,000-2,000 2 weeks
TURN 2,000-3,000 2-3 weeks
SDP parsing 1,000-2,000 1 week
Integration - 1-2 months
Total 25,000-40,000 6-10 months

Pros:

  • Zero external dependencies
  • Full control
  • Smallest binary size
  • Great for Zig ecosystem

Cons:

  • Massive undertaking
  • High risk of subtle protocol bugs
  • SCTP congestion control is notoriously complex
  • Only viable with dedicated funding

16.6 Comparison Table

Approach Time Pure Zig Dependencies Binary Size Risk
Bind libdatachannel 4-6 weeks 80% libdatachannel, TLS lib +200KB Low
Port libjuice + bind 4-6 months 60% usrsctp, TLS lib +150KB Medium
Full from-scratch 6-10 months 100% None +100KB High

16.7 Recommendation

Phase 1: Bind libdatachannel (4-6 weeks)

  • Achieves interoperability quickly
  • Proven, tested implementation
  • Can always replace later with pure Zig

Phase 2 (Future, Optional): Pure Zig Implementation

  • Only if there's strong community demand
  • Could be a separate project (zig-webrtc)
  • Start with ICE (port libjuice), then tackle SCTP

16.8 libdatachannel Integration Details

Build System

// build.zig additions
const libdatachannel = b.dependency("libdatachannel", .{
    .target = target,
    .optimize = optimize,
});

exe.linkLibrary(libdatachannel.artifact("datachannel"));
exe.linkSystemLibrary("ssl");
exe.linkSystemLibrary("crypto");

Package Manager (build.zig.zon)

.dependencies = .{
    .libdatachannel = .{
        .url = "https://github.com/user/libdatachannel-zig/archive/v0.1.0.tar.gz",
        .hash = "...",
    },
},

API Mapping

libdatachannel C API zig-p2p Transport API
rtcCreatePeerConnection() WebRTCTransport.init()
rtcSetRemoteDescription() WebRTCTransport.connect()
rtcSendMessage() Transport.send()
rtcReceiveMessage() Transport.receive()
rtcClose() Transport.close()
rtcGetState() Transport.getState()

16.9 Updated Project Timeline

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 1.5 weeks 5 weeks
4. File System & Threading 1 week 6 weeks
5. Native WebRTC (libdatachannel) 4 weeks 10 weeks
6. Integration & Polish 2 weeks 12 weeks

Total with full interoperability: 10-12 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 ~64KB per connection 256MB-1GB
Storage ~2MB 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.2 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