mpc_ristretto/network/
config.rs

1//! Groups network config related helpers
2
3use std::{sync::Arc, time::Duration};
4
5use quinn::{ClientConfig, IdleTimeout, ServerConfig, TransportConfig, VarInt};
6use rcgen::RcgenError;
7use rustls::{Certificate, ClientConfig as CryptoClientConfig};
8
9use crate::error::SetupError;
10use crate::network::cert_verifier::PassThroughCertVerifier;
11
12#[cfg(not(test))]
13const MAX_IDLE_TIMEOUT: u32 = 10_000; // milliseconds
14#[cfg(test)]
15const MAX_IDLE_TIMEOUT: u32 = 0; // No timeout
16const KEEP_ALIVE_INTERVAL: u64 = 3_000; // milliseconds
17pub(crate) const SERVER_NAME: &str = "otter.cash"; // dummy value
18
19/// Builds the configs for quinn p2p communication
20pub fn build_configs() -> Result<(ClientConfig, ServerConfig), SetupError> {
21    // 1. Transport config
22    let mut transport_config = TransportConfig::default();
23    transport_config.max_idle_timeout(Some(IdleTimeout::from(VarInt::from_u32(MAX_IDLE_TIMEOUT))));
24
25    transport_config.keep_alive_interval(Some(Duration::from_millis(KEEP_ALIVE_INTERVAL)));
26
27    let transport: Arc<TransportConfig> = Arc::new(transport_config);
28
29    // 2. Cryptography setup
30    // Generate a self-signed server certificate for the QUIC connection
31    let (cert, key) = generate_cert().map_err(|_| SetupError::KeygenError)?;
32
33    // Setup the certificate root
34    let mut roots = rustls::RootCertStore::empty();
35    roots.add(&cert).map_err(|_| SetupError::ServerSetupError)?;
36
37    // Pass the self-signed cert to the client, and disable auth; p2p auth should happen at a higher layer
38    let mut client_crypto_config = CryptoClientConfig::builder()
39        .with_safe_defaults()
40        .with_root_certificates(roots)
41        .with_no_client_auth();
42    client_crypto_config
43        .dangerous()
44        .set_certificate_verifier(Arc::new(PassThroughCertVerifier::new()));
45
46    // 3. Client and server setup
47    let mut client_config = ClientConfig::new(Arc::new(client_crypto_config));
48    client_config.transport_config(transport.clone());
49
50    let mut server_config = ServerConfig::with_single_cert(vec![cert], key)
51        .map_err(|_| SetupError::ServerSetupError)?;
52    server_config.transport = transport;
53
54    Ok((client_config, server_config))
55}
56
57/// Generates a self-signed certificate to construct TLS 1.3 connections with
58/// borrowed from https://github.com/maidsafe/qp2p/blob/main/src/config.rs#L317
59fn generate_cert() -> Result<(Certificate, rustls::PrivateKey), RcgenError> {
60    let cert = rcgen::generate_simple_self_signed(vec![SERVER_NAME.to_string()])?;
61
62    let key = cert.serialize_private_key_der();
63    let cert = cert.serialize_der().unwrap();
64
65    let key = rustls::PrivateKey(key);
66    let cert = Certificate(cert);
67    Ok((cert, key))
68}