torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use crate::error::{Error, Result};
use crate::torrent::{InfoHash, InfoHashV2};

pub fn decode_base32_info_hash(raw: &str) -> Result<InfoHash> {
    let bytes = decode_base32_fixed(raw, 20)?;
    let mut out = [0u8; 20];
    out.copy_from_slice(&bytes);
    Ok(InfoHash::from_bytes(out))
}

/// Decode a 52-char base32 encoding of a 32-byte v2 info-hash (not for `urn:btih`).
pub fn decode_base32_v2_info_hash(raw: &str) -> Result<InfoHashV2> {
    let bytes = decode_base32_fixed(raw, 32)?;
    let mut out = [0u8; 32];
    out.copy_from_slice(&bytes);
    Ok(InfoHashV2::from_bytes(out))
}

pub fn info_hash_to_base32(hash: &InfoHash) -> String {
    encode_base32(hash.as_bytes())
}

pub fn info_hash_v2_to_base32(hash: &InfoHashV2) -> String {
    encode_base32(hash.as_bytes())
}

fn decode_base32_fixed(raw: &str, expected_len: usize) -> Result<Vec<u8>> {
    let normalized: String = raw
        .chars()
        .filter(|c| !c.is_whitespace())
        .map(|c| c.to_ascii_uppercase())
        .collect();
    let bytes = decode_base32(&normalized)?;
    if bytes.len() != expected_len {
        return Err(Error::Torrent(format!(
            "base32 info hash decoded to {} bytes, expected {expected_len}",
            bytes.len()
        )));
    }
    Ok(bytes)
}

fn encode_base32(input: &[u8]) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
    let mut bits: u32 = 0;
    let mut bit_count: u32 = 0;
    let mut out = String::new();
    for &byte in input {
        bits = (bits << 8) | u32::from(byte);
        bit_count += 8;
        while bit_count >= 5 {
            bit_count -= 5;
            let idx = ((bits >> bit_count) & 0x1f) as usize;
            out.push(ALPHABET[idx] as char);
        }
    }
    if bit_count > 0 {
        let idx = ((bits << (5 - bit_count)) & 0x1f) as usize;
        out.push(ALPHABET[idx] as char);
    }
    out
}

fn decode_base32(input: &str) -> Result<Vec<u8>> {
    let mut bits: u32 = 0;
    let mut bit_count: u32 = 0;
    let mut out = Vec::new();
    for ch in input.chars() {
        let value = match ch {
            'A'..='Z' => ch as u8 - b'A',
            '2'..='7' => ch as u8 - b'2' + 26,
            '=' => continue,
            _ => {
                return Err(Error::Torrent(format!(
                    "invalid base32 character: {ch}"
                )));
            }
        };
        bits = (bits << 5) | u32::from(value);
        bit_count += 5;
        if bit_count >= 8 {
            bit_count -= 8;
            out.push(((bits >> bit_count) & 0xff) as u8);
        }
    }
    Ok(out)
}

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

    #[test]
    fn roundtrips_base32() {
        let hash = InfoHash::from_bytes([0xAB; 20]);
        let encoded = info_hash_to_base32(&hash);
        let decoded = decode_base32_info_hash(&encoded).expect("decode");
        assert_eq!(decoded, hash);
    }

    #[test]
    fn roundtrips_v2_base32() {
        let hash = InfoHashV2::from_bytes([0xCD; 32]);
        let encoded = info_hash_v2_to_base32(&hash);
        assert_eq!(encoded.len(), 52);
        let decoded = decode_base32_v2_info_hash(&encoded).expect("decode");
        assert_eq!(decoded, hash);
    }
}