torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use std::fmt;

use crate::net::random::random_bytes;

#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId([u8; 20]);

impl NodeId {
    pub fn random() -> Self {
        match random_bytes::<20>() {
            Ok(id) => Self(id),
            // Extremely rare OS CSPRNG failure: fall back to a distinct zero id is unsafe
            // for DHT identity, so panic — callers cannot safely continue without entropy.
            Err(_) => panic!("CSPRNG failure generating NodeId"),
        }
    }

    pub fn from_bytes(bytes: [u8; 20]) -> Self {
        Self(bytes)
    }

    pub fn from_info_hash(hash: &[u8; 20]) -> Self {
        Self(*hash)
    }

    pub fn as_bytes(&self) -> &[u8; 20] {
        &self.0
    }
}

impl fmt::Debug for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "NodeId({})", hex(&self.0[..8]))
    }
}

pub fn distance(a: &NodeId, b: &NodeId) -> [u8; 20] {
    let mut out = [0u8; 20];
    for (idx, byte) in out.iter_mut().enumerate() {
        *byte = a.0[idx] ^ b.0[idx];
    }
    out
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

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

    #[test]
    fn distance_is_symmetric() {
        let a = NodeId::from_bytes([1; 20]);
        let b = NodeId::from_bytes([2; 20]);
        assert_eq!(distance(&a, &b), distance(&b, &a));
    }
}