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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! BEP 52 — torrent v2 metadata (meta version 2, file tree, merkle piece layers).

use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};

use crate::bencode::BencodeValue;
use crate::error::{Error, Result};
use crate::piece::merkle::{
    build_piece_layers, parse_piece_layer_hashes, pieces_root_from_layer, verify_pieces_root,
    MERKLE_HASH_LEN,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetaVersion {
    V1,
    V2,
    Hybrid,
}

/// One file entry under BEP 52 `file tree` (+ piece-layer hashes).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct V2FileMeta {
    /// Torrent-relative path (same convention as [`crate::torrent::TorrentInfo::files`]).
    pub path: PathBuf,
    pub length: u64,
    pub pieces_root: [u8; 32],
    /// Piece-layer hashes for this file (always populated for non-empty files).
    /// Emitted into root `piece layers` only when there is more than one piece.
    pub piece_hashes: Vec<[u8; 32]>,
}

#[derive(Debug, Clone)]
pub struct V2Meta {
    pub files: Vec<V2FileMeta>,
    /// Concatenated piece-layer hashes in v2 piece-address order (for pure-v2 verify).
    pub piece_hashes: Vec<[u8; 32]>,
    /// Root of [`Self::piece_hashes`] (legacy single-content helper / first-file root).
    pub pieces_root: [u8; 32],
}

pub fn detect_meta_version(info: &BencodeValue, has_v1_pieces: bool) -> MetaVersion {
    let version = info
        .dict_get_str("meta version")
        .and_then(|v| v.as_int())
        .unwrap_or(1);
    match version {
        v if v >= 2 && has_v1_pieces => MetaVersion::Hybrid,
        v if v >= 2 => MetaVersion::V2,
        _ => MetaVersion::V1,
    }
}

/// True when a torrent-relative path is a BEP 47 padding file (`.pad/…`).
pub fn is_pad_path(path: &Path) -> bool {
    path.components().any(|c| matches!(c, Component::Normal(p) if p == ".pad"))
}

/// Build per-file v2 metadata from raw file bytes.
pub fn v2_file_from_bytes(
    path: PathBuf,
    data: &[u8],
    piece_length: u32,
) -> V2FileMeta {
    let piece_length = piece_length.max(1) as usize;
    if data.is_empty() {
        return V2FileMeta {
            path,
            length: 0,
            pieces_root: [0u8; 32],
            piece_hashes: Vec::new(),
        };
    }
    let mut piece_hashes = Vec::new();
    for chunk in data.chunks(piece_length) {
        piece_hashes.push(crate::piece::piece_hash_from_data(
            chunk,
            crate::piece::MERKLE_BLOCK_SIZE,
        ));
    }
    let pieces_root = pieces_root_from_layer(&piece_hashes);
    V2FileMeta {
        path,
        length: data.len() as u64,
        pieces_root,
        piece_hashes,
    }
}

pub fn v2_from_files(files: Vec<V2FileMeta>) -> V2Meta {
    let mut flat = Vec::new();
    for file in &files {
        flat.extend_from_slice(&file.piece_hashes);
    }
    let legacy_root = files
        .iter()
        .find(|f| f.length > 0)
        .map(|f| f.pieces_root)
        .unwrap_or([0u8; 32]);
    V2Meta {
        files,
        piece_hashes: flat,
        pieces_root: legacy_root,
    }
}

pub fn v2_from_piece_hashes(piece_hashes: Vec<[u8; 32]>) -> V2Meta {
    let pieces_root = pieces_root_from_layer(&piece_hashes);
    let files = if piece_hashes.is_empty() {
        Vec::new()
    } else {
        vec![V2FileMeta {
            path: PathBuf::from("content"),
            length: 0,
            pieces_root,
            piece_hashes: piece_hashes.clone(),
        }]
    };
    V2Meta {
        files,
        piece_hashes,
        pieces_root,
    }
}

