srt-runtime 0.13.0

SRT (Secure Reliable Transport, draft-sharabayko-srt-01) packet codecs, sans-IO HSv5 handshakes, a one-connection link engine, ARQ, TSBPD, LiveCC/FileCC congestion control, optional payload crypto and an optional tokio UDP adapter; no_std core.
Documentation
//! `udp_loopback` — an encrypted SRT connection over real UDP sockets on
//! 127.0.0.1, through the `tokio` adapter.
//!
//! An [`SrtListener`] binds an ephemeral port and accepts; an [`SrtSocket`]
//! connects to it with the same passphrase. Both sides run the HSv5 handshake,
//! exchange Key Material (AES-128, `draft-sharabayko-srt-01` §6), and the
//! caller sends ten payloads that arrive decrypted, in order.
//!
//! Every timeout, cadence and bound is the caller's: [`IoConfig`],
//! [`LinkCadence`] and [`ListenerLimits`] have no defaults.
//!
//! ```text
//! cargo run -p srt-runtime --features tokio --example udp_loopback
//! ```

use core::num::NonZeroUsize;
use core::time::Duration;

use broadcast_net::net::UdpOptions;
use broadcast_net::timeouts::Timeouts;
use srt_runtime::HandshakeConfig;
use srt_runtime::arq::{ArqBounds, ReceiverBounds, SenderBounds};
use srt_runtime::handshake_sm::CryptoConfig;
use srt_runtime::io::{
    ChannelCapacities, IoConfig, ListenerLimits, SrtListener, SrtSocket, SrtSocketConfig,
};
use srt_runtime::link::LinkCadence;
use srt_runtime::livecc::MaxBwConfig;
use srt_runtime::packet::EncryptionField;

const MTU: u32 = 1500;
const PAYLOADS: usize = 10;
const PASSPHRASE: &str = "correct-horse-battery";

fn io_config() -> Result<IoConfig, srt_runtime::Error> {
    let timeouts = Timeouts::new(
        Duration::from_secs(5),
        Duration::from_secs(5),
        Duration::from_secs(5),
        Duration::from_secs(5),
    );
    let cadence = LinkCadence {
        handshake_retransmit: Duration::from_millis(250),
        keepalive: Duration::from_secs(1),
        km_resend: Duration::from_millis(500),
        kmreq_min_interval: Duration::from_millis(100),
    };
    let listener = ListenerLimits {
        max_pending: 16,
        pending_tick: Duration::from_millis(100),
        cookie_key_rotation: Duration::from_secs(60),
        recent_accept_ttl: Duration::from_secs(10),
    };
    let arq = ArqBounds {
        receiver: ReceiverBounds {
            max_tracked_window: 1 << 18,
            max_pending_skips: 1024,
            max_outstanding_acks: 1024,
        },
        sender: SenderBounds {
            max_nak_seqs_per_packet: 1 << 16,
            min_retransmit_interval: Duration::from_millis(20),
            pacing_burst_packets: 16,
        },
    };
    let channels = ChannelCapacities {
        rx: NonZeroUsize::new(4096).expect("non-zero"),
        unrouted: NonZeroUsize::new(1024).expect("non-zero"),
        send: NonZeroUsize::new(1024).expect("non-zero"),
        deliver: NonZeroUsize::new(4096).expect("non-zero"),
        accept: NonZeroUsize::new(16).expect("non-zero"),
    };
    IoConfig::new(
        MTU as usize,
        timeouts,
        cadence,
        listener,
        arq,
        1000,
        channels,
        MaxBwConfig::Set(125_000_000),
    )
}

fn handshake(sek: Vec<u8>) -> HandshakeConfig {
    HandshakeConfig::new(
        Duration::from_millis(120),
        MTU,
        8192,
        Duration::from_millis(250),
        12,
    )
    .with_encryption_field(EncryptionField::Aes128)
    .with_crypto(Some(CryptoConfig::new(
        PASSPHRASE.as_bytes().to_vec(),
        [0x5A; 16],
        sek,
    )))
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut listener = SrtListener::bind(
        "127.0.0.1:0".parse::<std::net::SocketAddr>()?,
        SrtSocketConfig::new(handshake(Vec::new()), io_config()?, UdpOptions::new()),
    )
    .await?;
    let addr = listener.local_addr()?;
    println!("listening on {addr}");
    let accept = tokio::spawn(async move { listener.accept().await });

    let mut caller = SrtSocket::connect(
        addr,
        SrtSocketConfig::new(handshake(vec![0x22; 16]), io_config()?, UdpOptions::new()),
    )
    .await?;
    let mut receiver = accept.await??;
    println!("connected: AES-128 negotiated with a shared passphrase");

    for i in 0..PAYLOADS {
        caller.send(format!("payload {i}").as_bytes()).await?;
    }
    let mut received = Vec::new();
    while received.len() < PAYLOADS {
        match receiver.recv().await? {
            Some(payload) => received.push(String::from_utf8(payload.to_vec())?),
            None => break,
        }
    }
    println!("received {received:?}");
    if received.len() != PAYLOADS || received[0] != "payload 0" {
        return Err("expected every payload, decrypted and in order".into());
    }
    Ok(())
}