aria2-core 0.3.9

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
mod choke_api;
mod constructor;
mod integration_api;
mod peer_ban_api;
mod seed_api;
mod web_seed_api;

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::engine::choking_algorithm::ChokingAlgorithm;
use crate::engine::http_tracker_client::TrackerState;
use crate::engine::lpd_manager::LpdManager;
use crate::engine::multi_file_layout::MultiFileLayout;
use crate::rate_limiter::RateLimiter;
use crate::request::request_group::{AtomicProgress, RequestGroup};
use crate::util::rwlock_ext::RwLockRecover;

pub use crate::engine::bt_message_handler::{
    BLOCK_REQUEST_TIMEOUT_SECS, BLOCK_SIZE, MAX_BLOCK_READ_MESSAGES, MAX_RETRIES,
};
pub use crate::engine::bt_peer_interaction::{
    MAX_UNCHOKE_WAIT_ATTEMPTS, PEER_CONNECTION_DELAY_MS, PEER_MESSAGE_TIMEOUT_SECS,
};
pub use crate::engine::bt_piece_selector::ENDGAME_THRESHOLD;

// Re-export sub-module public items
pub use constructor::prepare_group_metadata;
pub(crate) use constructor::{
    apply_file_mappings, apply_select_file_filter, build_download_context_from_meta,
};
pub use seed_api::SeedStats;

pub(crate) const MAX_PUBLIC_TRACKERS_TO_TRY: usize = 10;

#[derive(Debug)]
pub(crate) struct BtRuntimeState {
    connections: std::sync::atomic::AtomicUsize,
    max_peers: std::sync::atomic::AtomicUsize,
}

impl BtRuntimeState {
    pub(crate) fn new(max_peers: usize) -> Self {
        Self {
            connections: std::sync::atomic::AtomicUsize::new(0),
            max_peers: std::sync::atomic::AtomicUsize::new(max_peers),
        }
    }

    pub(crate) fn set_connections(&self, connections: usize) {
        self.connections
            .store(connections, std::sync::atomic::Ordering::Release);
    }

    pub(crate) fn set_max_peers(&self, max_peers: usize) {
        self.max_peers
            .store(max_peers, std::sync::atomic::Ordering::Release);
    }

    pub(crate) fn connections(&self) -> usize {
        self.connections.load(std::sync::atomic::Ordering::Acquire)
    }

    pub(crate) fn max_peers(&self) -> usize {
        self.max_peers.load(std::sync::atomic::Ordering::Acquire)
    }

    pub(crate) fn min_peers(&self) -> usize {
        let max_peers = self.max_peers.load(std::sync::atomic::Ordering::Acquire);
        if max_peers == 0 {
            0
        } else {
            (max_peers * 4 / 5).max(1)
        }
    }

    pub(crate) fn less_than_min_peers(&self) -> bool {
        self.connections() < self.min_peers()
    }

    pub(crate) fn less_than_max_peers(&self) -> bool {
        self.max_peers() == 0 || self.connections() < self.max_peers()
    }
}

impl Drop for BtDownloadCommand {
    fn drop(&mut self) {
        self.bt_peer_route.take();

        if let Some(registry) = self.bt_registry.as_ref()
            && let Ok(mut registry) = registry.write()
        {
            if let Some(engine) = self.dht_engine.as_ref() {
                registry.clear_dht_engine_for_gid_if(self.group.recover().gid().value(), engine);
            }
            let gid = self.group.recover().gid().value();
            let owns_registration = self.tracker_runtime.as_ref().is_some_and(|runtime| {
                registry
                    .get(gid)
                    .and_then(|object| object.tracker_runtime.as_ref())
                    .is_some_and(|registered| Arc::ptr_eq(registered, runtime))
            });
            if owns_registration {
                registry.remove(gid);
            }
        }

        let mut storage = self
            .peer_storage
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let peers: Vec<_> = storage.used_peers().iter().cloned().collect();
        for peer in peers {
            storage.return_peer(&peer);
        }
    }
}

