vcl-protocol 0.4.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# VCL Protocol โ€” Usage Guide ๐Ÿ“–

## Overview

VCL Protocol is a cryptographically chained packet transport protocol. It ensures data integrity through SHA-256 hashing, authenticates packets using Ed25519 signatures, and encrypts all payloads with XChaCha20-Poly1305.

**Key Features:** โœจ

- Immutable packet chain (each packet links to previous via SHA-256)
- X25519 ephemeral handshake (no pre-shared keys needed)
- Ed25519 digital signatures for authentication
- XChaCha20-Poly1305 authenticated encryption for all payloads
- Replay protection via sequence numbers + nonce tracking
- Session management: close(), timeout, activity tracking
- UDP and TCP transport with Tokio async runtime
- **[v0.2.0]** Connection Events via async mpsc channel
- **[v0.2.0]** Ping / Heartbeat with round-trip latency measurement
- **[v0.2.0]** Mid-session Key Rotation via X25519
- **[v0.3.0]** Connection Pool via `VCLPool`
- **[v0.3.0]** Structured logging via `tracing`
- **[v0.3.0]** Performance benchmarks via `criterion`
- **[v0.3.0]** Full API docs on [docs.rs]https://docs.rs/vcl-protocol
- **[v0.4.0]** TCP/UDP Transport Abstraction via `VCLTransport`
- **[v0.4.0]** Automatic packet fragmentation and reassembly
- **[v0.4.0]** Sliding window flow control with RTT estimation
- **[v0.4.0]** Config presets: VPN, Gaming, Streaming, Auto

---

## Installation ๐Ÿš€

### Add to Cargo.toml
```toml
[dependencies]
vcl-protocol = "0.4.0"
tokio = { version = "1", features = ["full"] }
```

---

## Quick Start ๐Ÿ“

### Server Example
```rust
use vcl_protocol::connection::VCLConnection;

#[tokio::main]
async fn main() {
    let mut server = VCLConnection::bind("127.0.0.1:8080").await.unwrap();
    println!("Server started on 127.0.0.1:8080");

    server.accept_handshake().await.unwrap();
    println!("Client connected!");

    loop {
        match server.recv().await {
            Ok(packet) => {
                println!("Received: {}", String::from_utf8_lossy(&packet.payload));
            }
            Err(e) => { eprintln!("Error: {}", e); break; }
        }
    }
}
```

### Client Example
```rust
use vcl_protocol::connection::VCLConnection;

#[tokio::main]
async fn main() {
    let mut client = VCLConnection::bind("127.0.0.1:0").await.unwrap();

    client.connect("127.0.0.1:8080").await.unwrap();
    println!("Connected to server!");

    for i in 1..=5 {
        let msg = format!("Message {}", i);
        client.send(msg.as_bytes()).await.unwrap();
        println!("Sent: {}", msg);
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }

    client.close().unwrap();
}
```

---

## Config Presets โš™๏ธ

`VCLConfig` controls transport, reliability, fragmentation, and flow control.
```rust
use vcl_protocol::connection::VCLConnection;
use vcl_protocol::config::VCLConfig;

#[tokio::main]
async fn main() {
    // VPN mode โ€” TCP + reliable delivery
    let mut conn = VCLConnection::bind_with_config(
        "127.0.0.1:0",
        VCLConfig::vpn()
    ).await.unwrap();

    // Gaming mode โ€” UDP + partial reliability
    let mut conn = VCLConnection::bind_with_config(
        "127.0.0.1:0",
        VCLConfig::gaming()
    ).await.unwrap();

    // Streaming mode โ€” UDP + no retransmission
    let mut conn = VCLConnection::bind_with_config(
        "127.0.0.1:0",
        VCLConfig::streaming()
    ).await.unwrap();

    // Auto mode (default) โ€” adapts to network conditions
    let mut conn = VCLConnection::bind("127.0.0.1:0").await.unwrap();
}
```

### Preset Reference

| Preset | Transport | Reliability | Fragment size | Window | Use case |
|--------|-----------|-------------|---------------|--------|----------|
| `vpn()` | TCP | Reliable | 1200B | 64 | VPN, secure comms |
| `gaming()` | UDP | Partial | 1400B | 128 | Real-time games |
| `streaming()` | UDP | Unreliable | 1400B | 256 | Video/audio |
| `auto()` | Auto | Adaptive | 1200B | 64 | Unknown/mixed |