/// Parse root-level `piece layers` into root → piece-layer hashes.
pub fn parse_piece_layers_map(
    root: &BencodeValue,
) -> Result<BTreeMap<[u8; 32], Vec<[u8; 32]>>> {
    let Some(dict) = root
        .dict_get(b"piece layers".as_ref())
        .and_then(|v| v.as_dict())
    else {
        return Ok(BTreeMap::new());
    };
    let mut out = BTreeMap::new();
    for (root_key, raw) in dict {
        if root_key.len() != MERKLE_HASH_LEN {
            return Err(Error::Torrent(
                "piece layers key must be a 32-byte pieces root".into(),
            ));
        }
        let raw = raw
            .as_bytes()
            .ok_or_else(|| Error::Torrent("piece layers value must be bytes".into()))?;
        if raw.is_empty() || !raw.len().is_multiple_of(MERKLE_HASH_LEN) {
            return Err(Error::Torrent("invalid v2 piece layers length".into()));
        }
        let piece_count = (raw.len() / MERKLE_HASH_LEN) as u32;
        let mut pieces_root = [0u8; 32];
        pieces_root.copy_from_slice(root_key);
        if !verify_pieces_root(raw, piece_count, &pieces_root) {
            return Err(Error::Torrent(
                "invalid v2 piece layers merkle root".into(),
            ));
        }
        let piece_hashes = parse_piece_layer_hashes(raw, piece_count)
            .ok_or_else(|| Error::Torrent("invalid v2 piece layers length".into()))?;
        out.insert(pieces_root, piece_hashes);
    }
    Ok(out)
}

/// Legacy helper: single piece-layers entry validated against torrent piece count.
pub fn parse_piece_layers_dict(
    root: &BencodeValue,
    piece_count: u32,
) -> Result<Option<V2Meta>> {
    let map = parse_piece_layers_map(root)?;
    if map.is_empty() {
        return Ok(None);
    }
    let (pieces_root, piece_hashes) = map.into_iter().next().expect("non-empty");
    if piece_hashes.len() as u32 != piece_count && piece_count > 0 {
        // Multi-file layers may not equal torrent-wide piece count; keep first entry.
        return Ok(Some(V2Meta {
            files: vec![V2FileMeta {
                path: PathBuf::from("content"),
                length: 0,
                pieces_root,
                piece_hashes: piece_hashes.clone(),
            }],
            piece_hashes,
            pieces_root,
        }));
    }
    Ok(Some(V2Meta {
        files: vec![V2FileMeta {
            path: PathBuf::from("content"),
            length: 0,
            pieces_root,
            piece_hashes: piece_hashes.clone(),
        }],
        piece_hashes,
        pieces_root,
    }))
}

pub fn piece_layers_to_bencode(v2: &V2Meta) -> BencodeValue {
    let mut dict = BTreeMap::new();
    for file in &v2.files {
        // BEP 52: only files larger than one piece contribute a piece-layers entry.
        if file.piece_hashes.len() <= 1 {
            continue;
        }
        dict.insert(
            file.pieces_root.to_vec(),
            BencodeValue::Bytes(build_piece_layers(&file.piece_hashes)),
        );
    }
    // Legacy single-layer torrents without populated `files`.
    if dict.is_empty() && v2.piece_hashes.len() > 1 {
        dict.insert(
            v2.pieces_root.to_vec(),
            BencodeValue::Bytes(build_piece_layers(&v2.piece_hashes)),
        );
    }
    BencodeValue::Dict(dict)
}

/// Encode BEP 52 `file tree` from v2 file entries.
pub fn file_tree_to_bencode(files: &[V2FileMeta], torrent_name: &str) -> Result<BencodeValue> {
    let mut root: BTreeMap<Vec<u8>, BencodeValue> = BTreeMap::new();
    for file in files {
        if is_pad_path(&file.path) {
            continue;
        }
        let components = path_components_for_tree(&file.path, torrent_name)?;
        if components.is_empty() {
            return Err(Error::Torrent("file tree path is empty".into()));
        }
        insert_file_tree_leaf(&mut root, &components, file)?;
    }
    Ok(BencodeValue::Dict(root))
}

fn path_components_for_tree(relative: &Path, torrent_name: &str) -> Result<Vec<Vec<u8>>> {
    let stripped = relative
        .strip_prefix(torrent_name)
        .unwrap_or(relative);
    let mut parts = Vec::new();
    // Single-file: relative == torrent_name → one component = name.
    if stripped.as_os_str().is_empty() || relative == Path::new(torrent_name) {
        parts.push(torrent_name.as_bytes().to_vec());
        return Ok(parts);
    }
    // Multi-file: prefix with torrent name when relative already includes it.
    if relative.starts_with(torrent_name) {
        parts.push(torrent_name.as_bytes().to_vec());
    }
    for component in stripped.components() {
        match component {
            Component::Normal(part) => {
                let s = part
                    .to_str()
                    .ok_or_else(|| Error::Torrent("file tree path is not utf-8".into()))?;
                if s == "." || s == ".." {
                    return Err(Error::Torrent(
                        "file tree path must not contain . or ..".into(),
                    ));
                }
                parts.push(s.as_bytes().to_vec());
            }
            _ => {
                return Err(Error::Torrent("invalid file tree path component".into()));
            }
        }
    }
    Ok(parts)
}

