This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

980
docs/library_design.md Normal file
View File

@@ -0,0 +1,980 @@
# P2P Zig Library Architecture Design
## Table of Contents
1. [Overview](#overview)
2. [Module Architecture](#module-architecture)
3. [Core Components](#core-components)
4. [API Design](#api-design)
5. [Data Structures](#data-structures)
6. [Data Flow Diagrams](#data-flow-diagrams)
7. [Component Interactions](#component-interactions)
8. [Memory Management](#memory-management)
9. [Error Handling](#error-handling)
10. [Performance Considerations](#performance-considerations)
11. [Security Model](#security-model)
12. [Configuration](#configuration)
13. [Integration Patterns](#integration-patterns)
## Overview
The P2P Zig library is a native implementation of a peer-to-peer networking framework designed for high-performance, low-latency applications. The library provides a comprehensive set of tools for building distributed systems without relying on any third-party dependencies.
### Design Principles
- **Zero Dependencies**: Pure Zig implementation with only standard library usage
- **High Performance**: Optimized for low-latency, high-throughput scenarios
- **Memory Safe**: Zig's safety features prevent common networking vulnerabilities
- **Modular**: Flexible architecture allowing selective feature usage
- **Type Safe**: Strong typing throughout the codebase
- **Async/Sync Support**: Both synchronous and asynchronous operation modes
## Module Architecture
```
p2p/
├── core/ # Core networking abstractions
│ ├── address.zig # Network address handling
│ ├── buffer.zig # Buffer management
│ ├── connection.zig # Connection abstraction
│ └── error.zig # Error types and handling
├── transport/ # Transport layer implementations
│ ├── tcp.zig # TCP transport
│ ├── udp.zig # UDP transport
│ ├── quic.zig # QUIC transport (future)
│ └── interface.zig # Transport interface
├── protocol/ # Protocol implementations
│ ├── message.zig # Message definitions
│ ├── handler.zig # Message handlers
│ ├── router.zig # Message routing
│ └── serialization.zig # Data serialization
├── network/ # Network topology and management
│ ├── node.zig # Node representation
│ ├── topology.zig # Network topology
│ ├── discovery.zig # Peer discovery
│ └── routing.zig # Routing algorithms
├── crypto/ # Cryptographic operations
│ ├── hash.zig # Hash functions
│ ├── signature.zig # Digital signatures
│ ├── encryption.zig # Encryption/decryption
│ └── key_manager.zig # Key management
├── storage/ # Data persistence
│ ├── kv_store.zig # Key-value storage
│ ├── state_manager.zig # State synchronization
│ └── persistence.zig # Data persistence
├── sync/ # Synchronization primitives
│ ├── channel.zig # Channels
│ ├── mutex.zig # Mutexes
│ ├── atomic.zig # Atomic operations
│ └── barrier.zig # Barriers
└── main.zig # Main library interface
```
## Core Components
### 1. Core Module (`core/`)
#### Address Management (`address.zig`)
- Network address abstraction supporting IPv4, IPv6, and custom protocols
- Port management and validation
- Address parsing and formatting
- Comparison and hashing utilities
#### Buffer Management (`buffer.zig`)
- Zero-copy buffer operations
- Dynamic buffer resizing
- Memory pool allocation
- Stream and packet buffer types
#### Connection Management (`connection.zig`)
- Connection state tracking
- Connection pooling
- Health checking and keep-alive
- Graceful shutdown handling
### 2. Transport Layer (`transport/`)
#### Transport Interface (`interface.zig`)
```zig
pub const Transport = struct {
vtable: *const TransportVTable,
const TransportVTable = struct {
connect: *const fn (addr: Address, timeout: u32) Error!Connection,
listen: *const fn (addr: Address, backlog: u32) Error!Listener,
send: *const fn (conn: Connection, data: []const u8) Error!void,
receive: *const fn (conn: Connection, buffer: []u8) Error!usize,
close: *const fn (conn: Connection) Error!void,
};
};
```
#### TCP Implementation (`tcp.zig`)
- Asynchronous TCP socket operations
- Connection multiplexing
- Nagle's algorithm control
- Keep-alive configuration
#### UDP Implementation (`udp.zig`)
- Datagram-oriented operations
- Multicast support
- Connectionless communication
- Fragmentation handling
### 3. Protocol Layer (`protocol/`)
#### Message System (`message.zig`)
```zig
pub const Message = struct {
id: MessageId,
version: u16,
message_type: MessageType,
timestamp: u64,
payload: []const u8,
checksum: Checksum,
};
```
#### Message Handler (`handler.zig`)
- Message dispatching system
- Handler registration and lookup
- Message validation and processing
- Error handling and recovery
#### Message Router (`router.zig`)
- Destination-based routing
- Broadcast and multicast support
- Routing table management
- Path optimization
#### Serialization (`serialization.zig`)
- Binary serialization framework
- Schema validation
- Version compatibility
- Performance-optimized encoding
### 4. Network Layer (`network/`)
#### Node Representation (`node.zig`)
```zig
pub const Node = struct {
id: NodeId,
address: Address,
capabilities: CapabilityFlags,
last_seen: Timestamp,
reputation: f32,
metadata: Metadata,
};
```
#### Topology Management (`topology.zig`)
- Network topology discovery
- Graph-based representation
- Topology optimization
- Failure domain analysis
#### Peer Discovery (`discovery.zig`)
- Bootstrap node discovery
- DHT-based peer finding
- Peer validation and filtering
- Discovery caching
#### Routing (`routing.zig`)
- Distributed hash table (DHT)
- Kademlia-style routing
- Path discovery and optimization
- Route caching and refresh
### 5. Cryptographic Module (`crypto/`)
#### Hash Functions (`hash.zig`)
- SHA-256, SHA-3 implementations
- BLAKE2b for performance-critical paths
- Cryptographic hash abstraction
- Hardware acceleration support
#### Digital Signatures (`signature.zig`)
- ECDSA P-256 signature scheme
- Ed25519 for performance
- Key generation and validation
- Signature verification
#### Encryption (`encryption.zig`)
- AES-256-GCM for symmetric encryption
- Key derivation functions
- Nonce management
- Authenticated encryption
#### Key Management (`key_manager.zig`)
- Key pair generation
- Key storage and retrieval
- Key rotation support
- Secure key deletion
### 6. Storage Module (`storage/`)
#### Key-Value Store (`kv_store.zig`)
```zig
pub const KVStore = struct {
allocator: Allocator,
backend: StorageBackend,
pub fn get(self: *KVStore, key: []const u8) Error!?[]const u8;
pub fn put(self: *KVStore, key: []const u8, value: []const u8) Error!void;
pub fn delete(self: *KVStore, key: []const u8) Error!void;
};
```
#### State Manager (`state_manager.zig`)
- Distributed state synchronization
- Conflict resolution
- State versioning
- Snapshot and recovery
#### Persistence (`persistence.zig`)
- Data serialization to disk
- WAL (Write-Ahead Logging)
- Checkpointing
- Recovery procedures
### 7. Synchronization Module (`sync/`)
#### Channels (`channel.zig`)
- MPSC and MPMC channel implementations
- Bounded and unbounded variants
- Select operation support
- Lock-free implementation
#### Mutexes (`mutex.zig`)
- Fair mutex implementation
- Read-write locks
- Deadlock detection
- Performance monitoring
#### Atomic Operations (`atomic.zig`)
- Lock-free data structures
- Atomic pointers and counters
- Memory ordering guarantees
- Cache line optimization
#### Barriers (`barrier.zig`)
- Synchronization barriers
- Phase barriers
- Thread coordination
- Performance profiling
## API Design
### Main Library Interface
```zig
pub const P2PLibrary = struct {
config: Configuration,
runtime: Runtime,
/// Initialize the P2P library
pub fn init(config: Configuration) Error!P2PLibrary;
/// Start the network service
pub fn start(self: *P2PLibrary) Error!void;
/// Stop the network service
pub fn stop(self: *P2PLibrary) void;
/// Join the network
pub fn join(self: *P2PLibrary, bootstrap_nodes: []const Address) Error!void;
/// Leave the network
pub fn leave(self: *P2PLibrary) Error!void;
/// Send a message to a specific node
pub fn send(self: *P2PLibrary, node_id: NodeId, message: Message) Error!void;
/// Broadcast a message to all connected nodes
pub fn broadcast(self: *P2PLibrary, message: Message) Error!void;
/// Register a message handler
pub fn registerHandler(self: *P2PLibrary, message_type: MessageType, handler: MessageHandler) Error!void;
/// Get connected nodes
pub fn getNodes(self: *P2PLibrary) []const Node;
/// Get network statistics
pub fn getStats(self: *P2PLibrary) NetworkStats;
};
```
### Configuration Structure
```zig
pub const Configuration = struct {
/// Network configuration
network: NetworkConfig,
/// Transport configuration
transport: TransportConfig,
/// Security configuration
security: SecurityConfig,
/// Storage configuration
storage: StorageConfig,
/// Performance tuning
performance: PerformanceConfig,
};
pub const NetworkConfig = struct {
listen_address: Address,
listen_port: u16,
max_connections: u32,
connection_timeout: u32,
keep_alive_interval: u32,
bootstrap_nodes: []const Address,
};
pub const TransportConfig = struct {
tcp_enabled: bool,
udp_enabled: bool,
tcp_buffer_size: usize,
udp_buffer_size: usize,
enable_nagle: bool,
tcp_backlog: u32,
};
pub const SecurityConfig = struct {
enable_encryption: bool,
enable_signatures: bool,
key_rotation_interval: u32,
max_key_age: u32,
allowed_cipher_suites: []const CipherSuite,
};
pub const StorageConfig = struct {
data_directory: []const u8,
max_storage_size: usize,
enable_persistence: bool,
compression_enabled: bool,
cache_size: usize,
};
pub const PerformanceConfig = struct {
worker_threads: u32,
max_message_queue: usize,
buffer_pool_size: usize,
enable_zero_copy: bool,
cpu_affinity: []const u32,
};
```
### Runtime Context
```zig
pub const Runtime = struct {
event_loop: EventLoop,
thread_pool: ThreadPool,
memory_pool: MemoryPool,
scheduler: Scheduler,
pub fn createRuntime(config: Configuration) Error!Runtime;
pub fn runEventLoop(self: *Runtime) void;
pub fn submitTask(self: *Runtime, task: Task) void;
pub fn shutdown(self: *Runtime) void;
};
```
## Data Structures
### Node Identification
```zig
pub const NodeId = struct {
data: [32]u8,
pub fn generate() NodeId;
pub fn fromString(str: []const u8) Error!NodeId;
pub fn toString(self: NodeId) [64]u8;
pub fn equals(self: NodeId, other: NodeId) bool;
};
```
### Message Types
```zig
pub const MessageType = enum(u16) {
ping = 0x01,
pong = 0x02,
find_node = 0x03,
nodes = 0x04,
store = 0x05,
find_value = 0x06,
value = 0x07,
custom = 0x1000..,
};
pub const MessageId = struct {
data: [16]u8,
pub fn generate() MessageId;
pub fn timestamp(self: MessageId) u64;
};
```
### Network Address
```zig
pub const Address = struct {
family: AddressFamily,
data: AddressData,
pub const AddressFamily = enum(u8) {
ipv4 = 1,
ipv6 = 2,
unix = 3,
custom = 4,
};
pub const AddressData = union(AddressFamily) {
ipv4: Ipv4Address,
ipv6: Ipv6Address,
unix: UnixAddress,
custom: CustomAddress,
};
};
```
### Connection State
```zig
pub const ConnectionState = enum(u8) {
disconnected = 0,
connecting = 1,
connected = 2,
closing = 3,
closed = 4,
};
pub const Connection = struct {
id: ConnectionId,
peer: NodeId,
state: ConnectionState,
created_at: Timestamp,
last_activity: Timestamp,
transport: Transport,
};
```
### Network Topology
```zig
pub const Topology = struct {
nodes: []const Node,
edges: []const Edge,
routing_table: RoutingTable,
pub fn addNode(self: *Topology, node: Node) Error!void;
pub fn removeNode(self: *Topology, node_id: NodeId) Error!void;
pub fn addEdge(self: *Topology, from: NodeId, to: NodeId, weight: f32) Error!void;
pub fn findPath(self: *Topology, from: NodeId, to: NodeId) Error!?[]const NodeId;
};
```
## Data Flow Diagrams
### Message Flow
```
[Application] -> [Message Handler] -> [Router] -> [Transport] -> [Network]
|
v
[Network] -> [Transport] -> [Router] -> [Handler] -> [Application]
```
### Connection Establishment
```
[Initiator] [Responder]
| |
|--- SYN -------------------->|
| |
|<--- SYN-ACK ----------------|
| |
|--- ACK -------------------->|
| |
|<--- Handshake Data ---------|
| |
|--- Handshake Response ----->|
| |
[Connection Established]
```
### Peer Discovery Flow
```
[New Node] [Bootstrap Node]
| |
|--- Find Node --------------->|
| |
|<--- Nodes Response ---------|
| |
|--- Ping -------------------->|
| |
|<--- Pong --------------------|
| |
[Peer Added to Routing Table]
```
### Message Routing Flow
```
[Source Node] [Intermediate Node] [Destination Node]
| | |
|--- Message ------------>| |
| |--- Message ------------>|
| | |
| |<--- Response ----------|
| | |
|<--- Response -----------| |
| | |
[Message Delivered]
```
## Component Interactions
### Event Loop Integration
The library integrates with an event-driven architecture:
```zig
pub const Event = union(enum) {
connection_established: ConnectionEstablishedEvent,
connection_closed: ConnectionClosedEvent,
message_received: MessageReceivedEvent,
node_discovered: NodeDiscoveredEvent,
timeout: TimeoutEvent,
};
pub const EventHandler = struct {
handle: *const fn (event: Event) void,
};
pub const EventLoop = struct {
queue: Channel(Event),
handlers: HashMap(EventType, []const EventHandler),
pub fn post(self: *EventLoop, event: Event) void;
pub fn process(self: *EventLoop) void;
};
```
### Memory Management
The library provides sophisticated memory management:
```zig
pub const MemoryPool = struct {
pools: HashMap(usize, Pool),
pub fn allocate(self: *MemoryPool, size: usize) ?*anyopaque;
pub fn deallocate(self: *MemoryPool, ptr: *anyopaque, size: usize) void;
pub fn reset(self: *MemoryPool) void;
};
pub const Pool = struct {
free_list: ?*Node,
chunk_size: usize,
total_chunks: usize,
used_chunks: usize,
};
```
### Thread Safety
All public APIs are thread-safe:
```zig
pub const ThreadSafe(T: type) = struct {
data: T,
mutex: Mutex,
pub fn get(self: *ThreadSafe(T)) *T {
self.mutex.lock();
defer self.mutex.unlock();
return &self.data;
}
};
```
## Memory Management
### Buffer Management
The library implements a sophisticated buffer management system:
```zig
pub const Buffer = struct {
data: []u8,
capacity: usize,
read_pos: usize,
write_pos: usize,
pool: ?*BufferPool,
pub fn create(size: usize, pool: ?*BufferPool) Error!Buffer;
pub fn ensureCapacity(self: *Buffer, capacity: usize) Error!void;
pub fn write(self: *Buffer, data: []const u8) Error!void;
pub fn read(self: *Buffer, data: []u8) Error!usize;
pub fn reset(self: *Buffer) void;
};
```
### Memory Allocation Strategy
1. **Stack Allocation**: Small, short-lived objects
2. **Buffer Pool**: Network buffers with reuse
3. **Object Pool**: Frequently allocated objects
4. **Arena Allocation**: Bulk allocations with deferred cleanup
5. **Shared Pointers**: Reference-counted objects
### Garbage Collection Integration
While Zig doesn't have garbage collection, the library provides deterministic cleanup:
```zig
pub const Defer = struct {
cleanup: *const fn () void,
pub fn defer(cleanup_fn: *const fn () void) Defer {
return Defer{ .cleanup = cleanup_fn };
}
};
```
## Error Handling
### Error Types
```zig
pub const Error = error{
/// Network errors
NetworkError,
ConnectionRefused,
Timeout,
AddressInUse,
/// Protocol errors
ProtocolError,
InvalidMessage,
UnsupportedMessage,
MessageTooLarge,
/// Cryptographic errors
CryptoError,
InvalidSignature,
KeyNotFound,
EncryptionFailed,
/// Storage errors
StorageError,
DiskFull,
PermissionDenied,
CorruptionDetected,
/// System errors
OutOfMemory,
ThreadError,
InvalidArgument,
InvalidState,
};
```
### Error Propagation
All errors are explicitly propagated:
```zig
pub fn connect(remote: Address) Error!Connection {
const socket = try createSocket();
errdefer socket.close();
try socket.connect(remote);
return Connection.init(socket);
}
```
### Recovery Mechanisms
1. **Retry Logic**: Exponential backoff for transient failures
2. **Circuit Breaker**: Fail-fast for persistent failures
3. **Fallback Strategies**: Alternative paths and methods
4. **Graceful Degradation**: Reduced functionality during failures
## Performance Considerations
### Optimization Strategies
1. **Zero-Copy Operations**: Minimize memory copying
2. **Lock-Free Structures**: Reduce contention
3. **CPU Affinity**: Pin threads to specific cores
4. **Cache Line Alignment**: Avoid false sharing
5. **Batch Operations**: Group multiple operations
6. **Asynchronous I/O**: Non-blocking operations
### Performance Monitoring
```zig
pub const Metrics = struct {
bytes_sent: Atomic(u64),
bytes_received: Atomic(u64),
messages_sent: Atomic(u64),
messages_received: Atomic(u64),
connections_active: Atomic(u32),
latency_histogram: Histogram,
pub fn recordLatency(self: *Metrics, latency: u64) void;
pub fn recordMessageSent(self: *Metrics, size: usize) void;
pub fn recordMessageReceived(self: *Metrics, size: usize) void;
};
```
### Memory Layout Optimization
```zig
pub const Node = struct {
id: NodeId align(64),
address: Address align(8),
capabilities: CapabilityFlags align(4),
last_seen: u64 align(8),
reputation: f32 align(4),
metadata: Metadata align(8),
};
```
## Security Model
### Threat Model
1. **Network Attacks**: Man-in-the-middle, replay attacks
2. **DDoS**: Connection flooding, resource exhaustion
3. **Data Corruption**: Malicious messages, tampered data
4. **Privacy**: Traffic analysis, metadata leakage
### Security Measures
#### Encryption
- TLS-like handshake for connection establishment
- End-to-end encryption for messages
- Perfect forward secrecy with key rotation
#### Authentication
- Digital signatures for message authentication
- Certificate pinning for bootstrap nodes
- Reputation-based node validation
#### Rate Limiting
- Connection rate limiting
- Message rate limiting
- Bandwidth quotas per node
#### Secure Randomness
- Cryptographically secure random number generation
- Nonce generation for replay protection
- Key generation entropy
### Security Configuration
```zig
pub const SecurityConfig = struct {
enable_encryption: bool = true,
enable_signatures: bool = true,
require_mutual_auth: bool = false,
min_key_strength: u32 = 256,
certificate_validation: bool = true,
allow_unsigned_messages: bool = false,
max_message_rate: u32 = 1000,
max_connection_rate: u32 = 100,
};
```
## Configuration
### Configuration File Format
```json
{
"network": {
"listen_address": "0.0.0.0",
"listen_port": 8080,
"max_connections": 1000,
"connection_timeout": 30000,
"keep_alive_interval": 30000,
"bootstrap_nodes": [
"192.168.1.10:8080",
"192.168.1.11:8080"
]
},
"transport": {
"tcp_enabled": true,
"udp_enabled": true,
"tcp_buffer_size": 65536,
"udp_buffer_size": 65536,
"enable_nagle": false,
"tcp_backlog": 128
},
"security": {
"enable_encryption": true,
"enable_signatures": true,
"key_rotation_interval": 86400,
"max_key_age": 2592000,
"allowed_cipher_suites": ["AES-256-GCM"]
},
"storage": {
"data_directory": "./p2p_data",
"max_storage_size": 1073741824,
"enable_persistence": true,
"compression_enabled": true,
"cache_size": 104857600
},
"performance": {
"worker_threads": 4,
"max_message_queue": 10000,
"buffer_pool_size": 1024,
"enable_zero_copy": true,
"cpu_affinity": [0, 1, 2, 3]
}
}
```
### Environment Variables
```bash
P2P_LISTEN_PORT=8080
P2P_DATA_DIR=/var/lib/p2p
P2P_LOG_LEVEL=INFO
P2P_ENABLE_METRICS=true
P2P_MAX_CONNECTIONS=1000
```
### Runtime Configuration
```zig
pub fn updateConfig(self: *P2PLibrary, config: Configuration) Error!void {
self.config = config;
self.runtime.updateConfig(config);
self.network.updateConfig(config.network);
self.transport.updateConfig(config.transport);
self.security.updateConfig(config.security);
}
```
## Integration Patterns
### Standalone Application
```zig
pub fn main() !void {
const config = Configuration.fromFile("config.json");
var p2p = try P2PLibrary.init(config);
defer p2p.deinit();
try p2p.start();
try p2p.join(&bootstrap_nodes);
// Application logic here
try p2p.leave();
p2p.stop();
}
```
### Library Integration
```zig
const P2PLibrary = @import("p2p");
const MyApp = struct {
p2p: P2PLibrary,
pub fn init() !MyApp {
const config = Configuration.default();
const p2p = try P2PLibrary.init(config);
try p2p.registerHandler(.custom_message, handleCustomMessage);
return MyApp{ .p2p = p2p };
}
pub fn handleCustomMessage(msg: P2PLibrary.Message) !void {
// Handle custom message
}
};
```
### Microservice Integration
```zig
const HttpServer = @import("http_server");
const P2PLibrary = @import("p2p");
pub fn createMicroservice() !Microservice {
const p2p_config = P2PLibrary.Configuration.default();
const p2p = try P2PLibrary.init(p2p_config);
const http_server = try HttpServer.init(.{
.port = 8080,
.p2p = &p2p,
});
return Microservice{
.p2p = p2p,
.http_server = http_server,
};
}
```
### Testing Integration
```zig
const TestP2P = struct {
nodes: []P2PLibrary,
pub fn createNetwork(num_nodes: usize) !TestP2P {
var nodes = try std.ArrayList(P2PLibrary).initCapacity(std.testing.allocator, num_nodes);
for (0..num_nodes) |i| {
var config = Configuration.default();
config.network.listen_port = 8080 + @as(u16, @intCast(i));
const node = try P2PLibrary.init(config);
try nodes.append(node);
}
return TestP2P{ .nodes = try nodes.toOwnedSlice() };
}
pub fn connectNodes(self: *TestP2P) !void {
for (self.nodes, 0..) |*node, i| {
for (self.nodes[i + 1..], i + 1..) |other_node, j| {
const addr = try node.getAddressOf(j);
try node.connect(addr);
}
}
}
};
```
## Conclusion
This architecture design provides a comprehensive foundation for building a high-performance, secure, and scalable P2P library in Zig. The modular design allows for flexible integration while maintaining strong typing and memory safety throughout the codebase.
### Key Benefits
1. **Zero Dependencies**: Pure Zig implementation
2. **High Performance**: Optimized for modern hardware
3. **Memory Safe**: Zig's safety features prevent vulnerabilities
4. **Type Safe**: Strong typing prevents runtime errors
5. **Modular**: Flexible architecture for various use cases
6. **Secure**: Built-in cryptographic support
7. **Scalable**: Designed for large-scale networks
### Future Enhancements
1. **QUIC Transport**: Modern transport protocol support
2. **IPv6 Enhancements**: Better IPv6 support and optimization
3. **Hardware Acceleration**: SIMD and GPU acceleration
4. **Advanced Routing**: More sophisticated routing algorithms
5. **Mobile Support**: iOS and Android integration
6. **WebAssembly**: Browser-based P2P applications
This design serves as the blueprint for implementing a production-ready P2P library that can scale from small networks to large-scale distributed systems.