vcl-protocol 0.5.0

Cryptographically chained packet transport protocol with SHA-256 integrity, Ed25519 signatures, and XChaCha20-Poly1305 encryption
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# 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

[![Crates.io](https://img.shields.io/crates/v/vcl-protocol.svg)](https://crates.io/crates/vcl-protocol)
[![Docs.rs](https://docs.rs/vcl-protocol/badge.svg)](https://docs.rs/vcl-protocol)
[![Rust](https://img.shields.io/badge/Rust-1.70+-orange.svg)](https://www.rust-lang.org)
[![Tests](https://img.shields.io/badge/tests-113%2F113%20passing-brightgreen.svg)]()
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Status](https://img.shields.io/badge/Status-v0.5.0%20Stable-green.svg)]()

**Verified Commit Link** โ€” Cryptographically chained packet transport protocol

---

## ๐Ÿ“š Documentation

**[README]README.md** | **[Usage Guide]USAGE.md** | **[Crates.io]https://crates.io/crates/vcl-protocol** | **[Docs.rs]https://docs.rs/vcl-protocol** | **[GitHub]https://github.com/ultrakill148852-collab/vcl-protocol**

---

## ๐Ÿ“– 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.

**v0.5.0** adds WebSocket transport for browser-compatible connections, AIMD congestion control with retransmission, RFC 6298 RTT estimation, and a Metrics API for aggregating performance statistics across connections.

**Published on crates.io:** https://crates.io/crates/vcl-protocol
**API Documentation:** https://docs.rs/vcl-protocol

---

## โœจ Features

| Feature | Description |
|---------|-------------|
| ๐Ÿ” 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` |
| ๐Ÿ“– Full API Docs | Complete documentation on [docs.rs]https://docs.rs/vcl-protocol |
| ๐Ÿงช Full Test Suite | 113/113 tests passing (unit + integration + doc) |

---

## ๐Ÿ—๏ธ Architecture
```text
Packet N        Packet N+1      Packet N+2
+--------+     +--------+     +--------+
| hash   |     | prev   |     | prev   |
| 0x00.. | --> | 0x00.. | --> | 0x3a.. |
| 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
   |                               |
   | -- ClientHello (pubkey) ----> |
   |                               |
   | <---- ServerHello (pubkey) -- |
   |                               |
   | [Shared secret computed]      |
   | [Secure channel established]  |
```

### Encryption Flow
```text
Send: plaintext โ†’ fragment? โ†’ encrypt(XChaCha20) โ†’ sign(Ed25519) โ†’ send
Recv: receive โ†’ verify(Ed25519) โ†’ decrypt(XChaCha20) โ†’ reassemble? โ†’ 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) -----> |
   |                                   |
   | <--- 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 (v0.5.0)
```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 (v0.5.0)
```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
```

### 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
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
cargo add vcl-protocol
```

### 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();
}
```

### Config Preset Example
```rust
use vcl_protocol::connection::VCLConnection;
use vcl_protocol::config::VCLConfig;

#[tokio::main]
async fn main() {
    let mut server = VCLConnection::bind_with_config(
        "127.0.0.1:8080",
        VCLConfig::vpn()
    ).await.unwrap();

    server.accept_handshake().await.unwrap();
    let packet = server.recv().await.unwrap();
    println!("Received: {}", String::from_utf8_lossy(&packet.payload));
}
```

### WebSocket Example (v0.5.0)
```rust
use vcl_protocol::transport::VCLTransport;

#[tokio::main]
async fn main() {
    // Server
    let listener = VCLTransport::bind_ws("127.0.0.1:8080").await.unwrap();
    let mut server_conn = listener.accept().await.unwrap();

    // Client
    let mut client = VCLTransport::connect_ws("ws://127.0.0.1:8080").await.unwrap();

    client.send_raw(b"hello websocket").await.unwrap();
    let (data, _) = server_conn.recv_raw().await.unwrap();
    println!("{}", String::from_utf8_lossy(&data));
}
```

### Metrics Example (v0.5.0)
```rust
use vcl_protocol::metrics::VCLMetrics;

let mut m = VCLMetrics::new();
m.record_sent(1024);
m.record_received(512);
m.record_rtt_sample(std::time::Duration::from_millis(42));

println!("Loss rate: {:.2}%", m.loss_rate() * 100.0);
println!("Avg RTT:   {:?}", m.avg_rtt());
println!("Throughput sent: {:.0} B/s", m.throughput_sent_bps());
```

---

## ๐Ÿ“ฆ 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`):

| Operation | Time |
|-----------|------|
| 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 Tunnels
TCP transport + reliable delivery + fragmentation + retransmission โ€” production-grade transport protocol for VPN infrastructure.

### ๐ŸŒ 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)

### 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 (v0.5.0)
- **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

### Retransmission (v0.5.0)
- `timed_out_packets()` returns `RetransmitRequest { sequence, data, retransmit_count }`
- Data payload stored in-flight for retransmission
- Exponential backoff on repeated loss

### Metrics (v0.5.0)
- `VCLMetrics` tracks: bytes, packets, retransmits, drops, RTT, cwnd, throughput, uptime
- RTT and cwnd sliding windows of 64 samples
- `merge()` for pool-level aggregation

### 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
- `serde` + `bincode` โ€” Serialization
- `tracing` โ€” Structured logging
- `tracing-subscriber` โ€” Log output

---

## ๐Ÿ› ๏ธ Development
```bash
cargo test                         # Run all tests (113/113)
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>