Files
zigp2p/src/core
Muhammed Tanrıkulu 600fdd4245 harden core layer. panic on refcount underflow instead of silent error,
replace socket magic numbers with posix constants, fix race where socket
state was set after closing FD
2026-02-10 20:08:11 -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
2026-02-06 21:03:59 -03:00

P2P Library Core Networking Module

The core networking module provides the foundational building blocks for the P2P library, implementing zero-copy buffer management, comprehensive address handling, socket abstractions, and connection management - all built with pure Zig and the standard library.

Architecture Overview

src/core/
├── error.zig         # Comprehensive error handling
├── address.zig       # Network address abstraction
├── buffer.zig        # Zero-copy buffer management
├── socket.zig        # Socket operations and management
├── connection.zig    # High-level connection abstraction
└── README.md         # This documentation

Key Features

🔒 Zero Dependencies

  • Pure Zig implementation using only standard library
  • No external dependencies or C bindings
  • Cross-platform compatibility (Linux, macOS, Windows)

⚡ High Performance

  • Zero-copy buffer operations
  • Memory pool allocation and reuse
  • Lock-free data structures where possible
  • Optimized for low-latency, high-throughput scenarios

🛡️ Memory Safety

  • Zig's safety features prevent common vulnerabilities
  • Explicit error handling and propagation
  • Automatic memory management with proper cleanup
  • Buffer overflow and underflow protection

🔧 Type Safety

  • Strong typing throughout the codebase
  • Compile-time error detection
  • Generic abstractions for reusability
  • Comprehensive API contracts

Module Details

Error Handling (error.zig)

Provides a comprehensive error handling system for the entire P2P library:

const Error = @import("core/error.zig").Error;

// Error categories
pub const Error = error{
    // Network layer errors
    NetworkError,
    ConnectionRefused,
    ConnectionTimeout,
    AddressInUse,
    
    // Protocol errors
    ProtocolError,
    InvalidMessage,
    MessageTooLarge,
    
    // System errors
    OutOfMemory,
    ThreadError,
    InvalidArgument,
    InvalidState,
};

Key Features:

  • Error context with operation, component, and peer information
  • Global error statistics tracking
  • Error result types with additional metadata
  • Conversion helpers for system error codes

Address Management (address.zig)

Network address abstraction supporting multiple address families:

const Address = @import("core/address.zig").Address;

// IPv4 address
const addr = try Address.parse("192.168.1.100:8080");

// IPv6 address
const ipv6 = try Address.parse("[2001:db8::1]:8080");

// Unix socket
const unix = try Address.parse("/tmp/test.sock");

Key Features:

  • IPv4, IPv6, and Unix socket address support
  • Address parsing from strings
  • Address validation and comparison
  • System socket address conversion
  • Address resolution utilities

Buffer Management (buffer.zig)

Zero-copy buffer management with memory pooling:

const Buffer = @import("core/buffer.zig");
var manager = Buffer.BufferManager.init(.{}, allocator);
defer manager.deinit();

// Stream buffer (TCP-like)
const stream_buf = try manager.createStreamBuffer(1024);
defer stream_buf.release();

// Packet buffer (UDP-like)
const packet_buf = try manager.createPacketBuffer(512);
defer packet_buf.release();

// Message buffer with headers
const message_buf = try manager.createMessageBuffer(2048);
defer message_buf.release();

Key Features:

  • Memory pool allocation and reuse
  • Stream, packet, and message buffer types
  • Reference counting and automatic cleanup
  • Buffer compaction and capacity management
  • Reader/writer interfaces

Socket Operations (socket.zig)

Low-level socket management and operations:

const Socket = @import("core/socket.zig").Socket;

// TCP socket
var tcp_socket = try Socket.init(.tcp, allocator);
defer tcp_socket.deinit();

try tcp_socket.bind(try Address.parse("127.0.0.1:8080"));
try tcp_socket.listen(10);

