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::integrity::{
    checksum_block, encode_piece_parity, parity_from_bytes, parity_to_bytes, reconstruct_piece,
    recover_piece, verify_block_checksum, IntegrityConfig,
};

const CRC_LEN: usize = 4;

/// Seal a tracked sidecar (manifest, resume, etc.): CRC32c + optional RS ECC + AEAD.
pub fn seal_tracked(config: &IntegrityConfig, plaintext: &[u8], context: &str) -> Result<Vec<u8>> {
    let crc = checksum_block(plaintext);
    let mut body = Vec::with_capacity(CRC_LEN + plaintext.len());
    body.extend(crc.to_be_bytes());
    body.extend_from_slice(plaintext);

    let protected = if config.ecc_enabled {
        let parity = encode_piece_parity(0, &body, config.ecc_config())?;
        parity_to_bytes(&parity)
    } else {
        body
    };

    super::aead_seal(config, &protected, context)
}

/// Open and authenticate a tracked sidecar; verifies CRC32c and recovers via ECC when enabled.
pub fn open_tracked(config: &IntegrityConfig, stored: &[u8], context: &str) -> Result<Vec<u8>> {
    let protected = super::aead_open(config, stored, context)?;
    let body = if config.ecc_enabled {
        let parity = parity_from_bytes(&protected)?;
        reconstruct_piece(&parity, config.ecc_config())
            .or_else(|_| recover_piece(&parity, config.ecc_config()))?
    } else {
        protected
    };

    if body.len() < CRC_LEN {
        return Err(Error::Integrity("tracked sidecar body too short".into()));
    }
    let crc = u32::from_be_bytes(body[..CRC_LEN].try_into().expect("crc"));
    let plaintext = &body[CRC_LEN..];
    if !verify_block_checksum(plaintext, crc) {
        return Err(Error::Integrity("tracked sidecar crc mismatch".into()));
    }
    Ok(plaintext.to_vec())
}

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

    fn test_config(ecc: bool, encrypt: bool) -> IntegrityConfig {
        IntegrityConfig {
            verify_blocks: true,
            ecc_enabled: ecc,
            ecc_data_shards: 4,
            ecc_parity_shards: 1,
            encrypt_sidecars: encrypt,
            cipher: CipherConfig::from_key([11u8; 32]),
        }
    }

    #[test]
    fn tracked_roundtrip_with_crc_and_ecc() {
        let cfg = test_config(true, true);
        let plain = b"tracked sidecar payload";
        let sealed = seal_tracked(&cfg, plain, "test:tracked").expect("seal");
        let opened = open_tracked(&cfg, &sealed, "test:tracked").expect("open");
        assert_eq!(opened, plain);
    }

    #[test]
    fn tracked_rejects_tampered_ciphertext() {
        let cfg = test_config(true, true);
        let mut sealed = seal_tracked(&cfg, b"payload", "test:tamper").expect("seal");
        let last = sealed.len() - 1;
        sealed[last] ^= 0xFF;
        assert!(open_tracked(&cfg, &sealed, "test:tamper").is_err());
    }

    #[test]
    fn tracked_rejects_raw_plaintext_when_encrypt_off() {
        let cfg = test_config(false, false);
        assert!(open_tracked(&cfg, b"not-a-tracked-sidecar", "test:raw").is_err());
    }

    #[test]
    fn tracked_roundtrip_authenticated_cleartext() {
        let cfg = test_config(false, false);
        let plain = b"cleartext but crc-protected";
        let sealed = seal_tracked(&cfg, plain, "test:clear").expect("seal");
        let opened = open_tracked(&cfg, &sealed, "test:clear").expect("open");
        assert_eq!(opened, plain);
    }
}