pub struct BtDownloadCommand {
    /// Stable BitTorrent peer ID for this download session.
    pub(crate) local_peer_id: [u8; 20],
    pub(crate) group: Arc<std::sync::RwLock<RequestGroup>>,
    /// Direct access to progress counters -- avoids RwLock on the hot path.
    pub(crate) progress: Arc<AtomicProgress>,
    pub(crate) output_path: std::path::PathBuf,
    pub(crate) started: bool,
    /// Monotonic timestamp captured when execution begins.
    pub(crate) started_at: Option<Instant>,
    pub(crate) completed_bytes: u64,
    pub(crate) torrent_data: Vec<u8>,
    pub(crate) seed_enabled: bool,
    pub(crate) seed_time: Option<std::time::Duration>,
    pub(crate) seed_ratio: Option<f64>,
    pub(crate) total_uploaded: u64,
    pub(crate) udp_client: Option<crate::engine::udp_tracker_client::SharedUdpClient>,
    /// Unified tracker announcer (HTTP + UDP) using BtAnnounce state machine.
    /// Created during execute() from the torrent announce list.
    pub(crate) tracker_announcer: Option<crate::engine::bt_tracker_comm::TrackerAnnouncer>,
    /// Actual TCP listener port advertised to trackers for this command.
    pub(crate) listen_port: u16,
    pub(crate) bt_runtime: std::sync::Arc<BtRuntimeState>,
    pub(crate) peer_coordinator: crate::engine::bt_peer_coordinator::BtPeerCoordinator,
    pub(crate) dht_engine:
        Option<std::sync::Arc<aria2_protocol::bittorrent::dht::engine::DhtEngine>>,
    pub(crate) public_trackers:
        Option<std::sync::Arc<aria2_protocol::bittorrent::tracker::public_list::PublicTrackerList>>,
    pub(crate) choking_algo: Option<ChokingAlgorithm>,
    pub(crate) multi_file_layout: Option<MultiFileLayout>,

    /// File allocation strategy from options
    /// ("none" / "prealloc" / "falloc" / "trunc" / "mmap"). Mirrors C++
    /// `FileAllocationEntry` choosing an iterator from `PREF_FILE_ALLOCATION`.
    pub(crate) file_allocation: String,
    /// Zero-fill after fallocate on platforms that don't zero-fill.
    pub(crate) secure_falloc: bool,
    /// `--check-integrity`: verify existing data against piece hashes before
    /// downloading (C++ `CheckIntegrityMan`).
    pub(crate) check_integrity: bool,
    /// Only perform the piece hash check and terminate without peer discovery.
    pub(crate) hash_check_only: bool,
    /// Allow the BitTorrent completion hook/notification when an existing
    /// payload passes `check-integrity`.
    pub(crate) bt_enable_hook_after_hash_check: bool,
    /// Continue into the BitTorrent peer/seed lifecycle after a complete
    /// payload passes `check-integrity`.
    pub(crate) bt_hash_check_seed: bool,
    /// Treat an existing payload as complete without verifying piece hashes.
    pub(crate) bt_seed_unverified: bool,
    /// Whether the current command completed from an integrity check rather
    /// than by downloading missing pieces.
    pub(crate) hash_check_completed: bool,
    /// Whether the BT completion event was already emitted at the integrity
    /// check seam.
    pub(crate) bt_complete_event_emitted: bool,

    // P1/P2 integration fields (all use Option for backward compatibility)
    /// BT progress persistence manager
    pub(crate) progress_manager: Option<crate::engine::bt_progress_info_file::BtProgressManager>,
    /// Progress save interval (default 60 seconds)
    pub(crate) progress_save_interval: Duration,
    /// LPD LAN peer discovery manager
    pub(crate) lpd_manager: Option<Arc<LpdManager>>,
    /// Info-hash registered in the shared LPD manager for this command.
    pub(crate) lpd_registered_info_hash: Option<[u8; 20]>,
    /// Post-download handler manager
    pub(crate) hook_manager: Option<Arc<crate::engine::hook_manager::HookManager>>,