### Custom Config
```rust
use vcl_protocol::config::{VCLConfig, TransportMode, ReliabilityMode};

let config = VCLConfig {
    transport: TransportMode::Udp,
    reliability: ReliabilityMode::Partial,
    max_retries: 3,
    retry_interval_ms: 50,
    fragment_size: 800,
    flow_window_size: 32,
};
```

---

## Fragmentation ๐Ÿงฉ

Large payloads are automatically split and reassembled โ€” no manual steps needed.
```rust
// Sender โ€” payload > fragment_size is split automatically
let large_data = vec![0u8; 50_000];
client.send(&large_data).await.unwrap();

// Receiver โ€” recv() returns the complete reassembled payload
let packet = server.recv().await.unwrap();
assert_eq!(packet.payload.len(), 50_000);
```

Fragmentation behaviour is controlled by `VCLConfig::fragment_size` (default 1200 bytes).
Out-of-order fragment arrival is handled automatically.

---

## Flow Control ๐ŸŒŠ

The sliding window flow controller is built into every connection.
```rust
// Inspect flow stats
let conn = VCLConnection::bind("127.0.0.1:0").await.unwrap();

println!("Can send: {}", conn.flow().can_send());
println!("In flight: {}", conn.flow().in_flight_count());
println!("Loss rate: {:.2}%", conn.flow().loss_rate() * 100.0);

if let Some(rtt) = conn.flow().srtt() {
    println!("RTT estimate: {:?}", rtt);
}

// Manually ack a packet (advanced use)
conn.ack_packet(sequence_number);
```

Window size is configured via `VCLConfig::flow_window_size`.

---

## Transport Abstraction ๐Ÿ”Œ

Use `VCLTransport` directly for low-level TCP/UDP control.
```rust
use vcl_protocol::transport::VCLTransport;
use vcl_protocol::config::VCLConfig;

// UDP
let mut udp = VCLTransport::bind_udp("127.0.0.1:0").await.unwrap();

// TCP server
let listener = VCLTransport::bind_tcp("127.0.0.1:8080").await.unwrap();
let mut conn = listener.accept().await.unwrap();

// TCP client
let mut client = VCLTransport::connect_tcp("127.0.0.1:8080").await.unwrap();

// From config
let transport = VCLTransport::from_config_server("127.0.0.1:0", &VCLConfig::vpn()).await.unwrap();
assert!(transport.is_tcp());
```

---

## Connection Pool ๐ŸŠ
```rust
use vcl_protocol::VCLPool;

#[tokio::main]
async fn main() {
    let mut pool = VCLPool::new(10);

    let id1 = pool.bind("127.0.0.1:0").await.unwrap();
    let id2 = pool.bind("127.0.0.1:0").await.unwrap();

    pool.connect(id1, "127.0.0.1:8080").await.unwrap();
    pool.connect(id2, "127.0.0.1:8081").await.unwrap();

    pool.send(id1, b"Hello server 1!").await.unwrap();
    pool.send(id2, b"Hello server 2!").await.unwrap();

    let packet = pool.recv(id1).await.unwrap();
    println!("{}", String::from_utf8_lossy(&packet.payload));

    println!("Active connections: {}", pool.len());
    println!("Is full: {}", pool.is_full());

    pool.close(id1).unwrap();
    pool.close_all();
}
```

---

## Logging ๐Ÿ“
```rust
tracing_subscriber::fmt::init();
```

Log levels:
- `INFO` โ€” handshake, open/close, key rotation, fragmentation complete
- `DEBUG` โ€” packet send/receive, fragments, flow window
- `WARN` โ€” replay attacks, chain failures, flow window full, timeouts
- `ERROR` โ€” operations on closed connections

---

