use std::path::{Path, PathBuf};
use kdl::{KdlDocument, KdlNode};
use crate::error::{Error, Result};
use crate::integrity::{open_tracked, seal_tracked, IntegrityConfig, Checksum};
use crate::types::BlockKey;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockRecord {
pub piece: u32,
pub offset: u32,
pub length: u32,
pub crc32c: Checksum,
}
#[derive(Debug, Default, Clone)]
pub struct IntegrityManifest {
pub info_hash_hex: String,
pub blocks: Vec<BlockRecord>,
}
impl IntegrityManifest {
pub fn new(info_hash_hex: impl Into<String>) -> Self {
Self {
info_hash_hex: info_hash_hex.into(),
blocks: Vec::new(),
}
}
pub fn upsert_block(&mut self, key: BlockKey, length: u32, crc32c: Checksum) {
if let Some(record) = self
.blocks
.iter_mut()
.find(|record| record.piece == key.piece && record.offset == key.offset)
{
record.length = length;
record.crc32c = crc32c;
return;
}
self.blocks.push(BlockRecord {
piece: key.piece,
offset: key.offset,
length,
crc32c,
});
}
pub fn lookup(&self, key: BlockKey) -> Option<&BlockRecord> {
self.blocks
.iter()
.find(|record| record.piece == key.piece && record.offset == key.offset)
}
pub fn to_kdl(&self) -> String {
let mut lines = vec![
format!("info-hash \"{}\"", self.info_hash_hex),
"blocks {".into(),
];
for block in &self.blocks {
lines.push(format!(
" block piece={} offset={} length={} crc={}",
block.piece, block.offset, block.length, block.crc32c
));
}
lines.push("}".into());
lines.join("\n")
}
pub fn from_kdl(input: &str) -> Result<Self> {
let doc = input
.parse::<KdlDocument>()
.map_err(|err| Error::Store(format!("manifest parse: {err}")))?;
let info_hash_hex = doc
.get("info-hash")
.and_then(|node| node.entries().first())
.and_then(|entry| entry.value().as_string())
.ok_or_else(|| Error::Store("manifest missing info-hash".into()))?
.to_string();
let mut blocks = Vec::new();
if let Some(blocks_node) = doc.get("blocks").and_then(|node| node.children()) {
for entry in blocks_node.nodes() {
if entry.name().value() != "block" {
continue;
}
let piece = prop_u32(entry, "piece")?;
let offset = prop_u32(entry, "offset")?;
let length = prop_u32(entry, "length")?;
let crc32c = prop_crc(entry, "crc")?;
blocks.push(BlockRecord {
piece,
offset,
length,
crc32c,
});
}
}
Ok(Self {
info_hash_hex,
blocks,
})
}
pub async fn load_under_root(root: &Path, config: &IntegrityConfig) -> Result<Self> {
let relative = Path::new(".torrentdht").join("manifest.kdl");
let stored = match crate::security::read_bytes_under_root_async(root, &relative).await {
Ok(bytes) => bytes,
Err(Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(Self::default());
}
Err(err) => return Err(err),
};
let context = format!("manifest:{}", relative.display());
let plain = open_tracked(config, &stored, &context)?;
Self::from_kdl(std::str::from_utf8(&plain).map_err(|_| Error::Store("manifest utf-8".into()))?)
}
pub async fn save_under_root(&self, root: &Path, config: &IntegrityConfig) -> Result<()> {
let relative = Path::new(".torrentdht").join("manifest.kdl");
let kdl = self.to_kdl();
let context = format!("manifest:{}", relative.display());
let sealed = seal_tracked(config, kdl.as_bytes(), &context)?;
crate::security::write_bytes_under_root_async(root, &relative, sealed).await
}
pub async fn load(path: &Path, config: &IntegrityConfig) -> Result<Self> {
let root = path
.parent()
.and_then(|p| p.parent())
.ok_or_else(|| Error::Store("manifest path missing download root".into()))?;
Self::load_under_root(root, config).await
}
pub async fn save(&self, path: &Path, config: &IntegrityConfig) -> Result<()> {
let root = path
.parent()
.and_then(|p| p.parent())
.ok_or_else(|| Error::Store("manifest path missing download root".into()))?;
self.save_under_root(root, config).await
}
pub fn sidecar_dir(root: &Path) -> PathBuf {
root.join(".torrentdht")
}
pub fn manifest_path(root: &Path) -> PathBuf {
Self::sidecar_dir(root).join("manifest.kdl")
}
pub fn parity_path(root: &Path, piece: u32) -> PathBuf {
Self::sidecar_dir(root).join(format!("parity-{piece}.bin"))
}
pub fn parity_relative(piece: u32) -> PathBuf {
PathBuf::from(".torrentdht").join(format!("parity-{piece}.bin"))
}
}
fn prop_u32(node: &KdlNode, key: &str) -> Result<u32> {
let value = node
.get(key)
.and_then(|value| value.as_integer())
.ok_or_else(|| Error::Store(format!("manifest block missing {key}")))?;
u32_from_kdl(value, key)
}
fn prop_crc(node: &KdlNode, key: &str) -> Result<Checksum> {
prop_u32(node, key)
}
fn u32_from_kdl(value: i128, field: &str) -> Result<u32> {
if !(0..=u32::MAX as i128).contains(&value) {
return Err(Error::Store(format!("{field} out of range")));
}
Ok(value as u32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip_kdl() {
let mut manifest = IntegrityManifest::new("abcd");
manifest.upsert_block(BlockKey { piece: 0, offset: 0 }, 16384, 0x1234_5678);
let parsed = IntegrityManifest::from_kdl(&manifest.to_kdl()).expect("parse");
assert_eq!(parsed.blocks.len(), 1);
assert_eq!(parsed.blocks[0].crc32c, 0x1234_5678);
}
}