Files
zigp2p/src/network
..
2026-02-06 21:03:59 -03:00
2026-02-06 21:03:59 -03:00
2026-02-06 21:03:59 -03:00
2026-02-06 21:03:59 -03:00
2026-02-06 21:03:59 -03:00
2026-02-06 21:03:59 -03:00
2026-02-06 21:03:59 -03:00

Network Module - Peer Discovery and Management System

This directory contains the complete implementation of a peer discovery and management system for P2P networks, inspired by Kademlia DHT and modern P2P protocols.

Overview

The network module provides a comprehensive solution for peer-to-peer network operations including:

  • Peer Management: Individual peer tracking, reputation, and lifecycle management
  • Discovery: Network-wide peer discovery using broadcast and multicast protocols
  • Topology: Network structure management with various topology types
  • Node Operations: Individual node behavior and routing capabilities
  • Routing: Kademlia-inspired distributed routing table

Components

1. Peer Management (peer.zig)

Provides core peer data structures and management functionality:

  • PeerId: 256-bit unique peer identifiers
  • Peer: Individual peer representation with capabilities, reputation, and statistics
  • PeerManager: Collection manager for multiple peers
  • Connection state tracking and peer lifecycle management

Key Features:

  • Unique peer identification with hex string conversion
  • Reputation system (reliability, integrity, responsiveness)
  • Connection statistics and activity tracking
  • Efficient peer lookup and management

2. Discovery System (discovery.zig)

Implements peer discovery using network broadcast/multicast:

  • DiscoveryRequest/DiscoveryResponse: Discovery message formats
  • DiscoveryManager: Main discovery coordinator
  • MulticastDiscovery: Utility for multicast configuration

Key Features:

  • UDP-based discovery protocol
  • Support for link-local and site-local multicast
  • Configurable discovery intervals and timeouts
  • Automatic peer discovery and tracking

3. Topology Management (topology.zig)

Manages network structure and peer relationships:

  • NetworkTopology: Main topology coordinator
  • NodePosition: Individual node positioning
  • PeerConnection: Connection quality and metrics
  • Support for Mesh, Star, Tree, Ring, Hybrid, and DHT topologies

Key Features:

  • Multiple topology types support
  • Shortest path finding using BFS
  • Network metrics analysis (diameter, clustering coefficient, density)
  • Automatic topology optimization

4. Node Management (node.zig)

Handles individual node operations and routing:

  • Node: Main node representation
  • RoutingMessage: Message format for routing operations
  • NodeConfig: Node configuration options
  • Message processing and routing decisions

Key Features:

  • Node lifecycle management (start/stop/shutdown)
  • Message routing with confidence levels
  • Routing table management
  • Configurable node roles and capabilities

5. Kademlia Routing (routing.zig)

Implements Kademlia-inspired distributed routing table:

  • KademliaRoutingTable: Main routing table
  • RoutingBucket: Bucket-based peer organization
  • XORDistance: Distance calculation using XOR metric
  • PeerEntry: Individual routing table entries

Key Features:

  • XOR-based distance metric
  • 256 buckets organized by log distance
  • Efficient closest peer lookup
  • Automatic network maintenance

Architecture

┌─────────────────────────────────────────────────────────────┐
│                    Application Layer                        │
├─────────────────────────────────────────────────────────────┤
│  Network Module                                             │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │
│  │ Peer Mgmt   │ │ Discovery   │ │ Node Management         │ │
│  │ - PeerId    │ │ - Broadcast │ │ - Routing Messages      │ │
│  │ - Peer      │ │ - Multicast │ │ - Routing Decisions     │ │
│  │ - Manager   │ │ - Responses │ │ - Node Lifecycle        │ │
│  └─────────────┘ └─────────────┘ └─────────────────────────┘ │
│  ┌─────────────┐ ┌─────────────────────────────────────────┐ │
│  │ Topology    │ │ Kademlia Routing Table                   │ │
│  │ - Structure │ │ - XOR Distance                           │ │
│  │ - Paths     │ │ - Buckets (256)                          │ │
│  │ - Analysis  │ │ - Closest Peer Lookup                    │ │
│  └─────────────┘ └─────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│  Core Module (Address, Socket, Connection, Buffer)          │
└─────────────────────────────────────────────────────────────┘

Usage Examples

Basic Peer Setup

const allocator = std.testing.allocator;

// Create peer manager
var manager = PeerManager.init(allocator);
defer manager.deinit();

// Add peer
var address = Address.init();
address.port = 8080;
const peer = try manager.addPeer(address);

// Connect peer
peer.setState(.Connected);
peer.reputation.updateSuccess();

Network Discovery

// Configure discovery
var config = DiscoveryConfig{
    .broadcast_address = getBroadcastAddress(),
    .discovery_port = 9999,
};

// Start discovery
var discovery = try DiscoveryManager.init(allocator, config);
defer discovery.deinit();

