torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! MSE swarm prefer-addr heal policy.
//!
//! MSE has no certificate identity. Automatic heal is therefore gated:
//! - operator **static** peers, or
//! - peers previously **pinned** by BitTorrent `peer_id` after a successful session
//!
//! Failed heal cycles do **not** self-requeue (mirrors SecureNode prefer-addr give-up).
//! A new `signal_peer_broken` from an active session / healer may retry later.
//!
//! Pins expire (TTL) and are capacity-bounded (LRU by last touch) so heal state
//! cannot grow without limit across long-lived clients.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::time::{Duration, Instant};

use tokio::sync::RwLock;

use crate::peer::PeerId;
use crate::torrent::InfoHash;

/// Matches SecureNode prefer-addr give-up: three failures once backoff is maxed.
pub const MSE_HEAL_GIVE_UP_AT_MAX: u32 = 3;
pub const MSE_HEAL_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
pub const MSE_HEAL_MAX_BACKOFF: Duration = Duration::from_secs(30);

/// Default max retained MSE peer_id pins per Client.
pub const MSE_PIN_MAX_DEFAULT: usize = 512;
/// Default pin lifetime (refreshed on successful session / heal touch).
pub const MSE_PIN_TTL_DEFAULT: Duration = Duration::from_secs(24 * 60 * 60);

#[derive(Debug, Clone, Copy)]
struct PinEntry {
    peer_id: PeerId,
    touched: Instant,
}

#[derive(Debug)]
pub struct MseHealState {
    pins: RwLock<HashMap<(SocketAddr, InfoHash), PinEntry>>,
    max_pins: usize,
    ttl: Duration,
}

impl Default for MseHealState {
    fn default() -> Self {
        Self::with_limits(MSE_PIN_MAX_DEFAULT, MSE_PIN_TTL_DEFAULT)
    }
}

impl MseHealState {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_limits(max_pins: usize, ttl: Duration) -> Self {
        Self {
            pins: RwLock::new(HashMap::new()),
            max_pins: max_pins.max(1),
            ttl,
        }
    }

    pub async fn pin(&self, addr: SocketAddr, info_hash: InfoHash, peer_id: PeerId) {
        let mut pins = self.pins.write().await;
        Self::prune_expired(&mut pins, self.ttl);
        pins.insert(
            (addr, info_hash),
            PinEntry {
                peer_id,
                touched: Instant::now(),
            },
        );
        Self::evict_overflow(&mut pins, self.max_pins);
    }

    pub async fn pinned_id(&self, addr: SocketAddr, info_hash: InfoHash) -> Option<PeerId> {
        let mut pins = self.pins.write().await;
        Self::prune_expired(&mut pins, self.ttl);
        let key = (addr, info_hash);
        let entry = pins.get_mut(&key)?;
        if entry.touched.elapsed() > self.ttl {
            pins.remove(&key);
            return None;
        }
        entry.touched = Instant::now();
        Some(entry.peer_id)
    }

    pub async fn forget(&self, addr: SocketAddr, info_hash: InfoHash) {
        self.pins.write().await.remove(&(addr, info_hash));
    }

    fn prune_expired(pins: &mut HashMap<(SocketAddr, InfoHash), PinEntry>, ttl: Duration) {
        pins.retain(|_, entry| entry.touched.elapsed() <= ttl);
    }

    fn evict_overflow(pins: &mut HashMap<(SocketAddr, InfoHash), PinEntry>, max_pins: usize) {
        while pins.len() > max_pins {
            let Some(victim) = pins
                .iter()
                .min_by_key(|(_, entry)| entry.touched)
                .map(|(key, _)| *key)
            else {
                break;
            };
            pins.remove(&victim);
        }
    }
}

/// Outcome of one prefer-addr MSE heal attempt series.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MseHealOutcome {
    Recovered,
    /// Refused before dial (not static, not pinned).
    Ineligible,
    /// Dialed with backoff then gave up; caller must not self-requeue.
    GaveUp,
}

/// Drive backoff / give-up counters the same way SecureNode prefer-addr does.
#[derive(Debug)]
pub struct MseHealBackoff {
    backoff: Duration,
    attempts_at_max: u32,
}

impl MseHealBackoff {
    pub fn new() -> Self {
        Self {
            backoff: MSE_HEAL_INITIAL_BACKOFF,
            attempts_at_max: 0,
        }
    }

    pub fn current(&self) -> Duration {
        self.backoff
    }

    /// Record a failed dial. Returns `true` when the cycle should stop (gave up).
    pub fn note_failure(&mut self) -> bool {
        if self.backoff >= MSE_HEAL_MAX_BACKOFF {
            self.attempts_at_max = self.attempts_at_max.saturating_add(1);
            if self.attempts_at_max >= MSE_HEAL_GIVE_UP_AT_MAX {
                return true;
            }
        }
        self.backoff = (self.backoff * 2).min(MSE_HEAL_MAX_BACKOFF);
        false
    }
}

impl Default for MseHealBackoff {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn backoff_gives_up_after_three_at_max() {
        let mut b = MseHealBackoff::new();
        while b.current() < MSE_HEAL_MAX_BACKOFF {
            assert!(!b.note_failure());
        }
        assert_eq!(b.current(), MSE_HEAL_MAX_BACKOFF);
        assert!(!b.note_failure()); // 1
        assert!(!b.note_failure()); // 2
        assert!(b.note_failure()); // 3 → give up
    }

    #[tokio::test]
    async fn pins_expire_after_ttl() {
        let state = MseHealState::with_limits(8, Duration::from_millis(30));
        let addr = SocketAddr::V4(SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 1));
        let hash = InfoHash::from_bytes([9u8; 20]);
        state.pin(addr, hash, [1u8; 20]).await;
        assert_eq!(state.pinned_id(addr, hash).await, Some([1u8; 20]));
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert_eq!(state.pinned_id(addr, hash).await, None);
    }

    #[tokio::test]
    async fn pins_evict_oldest_when_over_capacity() {
        let state = MseHealState::with_limits(2, Duration::from_secs(3600));
        let hash = InfoHash::from_bytes([2u8; 20]);
        let a = SocketAddr::V4(SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 1));
        let b = SocketAddr::V4(SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 2));
        let c = SocketAddr::V4(SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 3));
        state.pin(a, hash, [1u8; 20]).await;
        tokio::time::sleep(Duration::from_millis(5)).await;
        state.pin(b, hash, [2u8; 20]).await;
        tokio::time::sleep(Duration::from_millis(5)).await;
        state.pin(c, hash, [3u8; 20]).await;
        assert_eq!(state.pinned_id(a, hash).await, None);
        assert_eq!(state.pinned_id(b, hash).await, Some([2u8; 20]));
        assert_eq!(state.pinned_id(c, hash).await, Some([3u8; 20]));
    }
}