torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
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
    }

    /// Pure BEP 52 v2 (no v1 `pieces`; magnet uses `urn:btmh` only).
    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 {
        // Placeholder length for piece_count(); pure-v2 verify uses merkle layers.
        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)
}

/// BEP 47 padding so each non-final file ends on a piece boundary (hybrid multi-file).
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());
    }
}