torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
mod checksum;
mod crypto;
mod ecc;
mod image;
mod manifest;
mod tracked;

pub use checksum::{checksum_block, verify_block_checksum, Checksum};
pub use crypto::{derive_storage_key, BlockCipher, CipherConfig};
pub use ecc::{
    encode_piece_parity, parity_from_bytes, parity_to_bytes, reconstruct_erased, reconstruct_piece,
    recover_piece, EccConfig, PieceParity,
};
mod signing;

pub use image::{
    build_integrity_image_async, default_sidecar_root, sidecar_root_for_config,
    validate_integrity_image, IntegrityImageReport,
};
pub use manifest::{BlockRecord, IntegrityManifest};
pub use tracked::{open_tracked, seal_tracked};
pub use signing::{
    derive_signing_seed, load_signing_key, sign_info_dict, signing_key_from_seed, verify_info_dict,
    TorrentSignature, PUBLIC_KEY_LEN, SEED_LEN, SIGNATURE_LEN,
};

use crate::error::{Error, Result};

#[derive(Debug, Clone)]
pub struct IntegrityConfig {
    pub verify_blocks: bool,
    pub ecc_enabled: bool,
    pub ecc_data_shards: usize,
    pub ecc_parity_shards: usize,
    pub encrypt_sidecars: bool,
    pub cipher: CipherConfig,
}

impl Default for IntegrityConfig {
    fn default() -> Self {
        Self {
            verify_blocks: true,
            ecc_enabled: true,
            ecc_data_shards: 4,
            ecc_parity_shards: 1,
            // Match Config default: encrypt sidecars when a real key is supplied.
            // CipherConfig::default is all-zero and encrypt refuses it (fail closed).
            encrypt_sidecars: true,
            cipher: CipherConfig::default(),
        }
    }
}

impl IntegrityConfig {
    pub fn from_app_config(cfg: &crate::config::Config, info_hash: &[u8; 20]) -> Result<Self> {
        Ok(Self {
            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: CipherConfig::from_app_config(cfg, info_hash)?,
        })
    }

    pub fn ecc_config(&self) -> EccConfig {
        EccConfig {
            data_shards: self.ecc_data_shards,
            parity_shards: self.ecc_parity_shards,
        }
    }
}

pub(crate) fn aead_seal(config: &IntegrityConfig, plaintext: &[u8], context: &str) -> Result<Vec<u8>> {
    if config.encrypt_sidecars {
        BlockCipher::new(&config.cipher).encrypt(plaintext, context.as_bytes())
    } else {
        // Encrypt-off still HMAC-SHA256 authenticates tracked/clear sidecars.
        Ok(hmac_wrap(&config.cipher, plaintext, context)?)
    }
}

pub(crate) fn aead_open(config: &IntegrityConfig, stored: &[u8], context: &str) -> Result<Vec<u8>> {
    if config.encrypt_sidecars {
        BlockCipher::new(&config.cipher).decrypt(stored, context.as_bytes())
    } else {
        hmac_unwrap(&config.cipher, stored, context)
    }
}

const HMAC_TAG_LEN: usize = 32;

fn hmac_wrap(cipher: &CipherConfig, plaintext: &[u8], context: &str) -> Result<Vec<u8>> {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;
    type HmacSha256 = Hmac<Sha256>;

    cipher.reject_if_all_zero()?;
    let mut mac = HmacSha256::new_from_slice(cipher.key_bytes())
        .map_err(|_| Error::Integrity("HMAC-SHA256 key init failed".into()))?;
    mac.update(context.as_bytes());
    mac.update(plaintext);
    let tag = mac.finalize().into_bytes();
    let mut out = Vec::with_capacity(plaintext.len() + HMAC_TAG_LEN);
    out.extend_from_slice(plaintext);
    out.extend_from_slice(&tag);
    Ok(out)
}

fn hmac_unwrap(cipher: &CipherConfig, stored: &[u8], context: &str) -> Result<Vec<u8>> {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;
    type HmacSha256 = Hmac<Sha256>;

    if stored.len() < HMAC_TAG_LEN {
        return Err(Error::Integrity("HMAC sidecar too short".into()));
    }
    cipher.reject_if_all_zero()?;
    let (plaintext, tag) = stored.split_at(stored.len() - HMAC_TAG_LEN);
    let mut mac = HmacSha256::new_from_slice(cipher.key_bytes())
        .map_err(|_| Error::Integrity("HMAC-SHA256 key init failed".into()))?;
    mac.update(context.as_bytes());
    mac.update(plaintext);
    mac.verify_slice(tag)
        .map_err(|_| Error::Integrity("HMAC-SHA256 sidecar authentication failed".into()))?;
    Ok(plaintext.to_vec())
}

/// Integrity config for host-level sidecars (peer store, DHT routing) — not torrent-bound.
pub fn host_state_integrity(cfg: &crate::config::Config) -> Result<IntegrityConfig> {
    let mut domain = [0u8; 20];
    domain[..15].copy_from_slice(b"torrentdht-host");
    IntegrityConfig::from_app_config(cfg, &domain)
}

pub fn seal_sidecar(config: &IntegrityConfig, plaintext: &[u8], context: &str) -> Result<Vec<u8>> {
    aead_seal(config, plaintext, context)
}

pub fn open_sidecar(config: &IntegrityConfig, stored: &[u8], context: &str) -> Result<Vec<u8>> {
    aead_open(config, stored, context)
}