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

24 KiB

Decentralization Roadmap: Path to 10/10

Document Version: 1.0 Created: February 2026 Status: Design Phase


Executive Summary

This document outlines the path to achieving fully decentralized P2P networking with zero infrastructure dependencies. The goal is a protocol that works with no internet, no servers, no bootstrap nodes, and no DNS.

Current Score: 7/10 Target Score: 10/10 Estimated Timeline: 3-4 months


Current State Assessment

Decentralization Audit

Component Current State Centralization Risk Score
Peer Discovery (DHT) Bootstrap nodes required Medium 7/10
NAT Traversal (STUN) External STUN servers High 5/10
NAT Fallback (TURN) Not implemented High 4/10
Data Transfer Fully P2P None 10/10
Encryption E2E Noise Protocol None 10/10
Identity Self-generated keys None 10/10
Code Distribution GitHub High 3/10

The Brutal Truth

First connection:     Needs bootstrap       → Centralized
NAT discovery:        Needs STUN            → Centralized
10% of connections:   Needs TURN relay      → Centralized
90% of connections:   Direct P2P            → Decentralized
All data:             E2E encrypted         → Decentralized

Overall: 7/10 - Decentralized after connected, but bootstrapping and NAT traversal are weak points.


Centralization Points & Solutions

1. Bootstrap Problem

Current State: Need hardcoded node addresses to join network initially.

Why It Matters: If bootstrap nodes go down or are blocked, new peers cannot join.

Solution: Multi-Method Discovery

Method Description Internet Required Effort
Local Broadcast UDP broadcast on LAN, mDNS No 1 week
Bluetooth/BLE Scan for peers in physical proximity No 3 weeks
LoRa Beacon Broadcast presence on radio mesh No See LoRa design
QR Code Exchange Scan to get first peer address No 1 day
Saved Peers Remember peers from last session No 2 days
Peer Gossip Any connected peer shares more peers Yes 2 weeks
DNS TXT Records Lookup _zig-p2p.example.com Yes 2 days
Hardcoded Bootstrap Last resort fallback Yes Already done

Discovery Priority Chain

const DiscoveryMethod = enum {
    local_broadcast,    // 1. Instant, no internet
    bluetooth_scan,     // 2. Physical proximity
    lora_beacon,        // 3. Off-grid radio
    saved_peers,        // 4. From last session
    peer_gossip,        // 5. Ask known peers for more
    dns_txt,            // 6. Semi-centralized fallback
    hardcoded_bootstrap // 7. Last resort
};

pub fn discoverPeers(self: *Discovery) ![]PeerAddress {
    // Try methods in order until we have enough peers
    for (discovery_methods) |method| {
        const peers = try self.tryMethod(method);
        if (peers.len >= min_peers) return peers;
        // Continue to next method
    }
    return error.NoPeersFound;
}

Local Broadcast Implementation

pub const LocalDiscovery = struct {
    socket: *UdpSocket,
    port: u16 = 9999,

    const DISCOVERY_MAGIC = "ZIG-P2P-DISCOVER-V1";
    const BROADCAST_INTERVAL_MS = 5000;

    pub fn broadcast(self: *LocalDiscovery) !void {
        const msg = DiscoveryMessage{
            .magic = DISCOVERY_MAGIC,
            .peer_id = self.local_peer_id,
            .listen_port = self.listen_port,
            .capabilities = self.capabilities,
        };

        // Broadcast to LAN
        try self.socket.sendTo(
            std.net.Address.initIp4(.{255, 255, 255, 255}, self.port),
            std.mem.asBytes(&msg),
        );
    }

    pub fn listen(self: *LocalDiscovery) !?PeerInfo {
        var buf: [512]u8 = undefined;
        const result = self.socket.recvFrom(&buf) catch return null;

        const msg = std.mem.bytesToValue(DiscoveryMessage, result.data);
        if (!std.mem.eql(u8, &msg.magic, DISCOVERY_MAGIC)) return null;

        return PeerInfo{
            .peer_id = msg.peer_id,
            .address = result.address,
            .capabilities = msg.capabilities,
        };
    }
};

