irontide-core 0.165.0

Core types for BitTorrent: hashes, metainfo, magnets, piece arithmetic
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
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

fn default_neg_one() -> i64 {
    -1
}

/// A partial piece that was in progress when the torrent was paused/stopped.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnfinishedPiece {
    /// Piece index.
    pub piece: i64,
    /// Bitmask of which blocks within the piece have been downloaded.
    #[serde(with = "serde_bytes")]
    pub bitmask: Vec<u8>,
}

/// libtorrent-compatible fast-resume data in bencode format.
///
/// This struct matches libtorrent's resume file format so that resume data
/// can be read/written by both Torrent and libtorrent-based clients.
/// Every field uses `#[serde(rename = "...")]` to match libtorrent's exact
/// bencode dictionary keys.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FastResumeData {
    /// Always "libtorrent resume file".
    #[serde(rename = "file-format")]
    pub file_format: String,

    /// Always 1.
    #[serde(rename = "file-version")]
    pub file_version: i64,

    /// 20-byte SHA1 info hash.
    #[serde(rename = "info-hash")]
    #[serde(with = "serde_bytes")]
    pub info_hash: Vec<u8>,

    /// Torrent name.
    #[serde(rename = "name")]
    pub name: String,

    /// Path where files are saved.
    #[serde(rename = "save_path")]
    pub save_path: String,

    /// Bitfield indicating which pieces are complete.
    #[serde(rename = "pieces")]
    #[serde(with = "serde_bytes")]
    pub pieces: Vec<u8>,

    /// Partially downloaded pieces.
    #[serde(rename = "unfinished")]
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub unfinished: Vec<UnfinishedPiece>,

    /// Total bytes uploaded.
    #[serde(rename = "total_uploaded")]
    pub total_uploaded: i64,

    /// Total bytes downloaded.
    #[serde(rename = "total_downloaded")]
    pub total_downloaded: i64,

    /// Total time active in seconds.
    #[serde(rename = "active_time")]
    pub active_time: i64,

    /// Total time spent seeding in seconds.
    #[serde(rename = "seeding_time")]
    pub seeding_time: i64,

    /// Total time in finished state in seconds.
    #[serde(rename = "finished_time")]
    pub finished_time: i64,

    /// POSIX timestamp when the torrent was added.
    #[serde(rename = "added_time")]
    pub added_time: i64,

    /// POSIX timestamp when the torrent completed.
    #[serde(rename = "completed_time")]
    #[serde(default)]
    pub completed_time: i64,

    /// POSIX timestamp of last download activity.
    #[serde(rename = "last_download")]
    #[serde(default)]
    pub last_download: i64,

    /// POSIX timestamp of last upload activity.
    #[serde(rename = "last_upload")]
    #[serde(default)]
    pub last_upload: i64,

    /// Whether the torrent is paused (0 or 1).
    #[serde(rename = "paused")]
    #[serde(default)]
    pub paused: i64,

    /// Whether the torrent is auto-managed.
    #[serde(rename = "auto_managed")]
    #[serde(default)]
    pub auto_managed: i64,

    /// Queue position (-1 = not queued).
    #[serde(rename = "queue_position")]
    #[serde(default = "default_neg_one")]
    pub queue_position: i64,

    /// Whether sequential download is enabled.
    #[serde(rename = "sequential_download")]
    #[serde(default)]
    pub sequential_download: i64,

    /// Whether seed mode is enabled.
    #[serde(rename = "seed_mode")]
    #[serde(default)]
    pub seed_mode: i64,

    /// Tracker tiers (list of lists of tracker URLs).
    #[serde(rename = "trackers")]
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub trackers: Vec<Vec<String>>,

    /// Compact IPv4 peers (6 bytes each: 4 IP + 2 port).
    #[serde(rename = "peers")]
    #[serde(with = "serde_bytes")]
    #[serde(default)]
    pub peers: Vec<u8>,

    /// Compact IPv6 peers (18 bytes each: 16 IP + 2 port).
    #[serde(rename = "peers6")]
    #[serde(with = "serde_bytes")]
    #[serde(default)]
    pub peers6: Vec<u8>,

    /// Per-file priority values.
    #[serde(rename = "file_priority")]
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub file_priority: Vec<i64>,

    /// Per-piece priority values.
    #[serde(rename = "piece_priority")]
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub piece_priority: Vec<i64>,

    /// Upload rate limit in bytes/sec (-1 = unlimited).
    #[serde(rename = "upload_rate_limit")]
    #[serde(default)]
    pub upload_rate_limit: i64,

    /// Download rate limit in bytes/sec (-1 = unlimited).
    #[serde(rename = "download_rate_limit")]
    #[serde(default)]
    pub download_rate_limit: i64,

    /// Max connections for this torrent (-1 = unlimited).
    #[serde(rename = "max_connections")]
    #[serde(default)]
    pub max_connections: i64,

    /// Max upload slots for this torrent (-1 = unlimited).
    #[serde(rename = "max_uploads")]
    #[serde(default)]
    pub max_uploads: i64,

    /// Raw bencoded info dictionary (for magnet links that have resolved).
    #[serde(rename = "info")]
    #[serde(with = "serde_bytes")]
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub info: Option<Vec<u8>>,

    /// BEP 16: whether super seeding was enabled.
    #[serde(rename = "super_seeding")]
    #[serde(default)]
    pub super_seeding: i64,

    /// BEP 19 web seed URLs (GetRight-style).
    #[serde(rename = "url_seeds")]
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub url_seeds: Vec<String>,

    /// BEP 17 HTTP seed URLs (Hoffman-style).
    #[serde(rename = "http_seeds")]
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub http_seeds: Vec<String>,

    /// SHA-256 v2 info hash (32 bytes, BEP 52).
    #[serde(rename = "info-hash2")]
    #[serde(with = "serde_bytes")]
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub info_hash2: Option<Vec<u8>>,

    /// Cached piece-layer Merkle hashes per file.
    /// Key: hex-encoded file root hash. Value: concatenated 32-byte piece hashes.
    /// Allows skipping piece-layer hash requests on resume.
    #[serde(rename = "trees")]
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    pub trees: HashMap<String, Vec<u8>>,
}