    // PEX (Peer Exchange, BEP 11) integration fields
    /// Track known peers for PEX exchange
    pub(crate) pex_known_peers: Vec<aria2_protocol::bittorrent::peer::connection::PeerAddr>,
    /// Timestamp of last PEX message sent (for rate limiting)
    pub(crate) pex_last_send_time: Option<Instant>,
    /// Interval between PEX messages (default 60 seconds)
    pub(crate) pex_send_interval: Duration,

    // Endgame mode (Phase 14 - B1/B2): duplicate request tracking for final pieces
    /// Tracks duplicate block requests during endgame mode
    pub(crate) endgame_state: super::bt_download_execute::EndgameState,

    // BEP 6 (Fast Extension): track AllowedFast messages sent to peers
    /// Track which AllowedFast pieces have been sent to each peer
    /// Key: stable peer identity.
    #[allow(dead_code)]
    pub(crate) allowed_fast_sent_peers:
        HashMap<super::bt_download_execute::types::PeerKey, HashSet<u32>>,

    /// Track suggest counts per peer to avoid spamming.
    pub(crate) suggest_sent_counts: HashMap<super::bt_download_execute::types::PeerKey, usize>,

    // Tracker event state machine (Phase 15 - H5): manages Started/Completed/Stopped events
    /// State machine for tracker announce events
    #[allow(dead_code)]
    pub(crate) tracker_state: TrackerState,

    // Web-seed (BEP 19 / HTTP fallback) integration
    /// Web seed manager for HTTP piece downloads (initialized on first use)
    pub(crate) web_seed_manager: Option<crate::engine::bt_web_seed::WebSeedManager>,

    // Periodic DHT peer lookup (C++ DHTGetPeersCommand)
    /// Tracks timing and retry state for periodic DHT get_peers lookups.
    /// C++: DHTGetPeersCommand runs as a per-torrent command that
    /// triggers DHT lookups at adaptive intervals (15min normal,
    /// 5min low peers, 1min zero peers, 5s retry).
    /// Periodic lookup completion is consumed at BT piece-loop scheduling
    /// boundaries after the background task publishes an event.
    pub(crate) dht_periodic_lookup: super::bt_download_execute::execute::DhtPeriodicLookup,

    // File lock (J6): prevents concurrent aria2 instances from writing to same output dir
    /// Download path lock held for the lifetime of this command.
    /// Prevents other aria2 instances from writing to the same output directory.
    pub download_path_lock: Option<crate::filesystem::file_lock::DownloadPathLock>,

    // Seeding mode (Phase 16 - Complete BitTorrent seeding)
    /// Seed manager for uploading after download completes
    pub(crate) seed_manager: Option<super::bt_seed_manager::BtSeedManager>,

    // BEP 0027 (Private Torrent): when true, DHT/PEX/LPD and public tracker
    // announcement are disabled to enforce the privacy guarantees of the
    // torrent private flag.
    pub(crate) is_private: bool,

    // BtRegistry integration: the command registers itself into the engine BtRegistry
    // during execute() so that info-hash reverse lookup, peer
    // blocklist, and cross-download coordination work end-to-end.
    // Set via set_bt_registry() after construction by the engine or caller.
    pub(crate) bt_registry: Option<Arc<std::sync::RwLock<super::bt_registry::BtRegistry>>>,
    /// Shared live tracker state published to the engine registry for RPC.
    pub(crate) tracker_runtime: Option<crate::engine::bt_tracker_comm::SharedTrackerRuntime>,

    /// Process-wide rate limiter from `DownloadEngine::global_limiter`.
    /// When `Some`, passed down to `ThrottledWriter` so that this torrent's
    /// piece writes share a single bandwidth ceiling with all concurrent
    /// downloads.
    pub(crate) global_limiter: Option<RateLimiter>,

