use std::path::Path;
use rayon::prelude::*;
use sha1::{Digest, Sha1};
use ed25519_dalek::SigningKey;
use crate::bencode::{encode, BencodeValue};
use crate::error::{Error, Result};
use crate::torrent::content::ContentLayout;
use crate::torrent::file::TorrentFile;
use crate::torrent::info::{info_to_bencode, InfoHash, TorrentInfo};
const DEFAULT_PIECE_LENGTH: u32 = 256 * 1024;
#[derive(Debug, Clone)]
pub struct TorrentBuilder {
input: std::path::PathBuf,
piece_length: u32,
announce: Option<String>,
name: Option<String>,
signing_key: Option<SigningKey>,
v2_hybrid: bool,
v2_only: bool,
}
impl TorrentBuilder {
pub fn new(input: impl AsRef<Path>) -> Self {
Self {
input: input.as_ref().to_path_buf(),
piece_length: DEFAULT_PIECE_LENGTH,
announce: None,
name: None,
signing_key: None,
v2_hybrid: false,
v2_only: false,
}
}
pub fn piece_length(mut self, piece_length: u32) -> Self {
self.piece_length = piece_length.max(16 * 1024);
self
}
pub fn announce(mut self, url: impl Into<String>) -> Self {
self.announce = Some(url.into());
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn signing_key(mut self, key: SigningKey) -> Self {
self.signing_key = Some(key);
self
}
pub fn v2_hybrid(mut self, enabled: bool) -> Self {
self.v2_hybrid = enabled;
if enabled {
self.v2_only = false;
}
self
}
pub fn v2_only(mut self, enabled: bool) -> Self {
self.v2_only = enabled;
if enabled {
self.v2_hybrid = false;
}
self
}
pub async fn build(self) -> Result<TorrentFile> {
let input = self.input.clone();
let piece_length = self.piece_length;
let announce = self.announce.clone();
let name = self.name.clone();
let signing_key = self.signing_key.clone();
let v2_hybrid = self.v2_hybrid;
let v2_only = self.v2_only;
tokio::task::spawn_blocking(move || {
build_sync(
input,
piece_length,
announce,
name,
signing_key,
v2_hybrid,
v2_only,
)
})
.await
.map_err(|err| Error::Torrent(format!("torrent build task failed: {err}")))?
}
pub async fn build_and_write(self, output: impl AsRef<Path>) -> Result<TorrentFile> {
let torrent = self.build().await?;
torrent.write_to(output).await?;
Ok(torrent)
}
}
fn build_sync(
input: std::path::PathBuf,
piece_length: u32,
announce: Option<String>,
name: Option<String>,
signing_key: Option<SigningKey>,
v2_hybrid: bool,
v2_only: bool,
) -> Result<TorrentFile> {
let layout = ContentLayout::from_path(&input, name)?;
let use_v2 = v2_hybrid || v2_only;
let (files, total_len, hash_layout) = if use_v2 && layout.files.len() > 1 {
let padded = build_padded_layout(&layout, piece_length)?;
let files = padded.torrent_files();
let total_len = padded.total_len;
(files, total_len, padded)
} else {
(
layout.torrent_files(),
layout.total_len,
layout.clone(),
)
};
let pieces = if v2_only {
let count = if total_len == 0 {
0
} else {
total_len.div_ceil(u64::from(piece_length)) as usize
};
vec![[0u8; 20]; count]
} else {
hash_pieces(&hash_layout, piece_length)?
};
let v2 = if use_v2 {
Some(build_v2_meta(&hash_layout, piece_length)?)
} else {
None
};
let meta_version = if v2_only {
crate::torrent::MetaVersion::V2
} else if v2_hybrid {
crate::torrent::MetaVersion::Hybrid
} else {
crate::torrent::MetaVersion::V1
};
let info_value = build_info_bencode(
&layout.name,
piece_length,
&pieces,
&files,
total_len,
meta_version,
v2.as_ref(),
)?;
let info_hash_v2 = if use_v2 {
Some(crate::torrent::InfoHashV2::from_info_dict(&info_value)?)
} else {
None
};
let info_hash = if v2_only {
info_hash_v2.expect("v2").truncate_to_v1()
} else {
InfoHash::from_info_dict(&info_value)?
};
let info = TorrentInfo {
info_hash,
info_hash_v2,
name: layout.name,
piece_length,
pieces,
files,
total_len,
private: false,
meta_version,
v2,
};
let mut torrent = TorrentFile {
announce: announce.clone(),
trackers: announce.into_iter().collect(),
web_seeds: Vec::new(),
info,
signature: None,
info_dict_bytes: encode(&info_value),
};
if let Some(key) = signing_key {
torrent.sign(&key);
}
Ok(torrent)
}
fn build_padded_layout(layout: &ContentLayout, piece_length: u32) -> Result<ContentLayout> {
let piece_length = u64::from(piece_length);
let mut files = Vec::new();
for (idx, src) in layout.files.iter().enumerate() {
files.push(src.clone());
let is_last = idx + 1 == layout.files.len();
if is_last {
continue;
}
let rem = src.length % piece_length;
if rem == 0 {
continue;
}
let pad = piece_length - rem;
files.push(crate::torrent::content::ContentSource {
absolute: std::path::PathBuf::new(),
relative: std::path::PathBuf::from(&layout.name)
.join(".pad")
.join(pad.to_string()),
length: pad,
is_pad: true,
});
}
let total_len = files
.iter()
.map(|f| f.length)
.try_fold(0u64, u64::checked_add)
.ok_or_else(|| Error::Torrent("padded content length overflow".into()))?;
Ok(ContentLayout {
name: layout.name.clone(),
files,
total_len,
})
}
fn hash_pieces(layout: &ContentLayout, piece_length: u32) -> Result<Vec<[u8; 20]>> {
let piece_length = piece_length as u64;
let piece_count = layout
.total_len
.checked_add(piece_length - 1)
.ok_or_else(|| Error::Torrent("piece count overflow".into()))?
/ piece_length;
let piece_count = piece_count as usize;
(0..piece_count)
.into_par_iter()
.map(|index| {
let data = layout.read_piece(index as u32, piece_length as u32)?;
Ok(hash_piece(&data))
})
.collect()
}
fn hash_piece(data: &[u8]) -> [u8; 20] {
let digest = Sha1::digest(data);
let mut out = [0u8; 20];
out.copy_from_slice(&digest);
out
}
fn build_v2_meta(
layout: &ContentLayout,
piece_length: u32,
) -> Result<crate::torrent::V2Meta> {
let mut tree_files = Vec::new();
let mut flat = Vec::new();
for src in &layout.files {
let data = if src.is_pad || src.length == 0 {
vec![0u8; src.length as usize]
} else {
let mut buf = vec![0u8; src.length as usize];
let mut handle = std::fs::File::open(&src.absolute)?;
use std::io::Read;
handle.read_exact(&mut buf)?;
buf
};
let meta = crate::torrent::v2::v2_file_from_bytes(
src.relative.clone(),
&data,
piece_length,
);
flat.extend_from_slice(&meta.piece_hashes);
if !src.is_pad {
tree_files.push(meta);
}
}
let mut v2 = crate::torrent::v2::v2_from_files(tree_files);
v2.piece_hashes = flat;
Ok(v2)
}
fn build_info_bencode(
name: &str,
piece_length: u32,
pieces: &[[u8; 20]],
files: &[(std::path::PathBuf, u64)],
total_len: u64,
meta_version: crate::torrent::MetaVersion,
v2: Option<&crate::torrent::V2Meta>,
) -> Result<BencodeValue> {
let info = TorrentInfo {
info_hash: InfoHash::from_bytes([0; 20]),
info_hash_v2: None,
name: name.to_string(),
piece_length,
pieces: pieces.to_vec(),
files: files.to_vec(),
total_len,
private: false,
meta_version,
v2: v2.cloned(),
};
info_to_bencode(&info)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::torrent::{info::info_to_bencode, InfoHash, TorrentFile, TorrentInfo};
fn write_temp_file(name: &str, contents: &[u8]) -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(name);
std::fs::write(&path, contents).expect("write");
dir
}
#[tokio::test]
async fn builds_single_file_torrent() {
let dir = write_temp_file("sample.txt", b"hello torrent creator");
let torrent = TorrentBuilder::new(dir.path().join("sample.txt"))
.announce("http://example.com/announce")
.piece_length(16 * 1024)
.build()
.await
.expect("build");
assert_eq!(torrent.info.name, "sample.txt");
assert_eq!(torrent.info.total_len, 21);
assert_eq!(torrent.info.pieces.len(), 1);
assert_eq!(
torrent.announce.as_deref(),
Some("http://example.com/announce")
);
let encoded = torrent.to_bytes().expect("encode");
let parsed = TorrentFile::parse(&encoded).expect("parse");
assert_eq!(parsed.info.info_hash, torrent.info.info_hash);
assert_eq!(parsed.info.name, "sample.txt");
}
#[tokio::test]
async fn builds_directory_torrent() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("a.txt"), b"aaa").expect("write a");
std::fs::create_dir(dir.path().join("sub")).expect("mkdir");
std::fs::write(dir.path().join("sub/b.txt"), b"bbbb").expect("write b");
let torrent = TorrentBuilder::new(dir.path())
.piece_length(16 * 1024)
.build()
.await
.expect("build");
assert_eq!(torrent.info.files.len(), 2);
assert_eq!(torrent.info.total_len, 7);
assert!(torrent.info.files.iter().any(|(path, _)| path.ends_with("a.txt")));
assert!(torrent
.info
.files
.iter()
.any(|(path, _)| path.ends_with("sub/b.txt")));
}
#[tokio::test]
async fn builds_hybrid_v2_torrent() {
let dir = write_temp_file("v2.bin", &vec![0u8; 32_768]);
let torrent = TorrentBuilder::new(dir.path().join("v2.bin"))
.piece_length(16_384)
.v2_hybrid(true)
.build()
.await
.expect("build");
assert_eq!(torrent.info.meta_version, crate::torrent::MetaVersion::Hybrid);
assert!(torrent.info.v2.is_some());
}
#[test]
fn roundtrip_info_bencode_single_file() {
let info = TorrentInfo {
info_hash: InfoHash::from_bytes([1; 20]),
info_hash_v2: None,
name: "file.bin".into(),
piece_length: 16384,
pieces: vec![[2; 20]],
files: vec![(std::path::PathBuf::from("file.bin"), 10)],
total_len: 10,
private: false,
meta_version: crate::torrent::MetaVersion::V1,
v2: None,
};
let encoded = info_to_bencode(&info).expect("encode");
let dict = encoded.as_dict().expect("dict");
assert!(dict.contains_key(b"length".as_ref()));
assert!(!dict.contains_key(b"files".as_ref()));
}
#[tokio::test]
async fn builds_pure_v2_and_btmh_magnet() {
let dir = write_temp_file("pure.bin", &vec![9u8; 32_768]);
let torrent = TorrentBuilder::new(dir.path().join("pure.bin"))
.piece_length(16_384)
.v2_only(true)
.build()
.await
.expect("build");
assert_eq!(torrent.info.meta_version, crate::torrent::MetaVersion::V2);
let v2 = torrent.info.info_hash_v2.expect("info_hash_v2");
assert_eq!(torrent.info.info_hash, v2.truncate_to_v1());
let uri = crate::torrent::torrent_to_magnet(&torrent);
assert!(uri.contains("xt=urn:btmh:1220"));
assert!(!uri.contains("urn:btih:"));
let parsed = crate::torrent::parse_magnet(&uri).expect("parse magnet");
assert!(!parsed.has_btih);
assert_eq!(parsed.info_hash_v2, Some(v2));
assert_eq!(parsed.info_hash, torrent.info.info_hash);
}
#[tokio::test]
async fn builds_hybrid_emits_btih_and_btmh() {
let dir = write_temp_file("hy.bin", &vec![3u8; 16_384]);
let torrent = TorrentBuilder::new(dir.path().join("hy.bin"))
.piece_length(16_384)
.v2_hybrid(true)
.build()
.await
.expect("build");
let uri = crate::torrent::torrent_to_magnet(&torrent);
assert!(uri.contains("xt=urn:btih:"));
assert!(uri.contains("xt=urn:btmh:1220"));
let parsed = crate::torrent::parse_magnet(&uri).expect("parse");
assert!(parsed.has_btih);
assert_eq!(parsed.info_hash, torrent.info.info_hash);
assert_eq!(parsed.info_hash_v2, torrent.info.info_hash_v2);
}
#[tokio::test]
async fn builds_hybrid_v2_with_file_tree_multi() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("a.bin"), vec![1u8; 20_000]).expect("a");
std::fs::write(dir.path().join("b.bin"), vec![2u8; 10_000]).expect("b");
let torrent = TorrentBuilder::new(dir.path())
.piece_length(16_384)
.v2_hybrid(true)
.build()
.await
.expect("build");
assert_eq!(torrent.info.meta_version, crate::torrent::MetaVersion::Hybrid);
let v2 = torrent.info.v2.as_ref().expect("v2");
assert_eq!(v2.files.len(), 2);
assert!(torrent.info.files.iter().any(|(p, _)| {
p.components().any(|c| matches!(c, std::path::Component::Normal(n) if n == ".pad"))
}));
let encoded = torrent.to_bytes().expect("encode");
let parsed = TorrentFile::parse(&encoded).expect("parse");
let parsed_v2 = parsed.info.v2.as_ref().expect("parsed v2");
assert_eq!(parsed_v2.files.len(), 2);
assert_eq!(parsed_v2.files[0].pieces_root, v2.files[0].pieces_root);
assert!(parsed.info.info_hash_v2.is_some());
}
}