Bluetooth Discovery Implementation

pub const BluetoothDiscovery = struct {
    adapter: *BluetoothAdapter,
    service_uuid: UUID = UUID.parse("zig-p2p-discovery-v1"),

    pub fn advertise(self: *BluetoothDiscovery) !void {
        try self.adapter.startAdvertising(.{
            .service_uuid = self.service_uuid,
            .local_name = "zig-p2p-peer",
            .service_data = self.peer_id[0..8], // First 8 bytes of peer ID
        });
    }

    pub fn scan(self: *BluetoothDiscovery) ![]PeerInfo {
        var peers = std.ArrayList(PeerInfo).init(self.allocator);

        try self.adapter.startScan(.{
            .service_uuid = self.service_uuid,
            .timeout_ms = 10000,
        });

        while (self.adapter.nextResult()) |result| {
            // Connect to get full peer info
            const conn = try self.adapter.connect(result.address);
            defer conn.close();

            const peer_info = try conn.readCharacteristic(peer_info_char);
            try peers.append(peer_info);
        }

        return peers.toOwnedSlice();
    }
};

2. STUN Problem

Current State: Need external STUN server to discover public IP behind NAT.

Why It Matters: STUN servers (often Google's) are centralized infrastructure.

Solution: Peer-to-Peer STUN

Every peer acts as a STUN server for others. When you connect to a peer, they tell you your public IP.

pub const PeerStun = struct {
    observed_addresses: std.AutoHashMap(PeerId, Address),

    /// Called when a new peer connects to us
    pub fn onIncomingConnection(
        self: *PeerStun,
        peer_id: PeerId,
        their_observed_addr: Address,
    ) void {
        // Tell the peer what address we see them connecting from
        self.sendMessage(peer_id, .{
            .msg_type = .your_observed_address,
            .address = their_observed_addr,
        });
    }

    /// Called when we receive our observed address from a peer
    pub fn onObservedAddress(
        self: *PeerStun,
        from_peer: PeerId,
        observed_addr: Address,
    ) void {
        self.observed_addresses.put(from_peer, observed_addr);

        // After 3+ peers report, we have consensus on our public IP
        if (self.observed_addresses.count() >= 3) {
            self.public_address = self.computeConsensusAddress();
        }
    }

    fn computeConsensusAddress(self: *PeerStun) ?Address {
        var addr_counts = std.AutoHashMap(Address, u32).init(self.allocator);

        var it = self.observed_addresses.valueIterator();
        while (it.next()) |addr| {
            const entry = addr_counts.getOrPut(addr.*);
            entry.value_ptr.* = (entry.value_ptr.* ) + 1;
        }

        // Return most commonly reported address
        var max_count: u32 = 0;
        var consensus_addr: ?Address = null;

        var count_it = addr_counts.iterator();
        while (count_it.next()) |entry| {
            if (entry.value_ptr.* > max_count) {
                max_count = entry.value_ptr.*;
                consensus_addr = entry.key_ptr.*;
            }
        }

        return consensus_addr;
    }
};

NAT Type Detection

pub const NatType = enum {
    open,              // No NAT, public IP
    full_cone,         // Easy traversal
    restricted_cone,   // Medium traversal
    port_restricted,   // Harder traversal
    symmetric,         // Needs relay
};

pub fn detectNatType(self: *PeerStun) NatType {
    const observations = self.observed_addresses.values();

    // All peers see same IP:port = open or full cone
    if (allSame(observations)) {
        return if (self.isPublicIp()) .open else .full_cone;
    }

    // Same IP, different ports = symmetric NAT
    if (sameIpDifferentPorts(observations)) {
        return .symmetric;
    }

    // Different based on destination = restricted
    return .port_restricted;
}

Effort: 1 week


3. TURN/Relay Problem

Current State: ~10% of NAT configurations cannot do direct P2P and need a relay. TURN relays are centralized.

Why It Matters: Relay operators see metadata (who talks to whom) and can censor.

Solution: Decentralized Relay Network

Approach Pros Cons
All peers relay Simple, always available Bandwidth cost for everyone
Opt-in relay Sustainable Fewer relays available
Friend relay Trust-based, private Limited reach
Incentivized relay Scalable, sustainable Needs payment layer
Onion routing Maximum privacy High latency

Relay Priority Chain

1. Direct connection (hole punch)
2. Friend-of-friend relay (mutual contacts)
3. Volunteer relay (altruistic peers)
4. Paid relay (incentive layer)

Implementation

pub const RelayManager = struct {
    known_relays: std.ArrayList(RelayInfo),
    friend_graph: FriendGraph,
    payment_channel: ?*PaymentChannel,

    pub fn connectViaBestRelay(
        self: *RelayManager,
        target: PeerId,
    ) !*Connection {
        // 1. Try friend-of-friend
        if (self.friend_graph.findMutualContact(target)) |friend| {
            if (try self.requestRelay(friend, target)) |conn| {
                return conn;
            }
        }

        // 2. Try volunteer relays
        for (self.known_relays.items) |relay| {
            if (!relay.requires_payment) {
                if (try self.requestRelay(relay.peer_id, target)) |conn| {
                    return conn;
                }
            }
        }

        // 3. Try paid relays
        if (self.payment_channel) |pay| {
            for (self.known_relays.items) |relay| {
                if (relay.requires_payment) {
                    try pay.reserveFunds(relay.price_per_mb);
                    if (try self.requestRelay(relay.peer_id, target)) |conn| {
                        return conn;
                    }
                }
            }
        }

        return error.NoRelayAvailable;
    }
};

Friend-of-Friend Relay Protocol

pub const FriendRelay = struct {
    /// Request a mutual friend to relay traffic
    pub fn requestRelay(
        self: *FriendRelay,
        friend: PeerId,
        target: PeerId,
    ) !?*RelayCircuit {
        // Prove we know the target (signed introduction)
        const intro = self.createIntroduction(target);

        const response = try self.sendRequest(friend, .{
            .msg_type = .relay_request,
            .target = target,
            .introduction = intro,
        });

        if (response.accepted) {
            return RelayCircuit.init(friend, target);
        }
        return null;
    }

    /// Handle relay request from a peer
    pub fn handleRelayRequest(
        self: *FriendRelay,
        from: PeerId,
        request: RelayRequest,
    ) !void {
        // Only relay for friends
        if (!self.isFriend(from)) {
            return self.sendResponse(from, .{ .accepted = false });
        }

        // Check we know the target
        if (!self.isFriend(request.target)) {
            return self.sendResponse(from, .{ .accepted = false });
        }

        // Verify introduction
        if (!self.verifyIntroduction(request.introduction)) {
            return self.sendResponse(from, .{ .accepted = false });
        }

        // Accept and create relay circuit
        try self.createRelayCircuit(from, request.target);
        return self.sendResponse(from, .{ .accepted = true });
    }
};

Incentivized Relay (Future)

pub const PaidRelay = struct {
    price_per_mb: u64, // In smallest currency unit
    stake: u64,        // Deposited stake for good behavior
    reputation: f32,   // 0.0 - 1.0

    pub const RelayProof = struct {
        bytes_relayed: u64,
        timestamp: i64,
        client_signature: [64]u8,
        relay_signature: [64]u8,
    };

    /// Generate proof of relay service for payment
    pub fn generateProof(
        self: *PaidRelay,
        circuit: *RelayCircuit,
    ) RelayProof {
        return .{
            .bytes_relayed = circuit.bytes_transferred,
            .timestamp = std.time.timestamp(),
            .client_signature = circuit.client.sign(circuit.hash()),
            .relay_signature = self.sign(circuit.hash()),
        };
    }
};

Effort: 4-6 weeks (basic), 3+ months (incentivized)


4. Code Distribution Problem

Current State: Code distributed via GitHub (centralized).

Why It Matters: GitHub can be blocked, accounts can be banned, repos can be taken down.

Solution: Self-Hosting Distribution

1. Signed releases with maintainer PGP/Ed25519 keys
2. Distribute binaries over zig-p2p network itself
3. Reproducible builds for independent verification
4. Multiple mirrors (IPFS, BitTorrent, direct P2P)

Implementation

pub const SelfUpdate = struct {
    current_version: SemanticVersion,
    maintainer_keys: []const PublicKey,

    pub const SignedRelease = struct {
        version: SemanticVersion,
        binary_hash: [32]u8,  // SHA-256
        signature: [64]u8,    // Ed25519
        signer: PublicKey,

        pub fn verify(self: SignedRelease, trusted_keys: []const PublicKey) bool {
            // Check signer is trusted
            const trusted = for (trusted_keys) |key| {
                if (std.mem.eql(u8, &key, &self.signer)) break true;
            } else false;

            if (!trusted) return false;

            // Verify signature
            return std.crypto.sign.Ed25519.verify(
                self.signature,
                self.binary_hash,
                self.signer,
            );
        }
    };

    pub fn checkForUpdates(self: *SelfUpdate) !?SignedRelease {
        // Query DHT for latest release announcement
        const release_key = "zig-p2p:latest-release";
        const announcement = try self.dht.get(release_key);

        const release = try SignedRelease.decode(announcement);
        if (!release.verify(self.maintainer_keys)) {
            return error.InvalidSignature;
        }

        if (release.version.isNewerThan(self.current_version)) {
            return release;
        }
        return null;
    }

    pub fn downloadUpdate(self: *SelfUpdate, release: SignedRelease) ![]u8 {
        // Download binary via P2P file transfer
        const binary = try self.file_transfer.download(release.binary_hash);

        // Verify hash
        const actual_hash = std.crypto.hash.sha2.Sha256.hash(binary);
        if (!std.mem.eql(u8, &actual_hash, &release.binary_hash)) {
            return error.HashMismatch;
        }

        return binary;
    }
};

Effort: 2 weeks


5. DNS Problem

Current State: Bootstrap nodes may be specified by hostname.

Why It Matters: DNS is centralized and can be censored.

Solution: Never Require DNS

  • Use peer IDs (public key hash) as addresses
  • Resolve peer ID → IP via DHT
  • All configuration uses IP addresses or peer IDs
pub const PeerAddress = union(enum) {
    ip: std.net.Address,           // Direct IP
    peer_id: [32]u8,               // Resolve via DHT
    multiaddr: []const u8,         // /ip4/1.2.3.4/udp/9000
    // NO hostname option - DNS not supported
};

pub fn resolve(addr: PeerAddress, dht: *DHT) !std.net.Address {
    return switch (addr) {
        .ip => |ip| ip,
        .peer_id => |id| try dht.findPeer(id),
        .multiaddr => |ma| try parseMultiaddr(ma),
    };
}

Status: Mostly already implemented.


10/10 Target Architecture

┌─────────────────────────────────────────────────────────────┐
│                     DISCOVERY LAYER                          │
│                                                              │
│   Local         Bluetooth       LoRa         Saved          │
│   Broadcast  →    Scan     →   Beacon   →   Peers   → DHT   │
│                                                              │
│              (no hardcoded anything required)                │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    NAT TRAVERSAL                             │
│                                                              │
│   Peer-STUN     Hole        Friend       Volunteer   Paid   │
│   Consensus  →  Punch   →   Relay    →    Relay   → Relay   │
│                                                              │
│                  (no external servers)                       │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    TRANSPORT LAYER                           │
│                                                              │
│         UDP  ←──→  WebRTC  ←──→  LoRa  ←──→  Bluetooth      │
│                                                              │
│                   (any medium works)                         │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    PROTOCOL LAYER                            │
│                                                              │
│            Noise Encryption → DHT → File Transfer            │
│                                                              │
│                   (same everywhere)                          │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                   APPLICATION LAYER                          │
│                                                              │
│         A2A Agents    File Sharing    Messaging    IoT       │
│                                                              │
└─────────────────────────────────────────────────────────────┘

Implementation Phases

Phase 1: Remove STUN Dependency (Score: 8/10)

Duration: 2-3 weeks

Task Effort Impact
Implement Peer-STUN 1 week Eliminate external STUN
NAT type detection 3 days Better traversal decisions
Local broadcast discovery 1 week LAN works offline
Save/restore peer list 2 days Remember peers across restarts

Deliverables:

  • src/nat/peer_stun.zig - Peer-to-peer STUN implementation
  • src/discovery/local.zig - Local broadcast discovery
  • src/discovery/persistence.zig - Saved peer list
  • Tests for all components

Phase 2: Add Relay Network (Score: 9/10)

Duration: 4-6 weeks

Task Effort Impact
Friend-of-friend relay 2 weeks Trusted relay path
Volunteer relay protocol 2 weeks Altruistic relay option
Relay circuit management 1 week Handle relay connections
Bluetooth discovery 2 weeks Proximity discovery

Deliverables:

  • src/relay/friend.zig - Friend-of-friend relay
  • src/relay/volunteer.zig - Volunteer relay network
  • src/relay/circuit.zig - Relay circuit management
  • src/discovery/bluetooth.zig - BLE discovery
  • Integration tests

Phase 3: Full Decentralization (Score: 10/10)

Duration: 6-8 weeks

Task Effort Impact
LoRa transport 6 weeks Off-grid capability
Incentivized relay 4 weeks Sustainable relay network
Self-update via P2P 2 weeks Decentralized distribution
Onion routing (optional) 4 weeks Maximum privacy

Deliverables:

  • src/transport/lora.zig - LoRa transport (see LoRa design doc)
  • src/relay/incentive.zig - Payment for relay
  • src/update/self_update.zig - P2P software updates
  • Full system integration tests

Score Progression

Phase Features Added Score
Current UDP, Noise, DHT, File Transfer 7/10
Phase 1 Peer-STUN, Local Discovery 8/10
Phase 2 Friend Relay, Bluetooth 9/10
Phase 3 LoRa, Incentives, Self-Update 10/10

Comparison After 10/10

Feature zig-p2p (10/10) libp2p BitTorrent
No bootstrap needed Yes No No
No STUN servers Yes No No
No relay servers Yes No No
Works offline (LAN) Yes Partial No
Works off-grid (LoRa) Yes No No
Proximity discovery Yes No No
Self-updating Yes No No
Incentivized relay Yes No No

The 10/10 Pitch

"Works with no internet. No servers. No bootstrap. No DNS. Find peers over radio, Bluetooth, or local network. True zero-infrastructure P2P."

This is a defensible, unique position that no existing solution holds.


Risk Assessment

Risk Likelihood Mitigation
Bluetooth API fragmentation High Abstract via platform layer
LoRa regulatory compliance Medium Region-specific duty cycle
Incentive mechanism gaming Medium Reputation + stake slashing
Sybil attacks on relay Medium Proof-of-work or stake
Adoption of new discovery Low Graceful fallback to bootstrap

Success Metrics

Metric Target
Bootstrap-free connection rate >90% on LAN
NAT traversal without external STUN 100%
Relay availability >99% when needed
Off-grid message delivery (LoRa) >95% within 3 hops
Update distribution latency <1 hour for critical

Appendix: Protocol Messages

Discovery Messages

pub const DiscoveryMessage = union(enum) {
    // Local broadcast
    announce: struct {
        peer_id: [32]u8,
        listen_port: u16,
        capabilities: Capabilities,
    },

    // Peer exchange
    peer_exchange_request: void,
    peer_exchange_response: struct {
        peers: []PeerInfo,
    },

    // Observed address (Peer-STUN)
    your_observed_address: struct {
        address: Address,
        timestamp: i64,
    },
};

Relay Messages

pub const RelayMessage = union(enum) {
    // Request relay
    relay_request: struct {
        target: [32]u8,
        introduction: ?SignedIntroduction,
    },

    relay_response: struct {
        accepted: bool,
        circuit_id: ?u64,
        reason: ?[]const u8,
    },

    // Relay data
    relay_data: struct {
        circuit_id: u64,
        payload: []const u8,
    },

    // Circuit management
    circuit_close: struct {
        circuit_id: u64,
    },
};

References


Document maintained by zig-p2p contributors.