    /// Shared rejection state for verified bad piece sources.
    pub(crate) peer_rejection: crate::engine::bt_peer_storage::SharedPeerRejection,

    /// Session-scoped peer identity pool shared by discovery and connection
    /// scheduling. Socket ownership remains in the download loop until the
    /// lifecycle adapter is wired in.
    pub(crate) peer_storage:
        std::sync::Arc<std::sync::Mutex<crate::engine::bt_peer_storage::DefaultPeerStorage>>,

    /// Receiver for incoming peers routed by the engine-owned listener.
    pub(crate) incoming_peers:
        Option<tokio::sync::mpsc::Receiver<crate::engine::bt_peer_listener::IncomingPeer>>,
    /// Shared uTP socket for outbound peers in this download task.
    pub(crate) utp_socket:
        Option<Arc<tokio::sync::Mutex<aria2_protocol::bittorrent::utp::UtpSocket>>>,
    /// Process-level listener shared by all BitTorrent downloads.
    pub(crate) bt_listener: Option<Arc<crate::engine::bt_peer_listener::BtPeerListenerManager>>,
    /// RAII registration for this torrent's info-hash route.
    pub(crate) bt_peer_route: Option<crate::engine::bt_peer_listener::BtPeerRouteHandle>,
    /// Rust-owned A2CF checkpoint for verified torrent pieces.
    pub(crate) checkpoint: Option<crate::engine::bt_checkpoint::BtCheckpoint>,
    /// Bytes verified since the last durable torrent checkpoint.
    pub(crate) checkpoint_bytes_since_save: u64,
    /// Time at which the last durable torrent checkpoint completed.
    pub(crate) checkpoint_last_save: Instant,
}