## Connection Events ๐Ÿ“ก
```rust
use vcl_protocol::{connection::VCLConnection, 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!("Handshake complete"),
                VCLEvent::Disconnected =>
                    println!("Connection closed"),
                VCLEvent::PacketReceived { sequence, size } =>
                    println!("Packet #{} ({} bytes)", sequence, size),
                VCLEvent::PingReceived =>
                    println!("Ping โ€” pong sent automatically"),
                VCLEvent::PongReceived { latency } =>
                    println!("RTT: {:?}", latency),
                VCLEvent::KeyRotated =>
                    println!("Key rotation complete"),
                VCLEvent::Error(msg) =>
                    eprintln!("Error: {}", msg),
            }
        }
    });

    conn.connect("127.0.0.1:8080").await.unwrap();
}
```

---

## Ping / Heartbeat ๐Ÿ“
```rust
client.ping().await.unwrap();

loop {
    match client.recv().await {
        Ok(packet) => { /* handle data */ }
        Err(e)     => { eprintln!("{}", e); break; }
    }
}
```

---

## Key Rotation ๐Ÿ”„
```rust
// Initiator
client.rotate_keys().await.unwrap();

// Responder โ€” handled automatically inside recv()
```

---

## Benchmarks ๐Ÿ“Š
```bash
cargo bench
```

| Operation | Time |
|-----------|------|
| keypair_generate | ~13 ยตs |
| encrypt 64B | ~1.5 ยตs |
| encrypt 16KB | ~12 ยตs |
| decrypt 64B | ~1.4 ยตs |
| packet_sign | ~32 ยตs |
| packet_verify | ~36 ยตs |
| full pipeline 64B | ~38 ยตs |

---

## API Reference ๐Ÿ”ง

### VCLConnection

| Method | Returns | Description |
|--------|---------|-------------|
| `bind(addr)` | `Result<Self, VCLError>` | Bind with default config |
| `bind_with_config(addr, config)` | `Result<Self, VCLError>` | Bind with custom config |
| `connect(addr)` | `Result<(), VCLError>` | Connect + X25519 handshake |
| `accept_handshake()` | `Result<(), VCLError>` | Accept incoming connection |
| `subscribe()` | `mpsc::Receiver<VCLEvent>` | Subscribe to events |
| `send(data)` | `Result<(), VCLError>` | Send data (auto-fragments if large) |
| `recv()` | `Result<VCLPacket, VCLError>` | Receive next data packet |
| `ping()` | `Result<(), VCLError>` | Send ping |
| `rotate_keys()` | `Result<(), VCLError>` | Mid-session key rotation |
| `close()` | `Result<(), VCLError>` | Close connection |
| `is_closed()` | `bool` | Connection closed? |
| `set_timeout(secs)` | `()` | Set inactivity timeout |
| `get_timeout()` | `u64` | Get timeout value |
| `last_activity()` | `Instant` | Last send/recv timestamp |
| `get_config()` | `&VCLConfig` | Current config |
| `flow()` | `&FlowController` | Flow control stats |
| `ack_packet(seq)` | `bool` | Manually ack a packet |
| `get_public_key()` | `Vec<u8>` | Local Ed25519 public key |
| `get_shared_secret()` | `Option<[u8; 32]>` | Current shared secret |
| `set_shared_key(key)` | `()` | Pre-shared key (testing only) |

### VCLError

| Variant | When |
|---------|------|
| `CryptoError(msg)` | Encryption/decryption failure |
| `SignatureInvalid` | Ed25519 verification failed |
| `InvalidKey(msg)` | Key wrong length or format |
| `ChainValidationFailed` | prev_hash mismatch |
| `ReplayDetected(msg)` | Duplicate sequence or nonce |
| `InvalidPacket(msg)` | Malformed or unexpected packet |
| `ConnectionClosed` | Operation on closed connection |
| `Timeout` | Inactivity timeout exceeded |
| `NoPeerAddress` | send() before peer known |
| `NoSharedSecret` | send()/recv() before handshake |
| `HandshakeFailed(msg)` | X25519 exchange failed |
| `ExpectedClientHello` | Wrong handshake message |
| `ExpectedServerHello` | Wrong handshake message |
| `SerializationError(msg)` | bincode failed |
| `IoError(msg)` | Socket or address error |

---

## Security Model ๐Ÿ”

### 1. Handshake (X25519)
- Ephemeral key exchange per connection
- No pre-shared keys required
- Forward secrecy

### 2. Chain Integrity (SHA-256)
- Send and receive chains tracked independently
- Tampering breaks the chain