impl FastResumeData {
    /// Create a new `FastResumeData` with format markers pre-filled and all
    /// other fields zeroed/empty. Rate limits default to -1 (unlimited).
    pub fn new(info_hash: Vec<u8>, name: String, save_path: String) -> Self {
        Self {
            file_format: "libtorrent resume file".into(),
            file_version: 1,
            info_hash,
            name,
            save_path,
            pieces: Vec::new(),
            unfinished: Vec::new(),
            total_uploaded: 0,
            total_downloaded: 0,
            active_time: 0,
            seeding_time: 0,
            finished_time: 0,
            added_time: 0,
            completed_time: 0,
            last_download: 0,
            last_upload: 0,
            paused: 0,
            auto_managed: 0,
            queue_position: -1,
            sequential_download: 0,
            seed_mode: 0,
            trackers: Vec::new(),
            peers: Vec::new(),
            peers6: Vec::new(),
            file_priority: Vec::new(),
            piece_priority: Vec::new(),
            upload_rate_limit: -1,
            download_rate_limit: -1,
            max_connections: -1,
            max_uploads: -1,
            super_seeding: 0,
            info: None,
            url_seeds: Vec::new(),
            http_seeds: Vec::new(),
            info_hash2: None,
            trees: HashMap::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn fast_resume_data_bencode_round_trip() {
        let mut resume =
            FastResumeData::new(vec![0xAA; 20], "test-torrent".into(), "/downloads".into());
        resume.total_uploaded = 1024 * 1024;
        resume.total_downloaded = 2048 * 1024;
        resume.active_time = 3600;
        resume.added_time = 1700000000;
        resume.trackers = vec![
            vec!["http://tracker1.example.com/announce".into()],
            vec![
                "http://tracker2.example.com/announce".into(),
                "http://tracker3.example.com/announce".into(),
            ],
        ];
        resume.pieces = vec![0xFF; 10];

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(resume, decoded);
    }

    #[test]
    fn unfinished_piece_bencode_round_trip() {
        let piece = UnfinishedPiece {
            piece: 42,
            bitmask: vec![0b1010_1010, 0b0101_0101],
        };

        let encoded = irontide_bencode::to_bytes(&piece).unwrap();
        let decoded: UnfinishedPiece = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(piece, decoded);
    }

    #[test]
    fn resume_data_with_unfinished_pieces() {
        let mut resume = FastResumeData::new(
            vec![0xBB; 20],
            "partial-torrent".into(),
            "/downloads".into(),
        );
        resume.unfinished = vec![
            UnfinishedPiece {
                piece: 5,
                bitmask: vec![0xFF, 0x0F],
            },
            UnfinishedPiece {
                piece: 12,
                bitmask: vec![0xF0],
            },
        ];

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(resume, decoded);
    }

    #[test]
    fn default_fields_serialize_correctly() {
        let resume = FastResumeData::new(vec![0x00; 20], "minimal".into(), "/tmp".into());

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(resume, decoded);

        // Verify default values survived the round-trip.
        assert_eq!(decoded.total_uploaded, 0);
        assert_eq!(decoded.total_downloaded, 0);
        assert_eq!(decoded.paused, 0);
        assert_eq!(decoded.upload_rate_limit, -1);
        assert_eq!(decoded.download_rate_limit, -1);
        assert_eq!(decoded.max_connections, -1);
        assert_eq!(decoded.max_uploads, -1);
        assert!(decoded.trackers.is_empty());
        assert!(decoded.unfinished.is_empty());
        assert!(decoded.file_priority.is_empty());
        assert!(decoded.info.is_none());
    }

    #[test]
    fn info_dict_embedding_round_trip() {
        let mut resume =
            FastResumeData::new(vec![0xCC; 20], "with-info".into(), "/downloads".into());
        // Simulate a raw bencoded info dict.
        resume.info = Some(
            b"d4:name10:test-torte12:piece lengthi262144e6:pieces20:AAAAAAAAAAAAAAAAAAAAe".to_vec(),
        );

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(resume, decoded);
        assert!(decoded.info.is_some());
        assert_eq!(decoded.info.unwrap().len(), resume.info.unwrap().len());
    }

    #[test]
    fn resume_data_queue_position_default() {
        let rd = FastResumeData::new(vec![0; 20], "test".into(), "/tmp".into());
        assert_eq!(rd.queue_position, -1);
    }

    #[test]
    fn format_markers_correct() {
        let resume = FastResumeData::new(vec![0x00; 20], "test".into(), "/tmp".into());
        assert_eq!(resume.file_format, "libtorrent resume file");
        assert_eq!(resume.file_version, 1);
    }

    #[test]
    fn resume_data_url_seeds_round_trip() {
        let mut resume =
            FastResumeData::new(vec![0xDD; 20], "web-seed-test".into(), "/downloads".into());
        resume.url_seeds = vec![
            "http://example.com/files".into(),
            "http://mirror.example.com/".into(),
        ];

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(decoded.url_seeds, resume.url_seeds);
    }

    #[test]
    fn resume_data_http_seeds_round_trip() {
        let mut resume =
            FastResumeData::new(vec![0xEE; 20], "http-seed-test".into(), "/downloads".into());
        resume.http_seeds = vec!["http://seed.example.com/seed".into()];

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(decoded.http_seeds, resume.http_seeds);
    }

    #[test]
    fn resume_data_super_seeding_round_trip() {
        let mut resume = FastResumeData::new(
            vec![0xFF; 20],
            "super-seed-test".into(),
            "/downloads".into(),
        );
        resume.super_seeding = 1;

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(decoded.super_seeding, 1);

        // Default should be 0
        let default_resume = FastResumeData::new(vec![0; 20], "test".into(), "/tmp".into());
        assert_eq!(default_resume.super_seeding, 0);
    }

    #[test]
    fn resume_data_v2_fields_round_trip() {
        let mut resume =
            FastResumeData::new(vec![0xAA; 20], "v2-torrent".into(), "/downloads".into());
        resume.info_hash2 = Some(vec![0xBB; 32]);
        resume.trees.insert(
            hex::encode([0xCC; 32]),
            vec![0xDD; 64], // 2 piece hashes
        );

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert_eq!(decoded.info_hash2, Some(vec![0xBB; 32]));
        assert_eq!(decoded.trees.len(), 1);
    }

    #[test]
    fn resume_data_v1_backward_compat() {
        let resume = FastResumeData::new(vec![0x00; 20], "v1-torrent".into(), "/tmp".into());
        assert!(resume.info_hash2.is_none());
        assert!(resume.trees.is_empty());

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert!(decoded.info_hash2.is_none());
        assert!(decoded.trees.is_empty());
    }

    #[test]
    fn resume_data_v2_empty_trees_not_serialized() {
        let resume = FastResumeData::new(vec![0x00; 20], "minimal".into(), "/tmp".into());
        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        // "5:trees" (bencode key) should not appear in output when empty
        let encoded_str = String::from_utf8_lossy(&encoded);
        assert!(!encoded_str.contains("5:trees"));
    }

    #[test]
    fn resume_data_empty_seeds_not_serialized() {
        let resume = FastResumeData::new(vec![0x00; 20], "no-seeds".into(), "/tmp".into());
        assert!(resume.url_seeds.is_empty());
        assert!(resume.http_seeds.is_empty());

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();
        assert!(decoded.url_seeds.is_empty());
        assert!(decoded.http_seeds.is_empty());
    }

    #[test]
    fn resume_data_hybrid_both_hashes() {
        // Hybrid torrents store both v1 (SHA-1, 20 bytes) and v2 (SHA-256, 32 bytes)
        let mut resume =
            FastResumeData::new(vec![0x11; 20], "hybrid-torrent".into(), "/downloads".into());
        resume.info_hash2 = Some(vec![0x22; 32]);
        resume.trees.insert(
            hex::encode([0x33; 32]),
            vec![0x44; 96], // 3 piece hashes
        );

        let encoded = irontide_bencode::to_bytes(&resume).unwrap();
        let decoded: FastResumeData = irontide_bencode::from_bytes(&encoded).unwrap();

        // Both hashes present and distinct
        assert_eq!(decoded.info_hash, vec![0x11; 20]);
        assert_eq!(decoded.info_hash2.as_deref(), Some([0x22; 32].as_ref()));

        // Trees preserved
        assert_eq!(decoded.trees.len(), 1);
        let layer = decoded.trees.values().next().unwrap();
        assert_eq!(layer.len(), 96);
    }
}