torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Host-defined identity, handshake approval, ratchet, and credential policy.

use std::net::SocketAddr;
use std::sync::Arc;

use rustls::pki_types::CertificateDer;
use tokio_rustls::server::TlsStream as ServerTlsStream;
use tokio_rustls::client::TlsStream as ClientTlsStream;
use tokio::net::TcpStream;

use crate::error::Result;
use crate::secure::credentials::{CredentialBundle, CredentialMode};

/// Host-defined node / network identity. Opaque to this crate.
#[derive(Debug, Clone)]
pub struct Identity {
    pub label: String,
    pub bytes: Vec<u8>,
}

impl Identity {
    pub fn new(label: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
        Self {
            label: label.into(),
            bytes: bytes.into(),
        }
    }

    /// Derive a 20-byte DHT lookup key from identity bytes (SHA-1).
    pub fn dht_key(&self) -> [u8; 20] {
        use sha1::{Digest, Sha1};
        let digest = Sha1::digest(&self.bytes);
        let mut out = [0u8; 20];
        out.copy_from_slice(&digest);
        out
    }
}

/// Host-defined handshake payload offered during the secure session setup.
#[derive(Debug, Clone)]
pub struct HandshakeOffer {
    pub payload: Vec<u8>,
}

/// Result of host approval of a remote peer's handshake offer.
#[derive(Debug, Clone)]
pub struct Approval {
    pub peer_label: String,
    pub notes: Vec<u8>,
}

/// Context passed to the host for DHT authenticity / anti-spoof ratchet logic.
/// Topology (routing table contents) is intentionally not included.
#[derive(Debug, Clone)]
pub struct RatchetContext {
    pub local_identity: Identity,
    pub peer_addr: SocketAddr,
    pub peer_offer: Vec<u8>,
    pub network_dht_key: [u8; 20],
    pub peer_certificate_der: Vec<Vec<u8>>,
}

/// Established secure session handed to the host for application protocols.
pub struct Handoff {
    pub peer_addr: SocketAddr,
    pub peer_label: String,
    pub local_identity: Identity,
    pub approval: Approval,
    pub credentials: CredentialBundle,
    pub transport: SecureTransport,
}

/// Lightweight notice for host observers (no TLS transport — that stays with Client).
#[derive(Debug, Clone)]
pub struct HandoffNotice {
    pub peer_addr: SocketAddr,
    pub peer_label: String,
    pub local_identity_label: String,
}

impl Handoff {
    pub fn notice(&self) -> HandoffNotice {
        HandoffNotice {
            peer_addr: self.peer_addr,
            peer_label: self.peer_label.clone(),
            local_identity_label: self.local_identity.label.clone(),
        }
    }
}

/// TLS-wrapped TCP stream (client or server role).
pub enum SecureTransport {
    Client(ClientTlsStream<TcpStream>),
    Server(ServerTlsStream<TcpStream>),
}

impl SecureTransport {
    pub fn into_client(self) -> Option<ClientTlsStream<TcpStream>> {
        match self {
            Self::Client(s) => Some(s),
            Self::Server(_) => None,
        }
    }

    pub fn into_server(self) -> Option<ServerTlsStream<TcpStream>> {
        match self {
            Self::Server(s) => Some(s),
            Self::Client(_) => None,
        }
    }
}

/// Host signals that the application connection is broken and should reconnect.
#[derive(Debug, Clone, Copy)]
pub struct SessionBroken {
    pub peer_addr: SocketAddr,
    /// When true, only redial `peer_addr` (no network-DHT candidate search).
    pub prefer_addr_only: bool,
}

/// Policy implemented by the project that pulls this crate in.
pub trait SecurePolicy: Send + Sync {
    fn identity(&self) -> Identity;

    /// DHT announce / get_peers key. Default: SHA-1 of identity bytes.
    fn network_dht_key(&self) -> [u8; 20] {
        self.identity().dht_key()
    }

    /// Host-defined handshake contents offered to the peer.
    fn handshake_offer(&self) -> Result<HandshakeOffer>;

    /// Host decides whether the peer's offer (and certs) are acceptable.
    fn approve_peer(
        &self,
        peer_offer: &HandshakeOffer,
        peer_certs: &[CertificateDer<'static>],
    ) -> Result<Approval>;

    /// Host-defined ratchet / DHT-environment authenticity check.
    /// Default: accept (no extra check). Override in the host project.
    fn ratchet(&self, _ctx: &RatchetContext) -> Result<()> {
        Ok(())
    }

    /// How credentials are exchanged after approval.
    /// Default: crate-owned sealed encrypted channel.
    /// [`CredentialMode::HostManaged`] still seals on the wire; host supplies/accepts plaintext blobs.
    fn credential_mode(&self) -> CredentialMode {
        CredentialMode::SealedChannel
    }

    /// Local credentials to seal and send (both default and host-managed modes).
    fn local_credentials(&self) -> Result<CredentialBundle> {
        Ok(CredentialBundle::empty())
    }

    /// When [`CredentialMode::HostManaged`], interpret the remote sealed plaintext.
    fn accept_remote_credentials(&self, remote: &[u8]) -> Result<CredentialBundle> {
        Ok(CredentialBundle::new(remote.to_vec()))
    }

    /// Called when a secure handoff is ready (optional hook).
    fn on_handoff(&self, _handoff: &Handoff) {}
}

/// Shared policy handle.
pub type PolicyHandle = Arc<dyn SecurePolicy>;