impl BtDownloadCommand {
    pub fn group(&self) -> std::sync::RwLockReadGuard<'_, RequestGroup> {
        use crate::util::rwlock_ext::RwLockRecover;
        self.group.recover()
    }

    pub fn group_handle(&self) -> Arc<std::sync::RwLock<RequestGroup>> {
        Arc::clone(&self.group)
    }

    /// Complete the asynchronous shutdown phase before the command is dropped.
    ///
    /// `Drop` can only reclaim synchronous resources. Callers that own the
    /// command lifecycle should await this method before aborting or dropping
    /// the task so tracker stopped announcements and DHT routing-table
    /// persistence are not lost.
    pub async fn shutdown(&mut self) {
        // The DHT engine owns background receive/maintenance tasks and its
        // final routing-table snapshot. Shut it down before the command is
        // dropped; DhtEngine::Drop only aborts tasks and cannot persist state.
        if let Some(engine) = self.dht_engine.as_ref()
            && let Some(registry) = self.bt_registry.as_ref()
            && let Ok(mut registry) = registry.write()
        {
            registry.clear_dht_engine_for_gid_if(self.group.recover().gid().value(), engine);
        }
        if let Some(engine) = self.dht_engine.take() {
            engine.shutdown_async().await;
        }
        if let (Some(manager), Some(info_hash)) =
            (&self.lpd_manager, self.lpd_registered_info_hash.take())
        {
            let info_hash_hex = hex::encode(info_hash);
            manager.unregister_torrent(&info_hash_hex).await;
        }
        if let Ok(meta) =
            aria2_protocol::bittorrent::torrent::parser::TorrentMeta::parse(&self.torrent_data)
            && let Some(ref mut announcer) = self.tracker_announcer
        {
            let total_size = meta.total_size();
            announcer
                .announce_stopped(
                    &meta.network_info_hash(),
                    &self.local_peer_id,
                    self.completed_bytes,
                    total_size.saturating_sub(self.completed_bytes),
                    self.total_uploaded,
                )
                .await;
        }
        self.bt_peer_route.take();
    }

    /// Set the process-wide rate limiter (from `DownloadEngine::global_limiter`).
    ///
    /// When set, piece writes performed by this command acquire tokens from
    /// this limiter (in addition to any per-download limiter) so that all
    /// concurrent downloads share a global bandwidth ceiling.
    pub fn set_global_limiter(&mut self, limiter: RateLimiter) {
        self.global_limiter = Some(limiter);
    }

    pub fn is_multi_file(&self) -> bool {
        self.multi_file_layout
            .as_ref()
            .is_some_and(|l| l.is_multi_file())
    }

    pub fn get_multi_file_layout(&self) -> Option<&MultiFileLayout> {
        self.multi_file_layout.as_ref()
    }

    /// Wrapper around crate::engine::bt_piece_downloader::write_piece_to_multi_files.
    pub async fn write_piece_to_multi_files(
        layout: &MultiFileLayout,
        piece_idx: u32,
        piece_data: &[u8],
        piece_length: u32,
    ) -> crate::error::Result<()> {
        crate::engine::bt_piece_downloader::write_piece_to_multi_files(
            layout,
            piece_idx,
            piece_data,
            piece_length,
        )
        .await
    }

    /// Wrapper around crate::engine::bt_piece_downloader::write_piece_to_multi_files_coalesced.
    ///
    /// Prefer this over write_piece_to_multi_files for production use -- it
    /// merges adjacent writes within a 4 KiB gap, reducing syscall count.
    pub async fn write_piece_to_multi_files_coalesced(
        layout: &MultiFileLayout,
        piece_idx: u32,
        piece_data: &bytes::Bytes,
        piece_length: u32,
    ) -> crate::error::Result<()> {
        crate::engine::bt_piece_downloader::write_piece_to_multi_files_coalesced(
            layout,
            piece_idx,
            piece_data,
            piece_length,
        )
        .await
    }

    pub async fn write_piece_to_multi_files_coalesced_with_limit(
        layout: &MultiFileLayout,
        piece_idx: u32,
        piece_data: &bytes::Bytes,
        piece_length: u32,
        max_open_files: usize,
    ) -> crate::error::Result<()> {
        crate::engine::bt_piece_downloader::write_piece_to_multi_files_coalesced_with_limit(
            layout,
            piece_idx,
            piece_data,
            piece_length,
            max_open_files,
        )
        .await
    }

    pub async fn announce_to_public_tracker(
        tracker_url: &str,
        info_hash: &[u8; 20],
        peer_id: &[u8; 20],
        total_size: u64,
    ) -> std::result::Result<Vec<(String, u16)>, String> {
        crate::engine::bt_tracker_comm::announce_to_public_tracker(
            tracker_url,
            info_hash,
            peer_id,
            total_size,
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::{BtDownloadCommand, BtRuntimeState};

    #[tokio::test]
    async fn shutdown_persists_owned_dht_engine_before_drop() {
        let torrent = crate::engine::bt_download_command_tests::build_test_torrent();
        let options = crate::request::request_group::DownloadOptions::default();
        let mut command = BtDownloadCommand::new(
            crate::request::request_group::GroupId::new(9),
            &torrent,
            &options,
            None,
        )
        .expect("test torrent should construct");

        let temp_dir = tempfile::tempdir().expect("temporary directory should be created");
        let dht_path = temp_dir.path().join("dht.dat");
        let dht = aria2_protocol::bittorrent::dht::engine::DhtEngine::start(
            aria2_protocol::bittorrent::dht::engine::DhtEngineConfig {
                self_id: [0xA5; 20],
                dht_file_path: Some(dht_path.clone()),
                ..aria2_protocol::bittorrent::dht::engine::DhtEngineConfig::local()
            },
        )
        .await
        .expect("local DHT engine should start");
        command.dht_engine = Some(dht);

        command.shutdown().await;

        let persisted =
            aria2_protocol::bittorrent::dht::persistence::DhtPersistence::load_from_file_sync(
                &dht_path,
            )
            .expect("command shutdown should persist dht.dat");
        assert_eq!(persisted.self_id, [0xA5; 20]);
    }

    #[test]
    fn runtime_state_uses_the_same_min_peer_boundary_as_tracker_demand() {
        let runtime = BtRuntimeState::new(55);
        assert_eq!(runtime.min_peers(), 44);
        assert!(runtime.less_than_min_peers());

        runtime.set_connections(44);
        assert!(!runtime.less_than_min_peers());

        runtime.set_max_peers(0);
        assert_eq!(runtime.min_peers(), 0);
        assert!(!runtime.less_than_min_peers());
        assert!(runtime.less_than_max_peers());
    }

    #[test]
    fn runtime_state_accepts_runtime_max_peer_changes() {
        let runtime = BtRuntimeState::new(10);
        runtime.set_connections(7);
        assert!(runtime.less_than_min_peers());

        runtime.set_max_peers(8);
        assert!(!runtime.less_than_min_peers());
        assert_eq!(runtime.max_peers(), 8);
    }

    #[test]
    fn explicit_zero_seed_time_overrides_the_default_seed_ratio() {
        let torrent = crate::engine::bt_download_command_tests::build_test_torrent();
        let options = crate::request::request_group::DownloadOptions {
            seed_time: Some(0.0),
            ..Default::default()
        };
        let command = BtDownloadCommand::new(
            crate::request::request_group::GroupId::new(10),
            &torrent,
            &options,
            None,
        )
        .expect("test torrent should construct");

        assert!(!command.seed_enabled);
    }

    #[test]
    fn positive_seed_options_enable_seeding() {
        let torrent = crate::engine::bt_download_command_tests::build_test_torrent();
        let options = crate::request::request_group::DownloadOptions {
            seed_time: Some(1.0),
            ..Default::default()
        };
        let command = BtDownloadCommand::new(
            crate::request::request_group::GroupId::new(11),
            &torrent,
            &options,
            None,
        )
        .expect("test torrent should construct");

        assert!(command.seed_enabled);
        assert_eq!(
            command.seed_time,
            Some(std::time::Duration::from_secs(60)),
            "seed-time is expressed in fractional minutes"
        );
    }

    #[test]
    fn command_uses_configured_peer_id_prefix() {
        let torrent = crate::engine::bt_download_command_tests::build_test_torrent();
        let options = crate::request::request_group::DownloadOptions {
            peer_id_prefix: "TEST-PREFIX-".to_string(),
            ..Default::default()
        };
        let command = BtDownloadCommand::new(
            crate::request::request_group::GroupId::new(12),
            &torrent,
            &options,
            None,
        )
        .expect("test torrent should construct");

        assert!(command.local_peer_id.starts_with(b"TEST-PREFIX-"));
    }

    #[test]
    fn command_loads_configured_peer_blocklist_into_peer_storage() {
        let torrent = crate::engine::bt_download_command_tests::build_test_torrent();
        let path = std::env::temp_dir().join(format!(
            "aria2-rust-command-blocklist-{}.txt",
            std::process::id()
        ));
        std::fs::write(&path, "10.0.0.0/8\n").expect("blocklist fixture should be writable");
        let options = crate::request::request_group::DownloadOptions {
            bt_peer_blocklist: Some(path.to_string_lossy().into_owned()),
            ..Default::default()
        };

        let command = BtDownloadCommand::new(
            crate::request::request_group::GroupId::new(13),
            &torrent,
            &options,
            None,
        )
        .expect("test torrent should construct");

        let blocked = crate::engine::bt_peer_storage::PeerEntry::new("10.0.0.1".into(), 6881);
        let allowed = crate::engine::bt_peer_storage::PeerEntry::new("192.0.2.1".into(), 6881);
        let mut storage = command.peer_storage.lock().unwrap();
        assert!(!storage.add_peer(blocked));
        assert!(storage.add_peer(allowed));
        drop(storage);
        let _ = std::fs::remove_file(path);
    }
}