torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! µTP / uTP (BEP 29) — reliable UDP transport for swarm peers.
//!
//! Enable with `swarm-transport "utp"` (requires `swarm-security "mse"`; mTLS is TCP-only).
//! Features: SYN/STATE handshake, windowed DATA flight, selective ACK, LEDBAT-lite cwnd.

mod packet;
mod stream;

pub use stream::{accept, bind_utp, connect, UtpEndpoint, UtpStream};

use crate::config::{Config, SwarmTransport};
use crate::error::{Error, Result};
use crate::swarm::SwarmStack;

/// uTP byte-stream transport is implemented.
pub const IMPLEMENTED: bool = true;

pub const UTP_RESERVED_BIT: u8 = 0x02;

pub fn is_implemented() -> bool {
    IMPLEMENTED
}

pub fn enable_utp(reserved: &mut [u8; 8]) {
    reserved[7] |= UTP_RESERVED_BIT;
}

pub fn supports_utp(reserved: &[u8; 8]) -> bool {
    reserved[7] & UTP_RESERVED_BIT != 0
}

/// True when config selects uTP (legacy flag or `swarm-transport`).
pub fn utp_preferred(cfg: &Config) -> bool {
    matches!(cfg.swarm_transport, SwarmTransport::Utp) || cfg.utp_enabled
}

pub fn dial_not_implemented<T>(stack: SwarmStack) -> Result<T> {
    Err(Error::Config(format!(
        "swarm stack {} cannot use uTP here",
        stack.describe()
    )))
}

pub fn accept_not_implemented<T>(stack: SwarmStack) -> Result<T> {
    dial_not_implemented(stack)
}

pub use packet::PacketType as ProtoPacketType;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn utp_enabled_flag_helpers() {
        let cfg = Config::default();
        assert!(!utp_preferred(&cfg));
        assert!(is_implemented());
        assert!(SwarmTransport::Utp.is_implemented());
        let mut reserved = [0u8; 8];
        enable_utp(&mut reserved);
        assert!(supports_utp(&reserved));
    }
}