fn insert_file_tree_leaf(
    node: &mut BTreeMap<Vec<u8>, BencodeValue>,
    components: &[Vec<u8>],
    file: &V2FileMeta,
) -> Result<()> {
    let (head, rest) = components
        .split_first()
        .ok_or_else(|| Error::Torrent("file tree path is empty".into()))?;
    if rest.is_empty() {
        let mut props = BTreeMap::new();
        props.insert(b"length".to_vec(), BencodeValue::Int(file.length as i64));
        if file.length > 0 {
            props.insert(
                b"pieces root".to_vec(),
                BencodeValue::Bytes(file.pieces_root.to_vec()),
            );
        }
        let leaf = BencodeValue::Dict(BTreeMap::from([(
            Vec::new(),
            BencodeValue::Dict(props),
        )]));
        if node.contains_key(head) {
            return Err(Error::Torrent("duplicate file tree path".into()));
        }
        node.insert(head.clone(), leaf);
        return Ok(());
    }
    let entry = node.entry(head.clone()).or_insert_with(|| {
        BencodeValue::Dict(BTreeMap::new())
    });
    let BencodeValue::Dict(child) = entry else {
        return Err(Error::Torrent(
            "file tree path conflicts with a file entry".into(),
        ));
    };
    if child.contains_key(&Vec::<u8>::new()) {
        return Err(Error::Torrent(
            "file tree path conflicts with a file entry".into(),
        ));
    }
    insert_file_tree_leaf(child, rest, file)
}

/// Parse `info["file tree"]` into ordered file metas (piece_hashes empty until layers attach).
pub fn parse_file_tree(
    info: &BencodeValue,
    torrent_name: &str,
) -> Result<Option<Vec<V2FileMeta>>> {
    let Some(tree) = info.dict_get_str("file tree") else {
        return Ok(None);
    };
    let dict = tree
        .as_dict()
        .ok_or_else(|| Error::Torrent("file tree must be a dict".into()))?;
    if dict.contains_key(&Vec::<u8>::new()) {
        return Err(Error::Torrent(
            "file tree root must not be a file entry".into(),
        ));
    }
    let mut files = Vec::new();
    walk_file_tree(dict, PathBuf::new(), torrent_name, &mut files)?;
    if files.is_empty() {
        return Err(Error::Torrent("file tree has no files".into()));
    }
    Ok(Some(files))
}

fn walk_file_tree(
    node: &BTreeMap<Vec<u8>, BencodeValue>,
    prefix: PathBuf,
    torrent_name: &str,
    out: &mut Vec<V2FileMeta>,
) -> Result<()> {
    for (key, value) in node {
        if key.is_empty() {
            return Err(Error::Torrent(
                "file properties must not appear as directory siblings".into(),
            ));
        }
        let name = String::from_utf8(key.clone())
            .map_err(|_| Error::Torrent("file tree key is not utf-8".into()))?;
        if name == "." || name == ".." {
            return Err(Error::Torrent(
                "file tree path must not contain . or ..".into(),
            ));
        }
        let child_path = if prefix.as_os_str().is_empty() {
            PathBuf::from(&name)
        } else {
            prefix.join(&name)
        };
        let dict = value
            .as_dict()
            .ok_or_else(|| Error::Torrent("file tree entry must be a dict".into()))?;
        if let Some(props) = dict.get(&Vec::<u8>::new()) {
            if dict.len() != 1 {
                return Err(Error::Torrent(
                    "file entry must not have sibling keys beside \"\"".into(),
                ));
            }
            let props = props
                .as_dict()
                .ok_or_else(|| Error::Torrent("file properties must be a dict".into()))?;
            let length = props
                .get(b"length".as_ref())
                .and_then(|v| v.as_int())
                .ok_or_else(|| Error::Torrent("file tree entry missing length".into()))?;
            if length < 0 {
                return Err(Error::Torrent("negative file tree length".into()));
            }
            let length = length as u64;
            let mut pieces_root = [0u8; 32];
            if length > 0 {
                let root = props
                    .get(b"pieces root".as_ref())
                    .and_then(|v| v.as_bytes())
                    .ok_or_else(|| Error::Torrent("non-empty file missing pieces root".into()))?;
                if root.len() != MERKLE_HASH_LEN {
                    return Err(Error::Torrent(
                        "pieces root must be 32 bytes".into(),
                    ));
                }
                pieces_root.copy_from_slice(root);
            }
            // Normalize to torrent-relative paths used elsewhere.
            let path = if child_path.starts_with(torrent_name) {
                child_path
            } else {
                PathBuf::from(torrent_name).join(child_path)
            };
            let path = crate::security::sanitize_torrent_relative_path(path)?;
            out.push(V2FileMeta {
                path,
                length,
                pieces_root,
                piece_hashes: Vec::new(),
            });
        } else {
            walk_file_tree(dict, child_path, torrent_name, out)?;
        }
    }
    Ok(())
}