try discovery.start();

// Send discovery request
const local_peer_id = PeerId.init();
try discovery.sendDiscoveryRequest(local_peer_id, 8080);

// Listen for responses
while (discovery.isRunning()) {
    _ = try discovery.listen(null);
}

Topology Management

// Create topology
var topology = NetworkTopology.init(allocator, .Mesh);
defer topology.deinit();

// Add nodes
const node1 = try topology.addNode(peer1_id, .Hub);
const node2 = try topology.addNode(peer2_id, .Regular);

// Create connections
try topology.addConnection(peer1_id, peer2_id, 85);

// Find paths
const path = try topology.findShortestPath(peer1_id, peer2_id);
defer path.deinit();

Node Operations

// Configure node
var config = NodeConfig{
    .is_hub = true,
    .preferred_role = .Hub,
};

// Initialize node
var node = Node.init(allocator, peer_id, address, &topology, config);
defer node.deinit();

// Start node
try node.start();

// Process messages
var message = try node.createMessage(.Data, dest_peer_id, "Hello");
var decision = try node.processMessage(&message, source_address);

Routing Table

// Initialize routing table
var routing_table = KademliaRoutingTable.init(allocator, local_id);
defer routing_table.deinit();

// Add peers
try routing_table.addPeer(peer, position);

// Find closest peers
const closest = try routing_table.findClosestPeers(target_id, 10);
defer allocator.free(closest);

// Perform maintenance
try routing_table.maintain();

Testing

The module includes comprehensive test coverage:

Individual Component Tests

  • Peer Tests (test_peer.zig): Peer creation, management, reputation system
  • Discovery Tests (test_discovery.zig): Discovery protocols, message handling
  • Topology Tests (test_topology.zig): Network structure, path finding
  • Node Tests (test_node.zig): Node lifecycle, routing decisions
  • Routing Tests (test_routing.zig): Kademlia operations, distance calculation

Integration Tests

  • Complete peer discovery workflow
  • High peer count stress testing
  • Network topology resilience
  • Realistic network performance benchmarks

Running Tests

# Run all network tests
./test/run_tests.sh

# Run specific test module
zig test test/network/test_peer.zig

# Run integration tests
zig test test/network/test_main.zig

Performance Characteristics

Time Complexity

  • Peer Lookup: O(1) average case using hash maps
  • Shortest Path: O(V + E) using BFS algorithm
  • Closest Peer: O(log n) using Kademlia bucketing
  • Discovery: O(1) for response handling

Space Complexity

  • Peer Manager: O(p) where p = number of peers
  • Topology: O(v + e) where v = vertices, e = edges
  • Routing Table: O(k) where k = number of buckets (256)

Scalability

  • Tested with 1000+ concurrent peers
  • Efficient memory usage with automatic cleanup
  • Support for various network sizes and topologies

Configuration Options

Discovery Configuration

DiscoveryConfig{
    .broadcast_address = Address.init(),
    .discovery_port = 9999,
    .timeout_ms = 5000,
    .max_peers = 100,
    .interval_seconds = 30,
    .multicast_ttl = 4,
}

Node Configuration

NodeConfig{
    .is_hub = false,
    .is_super_node = false,
    .is_gateway = false,
    .preferred_role = null,
    .max_routing_table_size = 1000,
    .routing_update_interval = 60,
    .msg_rate_limit = 1000,
}

Network Protocols

Discovery Protocol

  1. Discovery Request: Broadcast with peer ID, port, capabilities
  2. Discovery Response: Unicast response with peer information
  3. Peer Advertisement: Proactive peer sharing
  4. Keep-Alive: Connection maintenance
  5. Goodbye: Graceful peer departure

Message Types

  • Data: Standard message routing
  • RoutingUpdate: Routing table updates
  • LinkState: Topology changes
  • DistanceVector: Distance information
  • Error: Error notifications

Error Handling

The system includes comprehensive error handling:

  • Network Errors: Connection failures, timeouts
  • Protocol Errors: Invalid messages, version mismatches
  • Resource Errors: Memory allocation failures
  • State Errors: Invalid state transitions

Future Enhancements

Potential improvements and extensions:

  • Security: Encryption, authentication, anti-spam measures
  • Performance: Caching, compression, adaptive algorithms
  • Monitoring: Metrics collection, health monitoring
  • Resilience: Fault tolerance, self-healing networks
  • Scalability: Sharding, hierarchical routing
  • IPv6: Full IPv6 support and dual-stack operation

Dependencies

  • std: Zig standard library
  • Core networking modules (address, socket, connection, buffer)
  • No external dependencies required

License

This implementation is provided as-is for educational and development purposes.

Contributing

When extending or modifying this code:

  1. Follow Zig coding conventions
  2. Include comprehensive tests
  3. Update documentation
  4. Consider performance implications
  5. Maintain backward compatibility where possible