// Accept connections
const client_socket = try tcp_socket.accept();
defer client_socket.deinit();

// UDP socket
var udp_socket = try Socket.init(.udp, allocator);
defer udp_socket.deinit();

try udp_socket.bind(try Address.parse("0.0.0.0:8080"));

// Send/receive data
const data = "Hello, World!";
try udp_socket.send(data);

// Receive with sender address
const result = try udp_socket.receiveFrom(&buffer);

Key Features:

  • TCP, UDP, and Unix socket support
  • Socket option configuration
  • Non-blocking and timeout support
  • Socket pooling and management
  • Statistics and health monitoring

Connection Abstraction (connection.zig)

High-level connection management with TCP/UDP support:

const Connection = @import("core/connection.zig").Connection;

// TCP connection
var connection = try Connection.init(.tcp, config, allocator);
defer connection.deinit();

try connection.connect(try Address.parse("192.168.1.100:8080"));

// Send/receive with automatic buffer management
const send_buffer = try connection.createSendBuffer();
defer send_buffer.release();

try send_buffer.write("Hello, World!");
try connection.sendBuffer(send_buffer);

// Health checking
const health = connection.checkHealth();
connection.updateHealthStatus(health);

Key Features:

  • Connection pooling and management
  • Health checking and monitoring
  • Automatic buffer management
  • Graceful shutdown handling
  • Connection statistics and metrics

Usage Examples

Basic Server Setup

const std = @import("std");
const P2P = @import("core");

pub fn main() !void {
    var allocator = std.heap.page_allocator;
    defer (void) allocator.deinit();
    
    // Create TCP socket
    var socket = try P2P.Socket.init(.tcp, allocator);
    defer socket.deinit();
    
    // Bind and listen
    const address = try P2P.Address.parse("127.0.0.1:8080");
    try socket.bind(address);
    try socket.listen(10);
    
    std.debug.print("Server listening on {s}\n", .{try address.toString()});
    
    // Accept connections
    while (true) {
        const client = try socket.accept();
        defer client.deinit();
        
        // Handle client (in practice, would use async/concurrency)
        std.debug.print("New connection from {s}\n", .{
            client.getRemoteAddress().?.toString()
        });
    }
}

Basic Client Setup

pub fn main() !void {
    var allocator = std.heap.page_allocator;
    
    // Create connection
    var connection = try P2P.Connection.init(.tcp, config, allocator);
    defer connection.deinit();
    
    // Connect to server
    const server_addr = try P2P.Address.parse("127.0.0.1:8080");
    try connection.connect(server_addr);
    
    // Send data
    const data = "Hello, Server!";
    try connection.send(data);
    
    // Receive response
    var buffer: [1024]u8 = undefined;
    const n = try connection.receive(&buffer);
    
    std.debug.print("Received: {s}\n", .{buffer[0..n]});
}

Buffer Pool Usage

pub fn processMessages(allocator: mem.Allocator) !void {
    var buffer_manager = P2P.Buffer.BufferManager.init(.{}, allocator);
    defer buffer_manager.deinit();
    
    // Create multiple buffers from pool
    const buffers = try allocator.alloc(P2P.Buffer.StreamBuffer, 10);
    defer {
        for (buffers) |*buf| buf.release();
        allocator.free(buffers);
    }
    
    for (buffers) |*buf, i| {
        buf.* = try buffer_manager.createStreamBuffer(1024 + i * 256);
    }
    
    // Use buffers for network operations
    for (buffers) |*buf| {
        try buf.write("Test message");
        // Buffer will be automatically returned to pool when released
    }
}

Performance Characteristics

Memory Usage

  • Zero-copy operations: Minimizes memory copying overhead
  • Memory pooling: Reduces allocation/deallocation overhead
  • Reference counting: Efficient buffer lifecycle management
  • Compact data structures: Optimized memory layout

CPU Performance

  • Lock-free operations: Where safe, using atomic operations
  • Batch operations: Grouped operations for better cache utilization
  • Inline functions: Compile-time optimization for small operations
  • Memory alignment: Cache-friendly data structure layouts

