fx-torrent 0.10.3

FX Torrent is a feature rich Bittorrent protocol implementation written in rust supporting Linux, MacOS and Windows.
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*!
# FX-Torrent

FX-Torrent is the most complete BitTorrent implementation fully written in Rust, which supports both Linux, MacOS, and Windows.
It supports most of the Bittorrent protocol specifications, such as multi-file torrents, validating existing files, resuming torrent files,
and is based on the `libtorrent` library for functionality and naming convention.

## Getting Started

The entry point for the `fx_torrent` crate is the [`FxSession`].
A session manages the lifecycle of multiple torrents.

### Basic Usage

```rust
# use std::io;
use fx_torrent::prelude::*;
// The fx-torrent crate makes use of async tokio runtimes
// this requires that new sessions and torrents need to be created within a tokio runtime
#[tokio::main]
async fn main() -> Result<(), io::Error> {
    let session = FxSession::builder()
        .config(
            SessionConfig::builder()
                .base_path("/downloads")
                .client_name("MyClient")
                .build(),
        )
        .default_extensions()
        .dht(DhtTracker::builder()
            .default_routing_nodes()
            .build()
            .await?)
        .build()?;
    // 1. Add a torrent via Magnet URI
    let magnet_torrent = session
        .add_torrent_from_uri("magnet:?xt=urn:btih:...", TorrentFlags::default())
        .await;
    // 2. Add a torrent from a local .torrent file
    let file_torrent = session
        .add_torrent_from_uri("/path/to/file.torrent", TorrentFlags::default())
        .await;
    // 3. Add a torrent from raw metadata bytes
    let data: &[u8] = &[0; 1024]; // Replace with actual bencoded bytes
    let metadata = TorrentMetadata::try_from(data)?;
    let metadata_torrent = session
        .add_torrent_from_metadata(metadata, TorrentFlags::Paused)
        .await;
    Ok(())
}
```

