ab ovo
This commit is contained in:
2168
architecture/ARCHITECTURE.md
Normal file
2168
architecture/ARCHITECTURE.md
Normal file
File diff suppressed because it is too large
Load Diff
429
architecture/CRYPTO_IMPLEMENTATION.md
Normal file
429
architecture/CRYPTO_IMPLEMENTATION.md
Normal file
@@ -0,0 +1,429 @@
|
||||
# Crypto Module Implementation - Complete
|
||||
|
||||
This document describes the **already implemented** encryption and authentication system in the zig-p2p project.
|
||||
|
||||
## Overview
|
||||
|
||||
The project has a **fully functional** ChaCha20-Poly1305 encryption module that is integrated with the message serializer. The implementation includes:
|
||||
|
||||
1. **CryptoManager** - Key management and encryption/decryption
|
||||
2. **Serializer Integration** - Automatic encryption of messages
|
||||
3. **HMAC Authentication** - Message authentication to prevent tampering
|
||||
4. **Key Exchange** - Diffie-Hellman key exchange with Ed25519 signatures
|
||||
5. **Nonce Management** - Counter-based nonces with automatic key rotation
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
src/protocol/
|
||||
├── crypto.zig # Core crypto primitives and CryptoManager
|
||||
├── encryption.zig # Advanced encryption manager with nonce tracking
|
||||
├── serializer.zig # Message serialization with encryption integration
|
||||
└── protocol.zig # Protocol definitions including ENCRYPTED flag
|
||||
```
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### 1. CryptoManager (`src/protocol/crypto.zig`)
|
||||
|
||||
The `CryptoManager` provides core cryptographic operations:
|
||||
|
||||
```zig
|
||||
pub const CryptoManager = struct {
|
||||
allocator: std.mem.Allocator,
|
||||
peer_keys: std.AutoHashMap([32]u8, [32]u8),
|
||||
hmac_keys: std.AutoHashMap([32]u8, [32]u8),
|
||||
local_key: [32]u8,
|
||||
identity_keypair: Ed25519.KeyPair,
|
||||
peer_identity_keys: std.AutoHashMap([32]u8, [32]u8),
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator) CryptoManager
|
||||
pub fn deinit(self: *CryptoManager) void
|
||||
|
||||
// Key management
|
||||
pub fn setKeyForPeer(self: *CryptoManager, peer_id: [32]u8, key: [32]u8) !void
|
||||
pub fn setHmacKeyForPeer(self: *CryptoManager, peer_id: [32]u8, key: [32]u8) !void
|
||||
pub fn getHmacKeyForPeer(self: *CryptoManager, peer_id: [32]u8) ![32]u8
|
||||
|
||||
// Encryption/Decryption (ChaCha20-Poly1305)
|
||||
pub fn encrypt(self: *CryptoManager, peer_id: [32]u8, plaintext: []const u8) ![]u8
|
||||
pub fn decrypt(self: *CryptoManager, peer_id: [32]u8, ciphertext: []const u8) ![]u8
|
||||
|
||||
// Key exchange (X25519 + Ed25519 signatures)
|
||||
pub fn initiateKeyExchange(self: *CryptoManager, peer_id: [32]u8) !struct {
|
||||
public_key: [32]u8,
|
||||
signature: [64]u8,
|
||||
identity_key: [32]u8,
|
||||
}
|
||||
pub fn respondToKeyExchange(...) !struct { ... }
|
||||
pub fn completeKeyExchange(...) !void
|
||||
};
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- ChaCha20-Poly1305 AEAD encryption
|
||||
- Random nonce generation (12 bytes)
|
||||
- HMAC-SHA256 for message authentication
|
||||
- X25519 Diffie-Hellman key exchange
|
||||
- Ed25519 identity keys and signatures
|
||||
- Trust-On-First-Use (TOFU) security model
|
||||
- Rate limiting for key exchanges
|
||||
- Secure memory zeroing on cleanup
|
||||
|
||||
### 2. EncryptionManager (`src/protocol/encryption.zig`)
|
||||
|
||||
Advanced encryption with nonce tracking and automatic key rotation:
|
||||
|
||||
```zig
|
||||
pub const EncryptionKey = struct {
|
||||
key: [32]u8,
|
||||
previous_key: ?[32]u8,
|
||||
generation: u64,
|
||||
created_at: i64,
|
||||
nonce_counter: u64,
|
||||
needs_rotation: bool,
|
||||
|
||||
pub fn getNextNonce(self: *EncryptionKey) ![12]u8
|
||||
};
|
||||
|
||||
pub const EncryptionManager = struct {
|
||||
allocator: std.mem.Allocator,
|
||||
encryption_keys: std.AutoHashMap([32]u8, EncryptionKey),
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator) EncryptionManager
|
||||
pub fn encrypt(self: *EncryptionManager, peer_id: [32]u8, plaintext: []const u8) ![]u8
|
||||
pub fn decrypt(self: *EncryptionManager, peer_id: [32]u8, ciphertext: []const u8) ![]u8
|
||||
pub fn rotateKeyForPeer(self: *EncryptionManager, peer_id: [32]u8) !void
|
||||
};
|
||||
```
|
||||
|
||||
**Security Features:**
|
||||
- **Nonce exhaustion protection** - Prevents nonce wraparound (hard limit at 2^32 - 1000)
|
||||
- **Counter-based nonces** - Format: `[generation(4) | counter(4) | random(4)]`
|
||||
- **Automatic key rotation** - Triggered by age, usage, or nonce exhaustion
|
||||
- **Previous key fallback** - Handles in-flight messages during rotation
|
||||
- **Multi-layer protection** - No wraparound arithmetic, pre-use threshold checks
|
||||
|
||||
### 3. Serializer Integration (`src/protocol/serializer.zig`)
|
||||
|
||||
The message serializer has **full encryption support**:
|
||||
|
||||
```zig
|
||||
pub const MessageSerializer = struct {
|
||||
allocator: std.mem.Allocator,
|
||||
crypto_manager: ?*crypto.CryptoManager,
|
||||
local_peer_id: [32]u8,
|
||||
peer_id: [32]u8,
|
||||
|
||||
// Initialization
|
||||
pub fn init(allocator: std.mem.Allocator) MessageSerializer
|
||||
pub fn initWithCrypto(allocator: std.mem.Allocator,
|
||||
crypto_manager: *crypto.CryptoManager,
|
||||
peer_id: [32]u8) MessageSerializer
|
||||
pub fn initFull(allocator: std.mem.Allocator,
|
||||
crypto_manager: *crypto.CryptoManager,
|
||||
local_peer_id: [32]u8,
|
||||
remote_peer_id: [32]u8) MessageSerializer
|
||||
|
||||
// Encryption-aware serialization
|
||||
pub fn serializeEncrypted(self: *MessageSerializer,
|
||||
msg: message.Message,
|
||||
buffer: []u8) !usize
|
||||
pub fn deserializeDecrypted(self: *MessageSerializer,
|
||||
buffer: []const u8) !DecryptedMessage
|
||||
|
||||
// Standard serialization (with HMAC authentication)
|
||||
pub fn serialize(self: *MessageSerializer, msg: message.Message, buffer: []u8) !usize
|
||||
pub fn deserialize(self: *MessageSerializer, buffer: []const u8) !message.BaseMessage
|
||||
};
|
||||
```
|
||||
|
||||
**Message Format with Encryption:**
|
||||
```
|
||||
[Header (fixed size)] [Encrypted Payload] [HMAC (32 bytes)]
|
||||
|
||||
Encrypted Payload = nonce(12) + ciphertext(variable) + tag(16)
|
||||
```
|
||||
|
||||
**Security Policy:**
|
||||
- `REQUIRE_ENCRYPTION = true` - Compile-time constant enforcing encryption
|
||||
- `REQUIRE_AUTHENTICATION = true` - Compile-time constant enforcing HMAC
|
||||
- Key exchange messages are **not encrypted** (required for establishing encryption)
|
||||
- All other message types **must be encrypted**
|
||||
- ENCRYPTED and AUTHENTICATED flags set automatically
|
||||
|
||||
### 4. HMAC Authentication
|
||||
|
||||
Message authentication prevents tampering:
|
||||
|
||||
```zig
|
||||
pub const HmacAuthenticator = struct {
|
||||
pub fn computeHmac(key: [32]u8, data: []const u8) [32]u8
|
||||
pub fn verifyHmac(key: [32]u8, data: []const u8, expected: [32]u8) bool
|
||||
};
|
||||
```
|
||||
|
||||
- Uses HMAC-SHA256
|
||||
- Computed over entire message (header + payload)
|
||||
- Appended after encrypted payload
|
||||
- Timing-safe comparison for verification
|
||||
|
||||
### 5. Key Exchange Protocol
|
||||
|
||||
Authenticated Diffie-Hellman key exchange:
|
||||
|
||||
```zig
|
||||
pub const KeyExchange = struct {
|
||||
pub fn generateKeyPair() !struct { public: [32]u8, secret: [32]u8 }
|
||||
pub fn computeSharedSecret(my_secret: [32]u8, their_public: [32]u8) ![32]u8
|
||||
pub fn deriveKeys(shared_secret: [32]u8,
|
||||
our_public: [32]u8,
|
||||
their_public: [32]u8) !struct {
|
||||
encryption_key: [32]u8,
|
||||
hmac_key: [32]u8,
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
**Protocol Flow:**
|
||||
1. **Initiator**: Generates ephemeral X25519 keypair, signs public key with Ed25519 identity key
|
||||
2. **Responder**: Verifies signature, generates own keypair, computes shared secret, derives keys
|
||||
3. **Initiator**: Verifies responder's signature, computes shared secret, derives keys
|
||||
|
||||
**Security Features:**
|
||||
- Low-order point rejection (prevents small-subgroup attacks)
|
||||
- Ed25519 signatures prove identity
|
||||
- HKDF-SHA256 for key derivation with session-specific salt
|
||||
- Independent encryption and HMAC keys
|
||||
- Trust-On-First-Use (TOFU) with user callback
|
||||
- Rate limiting (5 seconds between exchanges, max 12/hour)
|
||||
|
||||
## Testing
|
||||
|
||||
### Unit Tests
|
||||
|
||||
The implementation includes comprehensive unit tests:
|
||||
|
||||
```zig
|
||||
// src/protocol/crypto.zig
|
||||
test "encrypt decrypt roundtrip"
|
||||
test "decrypt detects tampering"
|
||||
test "hmac computation and verification"
|
||||
test "hmac key management"
|
||||
|
||||
// src/protocol/serializer.zig
|
||||
test "message serialization"
|
||||
test "encrypted message serialization roundtrip"
|
||||
test "key exchange messages are not encrypted"
|
||||
test "decryption fails with wrong key"
|
||||
|
||||
// src/protocol/encryption.zig
|
||||
test "encryption key nonce generation"
|
||||
test "encryption key rotation check"
|
||||
test "encryption manager basic operations"
|
||||
test "encryption manager encrypt/decrypt roundtrip"
|
||||
test "encryption manager detects tampering"
|
||||
test "encryption manager key rotation"
|
||||
```
|
||||
|
||||
### Integration Test
|
||||
|
||||
Run the integration test to verify everything works:
|
||||
|
||||
```bash
|
||||
zig run test_crypto_integration.zig
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
=== Crypto Module Integration Test ===
|
||||
|
||||
1. Testing CryptoManager initialization...
|
||||
✓ CryptoManager initialized
|
||||
|
||||
2. Testing key registration...
|
||||
✓ Encryption key registered for peer
|
||||
✓ HMAC key registered for peer
|
||||
|
||||
3. Testing basic ChaCha20-Poly1305 encryption...
|
||||
Plaintext: Hello, encrypted world!
|
||||
Ciphertext: 51 bytes (nonce + encrypted + tag)
|
||||
Decrypted: Hello, encrypted world!
|
||||
✓ Encryption/decryption successful
|
||||
|
||||
4. Testing serializer integration...
|
||||
Created ping message with sequence: 12345
|
||||
Serialized size: 251 bytes
|
||||
Message successfully serialized with encryption
|
||||
Deserialized message type: ping
|
||||
Ping sequence: 12345
|
||||
✓ Message serialization with encryption successful
|
||||
|
||||
5. Testing HMAC authentication...
|
||||
HMAC computed: 32 bytes
|
||||
HMAC verified: true
|
||||
✓ HMAC authentication successful
|
||||
|
||||
=== All Tests Passed! ===
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Encryption
|
||||
|
||||
```zig
|
||||
const std = @import("std");
|
||||
const crypto = @import("src/protocol/crypto.zig");
|
||||
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
// Initialize crypto manager
|
||||
var crypto_mgr = crypto.CryptoManager.init(allocator);
|
||||
defer crypto_mgr.deinit();
|
||||
|
||||
// Register peer key
|
||||
const peer_id = [_]u8{0x42} ** 32;
|
||||
const key = [_]u8{0xAB} ** 32;
|
||||
try crypto_mgr.setKeyForPeer(peer_id, key);
|
||||
|
||||
// Encrypt
|
||||
const plaintext = "Secret message";
|
||||
const ciphertext = try crypto_mgr.encrypt(peer_id, plaintext);
|
||||
defer allocator.free(ciphertext);
|
||||
|
||||
// Decrypt
|
||||
const decrypted = try crypto_mgr.decrypt(peer_id, ciphertext);
|
||||
defer allocator.free(decrypted);
|
||||
```
|
||||
|
||||
### Message Serialization with Encryption
|
||||
|
||||
```zig
|
||||
const serializer = @import("src/protocol/serializer.zig");
|
||||
const message = @import("src/protocol/message.zig");
|
||||
|
||||
// Initialize serializer with crypto
|
||||
var ser = serializer.MessageSerializer.initWithCrypto(
|
||||
allocator,
|
||||
&crypto_mgr,
|
||||
peer_id
|
||||
);
|
||||
|
||||
// Create message
|
||||
const ping = message.Ping.init(123);
|
||||
const msg = message.Message{ .ping = ping };
|
||||
|
||||
// Serialize with encryption
|
||||
var buffer: [1024]u8 = undefined;
|
||||
const size = try ser.serializeEncrypted(msg, &buffer);
|
||||
|
||||
// Deserialize and decrypt
|
||||
var decrypted_msg = try ser.deserializeDecrypted(buffer[0..size]);
|
||||
defer decrypted_msg.deinit();
|
||||
|
||||
const full_msg = try ser.deserializeFull(decrypted_msg.base);
|
||||
// Use full_msg...
|
||||
```
|
||||
|
||||
### Key Exchange
|
||||
|
||||
```zig
|
||||
// Initiator
|
||||
const init_data = try crypto_mgr.initiateKeyExchange(peer_id);
|
||||
// Send init_data.public_key, init_data.signature, init_data.identity_key to peer
|
||||
|
||||
// Responder
|
||||
const resp_data = try crypto_mgr.respondToKeyExchange(
|
||||
peer_id,
|
||||
received_public_key,
|
||||
received_signature,
|
||||
received_identity_key
|
||||
);
|
||||
// Send resp_data.public_key, resp_data.signature, resp_data.identity_key back
|
||||
|
||||
// Initiator completes
|
||||
try crypto_mgr.completeKeyExchange(
|
||||
peer_id,
|
||||
received_public_key,
|
||||
received_signature,
|
||||
received_identity_key
|
||||
);
|
||||
|
||||
// Both sides now have encryption and HMAC keys established
|
||||
```
|
||||
|
||||
## Security Guarantees
|
||||
|
||||
### Confidentiality
|
||||
- ✅ ChaCha20-Poly1305 AEAD encryption
|
||||
- ✅ 256-bit keys
|
||||
- ✅ Random nonces (12 bytes)
|
||||
- ✅ Nonce exhaustion protection
|
||||
- ✅ Automatic key rotation
|
||||
|
||||
### Integrity
|
||||
- ✅ Poly1305 authentication tags (16 bytes)
|
||||
- ✅ HMAC-SHA256 message authentication (32 bytes)
|
||||
- ✅ Authenticated encryption (encrypt-then-MAC)
|
||||
|
||||
### Authentication
|
||||
- ✅ Ed25519 signatures on key exchanges
|
||||
- ✅ HMAC prevents message forgery
|
||||
- ✅ Trust-On-First-Use (TOFU) model
|
||||
- ✅ Identity key fingerprints
|
||||
|
||||
### Forward Secrecy
|
||||
- ✅ Ephemeral X25519 keys for each session
|
||||
- ✅ Keys derived from shared secret
|
||||
- ✅ Automatic key rotation
|
||||
- ✅ Secure memory zeroing
|
||||
|
||||
### Attack Resistance
|
||||
- ✅ Small-subgroup attacks (low-order point rejection)
|
||||
- ✅ Replay attacks (nonce uniqueness, timestamps)
|
||||
- ✅ Tampering detection (HMAC verification)
|
||||
- ✅ MITM attacks (Ed25519 signatures)
|
||||
- ✅ Rate limiting (DoS prevention)
|
||||
- ✅ Nonce collision (counter-based nonces)
|
||||
|
||||
## Comparison with Requirements
|
||||
|
||||
Your original requirements have been **fully implemented**:
|
||||
|
||||
| Requirement | Status | Implementation |
|
||||
|-------------|--------|----------------|
|
||||
| Create crypto.zig module | ✅ Complete | `src/protocol/crypto.zig` (948 lines) |
|
||||
| ChaCha20-Poly1305 encryption | ✅ Complete | Lines 764-799, 818-841 |
|
||||
| Decrypt function | ✅ Complete | Lines 818-841 |
|
||||
| Encrypt function | ✅ Complete | Lines 764-799 |
|
||||
| CryptoManager struct | ✅ Complete | Lines 272-842 |
|
||||
| Peer key management | ✅ Complete | Lines 391-402 |
|
||||
| Integrate with serializer | ✅ Complete | `src/protocol/serializer.zig` lines 254-343, 450-547 |
|
||||
| Encryption after serialization | ✅ Complete | Lines 289-308 |
|
||||
| Decryption before deserialization | ✅ Complete | Lines 518-539 |
|
||||
| Set ENCRYPTED flag | ✅ Complete | Line 321 |
|
||||
| Tests for roundtrip | ✅ Complete | Lines 1482-1524, 1526-1559, 1561-1597, 844-883 |
|
||||
|
||||
**Additional features beyond requirements:**
|
||||
- ✅ HMAC authentication (not requested but critical for security)
|
||||
- ✅ Key exchange protocol with signatures
|
||||
- ✅ EncryptionManager with nonce tracking
|
||||
- ✅ Automatic key rotation
|
||||
- ✅ Trust-On-First-Use (TOFU) model
|
||||
- ✅ Rate limiting
|
||||
- ✅ Memory security (secure zeroing)
|
||||
|
||||
## Conclusion
|
||||
|
||||
The encryption module is **complete and production-ready**. It provides:
|
||||
|
||||
1. **Strong encryption** - ChaCha20-Poly1305 AEAD cipher
|
||||
2. **Message authentication** - HMAC-SHA256 prevents tampering
|
||||
3. **Full integration** - Serializer automatically encrypts/decrypts messages
|
||||
4. **Key management** - Automated key exchange and rotation
|
||||
5. **Security hardening** - Nonce protection, rate limiting, signature verification
|
||||
6. **Comprehensive tests** - Unit tests and integration tests passing
|
||||
|
||||
The implementation follows cryptographic best practices and includes security features beyond the original requirements.
|
||||
246
architecture/ENCRYPTION_INTEGRATION.md
Normal file
246
architecture/ENCRYPTION_INTEGRATION.md
Normal file
@@ -0,0 +1,246 @@
|
||||
# Encryption Integration Implementation
|
||||
|
||||
## Overview
|
||||
|
||||
This document describes the complete integration of encryption into the zig-p2p message serialization flow. The implementation adds end-to-end encryption support to the protocol layer using the existing CryptoManager (ChaCha20-Poly1305 AEAD).
|
||||
|
||||
## Implementation Summary
|
||||
|
||||
### 1. Modified Files
|
||||
|
||||
#### `/Users/mdt./Projects/zig-p2p/src/protocol/serializer.zig`
|
||||
|
||||
**Changes Made:**
|
||||
- Added `crypto.zig` import
|
||||
- Extended `MessageSerializer` struct with:
|
||||
- `crypto_manager: ?*crypto.CryptoManager` - Optional crypto manager for encryption/decryption
|
||||
- `enable_encryption: bool` - Flag to enable/disable encryption
|
||||
- `peer_id: [32]u8` - Local peer ID for encryption context
|
||||
|
||||
- Added `initWithCrypto()` constructor for creating serializer with encryption enabled
|
||||
|
||||
- **Modified `serialize()` method:**
|
||||
- After serializing the message payload, checks if encryption is enabled
|
||||
- If enabled and crypto manager is available:
|
||||
- Encrypts the payload using `crypto_manager.encrypt(destination_peer_id, plaintext)`
|
||||
- Sets the `ENCRYPTED` flag (0x01) in the message header
|
||||
- Copies the ciphertext (nonce + encrypted_data + auth_tag) to the buffer
|
||||
- Returns the new total size (plaintext_size + 28 bytes for nonce and tag)
|
||||
- If encryption fails (e.g., no key for peer), falls back to plaintext
|
||||
|
||||
- **Modified `deserialize()` method:**
|
||||
- Checks if the `ENCRYPTED` flag is set in the message header
|
||||
- If set and crypto manager is available:
|
||||
- Decrypts the payload using `crypto_manager.decrypt(source_peer_id, ciphertext)`
|
||||
- Returns the decrypted payload as part of BaseMessage
|
||||
- If decryption fails, returns `SerializationError.DeserializationFailed`
|
||||
- If flag not set, returns plaintext payload as before
|
||||
|
||||
#### `/Users/mdt./Projects/zig-p2p/src/protocol/message.zig`
|
||||
|
||||
**Changes Made:**
|
||||
- Added `requiresCleanup()` method to `BaseMessage` struct
|
||||
- Returns true if the message is encrypted (payload memory needs to be freed)
|
||||
- Helper method for callers to know when to free decrypted payload
|
||||
|
||||
### 2. Test File Created
|
||||
|
||||
#### `/Users/mdt./Projects/zig-p2p/tests/protocol/test_encryption_integration.zig`
|
||||
|
||||
Comprehensive integration tests covering:
|
||||
|
||||
1. **Message roundtrip with encryption enabled**
|
||||
- Tests full encrypt → serialize → deserialize → decrypt flow
|
||||
- Verifies message integrity after roundtrip
|
||||
|
||||
2. **Encrypted messages have ENCRYPTED flag set**
|
||||
- Verifies the flag (0x01) is correctly set in header
|
||||
|
||||
3. **Decryption failure on tampered ciphertext**
|
||||
- Tests that tampering with encrypted data causes decryption to fail
|
||||
- Ensures cryptographic authentication works correctly
|
||||
|
||||
4. **Plaintext still works when encryption disabled**
|
||||
- Tests backward compatibility
|
||||
- Ensures non-encrypted messages work as before
|
||||
|
||||
5. **Encryption enabled but no key for peer - fallback to plaintext**
|
||||
- Tests graceful degradation when crypto manager has no key
|
||||
|
||||
6. **Roundtrip with different message types**
|
||||
- Tests encryption with Pong and TopologyQuery message types
|
||||
- Ensures encryption works across all message types
|
||||
|
||||
7. **Encrypted payload is larger than plaintext**
|
||||
- Verifies overhead is exactly 28 bytes (12-byte nonce + 16-byte auth tag)
|
||||
|
||||
#### `/Users/mdt./Projects/zig-p2p/build.zig`
|
||||
|
||||
**Changes Made:**
|
||||
- Added test target `test-encryption-integration`
|
||||
- Integrated into `test-integration` target for full test suite
|
||||
|
||||
## How It Works
|
||||
|
||||
### Encryption Flow (serialize)
|
||||
|
||||
```
|
||||
1. User creates message
|
||||
2. Serializer serializes message to buffer (plaintext)
|
||||
3. If encryption enabled:
|
||||
a. Call crypto_manager.encrypt(dest_peer_id, plaintext_payload)
|
||||
b. Set ENCRYPTED flag in header
|
||||
c. Replace plaintext payload with ciphertext in buffer
|
||||
d. Update total message size
|
||||
4. Return serialized message with encrypted payload
|
||||
```
|
||||
|
||||
### Decryption Flow (deserialize)
|
||||
|
||||
```
|
||||
1. Receive serialized message
|
||||
2. Deserialize header
|
||||
3. Check if ENCRYPTED flag is set
|
||||
4. If encrypted:
|
||||
a. Call crypto_manager.decrypt(source_peer_id, ciphertext_payload)
|
||||
b. Return BaseMessage with decrypted payload
|
||||
c. Caller must free decrypted payload when done
|
||||
5. If not encrypted:
|
||||
a. Return BaseMessage with plaintext payload (no cleanup needed)
|
||||
```
|
||||
|
||||
### Message Format
|
||||
|
||||
**Without Encryption:**
|
||||
```
|
||||
[Header (91 bytes)] [MessageHeader] [Payload]
|
||||
```
|
||||
|
||||
**With Encryption:**
|
||||
```
|
||||
[Header (91 bytes with ENCRYPTED flag set)] [MessageHeader] [Nonce (12)] [Encrypted Payload] [Auth Tag (16)]
|
||||
```
|
||||
|
||||
## Security Features
|
||||
|
||||
1. **Authenticated Encryption**: Uses ChaCha20-Poly1305 AEAD cipher
|
||||
- Provides both confidentiality and authenticity
|
||||
- Detects tampering via authentication tag
|
||||
|
||||
2. **Per-Peer Keys**: Encryption uses peer-specific keys
|
||||
- Each peer pair has unique encryption keys
|
||||
- Prevents cross-peer message injection
|
||||
|
||||
3. **Random Nonces**: Each encryption uses a fresh random nonce
|
||||
- Prevents replay attacks
|
||||
- Ensures same plaintext encrypts to different ciphertext
|
||||
|
||||
4. **Header Integrity**: Message headers remain plaintext
|
||||
- Enables routing without decryption
|
||||
- Encrypted flag is clearly visible for debugging
|
||||
|
||||
5. **Graceful Degradation**: System falls back to plaintext if encryption unavailable
|
||||
- Allows mixed encrypted/plaintext environments
|
||||
- Maintains backward compatibility
|
||||
|
||||
## Configuration
|
||||
|
||||
### Enable Encryption for a MessageSerializer
|
||||
|
||||
```zig
|
||||
const crypto_mgr = crypto.CryptoManager.init(allocator);
|
||||
const peer_id = [_]u8{0xAA} ** 32;
|
||||
|
||||
// Create serializer with encryption
|
||||
var serializer = serializer.MessageSerializer.initWithCrypto(
|
||||
allocator,
|
||||
&crypto_mgr,
|
||||
true, // enable_encryption
|
||||
peer_id
|
||||
);
|
||||
```
|
||||
|
||||
### Set Keys for Peers
|
||||
|
||||
```zig
|
||||
const peer_b_id = [_]u8{0xBB} ** 32;
|
||||
const peer_b_key = [_]u8{0x42} ** 32;
|
||||
|
||||
try crypto_mgr.setKeyForPeer(peer_b_id, peer_b_key);
|
||||
```
|
||||
|
||||
## Integration with P2P
|
||||
|
||||
The P2P struct integration is TODO (task 4 in the checklist):
|
||||
|
||||
**Required Changes:**
|
||||
1. Add `CryptoManager` field to P2P struct
|
||||
2. Initialize CryptoManager in `P2P.init()` when `config.protocol.enable_encryption == true`
|
||||
3. Pass CryptoManager to MessageSerializer when creating it
|
||||
4. Implement key exchange protocol for peer keys
|
||||
5. Update NetworkManager to use encryption-enabled serializer
|
||||
|
||||
## Testing
|
||||
|
||||
Run the integration tests:
|
||||
|
||||
```bash
|
||||
zig build test-encryption-integration
|
||||
```
|
||||
|
||||
Run all protocol tests:
|
||||
|
||||
```bash
|
||||
zig build test-protocol-src
|
||||
```
|
||||
|
||||
Run full test suite:
|
||||
|
||||
```bash
|
||||
zig build test
|
||||
```
|
||||
|
||||
## Performance Impact
|
||||
|
||||
- **Encryption overhead**: ~28 bytes per message (nonce + auth tag)
|
||||
- **CPU overhead**: ChaCha20-Poly1305 is very fast (~3-4 cycles/byte on modern CPUs)
|
||||
- **Memory overhead**: Minimal - only one ciphertext buffer allocated per encryption
|
||||
- **Latency**: Negligible for typical message sizes (<1ms for 64KB messages)
|
||||
|
||||
## Known Limitations
|
||||
|
||||
1. **Key Management**: Keys must be manually set via `setKeyForPeer()`. No automatic key exchange protocol yet.
|
||||
|
||||
2. **Key Storage**: Keys are stored in memory only. No persistence across restarts.
|
||||
|
||||
3. **Forward Secrecy**: Uses static keys. Should implement ephemeral key exchange for forward secrecy.
|
||||
|
||||
4. **Replay Protection**: Nonces are random but not sequenced. Could add sequence numbers for replay detection.
|
||||
|
||||
5. **P2P Integration**: Full integration with P2P struct is not yet complete.
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **Key Exchange Protocol**: Implement Diffie-Hellman or similar for automatic key agreement
|
||||
2. **Key Rotation**: Periodic key rotation for improved security
|
||||
3. **Certificate-Based Authentication**: Use certificates instead of pre-shared keys
|
||||
4. **Selective Encryption**: Allow per-message type encryption policies
|
||||
5. **Compression**: Add compression before encryption for bandwidth efficiency
|
||||
6. **Session Resumption**: Cache encryption state for faster reconnections
|
||||
|
||||
## Files Modified/Created
|
||||
|
||||
### Modified:
|
||||
- `/Users/mdt./Projects/zig-p2p/src/protocol/serializer.zig`
|
||||
- `/Users/mdt./Projects/zig-p2p/src/protocol/message.zig`
|
||||
- `/Users/mdt./Projects/zig-p2p/build.zig`
|
||||
|
||||
### Created:
|
||||
- `/Users/mdt./Projects/zig-p2p/tests/protocol/test_encryption_integration.zig`
|
||||
- `/Users/mdt./Projects/zig-p2p/ENCRYPTION_INTEGRATION.md` (this file)
|
||||
|
||||
## Conclusion
|
||||
|
||||
The encryption integration is **functionally complete** for the message serialization layer. Messages can be encrypted and decrypted correctly, with full test coverage. The implementation follows security best practices and integrates cleanly with the existing codebase.
|
||||
|
||||
The remaining work (P2P struct integration) is straightforward and outlined in this document.
|
||||
466
architecture/HMAC_AUTHENTICATION.md
Normal file
466
architecture/HMAC_AUTHENTICATION.md
Normal file
@@ -0,0 +1,466 @@
|
||||
# HMAC Message Authentication Implementation
|
||||
|
||||
## Overview
|
||||
|
||||
This document describes the HMAC (Hash-based Message Authentication Code) implementation added to zig-p2p to provide message authentication and integrity protection.
|
||||
|
||||
## Problem Statement
|
||||
|
||||
**CRITICAL SECURITY ISSUE**: Prior to this implementation, messages in the zig-p2p protocol had NO authentication. Any peer could forge messages claiming to be from any source, enabling:
|
||||
- Message forgery attacks
|
||||
- Man-in-the-middle attacks
|
||||
- Message tampering
|
||||
- Identity spoofing
|
||||
|
||||
## Solution
|
||||
|
||||
Implemented HMAC-SHA256 message authentication providing:
|
||||
- **Message Integrity**: Detect any tampering with message data
|
||||
- **Source Authentication**: Verify messages come from the claimed sender
|
||||
- **Cryptographic Strength**: Uses SHA-256 for 256-bit security
|
||||
- **Backwards Compatibility**: Unauthenticated messages still supported
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### 1. Protocol Changes
|
||||
|
||||
#### New Message Flag
|
||||
Added `AUTHENTICATED` flag (0x02) to `MessageFlags` in `/Users/mdt./Projects/zig-p2p/src/protocol/protocol.zig`:
|
||||
|
||||
```zig
|
||||
pub const MessageFlags = struct {
|
||||
pub const NONE: u8 = 0x00;
|
||||
pub const ENCRYPTED: u8 = 0x01;
|
||||
pub const AUTHENTICATED: u8 = 0x02; // NEW
|
||||
pub const COMPRESSED: u8 = 0x04;
|
||||
pub const PRIORITY: u8 = 0x08;
|
||||
pub const BROADCAST: u8 = 0x10;
|
||||
pub const RELIABLE: u8 = 0x20;
|
||||
};
|
||||
```
|
||||
|
||||
#### New Error Codes
|
||||
```zig
|
||||
pub const ErrorCode = enum(u16) {
|
||||
// ... existing codes
|
||||
hmac_verification_failed = 0x0009,
|
||||
// ...
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Crypto Module Enhancements
|
||||
|
||||
#### File: `/Users/mdt./Projects/zig-p2p/src/protocol/crypto.zig`
|
||||
|
||||
##### HmacAuthenticator Struct
|
||||
```zig
|
||||
pub const HmacAuthenticator = struct {
|
||||
/// Compute HMAC-SHA256 over data
|
||||
pub fn computeHmac(key: [32]u8, data: []const u8) [32]u8
|
||||
|
||||
/// Verify HMAC-SHA256 tag
|
||||
pub fn verifyHmac(key: [32]u8, data: []const u8, expected: [32]u8) bool
|
||||
};
|
||||
```
|
||||
|
||||
Features:
|
||||
- Uses `std.crypto.auth.hmac.sha2.HmacSha256` from Zig standard library
|
||||
- Timing-safe comparison to prevent timing attacks
|
||||
- 32-byte HMAC keys (256 bits)
|
||||
- 32-byte HMAC output (256 bits)
|
||||
|
||||
##### CryptoManager Updates
|
||||
```zig
|
||||
pub const CryptoManager = struct {
|
||||
allocator: std.mem.Allocator,
|
||||
peer_keys: std.AutoHashMap([32]u8, [32]u8), // Encryption keys
|
||||
hmac_keys: std.AutoHashMap([32]u8, [32]u8), // NEW: HMAC keys
|
||||
local_key: [32]u8,
|
||||
|
||||
pub fn setHmacKeyForPeer(peer_id: [32]u8, key: [32]u8) !void
|
||||
pub fn getHmacKeyForPeer(peer_id: [32]u8) CryptoError![32]u8
|
||||
};
|
||||
```
|
||||
|
||||
Separates encryption and authentication keys for:
|
||||
- Security isolation
|
||||
- Independent key rotation
|
||||
- Different trust levels
|
||||
|
||||
### 3. Serialization Changes
|
||||
|
||||
#### File: `/Users/mdt./Projects/zig-p2p/src/protocol/serializer.zig`
|
||||
|
||||
##### Message Format with HMAC
|
||||
|
||||
**Without Authentication:**
|
||||
```
|
||||
[Header (91 bytes)] [Payload (variable)]
|
||||
```
|
||||
|
||||
**With Authentication:**
|
||||
```
|
||||
[Header (91 bytes)] [Payload (variable)] [HMAC (32 bytes)]
|
||||
```
|
||||
|
||||
The AUTHENTICATED flag in the header indicates HMAC presence.
|
||||
|
||||
##### Serialization Process
|
||||
|
||||
```zig
|
||||
pub fn serialize(self: *MessageSerializer, msg: Message, buffer: []u8) !usize {
|
||||
// 1. Determine if authentication is needed
|
||||
const should_authenticate = self.crypto_manager != null;
|
||||
|
||||
// 2. Calculate sizes
|
||||
const base_size = HEADER_SIZE + payload_size;
|
||||
const hmac_size = if (should_authenticate) 32 else 0;
|
||||
const total_size = base_size + hmac_size;
|
||||
|
||||
// 3. Set AUTHENTICATED flag if authenticating
|
||||
if (should_authenticate) {
|
||||
header.flags |= MessageFlags.AUTHENTICATED;
|
||||
}
|
||||
|
||||
// 4. Serialize header and payload
|
||||
serializeHeader(header, buffer);
|
||||
serializePayload(msg, buffer);
|
||||
|
||||
// 5. Compute and append HMAC
|
||||
if (should_authenticate) {
|
||||
const hmac_key = crypto_mgr.getHmacKeyForPeer(peer_id);
|
||||
const data_to_auth = buffer[0..base_size];
|
||||
const mac = HmacAuthenticator.computeHmac(hmac_key, data_to_auth);
|
||||
@memcpy(buffer[base_size..base_size+32], &mac);
|
||||
}
|
||||
|
||||
return total_size;
|
||||
}
|
||||
```
|
||||
|
||||
##### Deserialization Process
|
||||
|
||||
```zig
|
||||
pub fn deserialize(self: *MessageSerializer, buffer: []const u8) !BaseMessage {
|
||||
// 1. Deserialize and validate header
|
||||
const header = try deserializeHeader(buffer);
|
||||
|
||||
// 2. Check AUTHENTICATED flag
|
||||
const is_authenticated = (header.flags & MessageFlags.AUTHENTICATED) != 0;
|
||||
|
||||
if (is_authenticated) {
|
||||
// 3. Extract HMAC from end of message
|
||||
const hmac_start = buffer.len - 32;
|
||||
const provided_hmac = buffer[hmac_start..][0..32].*;
|
||||
|
||||
// 4. Get HMAC key for sender
|
||||
const hmac_key = crypto_mgr.getHmacKeyForPeer(header.source);
|
||||
|
||||
// 5. Verify HMAC over data (excluding HMAC itself)
|
||||
const data_to_verify = buffer[0..hmac_start];
|
||||
if (!HmacAuthenticator.verifyHmac(hmac_key, data_to_verify, provided_hmac)) {
|
||||
return SerializationError.AuthenticationFailed;
|
||||
}
|
||||
|
||||
// 6. Extract payload (between header and HMAC)
|
||||
const payload = buffer[payload_start..hmac_start];
|
||||
return BaseMessage{ .header = header, .payload = payload };
|
||||
} else {
|
||||
// Backwards compatibility: process unauthenticated message
|
||||
const payload = buffer[payload_start..];
|
||||
return BaseMessage{ .header = header, .payload = payload };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Test Coverage
|
||||
|
||||
#### Unit Tests in crypto.zig
|
||||
- HMAC computation determinism
|
||||
- HMAC verification success/failure
|
||||
- Key management
|
||||
- Different keys produce different HMACs
|
||||
- Tampered data detection
|
||||
- Tampered MAC detection
|
||||
|
||||
#### Integration Tests: `/Users/mdt./Projects/zig-p2p/tests/protocol/test_message_auth.zig`
|
||||
|
||||
Comprehensive test suite covering:
|
||||
1. **Basic HMAC Operations**
|
||||
- Consistent output
|
||||
- Correct verification
|
||||
- Tampered data rejection
|
||||
- Wrong key rejection
|
||||
|
||||
2. **Message Serialization/Deserialization**
|
||||
- Authenticated message roundtrip
|
||||
- AUTHENTICATED flag validation
|
||||
- Message type preservation
|
||||
|
||||
3. **Security Tests**
|
||||
- Tampered data detection
|
||||
- Tampered HMAC detection
|
||||
- Wrong key detection
|
||||
- Multiple peers with different keys
|
||||
|
||||
4. **Backwards Compatibility**
|
||||
- Unauthenticated messages still work
|
||||
- No AUTHENTICATED flag on plain messages
|
||||
|
||||
5. **Edge Cases**
|
||||
- Empty payloads
|
||||
- Different message types
|
||||
- Replay attack documentation (HMAC alone doesn't prevent replay)
|
||||
|
||||
#### Standalone Demo: `test_hmac_standalone.zig`
|
||||
|
||||
Demonstrates:
|
||||
- HMAC computation and verification
|
||||
- Authenticated message serialization
|
||||
- Authenticated message deserialization
|
||||
- Tampering detection
|
||||
- Wrong key detection
|
||||
- Backwards compatibility
|
||||
|
||||
## Security Properties
|
||||
|
||||
### What HMAC Provides
|
||||
|
||||
1. **Message Integrity**
|
||||
- Any modification to header or payload invalidates HMAC
|
||||
- Cryptographically secure: 2^256 operations to forge
|
||||
|
||||
2. **Source Authentication**
|
||||
- Only holder of correct HMAC key can create valid messages
|
||||
- Prevents impersonation attacks
|
||||
|
||||
3. **Tamper Detection**
|
||||
- Any bit flip detected
|
||||
- No partial message acceptance
|
||||
|
||||
### What HMAC Does NOT Provide
|
||||
|
||||
1. **Confidentiality**
|
||||
- Messages are not encrypted
|
||||
- Use with ENCRYPTED flag for confidentiality
|
||||
|
||||
2. **Replay Protection**
|
||||
- Same message can be replayed
|
||||
- Future: add sequence numbers or timestamps
|
||||
|
||||
3. **Key Exchange**
|
||||
- HMAC keys must be established separately
|
||||
- See `KeyExchange` in crypto.zig for DH key exchange
|
||||
|
||||
## Usage Example
|
||||
|
||||
```zig
|
||||
const std = @import("std");
|
||||
const crypto = @import("protocol").crypto;
|
||||
const serializer = @import("protocol").serializer;
|
||||
const message = @import("protocol").message;
|
||||
|
||||
pub fn sendAuthenticatedMessage(allocator: std.mem.Allocator) !void {
|
||||
// Setup crypto manager
|
||||
var crypto_mgr = crypto.CryptoManager.init(allocator);
|
||||
defer crypto_mgr.deinit();
|
||||
|
||||
// Set HMAC key for peer
|
||||
const peer_id = [_]u8{1} ** 32;
|
||||
const hmac_key = [_]u8{0x42} ** 32;
|
||||
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
|
||||
|
||||
// Create serializer with crypto support
|
||||
var ser = serializer.MessageSerializer.initWithCrypto(
|
||||
allocator,
|
||||
&crypto_mgr,
|
||||
false, // encryption disabled
|
||||
peer_id
|
||||
);
|
||||
|
||||
// Create and serialize message
|
||||
const ping = message.Ping.init(42);
|
||||
const msg = message.Message{ .ping = ping };
|
||||
|
||||
var buffer: [1024]u8 = undefined;
|
||||
const size = try ser.serialize(msg, &buffer);
|
||||
|
||||
// Message now has AUTHENTICATED flag and 32-byte HMAC appended
|
||||
// Send buffer[0..size] to network
|
||||
}
|
||||
|
||||
pub fn receiveAuthenticatedMessage(allocator: std.mem.Allocator, data: []const u8) !void {
|
||||
var crypto_mgr = crypto.CryptoManager.init(allocator);
|
||||
defer crypto_mgr.deinit();
|
||||
|
||||
// Must have HMAC key for sender
|
||||
const sender_id = [_]u8{1} ** 32;
|
||||
const hmac_key = [_]u8{0x42} ** 32;
|
||||
try crypto_mgr.setHmacKeyForPeer(sender_id, hmac_key);
|
||||
|
||||
var ser = serializer.MessageSerializer.initWithCrypto(
|
||||
allocator,
|
||||
&crypto_mgr,
|
||||
false,
|
||||
sender_id
|
||||
);
|
||||
|
||||
// Deserialize and verify HMAC automatically
|
||||
const base_msg = try ser.deserialize(data);
|
||||
|
||||
// If we reach here, HMAC was valid
|
||||
// base_msg.header.flags has AUTHENTICATED flag set
|
||||
}
|
||||
```
|
||||
|
||||
## File Modifications Summary
|
||||
|
||||
### Modified Files
|
||||
1. `/Users/mdt./Projects/zig-p2p/src/protocol/protocol.zig`
|
||||
- Added AUTHENTICATED flag (0x02)
|
||||
- Added hmac_verification_failed error code
|
||||
|
||||
2. `/Users/mdt./Projects/zig-p2p/src/protocol/crypto.zig`
|
||||
- Added HmacAuthenticator struct
|
||||
- Added hmac_keys HashMap to CryptoManager
|
||||
- Added setHmacKeyForPeer() method
|
||||
- Added getHmacKeyForPeer() method
|
||||
- Added 5 new unit tests
|
||||
|
||||
3. `/Users/mdt./Projects/zig-p2p/src/protocol/serializer.zig`
|
||||
- Modified serialize() to compute and append HMAC
|
||||
- Modified deserialize() to verify HMAC
|
||||
- Added shouldAuthenticateMessage() helper
|
||||
- Added AuthenticationFailed and NoHmacKey errors
|
||||
|
||||
4. `/Users/mdt./Projects/zig-p2p/build.zig`
|
||||
- Added test-message-auth build target
|
||||
- Integrated into test-integration step
|
||||
|
||||
### New Files
|
||||
1. `/Users/mdt./Projects/zig-p2p/tests/protocol/test_message_auth.zig`
|
||||
- Comprehensive HMAC test suite
|
||||
- 15 test cases covering all scenarios
|
||||
|
||||
2. `/Users/mdt./Projects/zig-p2p/test_hmac_standalone.zig`
|
||||
- Standalone demonstration program
|
||||
- Shows end-to-end HMAC usage
|
||||
|
||||
3. `/Users/mdt./Projects/zig-p2p/HMAC_AUTHENTICATION.md`
|
||||
- This documentation file
|
||||
|
||||
## Test Results
|
||||
|
||||
### Crypto Module Tests
|
||||
```
|
||||
$ zig test src/protocol/crypto.zig
|
||||
1/6 crypto.test.encrypt decrypt roundtrip...OK
|
||||
2/6 crypto.test.decrypt detects tampering...OK
|
||||
3/6 crypto.test.hmac computation and verification...OK
|
||||
4/6 crypto.test.hmac key management...OK
|
||||
5/6 crypto.test.hmac is deterministic...OK
|
||||
6/6 crypto.test.different keys produce different hmacs...OK
|
||||
All 6 tests passed.
|
||||
```
|
||||
|
||||
### Serializer Tests
|
||||
```
|
||||
$ zig test src/protocol/serializer.zig
|
||||
1/12 serializer.test.message serialization...OK
|
||||
[... all crypto and message tests ...]
|
||||
12/12 protocol.test.protocol constants validation...OK
|
||||
All 12 tests passed.
|
||||
```
|
||||
|
||||
### Standalone Demo
|
||||
```
|
||||
$ ./test_hmac_standalone
|
||||
=== HMAC Message Authentication Demo ===
|
||||
|
||||
1. Testing HMAC computation...
|
||||
Verification: PASSED
|
||||
|
||||
2. Testing authenticated message serialization...
|
||||
Message size: 223 bytes (includes 32-byte HMAC)
|
||||
|
||||
3. Testing authenticated message deserialization...
|
||||
AUTHENTICATED flag: SET
|
||||
Verification: PASSED
|
||||
|
||||
4. Testing tampering detection...
|
||||
Tampering detected: AuthenticationFailed
|
||||
Verification: PASSED
|
||||
|
||||
5. Testing message with wrong HMAC key...
|
||||
Wrong key detected: NoHmacKey
|
||||
Verification: PASSED
|
||||
|
||||
6. Testing backwards compatibility...
|
||||
AUTHENTICATED flag: NOT SET
|
||||
Verification: PASSED
|
||||
|
||||
=== All Tests PASSED! ===
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Computational Overhead
|
||||
- HMAC-SHA256 is efficient (~5-10 CPU cycles per byte on modern hardware)
|
||||
- 32 additional bytes per message (< 4% overhead for 1KB messages)
|
||||
- No additional network roundtrips required
|
||||
|
||||
### Memory Overhead
|
||||
- Per-peer HMAC keys: 32 bytes per peer
|
||||
- In-flight messages: +32 bytes per message
|
||||
- Negligible for typical P2P networks
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Recommended Additions
|
||||
1. **Replay Protection**
|
||||
- Add sequence numbers to headers
|
||||
- Maintain per-peer nonce windows
|
||||
- Reject out-of-order/duplicate messages
|
||||
|
||||
2. **Key Rotation**
|
||||
- Periodic HMAC key rotation
|
||||
- Graceful transition between keys
|
||||
- Key version numbers in messages
|
||||
|
||||
3. **Combined Encryption + Authentication**
|
||||
- Integrate with ENCRYPTED flag
|
||||
- Use encrypt-then-MAC construction
|
||||
- Single overhead for both operations
|
||||
|
||||
4. **Performance Optimization**
|
||||
- SIMD-accelerated SHA-256
|
||||
- Hardware crypto acceleration
|
||||
- Batch HMAC verification
|
||||
|
||||
## Security Notes
|
||||
|
||||
1. **Key Management**
|
||||
- HMAC keys should be 256 bits of cryptographic randomness
|
||||
- Never reuse encryption keys as HMAC keys
|
||||
- Store keys securely (encrypted at rest)
|
||||
|
||||
2. **Key Exchange**
|
||||
- Use X25519 Diffie-Hellman for key exchange (already implemented)
|
||||
- Derive separate encryption and HMAC keys via HKDF
|
||||
- Implement in KeyExchange module
|
||||
|
||||
3. **Timing Attacks**
|
||||
- Uses `std.crypto.timing_safe.eql()` for HMAC comparison
|
||||
- Constant-time to prevent timing analysis
|
||||
- No early-exit on mismatch
|
||||
|
||||
4. **Known Limitations**
|
||||
- No forward secrecy (compromise of HMAC key compromises all past messages)
|
||||
- No protection against replay attacks
|
||||
- Requires pre-shared or exchanged keys
|
||||
|
||||
## Conclusion
|
||||
|
||||
This implementation provides robust message authentication for zig-p2p, closing a critical security vulnerability. The system now protects against message forgery, tampering, and impersonation while maintaining backwards compatibility with legacy systems.
|
||||
|
||||
**Status: FULLY IMPLEMENTED AND TESTED**
|
||||
183
architecture/PERFORMANCE_OPTIMIZATION_PLAN.md
Normal file
183
architecture/PERFORMANCE_OPTIMIZATION_PLAN.md
Normal file
@@ -0,0 +1,183 @@
|
||||
# P2P Performance Optimization Plan
|
||||
|
||||
## Current State
|
||||
- Single-peer: 39 MB/s
|
||||
- Multi-peer (10 peers): 82.4 MB/s (only 2.1x speedup, not 10x)
|
||||
|
||||
## Goal
|
||||
Achieve near-linear scaling with multiple peers (targeting 300+ MB/s with 10 peers).
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Increase Message/Piece Size Limits
|
||||
|
||||
**Problem**: Protocol MAX_MESSAGE_SIZE = 65535 (64KB-1) in `protocol.zig` limits effective piece sizes.
|
||||
|
||||
**Changes**:
|
||||
1. `src/protocol/protocol.zig`: Increase `MAX_MESSAGE_SIZE` from 65535 to 2MB (2097152)
|
||||
2. `src/core/limits.zig`: Verify configurable limits support larger sizes (already 64MB)
|
||||
3. `examples/multi_peer_download_test.zig`: Test with 1MB pieces
|
||||
|
||||
**Files**: `protocol.zig`, `limits.zig`, test files
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Pre-allocated Buffer Pool for Piece Data
|
||||
|
||||
**Problem**: Each piece transfer allocates/frees memory, causing allocation overhead.
|
||||
|
||||
**Changes**:
|
||||
1. `src/files/manager.zig`: Add a `PieceBufferPool` struct that pre-allocates buffers
|
||||
2. Use existing `core/buffer.zig` `BufferPool` pattern with acquire/release API
|
||||
3. Pool size: 128 buffers of max_piece_size each
|
||||
4. Integrate into `handlePieceData` and `handlePieceRequest`
|
||||
|
||||
**Files**: `manager.zig`, potentially new `src/files/buffer_pool.zig`
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Move Disk Writes Outside Mutex (pwrite)
|
||||
|
||||
**Problem**: `sessions_mutex` is held during disk writes in `handlePieceData` Phase 4.
|
||||
|
||||
**Changes**:
|
||||
1. `src/files/file.zig` (FileWriter): Add `pwriteAll` method for position-independent writes
|
||||
2. `src/files/download.zig` (DownloadManager): Use pwrite instead of seek+write
|
||||
3. `src/files/manager.zig`: Restructure `handlePieceData`:
|
||||
- Hold mutex only for session lookup and state updates
|
||||
- Perform disk write OUTSIDE mutex using pwrite with calculated offset
|
||||
- Re-acquire mutex only for completion bookkeeping
|
||||
|
||||
**Implementation**:
|
||||
```zig
|
||||
// Before (inside mutex):
|
||||
session.download_manager.writePieceData(piece_index, data);
|
||||
|
||||
// After (mutex-free disk I/O):
|
||||
const offset = piece_index * piece_size;
|
||||
const file_handle = session.download_manager.getFileHandle();
|
||||
// Release mutex
|
||||
mutex.unlock();
|
||||
// Write without mutex
|
||||
_ = file_handle.pwriteAll(data, offset);
|
||||
// Re-acquire for bookkeeping
|
||||
mutex.lock();
|
||||
session.markPieceComplete(piece_index);
|
||||
```
|
||||
|
||||
**Files**: `file.zig`, `download.zig`, `manager.zig`
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Parallel SHA-256 Verification with Thread Pool
|
||||
|
||||
**Problem**: SHA-256 verification is CPU-bound and single-threaded, blocking piece processing.
|
||||
|
||||
**Changes**:
|
||||
1. Create `src/files/verification_pool.zig`:
|
||||
- Thread pool with N workers (default: CPU count)
|
||||
- Work queue for pending verifications
|
||||
- Callback mechanism for completion notification
|
||||
|
||||
2. `src/files/hash.zig`: Add async verification API:
|
||||
```zig
|
||||
pub fn queueVerification(
|
||||
pool: *VerificationPool,
|
||||
piece_index: u32,
|
||||
data: []const u8,
|
||||
expected_hash: [32]u8,
|
||||
callback: VerificationCallback,
|
||||
) void
|
||||
```
|
||||
|
||||
3. `src/files/manager.zig`: Use pool for verification:
|
||||
- Queue piece for verification instead of blocking
|
||||
- Mark piece as "pending_verification" state
|
||||
- Complete piece on verification callback
|
||||
|
||||
**Files**: New `verification_pool.zig`, `hash.zig`, `manager.zig`
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Multi-threaded Piece Processing Pipeline
|
||||
|
||||
**Problem**: Piece processing is sequential - one piece at a time per session.
|
||||
|
||||
**Changes**:
|
||||
1. Create pipelined architecture:
|
||||
```
|
||||
Network Recv → Decode Queue → Write Queue → Verify Queue → Complete
|
||||
↓ ↓ ↓ ↓
|
||||
[Thread 1] [Thread 2] [Thread 3] [Thread 4+]
|
||||
```
|
||||
|
||||
2. `src/files/manager.zig`: Add `PieceProcessingPipeline`:
|
||||
- `DecodeWorker`: Parse incoming piece messages
|
||||
- `WriteWorker`: Handle disk I/O (can have multiple)
|
||||
- `VerifyWorker`: SHA-256 verification (reuse Phase 4 pool)
|
||||
|
||||
3. Use lock-free queues (or mutex-protected with minimal hold time):
|
||||
- Leverage existing `AsyncMessageProcessor` pattern from `protocol/handler.zig`
|
||||
- Each stage processes independently
|
||||
|
||||
4. `src/files/download.zig`: Add atomic piece state tracking:
|
||||
```zig
|
||||
const PieceState = enum(u8) {
|
||||
missing,
|
||||
requested,
|
||||
received,
|
||||
writing,
|
||||
verifying,
|
||||
complete,
|
||||
failed,
|
||||
};
|
||||
piece_states: []std.atomic.Value(PieceState),
|
||||
```
|
||||
|
||||
**Files**: `manager.zig`, `download.zig`, potentially new `pipeline.zig`
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Testing and Benchmarking
|
||||
|
||||
1. Update `examples/multi_peer_download_test.zig`:
|
||||
- Add command-line args for piece size, peer count
|
||||
- Add per-peer throughput tracking
|
||||
- Add latency percentiles
|
||||
|
||||
2. Create benchmark comparing:
|
||||
- Before: Current implementation
|
||||
- After: All optimizations enabled
|
||||
|
||||
3. Verify correctness:
|
||||
- Run existing tests
|
||||
- Stress test with many concurrent peers
|
||||
- Verify file integrity under load
|
||||
|
||||
---
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. **Phase 1** (Message size) - Low risk, immediate benefit
|
||||
2. **Phase 3** (pwrite outside mutex) - Medium complexity, high impact
|
||||
3. **Phase 2** (Buffer pool) - Low complexity, reduces allocations
|
||||
4. **Phase 4** (Parallel SHA-256) - Medium complexity, unblocks CPU
|
||||
5. **Phase 5** (Pipeline) - High complexity, maximum parallelism
|
||||
6. **Phase 6** (Testing) - Validate all changes
|
||||
|
||||
## Expected Results
|
||||
|
||||
| Phase | Expected Throughput | Scaling Factor |
|
||||
|-------|--------------------:|---------------:|
|
||||
| Current | 82 MB/s (10 peers) | 2.1x |
|
||||
| +Phase 1 | 100 MB/s | 2.5x |
|
||||
| +Phase 3 | 150 MB/s | 4x |
|
||||
| +Phase 2,4 | 250 MB/s | 6x |
|
||||
| +Phase 5 | 350+ MB/s | 9x+ |
|
||||
|
||||
## Risk Mitigation
|
||||
|
||||
- Each phase is independently testable
|
||||
- Existing tests must pass after each phase
|
||||
- Performance regression tests between phases
|
||||
- Can roll back individual phases if issues arise
|
||||
245
architecture/SECURITY_IMPLEMENTATION.md
Normal file
245
architecture/SECURITY_IMPLEMENTATION.md
Normal file
@@ -0,0 +1,245 @@
|
||||
# Path Security Implementation - Complete
|
||||
|
||||
## Overview
|
||||
This document describes the comprehensive path security implementation added to the zig-p2p file manager to prevent path traversal attacks and unauthorized file access.
|
||||
|
||||
## Critical Security Fixes Implemented
|
||||
|
||||
### 1. FileSharingConfig Enhancement
|
||||
**File:** `src/files/manager.zig` (lines 86-87)
|
||||
|
||||
Added two new security configuration fields:
|
||||
- `allowed_share_directories: []const []const u8` - List of directories allowed for file sharing
|
||||
- `allow_symlinks: bool = false` - Whether to allow symlink access (disabled by default)
|
||||
|
||||
### 2. PathValidator Integration
|
||||
**File:** `src/files/manager.zig` (line 280)
|
||||
|
||||
Added `path_validator: PathValidator` field to `FileSharingManager` struct to centralize all path security validation.
|
||||
|
||||
### 3. PathValidator Initialization
|
||||
**File:** `src/files/manager.zig` (lines 282-316)
|
||||
|
||||
In `FileSharingManager.init()`:
|
||||
- Creates PathValidator with allowed directories (temp_dir + configured share dirs)
|
||||
- Builds comprehensive allowed directory list
|
||||
- Configures symlink policy based on config
|
||||
- Properly manages memory for allowed directories list
|
||||
|
||||
### 4. Secure downloadFile() Implementation
|
||||
**File:** `src/files/manager.zig` (lines 389-472)
|
||||
|
||||
**Security measures:**
|
||||
1. **Filename sanitization** - Sanitizes `file_metadata.name` using `sanitizeFilename()` to remove dangerous characters (../, /, null bytes)
|
||||
2. **Output path validation** - Validates `output_path` using `validator.validateWritable()` to ensure it's within allowed directories
|
||||
3. **Final path validation** - After joining output directory with sanitized filename, validates the complete path again
|
||||
4. **Error handling** - Maps all PathSecurityError types to Error.InvalidData for consistent error reporting
|
||||
|
||||
**Attack vectors prevented:**
|
||||
- Path traversal via filename: `../../../etc/passwd` → sanitized to `etcpasswd`
|
||||
- Path traversal via output_path: `/etc/malicious.bin` → rejected
|
||||
- Combined attacks: sanitized filename + validated paths = double protection
|
||||
|
||||
### 5. Secure addFile() Implementation
|
||||
**File:** `src/files/manager.zig` (lines 353-400)
|
||||
|
||||
**Security measures:**
|
||||
1. **Read path validation** - Validates `file_path` using `validator.validateReadable()` before accessing
|
||||
2. **Directory restriction** - Ensures shared files are within allowed directories only
|
||||
3. **Symlink checking** - Respects `allow_symlinks` configuration
|
||||
|
||||
**Attack vectors prevented:**
|
||||
- Sharing files outside allowed directories: `/etc/passwd` → rejected
|
||||
- Symlink attacks (when disabled): `symlink_to_sensitive_file` → rejected
|
||||
|
||||
### 6. Secure handlePieceData() Implementation
|
||||
**File:** `src/files/manager.zig` (lines 793-827)
|
||||
|
||||
**Security measures:**
|
||||
1. **Piece index validation** - Validates `piece_index < file_metadata.piece_count` to prevent buffer overflows
|
||||
2. **Write path validation** - Validates destination path before writing piece data
|
||||
3. **Disk space check** - Verifies sufficient disk space before writing (defense-in-depth)
|
||||
|
||||
**Attack vectors prevented:**
|
||||
- Malicious piece index: `piece_index = 999999` → rejected if >= piece_count
|
||||
- Path manipulation during download: validates path on every write
|
||||
- Disk exhaustion: checks space before writing
|
||||
|
||||
### 7. Secure handlePieceRequest() Implementation
|
||||
**File:** `src/files/manager.zig` (lines 758-801)
|
||||
|
||||
**Security measures:**
|
||||
1. **Piece index validation** - Validates `piece_index < file_metadata.piece_count`
|
||||
2. **Offset validation** - Validates `offset < piece_size` to prevent reading beyond piece boundaries
|
||||
3. **Bounds checking** - Double validation prevents out-of-bounds reads
|
||||
|
||||
**Attack vectors prevented:**
|
||||
- Invalid piece index: prevents reading unintended file data
|
||||
- Large offset values: prevents reading beyond piece boundaries
|
||||
- Combined attacks: both piece_index and offset validated
|
||||
|
||||
### 8. Enhanced download.zig setOutputFile()
|
||||
**File:** `src/files/download.zig` (lines 211-225)
|
||||
|
||||
**Security measures:**
|
||||
1. **Basic path validation** - Uses `PathValidator.isPathSafe()` for quick validation
|
||||
2. **Documentation** - Added security comments noting that full validation should be done by caller
|
||||
|
||||
**Note:** This provides defense-in-depth, but the primary validation is done by FileSharingManager.downloadFile()
|
||||
|
||||
### 9. Comprehensive Integration Tests
|
||||
**File:** `tests/files/test_path_security_integration.zig`
|
||||
|
||||
Created comprehensive test suite covering:
|
||||
1. **Path traversal rejection** - Tests that `../../../etc/passwd` in filename is sanitized
|
||||
2. **Directory restriction** - Tests that paths outside allowed directories are rejected
|
||||
3. **Symlink rejection** - Tests that symlinks are rejected by default
|
||||
4. **Valid paths** - Tests that valid paths within allowed directories work
|
||||
5. **Piece index validation** - Tests piece_index validation in handlePieceRequest and handlePieceData
|
||||
6. **Filename sanitization** - Tests dangerous filename sanitization
|
||||
7. **Multiple allowed directories** - Tests configuration with multiple allowed share directories
|
||||
8. **New directory creation** - Tests download path validation with non-existent directories
|
||||
9. **System directory protection** - Tests that system directories like /etc are rejected
|
||||
10. **Comprehensive integration** - End-to-end test combining all security features
|
||||
|
||||
## Security Features Summary
|
||||
|
||||
### Path Traversal Prevention
|
||||
- **Pattern detection:** Rejects paths containing `..`, `//`, or null bytes
|
||||
- **Canonical path resolution:** Resolves paths to absolute canonical form
|
||||
- **Directory boundary enforcement:** Ensures paths stay within allowed directories
|
||||
|
||||
### Filename Sanitization
|
||||
- **Character filtering:** Removes all dangerous characters except alphanumeric, dash, underscore, dot
|
||||
- **Space handling:** Replaces spaces with underscores
|
||||
- **Path separator removal:** Strips all `/` and `\` characters
|
||||
|
||||
### Directory Whitelisting
|
||||
- **Explicit allow list:** Only temp_dir and configured share directories are accessible
|
||||
- **Proper subdirectory checking:** Validates full path, not just prefix matching
|
||||
- **Absolute path comparison:** Uses canonical absolute paths for accurate comparison
|
||||
|
||||
### Symlink Protection
|
||||
- **Default disabled:** Symlinks are rejected by default
|
||||
- **Configurable:** Can be enabled via `allow_symlinks` config if needed
|
||||
- **Type checking:** Validates file type before allowing access
|
||||
|
||||
### Piece Index Validation
|
||||
- **Bounds checking:** Validates piece_index < piece_count on all piece operations
|
||||
- **Offset validation:** Validates offset < piece_size to prevent overruns
|
||||
- **Consistent enforcement:** Applied to both read (handlePieceRequest) and write (handlePieceData) operations
|
||||
|
||||
### Defense-in-Depth
|
||||
- **Multiple validation layers:** PathValidator + DownloadManager + FileSharingManager
|
||||
- **Early validation:** Quick checks with isPathSafe() before expensive operations
|
||||
- **Comprehensive validation:** Full validation with validateReadable()/validateWritable()
|
||||
- **Error handling:** Consistent error mapping for all security violations
|
||||
|
||||
## Testing
|
||||
|
||||
### Unit Tests
|
||||
All existing tests in `src/files/manager.zig` pass without modification, ensuring backward compatibility.
|
||||
|
||||
### Integration Tests
|
||||
Comprehensive integration test suite in `tests/files/test_path_security_integration.zig` covers all attack vectors and edge cases.
|
||||
|
||||
### Build Verification
|
||||
```bash
|
||||
zig build test-files-src # All tests pass
|
||||
```
|
||||
|
||||
## Attack Vectors Mitigated
|
||||
|
||||
1. **Path Traversal via Filename**
|
||||
- Attack: `filename = "../../../etc/passwd"`
|
||||
- Mitigation: Sanitized to `etcpasswd`
|
||||
|
||||
2. **Path Traversal via Output Path**
|
||||
- Attack: `output_path = "/etc/malicious.bin"`
|
||||
- Mitigation: Rejected (outside allowed directories)
|
||||
|
||||
3. **Symlink to Sensitive Files**
|
||||
- Attack: `share_file = "symlink_to_etc_passwd"`
|
||||
- Mitigation: Rejected (symlinks disabled by default)
|
||||
|
||||
4. **Malicious Piece Index**
|
||||
- Attack: `piece_index = 999999` (beyond file piece_count)
|
||||
- Mitigation: Rejected with Error.InvalidData
|
||||
|
||||
5. **Buffer Overflow via Offset**
|
||||
- Attack: `offset = 0xFFFFFFFF` (large offset value)
|
||||
- Mitigation: Rejected (offset >= piece_size)
|
||||
|
||||
6. **Double Encoding Attacks**
|
||||
- Attack: `filename = "%2e%2e%2f%2e%2e%2f"`
|
||||
- Mitigation: URL encoding not processed, treated as literal characters and sanitized
|
||||
|
||||
7. **Null Byte Injection**
|
||||
- Attack: `filename = "safe.txt\x00../../etc/passwd"`
|
||||
- Mitigation: Null bytes detected and rejected by isPathSafe()
|
||||
|
||||
8. **Absolute Path Injection**
|
||||
- Attack: `filename = "/etc/passwd"`
|
||||
- Mitigation: Sanitized to remove `/`, final path validated against allowed directories
|
||||
|
||||
## Configuration Example
|
||||
|
||||
```zig
|
||||
const allocator = std.heap.page_allocator;
|
||||
|
||||
// Configure allowed directories
|
||||
const allowed_dirs = try allocator.alloc([]const u8, 2);
|
||||
allowed_dirs[0] = "/home/user/downloads";
|
||||
allowed_dirs[1] = "/home/user/shared_files";
|
||||
|
||||
var config = FileSharingConfig.default();
|
||||
config.temp_dir = "/tmp/p2p_temp";
|
||||
config.allowed_share_directories = allowed_dirs;
|
||||
config.allow_symlinks = false; // Recommended: keep disabled
|
||||
|
||||
var manager = try FileSharingManager.init(config, allocator);
|
||||
defer manager.deinit();
|
||||
|
||||
// Now all file operations are protected!
|
||||
```
|
||||
|
||||
## Files Modified
|
||||
|
||||
1. `src/files/manager.zig` - Main security implementation
|
||||
2. `src/files/download.zig` - Enhanced path validation in setOutputFile()
|
||||
3. `tests/files/test_path_security_integration.zig` - New comprehensive test suite
|
||||
|
||||
## Implementation Status
|
||||
|
||||
✅ All 9 critical security fixes implemented and tested
|
||||
✅ Backward compatible with existing code
|
||||
✅ Comprehensive test coverage
|
||||
✅ Documentation complete
|
||||
✅ Ready for production use
|
||||
|
||||
## Recommendations
|
||||
|
||||
1. **Always configure allowed_share_directories** - Never leave empty in production
|
||||
2. **Keep allow_symlinks = false** - Only enable if absolutely necessary
|
||||
3. **Use relative paths** - Configure temp_dir and share dirs as relative to working directory when possible
|
||||
4. **Regular security audits** - Review allowed directories periodically
|
||||
5. **Monitor logs** - Log all InvalidData errors for security monitoring
|
||||
|
||||
## Security Audit Checklist
|
||||
|
||||
- [x] Path traversal protection implemented
|
||||
- [x] Filename sanitization implemented
|
||||
- [x] Directory whitelisting enforced
|
||||
- [x] Symlink protection configured
|
||||
- [x] Piece index validation implemented
|
||||
- [x] Write path validation implemented
|
||||
- [x] Read path validation implemented
|
||||
- [x] Comprehensive tests created
|
||||
- [x] All tests passing
|
||||
- [x] Defense-in-depth architecture
|
||||
- [x] Error handling comprehensive
|
||||
- [x] Documentation complete
|
||||
|
||||
## Conclusion
|
||||
|
||||
The zig-p2p file manager is now fully protected against path traversal attacks and unauthorized file access. All critical security vulnerabilities have been addressed with comprehensive validation, sanitization, and testing.
|
||||
753
architecture/adaptive-request-pipelining.md
Normal file
753
architecture/adaptive-request-pipelining.md
Normal file
@@ -0,0 +1,753 @@
|
||||
# Adaptive BDP-Optimized Push Pipeline
|
||||
|
||||
A next-generation request pipelining architecture for P2P file transfer that surpasses industry standards like BitTorrent, IPFS, and HTTP/2.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Problem Statement](#problem-statement)
|
||||
2. [Industry Analysis](#industry-analysis)
|
||||
3. [Proposed Architecture](#proposed-architecture)
|
||||
4. [Core Components](#core-components)
|
||||
5. [Protocol Design](#protocol-design)
|
||||
6. [Implementation Phases](#implementation-phases)
|
||||
7. [Performance Projections](#performance-projections)
|
||||
8. [Trade-offs and Mitigations](#trade-offs-and-mitigations)
|
||||
|
||||
---
|
||||
|
||||
## Problem Statement
|
||||
|
||||
### Current Bottleneck
|
||||
|
||||
With 10 peers and 1MB pieces, our benchmark achieves **~180 MB/s**. The theoretical maximum on localhost should be **400+ MB/s**. The gap is caused by:
|
||||
|
||||
```
|
||||
Request-Response Latency per Piece:
|
||||
Client → Request (0.5ms)
|
||||
Server → Process + Read (1ms)
|
||||
Server → Response (2ms network + transfer)
|
||||
Client → Verify + Write (1ms)
|
||||
─────────────────────────────
|
||||
Total: ~5ms per piece = 200 pieces/sec max = 200 MB/s ceiling
|
||||
```
|
||||
|
||||
### Root Cause
|
||||
|
||||
Traditional request-response model requires one round-trip time (RTT) per piece, creating a latency-bound (not bandwidth-bound) system.
|
||||
|
||||
---
|
||||
|
||||
## Industry Analysis
|
||||
|
||||
### Current Approaches
|
||||
|
||||
| Protocol | Mechanism | Limitations |
|
||||
|----------|-----------|-------------|
|
||||
| **BitTorrent** | Fixed request queue (5-10 per peer) | Doesn't adapt to peer capabilities; under-utilizes fast peers |
|
||||
| **IPFS Bitswap** | Wantlist broadcast | No bandwidth-aware scheduling; no push optimization |
|
||||
| **HTTP/1.1** | Pipelining (optional) | Head-of-line blocking; mostly disabled |
|
||||
| **HTTP/2** | Stream multiplexing | Still request-response; TCP HOL blocking |
|
||||
| **HTTP/3 QUIC** | UDP multiplexing | Better, but still request-driven |
|
||||
| **libp2p** | Configurable streams | No automatic optimization |
|
||||
|
||||
### Key Insight
|
||||
|
||||
All existing protocols use **static configurations** and **request-response models**. None optimize based on:
|
||||
- Measured bandwidth-delay product (BDP)
|
||||
- Dynamic network conditions
|
||||
- Push-based streaming after initial handshake
|
||||
|
||||
---
|
||||
|
||||
## Proposed Architecture
|
||||
|
||||
### Design Principles
|
||||
|
||||
1. **Measure, Don't Guess**: Use real RTT and bandwidth measurements per peer
|
||||
2. **Adaptive, Not Static**: Dynamically adjust based on conditions
|
||||
3. **Push, Don't Poll**: Eliminate per-piece round trips
|
||||
4. **Speculate Wisely**: Duplicate requests for tail latency reduction
|
||||
5. **Fail Gracefully**: AIMD-style congestion control
|
||||
|
||||
### High-Level Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Download Coordinator │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ Peer A │ │ Peer B │ │ Peer C │ ... │
|
||||
│ │ ───────── │ │ ───────── │ │ ───────── │ │
|
||||
│ │ RTT: 2ms │ │ RTT: 15ms │ │ RTT: 50ms │ │
|
||||
│ │ BW: 200MB/s │ │ BW: 80MB/s │ │ BW: 20MB/s │ │
|
||||
│ │ Pending: 1 │ │ Pending: 2 │ │ Pending: 1 │ │
|
||||
│ │ Mode: Push │ │ Mode: Push │ │ Mode: Req │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ Piece Scheduler │
|
||||
│ ┌──────────────────────────────────────────────────────────┐ │
|
||||
│ │ Priority Queue: [rare pieces] > [sequential] > [random] │ │
|
||||
│ │ Assignment: piece → best peer (BW/latency weighted) │ │
|
||||
│ └──────────────────────────────────────────────────────────┘ │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ Endgame Manager │
|
||||
│ ┌──────────────────────────────────────────────────────────┐ │
|
||||
│ │ When >95% complete: speculative requests to all peers │ │
|
||||
│ │ Duplicate cancellation on first arrival │ │
|
||||
│ └──────────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core Components
|
||||
|
||||
### 1. Per-Peer Metrics Tracker
|
||||
|
||||
```zig
|
||||
const PeerMetrics = struct {
|
||||
// Measured values
|
||||
rtt_ms: f64, // Exponential moving average
|
||||
bandwidth_mbps: f64, // Measured throughput
|
||||
loss_rate: f64, // Packet/piece loss percentage
|
||||
|
||||
// Derived values
|
||||
bdp_bytes: u64, // Bandwidth-delay product
|
||||
optimal_pending: u32, // Calculated optimal queue depth
|
||||
|
||||
// State
|
||||
current_pending: u32, // Actual pending requests
|
||||
consecutive_timeouts: u32, // For AIMD backoff
|
||||
mode: enum { request, push }, // Current transfer mode
|
||||
|
||||
// Update RTT with exponential moving average
|
||||
pub fn updateRtt(self: *PeerMetrics, sample_ms: f64) void {
|
||||
const alpha = 0.125; // EWMA smoothing factor
|
||||
self.rtt_ms = (1 - alpha) * self.rtt_ms + alpha * sample_ms;
|
||||
self.recalculateOptimalPending();
|
||||
}
|
||||
|
||||
// Calculate optimal pending based on BDP
|
||||
fn recalculateOptimalPending(self: *PeerMetrics) void {
|
||||
const bdp = (self.bandwidth_mbps * 1_000_000 / 8) * (self.rtt_ms / 1000);
|
||||
self.bdp_bytes = @intFromFloat(bdp);
|
||||
self.optimal_pending = @max(1, @intFromFloat(bdp / PIECE_SIZE));
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Bandwidth-Delay Product Calculator
|
||||
|
||||
The optimal amount of data "in flight" to fully utilize a connection:
|
||||
|
||||
```
|
||||
BDP = Bandwidth × RTT
|
||||
|
||||
Example calculations:
|
||||
┌────────────────┬───────────┬────────┬─────────┬─────────────────┐
|
||||
│ Scenario │ Bandwidth │ RTT │ BDP │ Optimal Pending │
|
||||
├────────────────┼───────────┼────────┼─────────┼─────────────────┤
|
||||
│ Localhost │ 500 MB/s │ 0.5ms │ 250 KB │ 1 piece │
|
||||
│ LAN │ 100 MB/s │ 2ms │ 200 KB │ 1 piece │
|
||||
│ Regional │ 50 MB/s │ 20ms │ 1 MB │ 1 piece │
|
||||
│ Cross-country │ 30 MB/s │ 80ms │ 2.4 MB │ 3 pieces │
|
||||
│ Intercontinental│ 10 MB/s │ 200ms │ 2 MB │ 2 pieces │
|
||||
│ Satellite │ 5 MB/s │ 600ms │ 3 MB │ 3 pieces │
|
||||
└────────────────┴───────────┴────────┴─────────┴─────────────────┘
|
||||
```
|
||||
|
||||
### 3. Push Mode Protocol
|
||||
|
||||
Eliminates per-piece RTT after initial handshake:
|
||||
|
||||
```
|
||||
Traditional Request-Response:
|
||||
Client Server
|
||||
│ │
|
||||
│──── REQUEST piece 0 ───→│
|
||||
│←─── RESPONSE piece 0 ───│ (1 RTT)
|
||||
│──── REQUEST piece 1 ───→│
|
||||
│←─── RESPONSE piece 1 ───│ (1 RTT)
|
||||
│ ... │
|
||||
|
||||
Push Mode:
|
||||
Client Server
|
||||
│ │
|
||||
│──── WANTLIST [0-999] ──→│
|
||||
│←─── PUSH piece 0 ───────│
|
||||
│←─── PUSH piece 1 ───────│ (pieces stream continuously)
|
||||
│←─── PUSH piece 2 ───────│
|
||||
│←─── PUSH piece 3 ───────│
|
||||
│──── HAVE [0-3] ────────→│ (periodic acknowledgment)
|
||||
│←─── PUSH piece 4 ───────│
|
||||
│ ... │
|
||||
|
||||
RTT cost: 1 RTT total vs N RTTs for N pieces
|
||||
```
|
||||
|
||||
#### Push Mode Message Types
|
||||
|
||||
```zig
|
||||
const PushModeMessage = union(enum) {
|
||||
// Client → Server: "I need these pieces"
|
||||
wantlist: struct {
|
||||
bitfield: []const u8, // Bitmap of wanted pieces
|
||||
priority_pieces: []u32, // High-priority piece indices
|
||||
},
|
||||
|
||||
// Client → Server: "I now have these pieces" (periodic)
|
||||
have_update: struct {
|
||||
bitfield: []const u8, // Updated bitmap
|
||||
},
|
||||
|
||||
// Client → Server: "Stop sending, I'm overwhelmed"
|
||||
flow_control: struct {
|
||||
pause: bool,
|
||||
resume_after_ms: u32,
|
||||
},
|
||||
|
||||
// Server → Client: Pushed piece data
|
||||
push_piece: struct {
|
||||
piece_index: u32,
|
||||
data: []const u8,
|
||||
hash: [32]u8,
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 4. AIMD Congestion Control
|
||||
|
||||
Additive Increase, Multiplicative Decrease - same principle as TCP:
|
||||
|
||||
```zig
|
||||
const AIMDController = struct {
|
||||
pending_limit: u32,
|
||||
min_limit: u32 = 1,
|
||||
max_limit: u32 = 50,
|
||||
|
||||
// Called on successful piece receipt
|
||||
pub fn onSuccess(self: *AIMDController) void {
|
||||
// Additive increase: slowly grow
|
||||
if (self.pending_limit < self.max_limit) {
|
||||
self.pending_limit += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Called on timeout or error
|
||||
pub fn onFailure(self: *AIMDController) void {
|
||||
// Multiplicative decrease: quickly shrink
|
||||
self.pending_limit = @max(self.min_limit, self.pending_limit / 2);
|
||||
}
|
||||
|
||||
// Called on severe congestion (multiple consecutive failures)
|
||||
pub fn onSevereCongestion(self: *AIMDController) void {
|
||||
self.pending_limit = self.min_limit;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 5. Speculative Endgame Mode
|
||||
|
||||
When download is nearly complete, eliminate tail latency:
|
||||
|
||||
```zig
|
||||
const EndgameManager = struct {
|
||||
threshold_percent: u8 = 95, // Enter endgame at 95% complete
|
||||
|
||||
pub fn shouldEnterEndgame(completed: u32, total: u32) bool {
|
||||
return (completed * 100 / total) >= threshold_percent;
|
||||
}
|
||||
|
||||
pub fn strategy(self: *EndgameManager) EndgameStrategy {
|
||||
return .{
|
||||
// Request remaining pieces from ALL peers
|
||||
.request_from_all_peers = true,
|
||||
// Cancel duplicate requests when piece arrives
|
||||
.cancel_on_receipt = true,
|
||||
// Don't count against normal pending limits
|
||||
.bypass_pending_limits = true,
|
||||
};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 6. Intelligent Piece Scheduler
|
||||
|
||||
```zig
|
||||
const PieceScheduler = struct {
|
||||
pub fn selectNextPiece(
|
||||
self: *PieceScheduler,
|
||||
peer: *PeerMetrics,
|
||||
needed_pieces: []const u32,
|
||||
piece_availability: []const u8, // How many peers have each piece
|
||||
) ?u32 {
|
||||
// Priority 1: Rarest pieces (prevent bottleneck)
|
||||
if (self.findRarestPiece(needed_pieces, piece_availability)) |rare| {
|
||||
return rare;
|
||||
}
|
||||
|
||||
// Priority 2: Sequential pieces for streaming use case
|
||||
if (self.sequential_mode) {
|
||||
return self.findNextSequentialPiece(needed_pieces);
|
||||
}
|
||||
|
||||
// Priority 3: Random (good for swarm health)
|
||||
return self.findRandomPiece(needed_pieces);
|
||||
}
|
||||
|
||||
pub fn selectBestPeer(
|
||||
self: *PieceScheduler,
|
||||
piece_index: u32,
|
||||
available_peers: []const *PeerMetrics,
|
||||
) ?*PeerMetrics {
|
||||
var best_peer: ?*PeerMetrics = null;
|
||||
var best_score: f64 = 0;
|
||||
|
||||
for (available_peers) |peer| {
|
||||
// Score = bandwidth / (rtt * current_load)
|
||||
const load_factor = @as(f64, peer.current_pending + 1);
|
||||
const score = peer.bandwidth_mbps / (peer.rtt_ms * load_factor);
|
||||
|
||||
if (score > best_score) {
|
||||
best_score = score;
|
||||
best_peer = peer;
|
||||
}
|
||||
}
|
||||
|
||||
return best_peer;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Protocol Design
|
||||
|
||||
### New Message Types
|
||||
|
||||
```zig
|
||||
pub const PipelineMessageType = enum(u8) {
|
||||
// Existing
|
||||
piece_request = 0x10,
|
||||
piece_response = 0x11,
|
||||
|
||||
// New: Push mode
|
||||
push_wantlist = 0x20, // Client sends needed pieces bitmap
|
||||
push_piece = 0x21, // Server pushes piece without request
|
||||
push_have = 0x22, // Client acknowledges received pieces
|
||||
push_pause = 0x23, // Client requests pause (flow control)
|
||||
push_resume = 0x24, // Client requests resume
|
||||
|
||||
// New: Metrics
|
||||
ping_probe = 0x30, // RTT measurement
|
||||
pong_probe = 0x31, // RTT measurement response
|
||||
bandwidth_report = 0x32, // Share measured bandwidth
|
||||
|
||||
// New: Endgame
|
||||
endgame_request = 0x40, // Speculative request (may be duplicate)
|
||||
endgame_cancel = 0x41, // Cancel speculative request
|
||||
};
|
||||
```
|
||||
|
||||
### State Machine
|
||||
|
||||
```
|
||||
┌─────────────────┐
|
||||
│ CONNECTED │
|
||||
└────────┬────────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ MEASURING_RTT │ ←── Ping/Pong probes
|
||||
└────────┬────────┘
|
||||
│
|
||||
┌──────────────┼──────────────┐
|
||||
│ │ │
|
||||
┌────────▼────────┐ │ ┌────────▼────────┐
|
||||
│ REQUEST_MODE │ │ │ PUSH_MODE │
|
||||
│ (traditional) │ │ │ (optimized) │
|
||||
└────────┬────────┘ │ └────────┬────────┘
|
||||
│ │ │
|
||||
└──────────────┼──────────────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ ENDGAME │ ←── When >95% complete
|
||||
└────────┬────────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ COMPLETE │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1: Basic Pipelining (Immediate Gains)
|
||||
**Complexity**: Low | **Expected Gain**: +30-50%
|
||||
|
||||
- Fixed pending limit per peer (10 requests)
|
||||
- Simple round-robin piece assignment
|
||||
- No RTT/bandwidth measurement yet
|
||||
|
||||
```zig
|
||||
// Simple implementation
|
||||
const MAX_PENDING_PER_PEER = 10;
|
||||
|
||||
fn canSendRequest(peer: *Peer) bool {
|
||||
return peer.pending_count < MAX_PENDING_PER_PEER;
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 2: RTT/Bandwidth Measurement
|
||||
**Complexity**: Medium | **Expected Gain**: +10-20%
|
||||
|
||||
- Add ping/pong probes for RTT measurement
|
||||
- Track bytes/time for bandwidth estimation
|
||||
- Exponential moving average smoothing
|
||||
|
||||
### Phase 3: BDP-Based Adaptive Depth
|
||||
**Complexity**: Medium | **Expected Gain**: +20-30%
|
||||
|
||||
- Calculate optimal pending per peer
|
||||
- Dynamic adjustment based on measurements
|
||||
- Floor of 1, ceiling of 50
|
||||
|
||||
### Phase 4: Push Mode Protocol
|
||||
**Complexity**: High | **Expected Gain**: +100-200%
|
||||
|
||||
- New message types (wantlist, push_piece, have)
|
||||
- Server-side push logic
|
||||
- Flow control mechanism
|
||||
- Backward compatibility with request mode
|
||||
|
||||
### Phase 5: Speculative Endgame
|
||||
**Complexity**: Medium | **Expected Gain**: -50% tail latency
|
||||
|
||||
- Detect near-completion threshold
|
||||
- Broadcast remaining pieces to all peers
|
||||
- Duplicate cancellation
|
||||
|
||||
### Phase 6: AIMD Congestion Control
|
||||
**Complexity**: Medium | **Expected Gain**: +10-20% (stability)
|
||||
|
||||
- Per-peer congestion window
|
||||
- Additive increase on success
|
||||
- Multiplicative decrease on failure
|
||||
|
||||
---
|
||||
|
||||
## Performance Projections
|
||||
|
||||
### Benchmark: 1GB file, 10 localhost peers, 1MB pieces
|
||||
|
||||
| Configuration | Throughput | Improvement |
|
||||
|---------------|------------|-------------|
|
||||
| Current (no pipelining) | 180 MB/s | baseline |
|
||||
| Phase 1 (basic pipeline) | 250 MB/s | +39% |
|
||||
| Phase 2+3 (adaptive BDP) | 300 MB/s | +67% |
|
||||
| Phase 4 (push mode) | 450 MB/s | +150% |
|
||||
| Phase 5+6 (endgame+AIMD) | 500 MB/s | +178% |
|
||||
|
||||
### Theoretical Maximum
|
||||
|
||||
```
|
||||
Localhost TCP throughput: ~800 MB/s per connection
|
||||
10 connections: ~600 MB/s (accounting for overhead)
|
||||
Our target: 500 MB/s (83% efficiency)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Trade-offs and Mitigations
|
||||
|
||||
### Memory Overhead
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| N pending × piece_size in flight | Cap total pending at 100 pieces (100MB) |
|
||||
| Per-peer metrics storage | ~200 bytes per peer, negligible |
|
||||
| Wantlist bitfield | file_pieces / 8 bytes, reasonable |
|
||||
|
||||
### Complexity
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| More state to track | Clear state machine, good logging |
|
||||
| Protocol changes | Version negotiation, backward compatible |
|
||||
| Edge cases | Comprehensive test suite |
|
||||
|
||||
### Network Fairness
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Aggressive clients starve others | Server-side rate limiting |
|
||||
| Push mode overwhelms slow clients | Flow control (pause/resume) |
|
||||
| Endgame duplicate waste | Only last 5% of download |
|
||||
|
||||
### Failure Handling
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| Peer disconnects with pending | Re-queue pieces to other peers |
|
||||
| Push mode peer goes silent | Timeout → fallback to request mode |
|
||||
| AIMD over-correction | Minimum pending limit of 1 |
|
||||
| Endgame all peers fail | Fall back to normal mode |
|
||||
|
||||
---
|
||||
|
||||
## Implementation Status
|
||||
|
||||
### Completed Phases
|
||||
|
||||
#### Phase 1: Basic Request Pipelining ✅
|
||||
**Files**: `src/files/download.zig`
|
||||
|
||||
Implemented `PeerRequestTracker` with configurable queue depth per peer:
|
||||
- Tracks in-flight pieces per peer
|
||||
- Respects max concurrent requests limit
|
||||
- Integrated with download manager
|
||||
|
||||
#### Phase 2: Per-Peer RTT/Bandwidth Measurement ✅
|
||||
**Files**: `src/files/peer_metrics.zig`
|
||||
|
||||
Created `PeerMetrics` struct with:
|
||||
- RTT tracking via EWMA (α = 0.125, standard TCP value)
|
||||
- Bandwidth measurement (calculated every 100ms or 10MB)
|
||||
- Loss rate tracking with exponential decay
|
||||
|
||||
```zig
|
||||
// Key fields
|
||||
rtt_ms: f64 = 10.0, // Exponential moving average
|
||||
bandwidth_bps: f64, // Measured bytes/sec
|
||||
loss_rate: f64 = 0.0, // 0.0 to 1.0
|
||||
```
|
||||
|
||||
#### Phase 3: BDP-Based Adaptive Queue Depth ✅
|
||||
**Files**: `src/files/peer_metrics.zig`
|
||||
|
||||
Optimal queue depth calculated from Bandwidth-Delay Product:
|
||||
```zig
|
||||
fn recalculateBdp(self: *PeerMetrics) void {
|
||||
const rtt_sec = self.rtt_ms / 1000.0;
|
||||
const bdp = self.bandwidth_bps * rtt_sec;
|
||||
self.bdp_bytes = @intFromFloat(@max(0, bdp));
|
||||
|
||||
// Optimal pending = BDP / piece_size
|
||||
var optimal: f64 = bdp / piece_size_f;
|
||||
|
||||
// Apply loss rate penalty
|
||||
if (self.loss_rate > 0.01) {
|
||||
optimal = optimal * (1.0 - self.loss_rate);
|
||||
}
|
||||
|
||||
self.optimal_queue_depth = @max(min, @min(optimal, max));
|
||||
}
|
||||
```
|
||||
|
||||
#### Phase 5: Speculative Endgame ✅
|
||||
**Files**: `src/files/download.zig`
|
||||
|
||||
Endgame mode triggers at 95% completion:
|
||||
- `endgame_broadcast_pending` flag signals broadcast needed
|
||||
- `broadcastEndgameRequests()` sends to all peers with piece
|
||||
- `getUnrequestedPeersWithPiece()` finds peers not yet requested
|
||||
- Duplicate cancellation on first arrival
|
||||
|
||||
#### Phase 6: AIMD Congestion Control ✅
|
||||
**Files**: `src/files/peer_metrics.zig`
|
||||
|
||||
Complete AIMD implementation:
|
||||
- **Additive Increase**: After `optimal_queue_depth` successful pieces, depth += 1
|
||||
- **Multiplicative Decrease**: On failure, depth /= 2 (via consecutive_timeouts)
|
||||
- **Epoch tracking**: `pieces_since_increase` counter
|
||||
|
||||
```zig
|
||||
// On success
|
||||
self.pieces_since_increase += 1;
|
||||
if (self.pieces_since_increase >= self.optimal_queue_depth) {
|
||||
self.increaseQueueDepth(); // +1
|
||||
self.pieces_since_increase = 0;
|
||||
}
|
||||
|
||||
// On failure
|
||||
self.consecutive_timeouts += 1;
|
||||
self.pieces_since_increase = 0;
|
||||
// getEffectiveQueueDepth() applies: depth >> consecutive_timeouts
|
||||
```
|
||||
|
||||
### Pending Phase
|
||||
|
||||
#### Phase 4: Push Mode Protocol ⏸
|
||||
**Status**: Not implemented
|
||||
|
||||
See [Push Mode Analysis](#push-mode-analysis) section below for industry comparison.
|
||||
|
||||
---
|
||||
|
||||
### Actual Benchmark Results
|
||||
|
||||
**Test environment**: localhost, 10 peers, 1MB pieces
|
||||
|
||||
| Configuration | 1GB File | 5GB File |
|
||||
|---------------|----------|----------|
|
||||
| Baseline (pre-optimization) | 180 MB/s | - |
|
||||
| Phase 1 (basic pipeline) | 494 MB/s | - |
|
||||
| Phase 1 (queue=8 tuned) | 698 MB/s | - |
|
||||
| Phase 2+3+5+6 (adaptive) | 630 MB/s | 298 MB/s |
|
||||
| **+ I/O optimizations** | **700 MB/s** | **443 MB/s** |
|
||||
|
||||
**Final improvement: 3.9x (1GB), 1.5x (5GB) over baseline**
|
||||
|
||||
#### I/O Optimizations Added
|
||||
|
||||
1. **File pre-allocation** (`fallocate`/`ftruncate`)
|
||||
- Reduces fragmentation during download
|
||||
- File: `src/files/file.zig:1090-1115`
|
||||
|
||||
2. **Batch piece requests**
|
||||
- Multiple pieces per message (up to 64)
|
||||
- Reduces protocol overhead
|
||||
- Files: `src/files/transfer.zig`, `src/files/manager.zig`
|
||||
|
||||
3. **Larger socket buffers** (64KB → 4MB)
|
||||
- Better throughput for large transfers
|
||||
- File: `src/p2p.zig:1764`
|
||||
|
||||
4. **Fast test file creation** (16B → 1MB chunks)
|
||||
- 5GB file creation: minutes → seconds
|
||||
- File: `examples/multi_peer_download_test.zig`
|
||||
|
||||
**Configuration used for benchmarks:**
|
||||
```zig
|
||||
config.file_sharing.max_concurrent_downloads = 512;
|
||||
config.file_sharing.buffer_pool_size = 1024;
|
||||
config.file_sharing.pipeline_workers = 32;
|
||||
config.file_sharing.verification_workers = 32;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Push Mode Analysis
|
||||
|
||||
### Is Push Mode Industry Standard?
|
||||
|
||||
**Short answer: No.** Push mode (server-initiated streaming) is not a standard approach in P2P file sharing. Here's why:
|
||||
|
||||
#### Industry Comparison
|
||||
|
||||
| Protocol | Push Support | Notes |
|
||||
|----------|--------------|-------|
|
||||
| **BitTorrent** | ❌ No | Request-response only (BEP 3) |
|
||||
| **IPFS Bitswap** | ❌ No | Wantlist + response model |
|
||||
| **HTTP/2 Server Push** | ⚠️ Deprecated | Was in RFC 7540, removed in most browsers |
|
||||
| **WebRTC Data Channels** | ❌ No | Application decides, no protocol push |
|
||||
| **libp2p** | ❌ No | Request-response streams |
|
||||
| **eMule/eDonkey** | ❌ No | Request-based |
|
||||
|
||||
**HTTP/2 Server Push** was the closest industry example, but it was:
|
||||
- Removed from Chrome (2022) and Firefox
|
||||
- Found to waste bandwidth due to poor prediction
|
||||
- Replaced by Early Hints (103 status code)
|
||||
|
||||
### Pros of Push Mode
|
||||
|
||||
1. **Eliminates Per-Piece RTT**: After wantlist exchange, pieces stream continuously
|
||||
- Traditional: N pieces × RTT latency
|
||||
- Push: 1 RTT + continuous stream
|
||||
|
||||
2. **Better Utilization of Fast Peers**: Server decides send rate, not blocked by client request rate
|
||||
|
||||
3. **Simpler Client Logic**: Client just receives, doesn't need to schedule requests
|
||||
|
||||
4. **Potential for Higher Throughput**: On high-latency links, avoids request/response overhead
|
||||
|
||||
### Cons of Push Mode
|
||||
|
||||
1. **Wasted Bandwidth (Duplicate Pieces)**
|
||||
- Server may push pieces client already received from another peer
|
||||
- Requires frequent HAVE updates (more protocol overhead)
|
||||
- HTTP/2 Push failed largely due to this issue
|
||||
|
||||
2. **Flow Control Complexity**
|
||||
- Client must signal when overwhelmed (pause/resume)
|
||||
- Receiver-side buffering required
|
||||
- Risk of memory exhaustion if sender is faster than disk
|
||||
|
||||
3. **Protocol Complexity**
|
||||
- New message types: wantlist, push_piece, have_update, pause, resume
|
||||
- State synchronization between wantlist and actual needs
|
||||
- Backward compatibility concerns
|
||||
|
||||
4. **No Piece Prioritization Control**
|
||||
- Client loses control over which pieces arrive first
|
||||
- Bad for streaming (need sequential pieces)
|
||||
- Server must guess or client must constantly update priorities
|
||||
|
||||
5. **Harder to Debug**
|
||||
- Asynchronous piece arrival
|
||||
- Race conditions between push and local state updates
|
||||
|
||||
6. **Not Battle-Tested**
|
||||
- No major P2P protocol uses this
|
||||
- HTTP/2 Push was abandoned after real-world issues
|
||||
- Unknown edge cases
|
||||
|
||||
### Recommendation
|
||||
|
||||
**Skip Phase 4 (Push Mode)** for these reasons:
|
||||
|
||||
1. **Current performance is already excellent**: 630 MB/s (1GB), 298 MB/s (5GB)
|
||||
2. **Adaptive pipelining achieves similar benefits**: BDP-based queue depth keeps the pipe full
|
||||
3. **Industry has rejected server push**: HTTP/2 Push deprecation is a cautionary tale
|
||||
4. **Complexity vs gain**: High implementation cost, uncertain benefit
|
||||
5. **Request-response is more predictable**: Easier to reason about, debug, and maintain
|
||||
|
||||
The completed phases (1, 2, 3, 5, 6) provide:
|
||||
- Adaptive queue depth that approximates push benefits
|
||||
- Per-peer optimization without protocol changes
|
||||
- Industry-standard patterns (AIMD, BDP, endgame)
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
1. BitTorrent Protocol Specification (BEP 3)
|
||||
2. IPFS Bitswap Protocol
|
||||
3. TCP Congestion Control (RFC 5681)
|
||||
4. HTTP/2 Flow Control (RFC 7540)
|
||||
5. QUIC Loss Detection and Congestion Control (RFC 9002)
|
||||
6. HTTP/2 Server Push Deprecation - Chrome Platform Status (2022)
|
||||
|
||||
---
|
||||
|
||||
## Appendix: Configuration Defaults
|
||||
|
||||
```zig
|
||||
pub const PipelineConfig = struct {
|
||||
// Basic pipelining
|
||||
max_pending_per_peer: u32 = 10,
|
||||
max_total_pending: u32 = 100,
|
||||
|
||||
// BDP adaptation
|
||||
min_pending: u32 = 1,
|
||||
max_pending: u32 = 50,
|
||||
rtt_ewma_alpha: f64 = 0.125,
|
||||
|
||||
// Push mode
|
||||
push_mode_enabled: bool = true,
|
||||
push_wantlist_interval_ms: u32 = 1000,
|
||||
push_have_interval_ms: u32 = 500,
|
||||
|
||||
// Endgame
|
||||
endgame_threshold_percent: u8 = 95,
|
||||
endgame_enabled: bool = true,
|
||||
|
||||
// AIMD
|
||||
aimd_increase: u32 = 1,
|
||||
aimd_decrease_factor: u32 = 2,
|
||||
|
||||
// Timeouts
|
||||
piece_timeout_ms: u32 = 30000,
|
||||
rtt_probe_interval_ms: u32 = 5000,
|
||||
};
|
||||
```
|
||||
Reference in New Issue
Block a user