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
//! QUIC Transport Layer for Sprint 140.2.
//!
//! Provides a QUIC transport using `quinn` with self-signed TLS certificates
//! from `rcgen`. Implements `QuicEndpoint` (server/client), `QuicConnection`
//! (bidirectional streams), and ports the DID challenge-response handshake
//! from TCP to QUIC.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────┐ QUIC ┌─────────────┐
//! │ QuicEndpoint│◄────────────►│ QuicEndpoint│
//! │ (server) │ (TLS 1.3) │ (client) │
//! └──────┬──────┘ └──────┬──────┘
//! │ │
//! ▼ ▼
//! ┌─────────────┐ ┌─────────────┐
//! │QuicConnection│ │QuicConnection│
//! │ (bi-streams) │ │ (bi-streams) │
//! └─────────────┘ └─────────────┘
//! ```
use std::net::SocketAddr;
use std::sync::Arc;
use serde::{Serialize, Deserialize};
// Install the ring crypto provider for rustls (required by rustls 0.23)
fn ensure_crypto_provider() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
// ---------------------------------------------------------------------------
// TLS Certificate Generation (Story 140.2.3)
// ---------------------------------------------------------------------------
/// A self-signed TLS certificate and its corresponding private key.
/// Used to configure QUIC endpoints for encrypted communication.
pub struct TlsCertificate {
pub cert_der: Vec<u8>,
pub key_der: Vec<u8>,
pub subject: String,
}
/// Generate a self-signed TLS certificate using `rcgen`.
///
/// The certificate uses an Ed25519 key (same curve as the CLM DID system)
/// and is suitable for QUIC/TLS 1.3 server authentication.
///
/// # Arguments
/// * `subject` - The subject name for the certificate (e.g. "pkc-node-1")
///
/// # Returns
/// A `TlsCertificate` containing the DER-encoded certificate and private key.
pub fn generate_self_signed_cert(subject: &str) -> Result<TlsCertificate, String> {
use rcgen::{CertificateParams, KeyPair, PKCS_ED25519};
let params = CertificateParams::new(vec![subject.to_string()])
.map_err(|e| format!("Failed to create cert params: {}", e))?;
let key_pair = KeyPair::generate_for(&PKCS_ED25519)
.map_err(|e| format!("Failed to generate key pair: {}", e))?;
let cert = params.self_signed(&key_pair)
.map_err(|e| format!("Failed to self-sign certificate: {}", e))?;
let cert_der = cert.der().to_vec();
let key_der = key_pair.serialize_der();
Ok(TlsCertificate {
cert_der,
key_der,
subject: subject.to_string(),
})
}
// ---------------------------------------------------------------------------
// QuicEndpoint (Story 140.2.1)
// ---------------------------------------------------------------------------
/// A QUIC endpoint that can act as both server and client.
///
/// Wraps `quinn::Endpoint` and holds the server configuration (if any).
/// The endpoint binds to a UDP port and can accept incoming QUIC connections
/// or initiate outgoing connections.
pub struct QuicEndpoint {
endpoint: quinn::Endpoint,
#[allow(dead_code)]
server_config: Option<quinn::ServerConfig>,
}
impl QuicEndpoint {
/// Create a QUIC server endpoint bound to the specified port.
///
/// The server uses the provided TLS certificate for encrypted QUIC
/// connections. It can both accept incoming connections and initiate
/// outgoing connections.
///
/// # Arguments
/// * `port` - The UDP port to bind to
/// * `cert` - The TLS certificate for server authentication
pub fn new_server(port: u16, cert: &TlsCertificate) -> Result<Self, String> {
ensure_crypto_provider();
let server_crypto = build_server_crypto(cert)?;
let server_config = quinn::ServerConfig::with_crypto(Arc::new(server_crypto));
let bind_addr: SocketAddr = format!("127.0.0.1:{}", port)
.parse()
.map_err(|e| format!("Invalid bind address: {}", e))?;
let endpoint = quinn::Endpoint::server(server_config.clone(), bind_addr)
.map_err(|e| format!("Failed to bind QUIC endpoint to {}: {}", bind_addr, e))?;
Ok(Self {
endpoint,
server_config: Some(server_config),
})
}
/// Create a QUIC client endpoint that can connect to servers.
///
/// The client is configured to accept self-signed certificates
/// (development mode). In production, a proper CA chain should be used.
pub fn new_client() -> Result<Self, String> {
ensure_crypto_provider();
let bind_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let endpoint = quinn::Endpoint::client(bind_addr)
.map_err(|e| format!("Failed to create client endpoint: {}", e))?;
Ok(Self {
endpoint,
server_config: None,
})
}
/// Create a QUIC client endpoint with explicit client config.
pub fn new_client_with_config() -> Result<Self, String> {
ensure_crypto_provider();
let bind_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let endpoint = quinn::Endpoint::client(bind_addr)
.map_err(|e| format!("Failed to create client endpoint: {}", e))?;
Ok(Self {
endpoint,
server_config: None,
})
}
/// Connect to a remote QUIC server.
///
/// # Arguments
/// * `addr` - The server address to connect to
/// * `server_name` - The server name for TLS verification (matches cert subject)
pub async fn connect(&self, addr: &str, server_name: &str) -> Result<QuicConnection, String> {
ensure_crypto_provider();
let client_crypto = build_dangerous_client_crypto();
let quic_client_config = quinn::crypto::rustls::QuicClientConfig::try_from(client_crypto)
.map_err(|e| format!("Failed to create QUIC client config: {}", e))?;
let client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));
let socket_addr: SocketAddr = addr
.parse()
.map_err(|e| format!("Invalid server address {}: {}", addr, e))?;
let connection = self.endpoint
.connect_with(client_config, socket_addr, server_name)
.map_err(|e| format!("Failed to initiate connection: {}", e))?
.await
.map_err(|e| format!("QUIC connection failed: {}", e))?;
Ok(QuicConnection { conn: connection })
}
/// Accept an incoming QUIC connection.
pub async fn accept(&self) -> Result<QuicConnection, String> {
let incoming = self.endpoint.accept()
.await
.ok_or_else(|| "No incoming QUIC connection".to_string())?;
let connection = incoming.await
.map_err(|e| format!("Failed to accept QUIC connection: {}", e))?;
Ok(QuicConnection { conn: connection })
}
/// Get the local address the endpoint is bound to.
pub fn local_addr(&self) -> Result<SocketAddr, String> {
self.endpoint.local_addr()
.map_err(|e| format!("Failed to get local addr: {}", e))
}
/// Close the endpoint and stop accepting connections.
pub fn close(&self) {
self.endpoint.close(0u32.into(), b"shutdown");
}
/// Accept an incoming QUIC connection with support for cancellation.
pub async fn accept_with_cancellation(
&self,
token: &tokio_util::sync::CancellationToken,
) -> Result<Option<QuicConnection>, String> {
tokio::select! {
_ = token.cancelled() => Ok(None),
res = self.accept() => res.map(Some),
}
}
/// Run an accept loop with a CancellationToken until cancelled.
pub async fn run_accept_loop<F, Fut>(
&self,
token: tokio_util::sync::CancellationToken,
handler: F,
) -> Result<(), String>
where
F: Fn(QuicConnection) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
loop {
tokio::select! {
_ = token.cancelled() => {
self.close();
break;
}
res = self.accept() => {
match res {
Ok(conn) => {
tokio::spawn(handler(conn));
}
Err(e) => {
if token.is_cancelled() {
break;
}
return Err(e);
}
}
}
}
}
Ok(())
}
}
// ---------------------------------------------------------------------------
// QuicConnection (Story 140.2.2)
// ---------------------------------------------------------------------------
/// A QUIC connection wrapping `quinn::Connection`.
///
/// Supports bidirectional streams for sending and receiving data.
/// Multiple streams can be multiplexed over a single connection.
pub struct QuicConnection {
pub conn: quinn::Connection,
}
impl QuicConnection {
/// Send data over a new bidirectional stream and return the stream ID.
///
/// Opens a new bidirectional QUIC stream, writes the data, and closes
/// the send side. The receive side remains open for the peer's response.
pub async fn send(&self, data: &[u8]) -> Result<Vec<u8>, String> {
let (mut send_stream, mut recv_stream) = self.conn
.open_bi()
.await
.map_err(|e| format!("Failed to open bidirectional stream: {}", e))?;
send_stream.write_all(data)
.await
.map_err(|e| format!("Failed to write to QUIC stream: {}", e))?;
send_stream.finish()
.map_err(|e| format!("Failed to finish send stream: {}", e))?;
let response = recv_stream.read_to_end(1024 * 1024)
.await
.map_err(|e| format!("Failed to read response from QUIC stream: {}", e))?;
Ok(response)
}
/// Send data and don't wait for a response (fire-and-forget).
pub async fn send_one_way(&self, data: &[u8]) -> Result<(), String> {
let mut send_stream = self.conn
.open_uni()
.await
.map_err(|e| format!("Failed to open unidirectional stream: {}", e))?;
send_stream.write_all(data)
.await
.map_err(|e| format!("Failed to write to QUIC stream: {}", e))?;
send_stream.finish()
.map_err(|e| format!("Failed to finish send stream: {}", e))?;
Ok(())
}
/// Receive data from a bidirectional stream opened by the peer.
///
/// This is used on the server side to read incoming requests and send
/// responses back.
pub async fn recv_bi(&self) -> Result<(Vec<u8>, quinn::SendStream, quinn::RecvStream), String> {
let (send_stream, mut recv_stream) = self.conn
.accept_bi()
.await
.map_err(|e| format!("Failed to accept bidirectional stream: {}", e))?;
let data = recv_stream.read_to_end(1024 * 1024)
.await
.map_err(|e| format!("Failed to read from QUIC stream: {}", e))?;
Ok((data, send_stream, recv_stream))
}
/// Send a response back on a bidirectional stream.
pub async fn respond(
&self,
mut send_stream: quinn::SendStream,
data: &[u8],
) -> Result<(), String> {
send_stream.write_all(data)
.await
.map_err(|e| format!("Failed to write response: {}", e))?;
send_stream.finish()
.map_err(|e| format!("Failed to finish response stream: {}", e))?;
Ok(())
}
/// Get the remote peer's address.
pub fn remote_address(&self) -> SocketAddr {
self.conn.remote_address()
}
/// Get the connection's stable ID.
pub fn stable_id(&self) -> usize {
self.conn.stable_id()
}
/// Close the connection.
pub fn close(&self, reason: &str) {
self.conn.close(0u32.into(), reason.as_bytes());
}
}
// ---------------------------------------------------------------------------
#[path = "quic_transport_handshake.rs"]
mod quic_transport_handshake;
#[allow(unused_imports)]
pub use quic_transport_handshake::*;
#[cfg(test)]
#[path = "quic_transport_tests.rs"]
mod tests;