For more advanced examples, see the [examples](https://github.com/yoep/fx-torrent/tree/master/examples) directory.

### Working with Magnets and Metadata

#### Magnets

You can parse a magnet string or construct one manually using the builder pattern.

```rust,no_run
# use fx_torrent::Magnet;
# use std::str::FromStr;

# fn example() {
    // Parsing from a string
    match Magnet::from_str("magnet:?xt=urn:btih:2C6B6858D61DA9543D4231A71DB4B1C9264B0685&...") {
        Ok(magnet) => println!("{:?}", magnet),
        Err(e) => println!("{:?}", e),
    }

    // Using the builder
    match Magnet::builder()
        .exact_topic("xt=urn:btih:2C6B6858D61DA9543D4231A71DB4B1C9264B0685")
        .build() {
        Ok(magnet) => println!("{:?}", magnet),
        Err(e) => println!("{:?}", e),
    }
# }
```

#### Metadata

Metadata can be decoded from bencoded bytes (using `TorrentMetadata::try_from`) or constructed manually.

```rust
# use fx_torrent::TorrentMetadata;
# fn example() {
    // Parsing from bencoded bytes
    match TorrentMetadata::try_from(&[0; 1024]) {
        Ok(metadata) => println!("{:?}", metadata),
        Err(e) => println!("{:?}", e),
    }

    // Using the builder
    let metadata = TorrentMetadata::builder()
        .name("MyTorrent")
        .build();
    println!("{:?}", metadata);
# }
```

### Streaming

The fx_torrent engine supports sequential file streaming through [FileStream].
This allows you to stream file data (such as media files) over the network before
the entire torrent finishes downloading.

Because [FileStream] implements the standard [futures::Stream] trait,
it can be easily integrated into asynchronous loops or piped directly into web frameworks like axum.

_Basic Usage_
```rust,no_run
# use fx_torrent::Torrent;
# use fx_torrent::TorrentMetadata;
# use futures::StreamExt;

# async fn example(metadata: TorrentMetadata) {
    let torrent = Torrent::request()
        .metadata(metadata)
        .build()
        .unwrap();
    let file = torrent.file_by_name("example.mp4").await.unwrap();

    let mut stream = torrent.stream(&file).await.unwrap();
    while let Some(bytes) = stream.next().await {
        // use the bytes here
    }
# }
```

_Axum Integration Example_
```rust
# use axum::body::Body;
# use axum::response::Response;
# use futures::StreamExt;
# use fx_torrent::Torrent;

fn axum_example(filename: &str) -> Response<Body> {
    let torrent = Torrent::request()
         .build()
         .unwrap();
     let file = torrent.file_by_name(filename).await.unwrap();

    let stream = torrent.stream(&file).await.unwrap();
    Response::builder()
        .body(Body::from_stream(Box::into_pin(stream)))
}
```

## Extensions

The `fx_torrent` crate is designed to be highly extensible.
You can modify the core behavior of components by implementing and registering "extension" traits.
These allow for custom logic in peer communication and data persistence.

### Peer Extension

Peer extensions allow you to extend the BitTorrent protocol with custom messaging and handshake
capabilities, following the **BEP 10** specification.

To modify peer protocol behavior, implement the [peer::extension::Extension] trait.
Once implemented, these extensions can be attached to individual torrents or globally across a session.

_example peer extension_
```rust
# use fx_torrent::prelude::*;
# use fx_torrent::peer::BitTorrentPeerContext;
# use fx_torrent::peer::extension::Extension;
# use fx_torrent::peer::extension::Result;

#[derive(Debug)]
pub struct MyPeerExtension;
impl Extension for MyPeerExtension {
    fn name(&self) -> &str {
        "my-extension"
    }

    // Additional trait methods
}

# fn example() {
    // 1. Peer extension directly in a torrent
    let torrent = Torrent::request()
        .extension(|| MyPeerExtension.into())
        .build()
        .unwrap();

    // 2. Peer extension in a session
    let session = FxSession::builder()
        .extension(|| MyPeerExtension.into())
        .build()
        .unwrap();
# }
```

### Storage Extension

Storage extensions allow you to customize how data is read from and written to disk (or memory).
This is useful for implementing custom caching layers, encrypted storage, or cloud-backed persistence.

To create your own storage backend, implement the [storage::Extension] trait.

_example storage extension_
```rust,no_run
# use fx_torrent::prelude::*;
# use fx_torrent::storage::Extension;
# use fx_torrent::storage::StorageParams;

#[derive(Debug)]
pub struct MyStorageExtension;
impl MyStorageExtension {
    pub fn new(_params: StorageParams) -> Self {
        Self
    }
}
impl Extension for MyStorageExtension {
    async fn read(&self, buffer: &mut [u8], piece: &PieceIndex, offset: usize) -> Result<usize> {
        // Read piece data from storage
        Ok(0)
    }

    // Additional trait methods
}

# fn example() {
    // 1. Storage extension directly in a torrent
    let torrent = Torrent::request()
        .storage(|params| MyStorageExtension::new(params).into())
        .build()
        .unwrap();

    // 2. Storage extension in a session
    let session = FxSession::builder()
        .storage(|params| MyStorageExtension::new(params).into())
        .build().unwrap();
# }
```

### Operation Extension

Operation extensions are **tick-based** tasks invoked by the [TorrentContext].
These operations are executed sequentially in an order-dependent chain,
meaning the sequence in which you register them determines their execution priority.

_example operation extension_
```rust
# use fx_torrent::prelude::*;
# use fx_torrent::TorrentContext;
# use fx_torrent::operation::Extension;
# use fx_torrent::operation::TorrentOperationResult;
# use fx_torrent::peer::PeerDiscovery;
# use async_trait::async_trait;

#[derive(Debug)]
pub struct MyOperation;
#[async_trait]
impl Extension for MyOperation {
    /// The `tick` method is called periodically by the torrent engine.
    async fn tick(&self, context: &mut TorrentContext, peer_discoveries: &[PeerDiscovery]) -> TorrentOperationResult {
        // Logic for your custom operation goes here
        TorrentOperationResult::Continue
    }

    // Additional trait methods
}

# fn example() {
    // 1. Operation extension directly in a torrent
    let torrent = Torrent::request()
        .operation(MyOperation.into())
        .build()
        .unwrap();

    // 2. Operation extension in a session
    let session = FxSession::builder()
        .operation(|| MyOperation.into())
        .build()
        .unwrap();
# }
```

### Piece Picker Extension

Piece picker extensions allow you to customize or completely override the core piece selection algorithm.
Piece selection tasks are executed either periodically via a background ticker or instantly on-demand when requested by a peer.

To implement a custom piece picker algorithm, implement the [piece_picker::Extension] trait.

_example piece picker extension_
```rust
# use async_trait;
# use fx_torrent::DataPool;
# use fx_torrent::FxSession;
# use fx_torrent::InnerTorrent;
# use fx_torrent::Torrent;
# use fx_torrent::peer::Peer;
# use fx_torrent::piece_picker::Extension;
# use fx_torrent::piece_picker::PickerOptions;
# use fx_torrent::storage::Storage;
# use std::sync::Arc;

#[derive(Debug)]
pub struct MyPiecePicker;
#[async_trait]
impl Extension for MyPiecePicker {
    async fn pick_pieces(&mut self, peer: &Peer) {
        // Your custom piece picking algorithm goes here
    }

    async fn tick<'a>(&'a mut self, peers: Vec<&'a Peer>) {
        // Tick-based piece picking logic goes here
    }

    // Additional trait methods
}

# fn example () {
    // 1. Piece picker extension directly in a torrent
    let torrent = Torrent::request()
        .piece_picker(|
            torrent: InnerTorrent,
            data_pool: DataPool,
            storage: Storage,
            options: PickerOptions| MyPiecePicker.into())
        .build()
        .unwrap();

    // 2. Piece picker extension in a session
    let session = FxSession::builder()
        .piece_picker(|
            torrent: InnerTorrent,
            data_pool: DataPool,
            storage: Storage,
            options: PickerOptions| MyPiecePicker.into())
        .build()
        .unwrap();
# }
```

#### Piece Picker Strategy Extension

The [piece_picker::FxPiecePicker] architecture allows sub-strategies to be sequentially stacked or overridden.
These strategies operate in an order-dependent chain,
meaning their registration order explicitly dictates execution priority during the piece picking lifecycle.

```rust,no_run
# use fx_torrent::DataPool;
# use fx_torrent::TorrentHandle;
# use fx_torrent::peer::Peer;
# use fx_torrent::piece_picker::FxPiecePicker;
# use fx_torrent::piece_picker::PickerOptions;
# use fx_torrent::piece_picker::PiecePicker;
# use fx_torrent::piece_picker::PiecePickerBlock;
# use fx_torrent::piece_picker::strategy::{Extension, PriorityStrategy};
# use fx_torrent::prelude::*;
# use fx_torrent::storage::Storage;
# use std::sync::Arc;

#[derive(Debug)]
pub struct MyStrategy;
impl Extension for MyStrategy {
    async fn pick_pieces<'a>(
        &self,
        peer: &Peer,
        blocks: &'a Vec<PiecePickerBlock>,
        target_queue_len: usize,
        suggested_pieces: &[PieceIndex],
        is_end_game: bool,
        options: PickerOptions,
    ) -> Vec<&'a PiecePickerBlock> {
        // Your custom piece picking logic goes here
        vec![]
    }
}

# fn example() {
    let torrent = Torrent::request()
        .piece_picker(|
            handle: TorrentHandle,
            data_pool: DataPool,
            storage: Storage,
            options: PickerOptions| {
            FxPiecePicker::new(
                handle,
                data_pool,
                storage,
                vec![
                    MyStrategy.into(),
                    PriorityStrategy::new().into(),
                ],
                32 * 1024
            )
        })
        .build()
        .unwrap();
# }
```

*/

pub use compact::*;
pub use config::*;
pub use error::*;
pub use file::*;
pub use info_hash::*;
#[cfg(feature = "lsd")]
pub use lsd::*;
pub use magnet::*;
pub use piece::*;
pub use session::*;
pub use session_cache::*;
pub use stream::*;
pub use torrent::*;
pub use torrent_flags::*;
pub use torrent_health::*;
pub use torrent_metadata::*;
pub use torrent_metrics::*;
pub use torrent_tracker::*;
pub use types::*;

use std::ops::Range;

#[cfg(test)]
#[macro_use]
mod test_macros;
#[macro_use]
mod macros;

pub mod bencode;
mod bloom_filter;
mod channel;
mod compact;
mod config;
#[cfg(feature = "dht")]
pub mod dht;
mod error;
mod file;
mod info_hash;
#[cfg(feature = "lsd")]
mod lsd;
mod magnet;
mod merkle;
pub mod metrics;
pub mod operation;
pub mod peer;
mod peer_pool;
mod piece;
pub mod piece_picker;
mod serde;
mod session;
mod session_cache;
pub mod storage;
mod stream;
mod torrent;
mod torrent_data;
mod torrent_flags;
mod torrent_health;
mod torrent_metadata;
mod torrent_metrics;
mod torrent_tracker;
pub mod tracker;
mod types;

/// A prelude for conveniently writing applications using this library.
pub mod prelude {
    #[cfg(feature = "dht")]
    pub use crate::dht::prelude::*;
    pub use crate::FxSession;
    pub use crate::InfoHash;
    #[cfg(feature = "lsd")]
    pub use crate::LocalServiceDiscovery;
    pub use crate::Metrics;
    pub use crate::PieceIndex;
    pub use crate::PiecePriority;
    pub use crate::SessionConfig;
    pub use crate::SessionEvent;
    pub use crate::Torrent;
    pub use crate::TorrentEvent;
    pub use crate::TorrentFlags;
    pub use crate::TorrentMetadata;
    pub use crate::TorrentState;

    pub use crate::format_bytes;
}

use crate::peer::ProtocolExtensionFlags;

const DEFAULT_TORRENT_PROTOCOL_EXTENSIONS: fn() -> ProtocolExtensionFlags = || {
    ProtocolExtensionFlags::LTEP | ProtocolExtensionFlags::Fast | ProtocolExtensionFlags::SupportV2
};

/// Formats the given number of bytes into a human-readable format with appropriate units.
///
/// This function converts a byte size into a more readable format using common storage units (B, KB, MB, GB, TB).
/// The result is rounded to two decimal places for clarity. It ensures that the byte count is represented with
/// the most appropriate unit based on the size of the input. The units scale based on powers of 1024.
///
/// # Arguments
/// - `bytes`: The size in bytes to be formatted.
///
/// # Returns
///
/// It returns the formatted byte size with the corresponding unit.
///
/// # Example
///
/// ```rust
/// # use fx_torrent::format_bytes;
///
/// let formatted = format_bytes(1048576);
/// println!("{}", formatted); // "1.00 MB"
/// ```
///
/// # Notes
/// The function uses the binary system for scaling (i.e., 1024 bytes = 1 KB).
pub fn format_bytes(bytes: usize) -> String {
    let units = ["B", "KB", "MB", "GB", "TB"];
    let mut value = bytes as f64;
    let mut unit = 0;

    while value >= 1024.0 && unit < units.len() - 1 {
        value /= 1024.0;
        unit += 1;
    }

    format!("{:.2} {}", value, units[unit])
}

/// Calculates the data transfer rate in bytes per second.
///
/// This function computes the data transfer rate based on the number of bytes transferred and the
/// elapsed time in microseconds. It returns the rate as bytes per second (B/s). If the elapsed time is less
/// than one second (1,000,000 microseconds), it simply returns the number of bytes as the rate.
///
/// # Arguments
/// - `bytes`: The number of bytes transferred.
/// - `elapsed_micro_secs`: The time elapsed in microseconds.
///
/// # Returns
/// A `u64` representing the data transfer rate in bytes per second (B/s).
///
/// # Example
///
/// ```rust,no_run
/// use fx_torrent::calculate_byte_rate;
///
/// let rate = calculate_byte_rate(1_000_000, 1_500_000);
/// println!("{}", rate); // "666666" (bytes per second);
///
/// let rate = calculate_byte_rate(1_000_000, 2_000_000);
/// println!("{}", rate); // "500000" (bytes per second);
/// ```
///
/// # Notes
/// The function assumes that the elapsed time is given in microseconds. If the elapsed time is very short,
/// it will default to the total byte count as the rate.
pub fn calculate_byte_rate(bytes: usize, elapsed_micro_secs: u128) -> u64 {
    if elapsed_micro_secs <= 1_000_000 {
        return bytes as u64;
    }

    ((bytes as u128 * 1_000_000) / elapsed_micro_secs) as u64
}

/// Get the overlapping range of two ranges.
/// It returns the overlapping range if there is one, else [None].
#[inline]
pub(crate) fn overlapping_range<T>(r1: Range<T>, r2: &Range<T>) -> Option<Range<T>>
where
    T: Ord + Copy,
{
    let start = r1.start.max(r2.start);
    let end = r1.end.min(r2.end);

    if start < end {
        Some(start..end)
    } else {
        None
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use log::trace;
    use std::path::PathBuf;
    use std::time::Duration;
    use std::{env, fs};

    /// Retrieve the path to the testing resource directory.
    ///
    /// It returns the [PathBuf] to the testing resources directory.
    pub fn test_resource_directory() -> PathBuf {
        let root_dir = &env::var("CARGO_MANIFEST_DIR").expect("$CARGO_MANIFEST_DIR");
        let mut source = PathBuf::from(root_dir);
        source.push("test");

        source
    }

    /// Retrieve the filepath of a testing resource file.
    /// These are files located within the "test" directory of the crate.
    ///
    /// It returns the created [PathBuf] for the given filename.
    pub fn test_resource_filepath(filename: &str) -> PathBuf {
        let mut source = test_resource_directory();
        source.push(filename);

        source
    }

    pub fn read_test_file_to_bytes(filename: &str) -> Vec<u8> {
        let source = test_resource_filepath(filename);

        fs::read(&source).unwrap()
    }

    pub fn copy_test_file(temp_dir: &str, filename: &str, output_filename: Option<&str>) -> String {
        let root_dir = &env::var("CARGO_MANIFEST_DIR").expect("$CARGO_MANIFEST_DIR");
        let source = PathBuf::from(root_dir).join("test").join(filename);
        let destination = PathBuf::from(temp_dir).join(output_filename.unwrap_or(filename));

        // make sure the parent dir exists
        fs::create_dir_all(destination.parent().unwrap()).unwrap();

        trace!("Copying test file {} to {:?}", filename, destination);
        fs::copy(&source, &destination).unwrap();

        destination.to_str().unwrap().to_string()
    }

    mod overlapping_range {
        use super::*;

        #[test]
        fn test_overlap_range() {
            let r1 = 0..10;
            let r2 = 5..15;
            let result = overlapping_range(r1, &r2);
            assert_eq!(Some(5..10), result);

            let r1 = 16..32;
            let r2 = 30..64;
            let result = overlapping_range(r1, &r2);
            assert_eq!(Some(30..32), result);

            let r1 = 128..256;
            let r2 = 512..1024;
            let result = overlapping_range(r1, &r2);
            assert_eq!(None, result);
        }
    }

    pub mod helpers {
        use super::*;
        use fx_callback::Callback;
        use tokio::{select, time};

        pub async fn wait_for_torrent_pieces(torrent: &Torrent) {
            let mut receiver = torrent.subscribe();
            if torrent.pieces().await.filter(|e| !e.is_empty()).is_some() {
                return;
            }

            select! {
                _ = time::sleep(Duration::from_secs(2)) => assert!(false, "expected the pieces of {} to have been created", torrent),
                _ = async {
                    while let Ok(event) = receiver.recv().await {
                        match &*event {
                            TorrentEvent::PiecesChanged(_) => break,
                            _ => {}
                        }
                    }
                } => {}
            }
        }
    }
}