### 3. Authentication (Ed25519)
- Every packet signed
- Prevents spoofing

### 4. Encryption (XChaCha20-Poly1305)
- All payloads encrypted with AEAD
- Unique nonce per packet

### 5. Replay Protection
- Sequence numbers strictly increasing
- Nonces tracked in sliding window (1000 entries)

### 6. Session Management
- close() clears all sensitive state
- Timeout prevents resource leaks

### 7. Key Rotation
- Fresh X25519 per rotation
- Old key encrypts rotation messages

---

## Testing ๐Ÿงช
```bash
cargo test                         # All 89 tests
cargo test --lib                   # Unit tests
cargo test --test integration_test # Integration tests
cargo bench                        # Benchmarks
cargo run --example server         # Example server
cargo run --example client         # Example client
```

---

## Project Structure ๐Ÿ“ฆ
vcl-protocol/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main.rs          # Demo application
โ”‚   โ”œโ”€โ”€ lib.rs           # Library entry point
โ”‚   โ”œโ”€โ”€ connection.rs    # VCLConnection โ€” main API
โ”‚   โ”œโ”€โ”€ event.rs         # VCLEvent enum
โ”‚   โ”œโ”€โ”€ pool.rs          # VCLPool โ€” connection manager
โ”‚   โ”œโ”€โ”€ packet.rs        # VCLPacket + PacketType
โ”‚   โ”œโ”€โ”€ crypto.rs        # KeyPair, encrypt, decrypt
โ”‚   โ”œโ”€โ”€ error.rs         # VCLError
โ”‚   โ”œโ”€โ”€ handshake.rs     # X25519 handshake
โ”‚   โ”œโ”€โ”€ config.rs        # VCLConfig + presets
โ”‚   โ”œโ”€โ”€ transport.rs     # VCLTransport (TCP/UDP abstraction)
โ”‚   โ”œโ”€โ”€ fragment.rs      # Fragmenter + Reassembler
โ”‚   โ””โ”€โ”€ flow.rs          # FlowController
โ”œโ”€โ”€ benches/
โ”‚   โ””โ”€โ”€ vcl_benchmarks.rs
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ client.rs
โ”‚   โ””โ”€โ”€ server.rs
โ”œโ”€โ”€ tests/
โ”‚   โ””โ”€โ”€ integration_test.rs
โ”œโ”€โ”€ Cargo.toml
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ USAGE.md
โ””โ”€โ”€ LICENSE

---

## Contributing ๐Ÿค

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Run `cargo test` and `cargo clippy`
6. Submit a pull request

---

## License ๐Ÿ“„

MIT License โ€” see LICENSE file for details.

---

## Support ๐Ÿ“ฌ

- Issues: https://github.com/ultrakill148852-collab/vcl-protocol/issues
- Discussions: https://github.com/ultrakill148852-collab/vcl-protocol/discussions

---

## Changelog ๐Ÿ”„

### v0.4.0 (Current) โœจ
- **TCP/UDP Transport Abstraction** โ€” `VCLTransport` with unified send/recv API
- **Packet Fragmentation** โ€” automatic split and reassembly for large payloads
- **Flow Control** โ€” sliding window with RTT estimation and retransmission detection
- **Config Presets** โ€” `VCLConfig::vpn()`, `gaming()`, `streaming()`, `auto()`
- **`bind_with_config()`** โ€” configure connection at bind time
- **89/89 tests passing**

### v0.3.0 โœ…
- Connection Pool (`VCLPool`)
- Tracing logs
- Benchmarks (criterion)
- Full API docs on docs.rs
- 33/33 tests passing

### v0.2.0 โœ…
- Connection Events (`VCLEvent` + `subscribe()`)
- Ping / Heartbeat with latency measurement
- Mid-session Key Rotation
- Custom Error Types (`VCLError`)
- Bidirectional chain fix

### v0.1.0 โœ…
- Cryptographic chain with SHA-256
- Ed25519 signatures + X25519 handshake
- XChaCha20-Poly1305 authenticated encryption
- Replay protection
- Session management
- 17/17 tests passing

---

<div align="center">

**Made with โค๏ธ using Rust**

*Secure โ€ข Chained โ€ข Verified โ€ข Production Ready*

</div>