vcl-protocol 0.3.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
# 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 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

---

## Installation ๐Ÿš€

### Add to Cargo.toml
```toml
[dependencies]
vcl-protocol = "0.3.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();
}
```

---

## Connection Pool ๐ŸŠ

`VCLPool` manages multiple connections under a single manager.
```rust
use vcl_protocol::VCLPool;

#[tokio::main]
async fn main() {
    // Create pool with max 10 connections
    let mut pool = VCLPool::new(10);

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

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

    // Send on specific connection
    pool.send(id1, b"Hello server 1!").await.unwrap();
    pool.send(id2, b"Hello server 2!").await.unwrap();

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

    // Pool info
    println!("Active connections: {}", pool.len());
    println!("Is full: {}", pool.is_full());
    println!("IDs: {:?}", pool.connection_ids());

    // Close one or all
    pool.close(id1).unwrap();
    pool.close_all();
}
```

### VCLPool API

| Method | Returns | Description |
|--------|---------|-------------|
| `new(max)` | `VCLPool` | Create pool with max connection limit |
| `bind(addr)` | `Result<ConnectionId, VCLError>` | Bind new connection, add to pool |
| `connect(id, addr)` | `Result<(), VCLError>` | Connect to remote peer |
| `accept_handshake(id)` | `Result<(), VCLError>` | Accept incoming handshake |
| `send(id, data)` | `Result<(), VCLError>` | Send data on connection |
| `recv(id)` | `Result<VCLPacket, VCLError>` | Receive data on connection |
| `ping(id)` | `Result<(), VCLError>` | Send ping on connection |
| `rotate_keys(id)` | `Result<(), VCLError>` | Rotate keys on connection |
| `close(id)` | `Result<(), VCLError>` | Close and remove connection |
| `close_all()` | `()` | Close all connections |
| `len()` | `usize` | Number of active connections |
| `is_empty()` | `bool` | True if no connections |
| `is_full()` | `bool` | True if at max capacity |
| `contains(id)` | `bool` | True if ID exists in pool |
| `connection_ids()` | `Vec<ConnectionId>` | List all active IDs |

---

## Logging ๐Ÿ“

VCL Protocol uses the `tracing` crate for structured logging.
Add one line to your `main()` to enable log output:
```rust
tracing_subscriber::fmt::init();
```

Log levels used:
- `INFO` โ€” handshake, connection open/close, key rotation
- `DEBUG` โ€” packet send/receive, ping/pong, nonce window
- `WARN` โ€” replay attacks, chain failures, signature errors, timeouts
- `ERROR` โ€” operations on closed connections

Example output:
```
2024-01-01T00:00:00Z  INFO vcl_protocol::connection: VCLConnection bound addr=127.0.0.1:8080
2024-01-01T00:00:00Z  INFO vcl_protocol::connection: Handshake complete (server) peer=127.0.0.1:12345
2024-01-01T00:00:00Z DEBUG vcl_protocol::connection: Packet sent seq=0 size=11 packet_type=Data
```

---

## 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, secure channel ready"),
                VCLEvent::Disconnected =>
                    println!("Connection closed"),
                VCLEvent::PacketReceived { sequence, size } =>
                    println!("Packet #{} received ({} bytes)", sequence, size),
                VCLEvent::PingReceived =>
                    println!("Ping received โ€” pong sent automatically"),
                VCLEvent::PongReceived { latency } =>
                    println!("Round-trip latency: {:?}", latency),
                VCLEvent::KeyRotated =>
                    println!("Key rotation complete โ€” new shared secret active"),
                VCLEvent::Error(msg) =>
                    eprintln!("Internal 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
```

Results (WSL2 Debian, optimized):

| 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>` | Create connection bound to local address |
| `connect(addr)` | `Result<(), VCLError>` | Connect to remote peer (X25519 handshake) |
| `accept_handshake()` | `Result<(), VCLError>` | Accept incoming connection (server side) |
| `subscribe()` | `mpsc::Receiver<VCLEvent>` | Subscribe to connection events |
| `send(data)` | `Result<(), VCLError>` | Encrypt, sign, and send a data packet |
| `recv()` | `Result<VCLPacket, VCLError>` | Receive, verify, decrypt next data packet |
| `ping()` | `Result<(), VCLError>` | Send a ping; pong handled inside recv() |
| `rotate_keys()` | `Result<(), VCLError>` | Initiate mid-session key rotation |
| `close()` | `Result<(), VCLError>` | Gracefully close connection and clear state |
| `is_closed()` | `bool` | Check if connection is closed |
| `set_timeout(secs)` | `()` | Set inactivity timeout in seconds |
| `get_timeout()` | `u64` | Get current timeout value |
| `last_activity()` | `Instant` | Get timestamp of last send/recv |
| `get_public_key()` | `Vec<u8>` | Get local Ed25519 public key |
| `get_shared_secret()` | `Option<[u8; 32]>` | Get current X25519 shared secret |
| `set_shared_key(key)` | `()` | Set pre-shared key (testing only) |

### VCLError

| Variant | When |
|---------|------|
| `CryptoError(msg)` | Encryption/decryption failure |
| `SignatureInvalid` | Ed25519 signature verification failed |
| `InvalidKey(msg)` | Key has wrong length or format |
| `ChainValidationFailed` | prev_hash mismatch |
| `ReplayDetected(msg)` | Duplicate sequence number or nonce |
| `InvalidPacket(msg)` | Malformed or unexpected packet |
| `ConnectionClosed` | Operation on a closed connection |
| `Timeout` | No activity for longer than timeout_secs |
| `NoPeerAddress` | send() called before peer address is known |
| `NoSharedSecret` | send()/recv() called before handshake |
| `HandshakeFailed(msg)` | X25519 key exchange failed |
| `ExpectedClientHello` | Server received wrong handshake message |
| `ExpectedServerHello` | Client received wrong handshake message |
| `SerializationError(msg)` | bincode failed |
| `IoError(msg)` | UDP socket or address parse 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 is digitally signed
- Prevents spoofing

### 4. Encryption (XChaCha20-Poly1305)
- All payloads encrypted with AEAD cipher
- 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 33 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    # Connection 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
โ”œโ”€โ”€ 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.3.0 (Current) โœจ
- **Connection Pool** โ€” `VCLPool` for managing multiple connections
- **Tracing logs** โ€” structured `INFO/DEBUG/WARN/ERROR` via `tracing`
- **Benchmarks** โ€” `criterion` benchmarks for all crypto and packet ops
- **Full API docs** โ€” complete `///` doc comments, published on [docs.rs]https://docs.rs/vcl-protocol
- **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

### Planned for v0.4.0
- VPN support (TUN/TAP interface)
- IP packets inside VCL packets
- Routing

---

<div align="center">

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

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

</div>