# VCL Protocol
โ ๏ธ **Development Branch**
>
> You're viewing the `main` branch which is under active development.
> Code here may be unstable or incomplete.
>
> โ
**For stable version:** [crates.io/vcl-protocol](https://crates.io/crates/vcl-protocol)
[](https://crates.io/crates/vcl-protocol)
[](https://docs.rs/vcl-protocol)
[](https://www.rust-lang.org)
[]()
[](LICENSE)
[]()
**Verified Commit Link** โ Cryptographically chained packet transport protocol
---
## ๐ Documentation
---
## ๐ About
VCL Protocol is a transport protocol where each packet cryptographically links to the previous one, creating an immutable chain of data transmission. Inspired by blockchain principles, optimized for real-time networking.
**v1.0.0** is the production release โ adds TUN interface for IP packet capture, full IP/TCP/UDP/ICMP parsing, multipath routing across multiple network interfaces, automatic MTU negotiation, NAT keepalive, automatic reconnection, DNS leak protection, and traffic obfuscation to bypass DPI censorship.
**Published on crates.io:** https://crates.io/crates/vcl-protocol
**API Documentation:** https://docs.rs/vcl-protocol
---
## โจ Features
| ๐ Cryptographic Chain | Each packet references hash of previous packet via SHA-256 |
| โ๏ธ Ed25519 Signatures | Fast and secure digital signatures |
| ๐ X25519 Handshake | Ephemeral key exchange, no pre-shared keys needed |
| ๐ XChaCha20-Poly1305 | Authenticated encryption for all payloads |
| ๐ก๏ธ Replay Protection | Sequence numbers + nonce tracking prevent packet replay |
| ๐ช Session Management | close(), is_closed(), timeout handling |
| โฑ๏ธ Inactivity Timeout | Auto-close idle connections (configurable) |
| โ
Chain Validation | Automatic integrity checking on every packet |
| โก UDP Transport | Low latency, high performance |
| ๐ TCP Transport | Reliable ordered delivery for VPN scenarios |
| ๐ WebSocket Transport | Browser-compatible, works through HTTP proxies |
| ๐ Transport Abstraction | Single API works with UDP, TCP, and WebSocket |
| ๐ซ Custom Error Types | Typed `VCLError` enum with full `std::error::Error` impl |
| ๐ก Connection Events | Subscribe to lifecycle & data events via async mpsc channel |
| ๐ Ping / Heartbeat | Built-in ping/pong with automatic round-trip latency measurement |
| ๐ Key Rotation | Rotate encryption keys mid-session without reconnecting |
| ๐ Connection Pool | Manage multiple connections under a single `VCLPool` manager |
| ๐งฉ Packet Fragmentation | Automatic split and reassembly for large payloads |
| ๐ Flow Control | Sliding window with RFC 6298 RTT estimation |
| ๐ Congestion Control | AIMD algorithm with slow start and retransmission |
| ๐ Retransmission | Automatic retransmit on timeout with exponential backoff |
| ๐ Metrics API | `VCLMetrics` aggregates stats across connections and pools |
| โ๏ธ Config Presets | VPN, Gaming, Streaming, Auto โ one line setup |
| ๐ Tracing Logs | Structured logging via `tracing` crate |
| ๐ Benchmarks | Performance benchmarks via `criterion` |
| ๐ฅ๏ธ TUN Interface | Capture IP packets from OS network stack (Linux) |
| ๐ฆ IP Packet Parser | Full IPv4/IPv6/TCP/UDP/ICMP header parsing |
| ๐ Multipath | Send across multiple interfaces (WiFi + LTE) simultaneously |
| ๐ MTU Negotiation | Automatic path MTU discovery via binary search |
| ๐ Keepalive | NAT keepalive presets for Mobile/Home/Corporate networks |
| ๐ Reconnect | Exponential backoff reconnection with jitter |
| ๐ก๏ธ DNS Leak Protection | Intercept DNS, blocklist, split DNS, response caching |
| ๐ญ Traffic Obfuscation | TLS/HTTP2 mimicry to bypass DPI censorship (ะะขะก, Beeline) |
| ๐ Full API Docs | Complete documentation on [docs.rs](https://docs.rs/vcl-protocol) |
| ๐งช Full Test Suite | 257/257 tests passing (unit + integration + doc) |
---
## ๐๏ธ Architecture
```text
Packet N Packet N+1 Packet N+2
+--------+ +--------+ +--------+
| sig | | sig | | sig |
+--------+ +--------+ +--------+
hash(Packet N) -> stored in prev_hash of Packet N+1
hash(Packet N+1) -> stored in prev_hash of Packet N+2
```
### Handshake Flow
```text
Client Server
| |
| <---- ServerHello (pubkey) -- |
| |
| [Shared secret computed] |
| [Secure channel established] |
```
### Encryption Flow
```text
Send: plaintext โ obfuscate? โ fragment? โ encrypt(XChaCha20) โ sign(Ed25519) โ send
Recv: receive โ verify(Ed25519) โ decrypt(XChaCha20) โ reassemble? โ deobfuscate? โ plaintext
```
### Session Management
```text
- close() โ Gracefully close connection, clear state
- is_closed() โ Check if connection is closed
- set_timeout() โ Configure inactivity timeout (default: 60s)
- last_activity() โ Get timestamp of last send/recv
```
### Event Flow
```text
conn.subscribe() โ mpsc::Receiver<VCLEvent>
Events:
Connected โ handshake completed
Disconnected โ close() called
PacketReceived โ data packet arrived { sequence, size }
PingReceived โ peer pinged us (pong sent automatically)
PongReceived โ our ping was answered { latency: Duration }
KeyRotated โ key rotation completed
Error(msg) โ non-fatal internal error
```
### Key Rotation Flow
```text
Client Server
| |
| <--- KeyRotation(new_pubkey) ---- |
| |
| [both sides now use new key] |
```
### Connection Pool
```text
VCLPool::new(max)
|
โโโ bind("addr") โ ConnectionId(0)
โโโ bind("addr") โ ConnectionId(1)
โโโ bind("addr") โ ConnectionId(2)
|
โโโ connect(id, peer)
โโโ send(id, data)
โโโ recv(id) โ VCLPacket
โโโ ping(id)
โโโ rotate_keys(id)
โโโ close(id)
โโโ close_all()
```
### Fragmentation Flow
```text
send(large_payload)
|
โโโ payload > fragment_size?
| YES โ Fragmenter::split โ [Frag0][Frag1][Frag2]...
| each fragment encrypted + signed separately
| NO โ single Data packet
|
recv()
|
โโโ PacketType::Fragment โ Reassembler::add(frag)
| incomplete โ loop, wait for more fragments
| complete โ return reassembled VCLPacket
โโโ PacketType::Data โ return directly
```
### Flow Control & Congestion Control
```text
FlowController (sliding window + AIMD)
|
โโโ can_send() โ effective window has space?
โโโ on_send(seq, data) โ register packet as in-flight
โโโ on_ack(seq) โ remove from window, update RTT (RFC 6298)
โโโ timed_out_packets() โ RetransmitRequest[] with data to resend
โโโ loss_rate() โ f64 packet loss rate
โโโ cwnd() โ current congestion window
โโโ in_slow_start() โ slow start phase active?
AIMD:
No loss โ cwnd += 1/cwnd per ack (additive increase)
Loss โ cwnd = 1, ssthresh /= 2 (multiplicative decrease)
RTO โ doubles on loss, min 50ms, max 60s
```
### WebSocket Transport
```text
VCLTransport::bind_ws("addr") โ WebSocketListener
VCLTransport::connect_ws("url") โ WebSocketClient
listener.accept() โ WebSocketServer
All send/recv via binary frames โ same API as TCP/UDP
Works through HTTP proxies and firewalls
```
### TUN Interface (v1.0.0)
```text
OS Network Stack
โ (routing table)
TUN interface (vcl0) โ VCLTun::create(TunConfig)
โ VCLTun::read_packet()
IP Packet โ parse_ip_packet() โ ParsedPacket { src, dst, protocol, ... }
โ encrypt + send via VCLConnection
โ recv + decrypt
VCLTun::write_packet() โ inject back into OS stack
```
### Multipath (v1.0.0)
```text
MultipathSender (scheduling policies):
BestPath โ highest bandwidth/latency score
RoundRobin โ alternate across all active paths
WeightedRoundRobinโ more traffic to higher-bandwidth paths
Redundant โ send on ALL paths simultaneously
LowestLatency โ always pick fastest path
MultipathReceiver:
Reordering buffer โ delivers packets in sequence order
Duplicate detection โ silently drops redundant copies
```
### Traffic Obfuscation (v1.0.0)
```text
ObfuscationMode::TlsMimicry โ looks like TLS 1.3 HTTPS
ObfuscationMode::Http2Mimicry โ looks like HTTP/2 DATA frames
ObfuscationMode::Full โ TLS + size normalization + jitter
ObfuscationMode::Padding โ random padding only
recommended_mode("mts") โ Full
recommended_mode("home") โ TlsMimicry
recommended_mode("office") โ Http2Mimicry
```
### Config Presets
```text
VCLConfig::vpn() โ TCP + Reliable (VPN, file transfer)
VCLConfig::gaming() โ UDP + Partial (games, real-time)
VCLConfig::streaming() โ UDP + Unreliable (video, audio)
VCLConfig::auto() โ Auto + Adaptive (recommended default)
```
---
## ๐ Quick Start
### Installation
```bash
```
### Run Demo
```bash
cargo run
```
### Run Tests
```bash
cargo test
```
### Run Benchmarks
```bash
cargo bench
```
### Event Subscription Example
```rust
use vcl_protocol::connection::VCLConnection;
use vcl_protocol::VCLEvent;
#[tokio::main]
async fn main() {
let mut conn = VCLConnection::bind("127.0.0.1:0").await.unwrap();
let mut events = conn.subscribe();
tokio::spawn(async move {
while let Some(event) = events.recv().await {
match event {
VCLEvent::Connected => println!("Connected!"),
VCLEvent::PongReceived { latency } => println!("Latency: {:?}", latency),
VCLEvent::KeyRotated => println!("Keys rotated!"),
VCLEvent::Disconnected => break,
_ => {}
}
}
});
conn.connect("127.0.0.1:8080").await.unwrap();
}
```
### Connection Pool Example
```rust
use vcl_protocol::VCLPool;
#[tokio::main]
async fn main() {
let mut pool = VCLPool::new(10);
let id = pool.bind("127.0.0.1:0").await.unwrap();
pool.connect(id, "127.0.0.1:8080").await.unwrap();
pool.send(id, b"Hello from pool!").await.unwrap();
let packet = pool.recv(id).await.unwrap();
println!("{}", String::from_utf8_lossy(&packet.payload));
pool.close(id).unwrap();
}
```
### Obfuscation Example (v1.0.0)
```rust
use vcl_protocol::obfuscation::{Obfuscator, ObfuscationConfig, recommended_mode, ObfuscationMode};
// For ะะขะก/Beeline mobile networks
let mode = recommended_mode("mts"); // โ Full
let mut obf = Obfuscator::new(ObfuscationConfig::full());
let data = b"vcl packet payload";
let obfuscated = obf.obfuscate(data); // looks like TLS to DPI
let restored = obf.deobfuscate(&obfuscated).unwrap();
assert_eq!(restored, data);
println!("Overhead: {:.1}%", obf.overhead_ratio() * 100.0);
```
### Keepalive Example (v1.0.0)
```rust
use vcl_protocol::keepalive::{KeepaliveManager, KeepalivePreset, KeepaliveAction};
// Mobile preset โ keeps NAT alive on ะะขะก/Beeline (30s timeout)
let mut keepalive = KeepaliveManager::from_preset(KeepalivePreset::Mobile);
loop {
match keepalive.check() {
KeepaliveAction::SendPing => {
keepalive.record_keepalive_sent();
// conn.ping().await?;
}
KeepaliveAction::PongTimeout => { keepalive.record_pong_missed(); }
KeepaliveAction::ConnectionDead => { break; /* reconnect */ }
KeepaliveAction::Idle => {}
}
// tokio::time::sleep(Duration::from_secs(1)).await;
}
```
### DNS Protection Example (v1.0.0)
```rust
use vcl_protocol::dns::{DnsFilter, DnsConfig, DnsAction, DnsQueryType};
let config = DnsConfig::cloudflare()
.with_blocked_domain("ads.example.com")
.with_split_domain("corp.internal");
let mut filter = DnsFilter::new(config);
match filter.decide("ads.example.com", &DnsQueryType::A) {
DnsAction::Block => { /* return NXDOMAIN */ }
DnsAction::ForwardThroughTunnel => { /* send via VCL */ }
DnsAction::AllowDirect => { /* use OS resolver */ }
DnsAction::ReturnCached(addr) => { /* return cached IP */ }
}
```
---
## ๐ฆ Packet Structure
```rust
pub struct VCLPacket {
pub version: u8, // Protocol version (2)
pub packet_type: PacketType, // Data | Ping | Pong | KeyRotation | Fragment
pub sequence: u64, // Monotonic packet sequence number
pub prev_hash: Vec<u8>, // SHA-256 hash of previous packet
pub nonce: [u8; 24], // XChaCha20 nonce for encryption
pub payload: Vec<u8>, // Decrypted data payload (after recv())
pub signature: Vec<u8>, // Ed25519 signature
}
```
---
## ๐ Benchmarks
Measured on WSL2 Debian, optimized build (`cargo bench`):
| keypair_generate | ~13 ยตs |
| encrypt 64B | ~1.5 ยตs |
| encrypt 16KB | ~12 ยตs |
| decrypt 64B | ~1.4 ยตs |
| decrypt 16KB | ~13 ยตs |
| packet_sign | ~32 ยตs |
| packet_verify | ~36 ยตs |
| packet_serialize | ~0.8 ยตs |
| packet_deserialize | ~1.1 ยตs |
| full pipeline 64B | ~38 ยตs |
| full pipeline 4KB | ~48 ยตs |
---
## ๐ฏ Use Cases
### ๐ฐ Financial Transactions
Immutable audit log of all transactions with cryptographic proof of integrity.
### ๐ฎ Anti-Cheat Systems
Verify integrity of game events and detect tampering in real-time.
### ๐ Audit Logging
Cryptographically proven data integrity for compliance and debugging.
### ๐ Secure Communications
Authenticated, encrypted channel with replay protection and session management.
### ๐ VPN Infrastructure
TUN interface + multipath + keepalive + reconnect + DNS protection โ complete VPN protocol foundation.
### ๐ Censorship Circumvention
Traffic obfuscation (TLS/HTTP2 mimicry) bypasses DPI used by ISPs like ะะขะก and Beeline.
### ๐ฅ๏ธ Browser Clients
WebSocket transport allows VCL Protocol to work from browsers and through corporate HTTP proxies.
---
## ๐ฌ Technical Details
### Cryptography
- **Hashing:** SHA-256
- **Signatures:** Ed25519
- **Key Exchange:** X25519
- **Encryption:** XChaCha20-Poly1305 (AEAD)
- **Key Generation:** CSPRNG
- **Replay Protection:** Sequence validation + nonce tracking (1000-entry window)
### Transport
- **UDP** โ low latency, default
- **TCP** โ reliable, ordered (VPN mode)
- **WebSocket** โ browser-compatible, HTTP proxy-friendly
- **Runtime:** Tokio async
- **Max Packet Size:** 65535 bytes
- **TCP/WS Framing:** 4-byte big-endian length prefix (TCP), binary frames (WS)
### TUN Interface (v1.0.0)
- **Platform:** Linux only (requires `CAP_NET_ADMIN` or root)
- **Default MTU:** 1420 bytes
- **IP versions:** IPv4 and IPv6
- **Crate:** `tun` with async feature
### IP Parsing (v1.0.0)
- **IPv4/IPv6** header parsing via `etherparse`
- **Protocols:** TCP, UDP, ICMP, ICMPv6, and any other protocol number
- **Helpers:** `is_dns()`, `is_ping()`, `summary()`
### Multipath (v1.0.0)
- **Scheduling:** BestPath, RoundRobin, WeightedRoundRobin, Redundant, LowestLatency
- **Reorder buffer:** up to 256 out-of-order packets
- **Duplicate detection:** sequence-based
### MTU Negotiation (v1.0.0)
- **Algorithm:** Binary search probing
- **Range:** 576โ1500 bytes (configurable up to 9000 for jumbo frames)
- **VCL overhead:** 149 bytes (Ed25519 + hash + nonce + headers)
### Keepalive (v1.0.0)
- **Mobile preset:** 20s interval (ะะขะก/Beeline 30s NAT timeout)
- **Adaptive:** adjusts interval based on measured RTT
- **Dead detection:** configurable missed pong count
### DNS Protection (v1.0.0)
- **Upstream:** Cloudflare (1.1.1.1), Google (8.8.8.8), Quad9 (9.9.9.9)
- **Cache:** TTL-based, up to 1024 entries
- **Blocklist:** wildcard subdomain matching
- **Split DNS:** per-domain bypass rules
### Traffic Obfuscation (v1.0.0)
- **TLS Mimicry:** Content-Type 0x17, Version 0x0303 (TLS 1.3 compat)
- **HTTP/2 Mimicry:** DATA frame (type 0x00) with stream ID rotation
- **Size Normalization:** pads to common HTTPS sizes (64โ1460 bytes)
- **XOR Scrambling:** lightweight payload scrambling
- **Timing Jitter:** pseudo-random delay to disguise traffic patterns
### Fragmentation
- **Threshold:** configurable via `VCLConfig::fragment_size` (default 1200 bytes)
- **Out-of-order reassembly:** supported
- **Duplicate fragments:** silently ignored
- **Max pending messages:** 256 (configurable)
### Flow Control & Congestion Control
- **Algorithm:** Sliding window + AIMD
- **Slow start:** exponential cwnd growth until ssthresh
- **Congestion avoidance:** additive increase 1/cwnd per ack
- **Loss response:** cwnd = 1, ssthresh halved, back to slow start
- **RTT estimation:** RFC 6298 (SRTT + RTTVAR)
- **RTO:** dynamic, doubles on loss, min 50ms, max 60s
### Serialization
- **Format:** Bincode
- **Efficiency:** Minimal overhead, fast serialization
### Dependencies
- `ed25519-dalek` โ Ed25519 signatures
- `x25519-dalek` โ X25519 key exchange
- `chacha20poly1305` โ XChaCha20-Poly1305 AEAD encryption
- `sha2` โ SHA-256 hashing
- `tokio` โ Async runtime
- `tokio-tungstenite` โ WebSocket transport
- `futures-util` โ async stream utilities
- `tun` โ TUN virtual network interface
- `etherparse` โ IP/TCP/UDP packet parsing
- `serde` + `bincode` โ Serialization
- `tracing` โ Structured logging
- `tracing-subscriber` โ Log output
---
## ๐ ๏ธ Development
```bash
cargo test # Run all tests (257/257)
cargo test --lib # Unit tests only
cargo test --test integration_test # Integration tests only
cargo bench # Run benchmarks
cargo run --example server # Run example server
cargo run --example client # Run example client
cargo fmt # Format code
cargo clippy # Linting
cargo build --release # Release build
cargo doc --open # Generate and open docs locally
```
---
## ๐ License
MIT License โ see [LICENSE](LICENSE) file for details.
---
## ๐ค Author
**ultrakill148852-collab** โ Creator of the VCL Protocol
GitHub: [@ultrakill148852-collab](https://github.com/ultrakill148852-collab)
---
## ๐ Acknowledgments
- **Ed25519** โ Fast and secure cryptography
- **X25519** โ Efficient elliptic-curve key exchange
- **XChaCha20-Poly1305** โ Modern authenticated encryption
- **Tokio** โ Asynchronous runtime for Rust
- **Rust** โ The language that makes the impossible possible
---
<div align="center">
**Made with โค๏ธ using Rust**
[โฌ๏ธ Back to top](#vcl-protocol)
</div>