/// Attach piece-layer hashes to file-tree entries; build flat [`V2Meta`].
pub fn attach_piece_layers(
    mut files: Vec<V2FileMeta>,
    layers: &BTreeMap<[u8; 32], Vec<[u8; 32]>>,
    piece_length: u32,
) -> Result<V2Meta> {
    for file in &mut files {
        if file.length == 0 {
            continue;
        }
        let expected = file.length.div_ceil(u64::from(piece_length.max(1))) as usize;
        if expected > 1 {
            let hashes = layers.get(&file.pieces_root).ok_or_else(|| {
                Error::Torrent(format!(
                    "piece layers missing for file {}",
                    file.path.display()
                ))
            })?;
            if hashes.len() != expected {
                return Err(Error::Torrent(format!(
                    "piece layers count {} != expected {expected} for {}",
                    hashes.len(),
                    file.path.display()
                )));
            }
            if pieces_root_from_layer(hashes) != file.pieces_root {
                return Err(Error::Torrent(format!(
                    "piece layers root mismatch for {}",
                    file.path.display()
                )));
            }
            file.piece_hashes = hashes.clone();
        } else {
            if layers.contains_key(&file.pieces_root) {
                return Err(Error::Torrent(format!(
                    "piece layers must not be present for small file {}",
                    file.path.display()
                )));
            }
            // Single piece: root equals the sole piece-layer hash.
            file.piece_hashes = vec![file.pieces_root];
        }
    }
    Ok(v2_from_files(files))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::piece::{piece_hash_from_data, MERKLE_BLOCK_SIZE};
    use crate::piece::merkle::build_piece_layers;

    #[test]
    fn detects_hybrid_meta_version() {
        let info = BencodeValue::Dict(BTreeMap::from([(
            b"meta version".to_vec(),
            BencodeValue::Int(2),
        )]));
        assert_eq!(detect_meta_version(&info, true), MetaVersion::Hybrid);
        assert_eq!(detect_meta_version(&info, false), MetaVersion::V2);
    }

    #[test]
    fn parses_v2_piece_layers_two_pieces() {
        let data_a = vec![0u8; MERKLE_BLOCK_SIZE];
        let data_b = vec![1u8; MERKLE_BLOCK_SIZE];
        let a = piece_hash_from_data(&data_a, MERKLE_BLOCK_SIZE);
        let b = piece_hash_from_data(&data_b, MERKLE_BLOCK_SIZE);
        let v2 = v2_from_piece_hashes(vec![a, b]);
        let root = BencodeValue::Dict(BTreeMap::from([(
            b"piece layers".to_vec(),
            piece_layers_to_bencode(&v2),
        )]));
        let meta = parse_piece_layers_dict(&root, 2).expect("parse");
        let meta = meta.expect("some");
        assert_eq!(meta.piece_hashes.len(), 2);
        assert_eq!(meta.piece_hashes[0], a);
        assert_eq!(meta.piece_hashes[1], b);
        assert_eq!(meta.pieces_root, v2.pieces_root);
        assert_eq!(build_piece_layers(&meta.piece_hashes).len(), 64);
    }

    #[test]
    fn file_tree_roundtrip_single_file() {
        let data = vec![7u8; MERKLE_BLOCK_SIZE * 2];
        let file = v2_file_from_bytes(PathBuf::from("hello.bin"), &data, MERKLE_BLOCK_SIZE as u32);
        let tree = file_tree_to_bencode(std::slice::from_ref(&file), "hello.bin").expect("tree");
        let info = BencodeValue::Dict(BTreeMap::from([(b"file tree".to_vec(), tree)]));
        let parsed = parse_file_tree(&info, "hello.bin")
            .expect("parse")
            .expect("some");
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0].length, data.len() as u64);
        assert_eq!(parsed[0].pieces_root, file.pieces_root);
    }

    #[test]
    fn pad_path_detection() {
        assert!(is_pad_path(Path::new("demo/.pad/1024")));
        assert!(!is_pad_path(Path::new("demo/file.txt")));
    }
}