torrentdht 0.1.1

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

use crate::config::Config;
use crate::error::{Error, Result};
use crate::integrity::IntegrityConfig;
use crate::session::ResumeCheckpoint;

#[derive(Debug, Clone)]
pub struct DownloadStatus {
    pub info_hash_hex: String,
    /// Content root: `{download_dir}/{info_hash}/`.
    pub path: PathBuf,
    /// State/ledger root (resume + integrity sidecars).
    pub state_path: PathBuf,
    pub pieces_complete: u32,
    pub bytes_downloaded: u64,
    pub has_checkpoint: bool,
}

pub async fn scan_download_dir(cfg: &Config) -> Result<Vec<DownloadStatus>> {
    let download_dir = &cfg.download_dir;
    let mut out = Vec::new();
    let mut entries = tokio::fs::read_dir(download_dir).await.map_err(|err| {
        Error::Session(format!(
            "read download dir {}: {err}",
            download_dir.display()
        ))
    })?;

    while let Some(entry) = entries.next_entry().await? {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        if name.len() != 40 || !name.chars().all(|c| c.is_ascii_hexdigit()) {
            continue;
        }

        let layout = cfg.torrent_layout(name);
        let checkpoint_path = cfg.resume_path(name);
        let integrity = integrity_for_status(cfg, name);
        let checkpoint = ResumeCheckpoint::load(&checkpoint_path, &integrity).await.ok();
        let pieces_complete = checkpoint
            .as_ref()
            .map(|cp| cp.completed_pieces.len() as u32)
            .unwrap_or(0);
        let bytes_downloaded = checkpoint.as_ref().map(|cp| cp.bytes_downloaded).unwrap_or(0);

        out.push(DownloadStatus {
            info_hash_hex: name.to_ascii_lowercase(),
            path: layout.content_root,
            state_path: layout.state_root,
            pieces_complete,
            bytes_downloaded,
            has_checkpoint: checkpoint.is_some(),
        });
    }

    // Also surface torrents that only have state (content dir missing / empty hash dirs).
    if let Some(state_dir) = &cfg.state_dir {
        let torrents = state_dir.join("torrents");
        if torrents.is_dir() {
            let mut state_entries = tokio::fs::read_dir(&torrents).await.map_err(|err| {
                Error::Session(format!("read state torrents {}: {err}", torrents.display()))
            })?;
            while let Some(entry) = state_entries.next_entry().await? {
                let path = entry.path();
                if !path.is_dir() {
                    continue;
                }
                let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
                    continue;
                };
                if name.len() != 40 || !name.chars().all(|c| c.is_ascii_hexdigit()) {
                    continue;
                }
                let hex = name.to_ascii_lowercase();
                if out.iter().any(|row| row.info_hash_hex == hex) {
                    continue;
                }
                let layout = cfg.torrent_layout(name);
                let checkpoint_path = cfg.resume_path(name);
                let integrity = integrity_for_status(cfg, name);
                let checkpoint = ResumeCheckpoint::load(&checkpoint_path, &integrity).await.ok();
                out.push(DownloadStatus {
                    info_hash_hex: hex,
                    path: layout.content_root,
                    state_path: layout.state_root,
                    pieces_complete: checkpoint
                        .as_ref()
                        .map(|cp| cp.completed_pieces.len() as u32)
                        .unwrap_or(0),
                    bytes_downloaded: checkpoint
                        .as_ref()
                        .map(|cp| cp.bytes_downloaded)
                        .unwrap_or(0),
                    has_checkpoint: checkpoint.is_some(),
                });
            }
        }
    }

    out.sort_by(|a, b| a.info_hash_hex.cmp(&b.info_hash_hex));
    Ok(out)
}

fn integrity_for_status(cfg: &Config, info_hash_hex: &str) -> IntegrityConfig {
    let mut hash = [0u8; 20];
    if hex_decode_20(info_hash_hex, &mut hash).is_ok() {
        if let Ok(integrity) = IntegrityConfig::from_app_config(cfg, &hash) {
            return integrity;
        }
    }
    // Fall back: honor encrypt-sidecars + env handshake key when Config keying fails.
    let mut fallback = IntegrityConfig {
        verify_blocks: cfg.integrity_verify_blocks,
        ecc_enabled: cfg.integrity_ecc_enabled,
        ecc_data_shards: cfg.integrity_ecc_data_shards.max(2),
        ecc_parity_shards: cfg.integrity_ecc_parity_shards.max(1),
        encrypt_sidecars: cfg.integrity_encrypt_sidecars,
        cipher: crate::integrity::CipherConfig::default(),
    };
    if let Ok(cipher) = crate::integrity::CipherConfig::from_app_config(cfg, &hash) {
        fallback.cipher = cipher;
    }
    fallback
}

fn hex_decode_20(hex: &str, out: &mut [u8; 20]) -> Result<()> {
    if hex.len() != 40 {
        return Err(Error::Session("info-hash hex must be 40 chars".into()));
    }
    for (idx, chunk) in hex.as_bytes().chunks(2).enumerate() {
        let part = std::str::from_utf8(chunk).map_err(|_| Error::Session("bad hex".into()))?;
        out[idx] =
            u8::from_str_radix(part, 16).map_err(|_| Error::Session("bad hex digit".into()))?;
    }
    Ok(())
}

pub fn format_status_table(rows: &[DownloadStatus]) -> String {
    if rows.is_empty() {
        return "no torrent download directories found".into();
    }
    let show_state = rows.iter().any(|row| row.state_path != row.path);
    let mut lines = if show_state {
        vec![
            "info-hash                              pieces  bytes      checkpoint  state-path"
                .into(),
            "-------------------------------------- ------- ---------- ----------  ----------"
                .into(),
        ]
    } else {
        vec![
            "info-hash                              pieces  bytes      checkpoint".into(),
            "-------------------------------------- ------- ---------- ----------".into(),
        ]
    };
    for row in rows {
        if show_state {
            lines.push(format!(
                "{}  {:>7}  {:>10}  {:<10}  {}",
                row.info_hash_hex,
                row.pieces_complete,
                row.bytes_downloaded,
                if row.has_checkpoint { "yes" } else { "no" },
                row.state_path.display(),
            ));
        } else {
            lines.push(format!(
                "{}  {:>7}  {:>10}  {}",
                row.info_hash_hex,
                row.pieces_complete,
                row.bytes_downloaded,
                if row.has_checkpoint { "yes" } else { "no" }
            ));
        }
    }
    lines.join("\n")
}

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

    #[tokio::test]
    async fn empty_dir_reports_none() {
        let dir = tempfile::tempdir().expect("tempdir");
        let cfg = Config {
            download_dir: dir.path().to_path_buf(),
            integrity_encrypt_sidecars: false,
            integrity_passphrase: Some(zeroize::Zeroizing::new("status-scan-test".into())),
            ..Config::default()
        };
        let rows = scan_download_dir(&cfg).await.expect("scan");
        assert!(rows.is_empty());
    }

    #[test]
    fn status_table_includes_state_path_when_distinct() {
        let rows = vec![DownloadStatus {
            info_hash_hex: "a".repeat(40),
            path: PathBuf::from("/content/hash"),
            state_path: PathBuf::from("/ledger/torrents/hash"),
            pieces_complete: 2,
            bytes_downloaded: 100,
            has_checkpoint: true,
        }];
        let table = format_status_table(&rows);
        assert!(table.contains("state-path"));
        assert!(table.contains("/ledger/torrents/hash"));
    }
}