Network Performance

  • Buffer pooling: Reduces GC pressure and allocation latency
  • Selective receive: Efficient handling of partial data
  • Connection pooling: Reuses established connections
  • Health monitoring: Proactive connection management

Thread Safety

All public APIs are designed to be thread-safe:

  • Immutable data: Address and configuration structures
  • Atomic operations: For counters and state management
  • Mutual exclusion: For shared mutable state
  • Copy-on-write: For buffer modifications

Error Handling

Comprehensive error handling with explicit propagation:

// All functions return explicit errors
pub fn connect(self: *Connection, address: Address) Error!void {
    if (self.state != .disconnected) {
        return Error.ConnectionAlreadyExists;
    }
    
    // ... connection logic
    
    return;
}

Error contexts provide additional debugging information:

const context = ErrorContext.init("connect", "tcp_transport")
    .withPeerId("peer123")
    .withConnectionId("conn456");

const error_result = errWithContext(
    Error.ConnectionRefused,
    context,
    "Failed to connect to peer",
);

Testing

Comprehensive test suite covers:

  • Unit tests: Individual component testing
  • Integration tests: Component interaction testing
  • Performance tests: Benchmark critical operations
  • Memory tests: Valgrind and leak detection
  • Error path tests: Error handling validation

Run tests with:

# Run all tests
bash test/run_tests.sh

# Run individual module tests
zig test test/core/test_error.zig
zig test test/core/test_address.zig
zig test test/core/test_buffer.zig
zig test test/core/test_socket.zig
zig test test/core/test_connection.zig

# Run with coverage
zig test --test-coverage test/core/test_main.zig

Configuration

Socket Configuration

const socket_config = SocketConfig{
    .protocol = .tcp,
    .non_blocking = false,
    .reuse_address = true,
    .reuse_port = false,
    .keep_alive = true,
    .no_delay = true,
    .buffer_size = 64 * 1024, // 64KB
    .timeout_ms = 30000,      // 30 seconds
};

Connection Configuration

const connection_config = ConnectionConfig{
    .connection_type = .tcp,
    .buffer_size = 64 * 1024,
    .timeout_ms = 30000,
    .keep_alive = true,
    .no_delay = true,
    .max_retry_attempts = 3,
    .retry_delay_ms = 1000,
    .health_check_interval = 30000,
    .enable_metrics = true,
};

Buffer Pool Configuration

const pool_config = PoolConfig{
    .min_chunk_size = 1024,
    .max_chunk_size = 1024 * 1024, // 1MB
    .initial_chunks = 8,
    .max_chunks = 256,
    .grow_factor = 2.0,
};

Platform Support

  • Linux: Full support with all features
  • macOS: Full support with all features
  • Windows: Full support (Unix socket support limited)
  • WebAssembly: Experimental (limited I/O support)

Security Considerations

  • Memory safety: Zig's safety features prevent buffer overflows
  • Error handling: Explicit error propagation prevents silent failures
  • Input validation: Address parsing validates all inputs
  • Resource limits: Configurable limits prevent resource exhaustion

Future Enhancements

  • QUIC support: Modern transport protocol
  • IPv6 enhancements: Better IPv6 optimization
  • Async I/O: Event-driven architecture
  • Performance monitoring: Detailed metrics and profiling
  • Compression: Built-in data compression
  • Encryption: Transport layer security

Contributing

When contributing to the core networking module:

  1. Maintain zero dependencies: Use only Zig standard library
  2. Follow error handling patterns: Explicit error propagation
  3. Add comprehensive tests: Include unit, integration, and performance tests
  4. Document public APIs: Provide clear documentation for all public interfaces
  5. Consider thread safety: Ensure all operations are thread-safe
  6. Optimize for performance: Keep zero-copy and efficiency in mind

License

This module is part of the P2P library and follows the same licensing terms.