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
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
#![allow(clippy::collapsible_if)]

use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use tracing::{info, Level};
use tracing_subscriber::EnvFilter;

use torrentdht::{
    build_integrity_image_async, format_status_table, load_signing_key, scan_download_dir,
    sidecar_root_for_config, torrent_to_magnet, validate_integrity_image, Client, Config,
    ContentLayout, IntegrityConfig, PeerDiscoveryMode, Session, TorrentBuilder, TorrentFile,
};

struct SessionOptions {
    config_path: PathBuf,
    dht_only: bool,
    tracker_only: bool,
    static_peers: Vec<SocketAddr>,
    download_files: Vec<String>,
}

impl SessionOptions {
    fn parse(args: &[String], require_target: bool, target_label: &str) -> torrentdht::Result<(Self, Option<String>)> {
        let mut config_path = PathBuf::from("config/default.kdl");
        let mut target = None;
        let mut dht_only = false;
        let mut tracker_only = false;
        let mut static_peers = Vec::new();
        let mut download_files = Vec::new();
        let mut idx = 0;
        while idx < args.len() {
            match args[idx].as_str() {
                "-c" | "--config" => {
                    idx += 1;
                    config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
                }
                "--dht-only" => dht_only = true,
                "--tracker-only" => tracker_only = true,
                "--peer" => {
                    idx += 1;
                    let addr = args
                        .get(idx)
                        .ok_or_else(missing("peer address"))?
                        .parse::<SocketAddr>()
                        .map_err(|_| {
                            torrentdht::Error::Session(
                                "peer address must be host:port".into(),
                            )
                        })?;
                    static_peers.push(addr);
                }
                "--files" => {
                    idx += 1;
                    download_files.push(
                        args.get(idx)
                            .ok_or_else(missing("file pattern"))?
                            .to_string(),
                    );
                }
                value if value.starts_with('-') => {
                    return Err(torrentdht::Error::Session(format!(
                        "unknown flag: {value}"
                    )));
                }
                value => {
                    if target.is_some() {
                        return Err(torrentdht::Error::Session(format!(
                            "{target_label} accepts a single target"
                        )));
                    }
                    target = Some(value.to_string());
                }
            }
            idx += 1;
        }
        if require_target && target.is_none() {
            return Err(torrentdht::Error::Session(format!(
                "{target_label} requires a target"
            )));
        }
        Ok((
            Self {
                config_path,
                dht_only,
                tracker_only,
                static_peers,
                download_files,
            },
            target,
        ))
    }

    fn apply_to_config(&self, cfg: &mut Config) -> torrentdht::Result<()> {
        if self.dht_only && self.tracker_only {
            return Err(torrentdht::Error::Config(
                "cannot use --dht-only and --tracker-only together".into(),
            ));
        }
        if self.dht_only {
            cfg.peer_discovery = PeerDiscoveryMode::Dht;
            cfg.dht_enabled = true;
        } else if self.tracker_only {
            cfg.peer_discovery = PeerDiscoveryMode::Tracker;
            cfg.dht_enabled = false;
        }
        Ok(())
    }
}

async fn load_torrent_file(data: &[u8], cfg: &Config) -> torrentdht::Result<TorrentFile> {
    let torrent = TorrentFile::parse(data)?;
    torrentdht::ensure_torrent_trusted(cfg, &torrent)?;
    Ok(torrent)
}

async fn cmd_daemon(args: &[String]) -> torrentdht::Result<()> {
    let mut config_path = PathBuf::from("config/default.kdl");
    let mut idx = 0;
    while idx < args.len() {
        match args[idx].as_str() {
            "-c" | "--config" => {
                idx += 1;
                config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
            }
            value if value.starts_with('-') => {
                return Err(torrentdht::Error::Session(format!(
                    "unknown flag: {value}"
                )));
            }
            _ => {
                return Err(torrentdht::Error::Session(
                    "daemon accepts only -c/--config".into(),
                ));
            }
        }
        idx += 1;
    }

    let cfg = Config::from_kdl_file(&config_path)?;
    let client = Client::open(cfg).await?;
    if client.config().rpc_enabled {
        info!(
            listen = client.config().rpc_listen.as_deref().unwrap_or(""),
            "daemon running with RPC (auth <token> then status|progress|add_torrent|add_magnet|stop|remove|ping)"
        );
    } else {
        info!("daemon running (secure client held open until ctrl-c; RPC off)");
    }

    tokio::signal::ctrl_c().await.map_err(|err| {
        torrentdht::Error::Session(format!("ctrl-c handler failed: {err}"))
    })?;
    client.persist_dht().await?;
    info!("daemon stopped");
    Ok(())
}

async fn cmd_run(args: &[String]) -> torrentdht::Result<()> {
    let mut config_path = PathBuf::from("config/default.kdl");
    let mut dht_only = false;
    let mut tracker_only = false;
    let mut targets = Vec::new();
    let mut idx = 0;
    while idx < args.len() {
        match args[idx].as_str() {
            "-c" | "--config" => {
                idx += 1;
                config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
            }
            "--dht-only" => dht_only = true,
            "--tracker-only" => tracker_only = true,
            value if value.starts_with('-') => {
                return Err(torrentdht::Error::Session(format!(
                    "unknown flag: {value}"
                )));
            }
            value => targets.push(value.to_string()),
        }
        idx += 1;
    }
    if targets.is_empty() {
        return Err(torrentdht::Error::Session(
            "run requires one or more torrent files or magnet URIs".into(),
        ));
    }

    let mut cfg = Config::from_kdl_file(&config_path)?;
    let opts = SessionOptions {
        config_path,
        dht_only,
        tracker_only,
        static_peers: Vec::new(),
        download_files: Vec::new(),
    };
    opts.apply_to_config(&mut cfg)?;

    let client = Client::open(cfg).await?;
    let progress_client = Arc::clone(&client);
    let progress_task = tokio::spawn(async move {
        let mut interval = tokio::time::interval(Duration::from_secs(15));
        interval.tick().await;
        loop {
            interval.tick().await;
            let sessions = progress_client.sessions().await;
            if sessions.is_empty() {
                continue;
            }
            let mut all_done = true;
            for session in &sessions {
                let complete = session.picker().read().await.complete_count() as u32;
                let total = session.info().piece_count();
                info!(
                    name = %session.info().name,
                    hash = %session.info_hash().to_hex(),
                    complete,
                    total,
                    "run progress"
                );
                if complete < total {
                    all_done = false;
                }
            }
            if all_done {
                break;
            }
        }
    });

    let mut handles = Vec::new();

    for target in targets {
        let session = if target.starts_with("magnet:?") {
            let magnet = torrentdht::parse_magnet(&target)?;
            info!(hash = %magnet.info_hash.to_hex(), "loaded magnet");
            client.add_magnet(magnet).await?
        } else {
            let torrent_data = tokio::fs::read(&target).await?;
            let torrent = load_torrent_file(&torrent_data, client.config()).await?;
            info!(name = %torrent.info.name, hash = %torrent.info.info_hash.to_hex(), "loaded torrent");
            client.add_torrent(torrent).await?
        };

        let worker = Arc::clone(&session);
        handles.push(tokio::spawn(async move {
            let name = worker.info().name.clone();
            match worker.run().await {
                Ok(progress) => info!(
                    name,
                    pieces = progress.pieces_complete,
                    total = progress.piece_count,
                    "download complete"
                ),
                Err(err) => tracing::error!(%err, name, "download failed"),
            }
        }));
    }

    for handle in handles {
        let _ = handle.await;
    }
    progress_task.abort();
    Ok(())
}

async fn cmd_status(args: &[String]) -> torrentdht::Result<()> {
    let mut config_path = PathBuf::from("config/default.kdl");
    let mut idx = 0;
    while idx < args.len() {
        match args[idx].as_str() {
            "-c" | "--config" => {
                idx += 1;
                config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
            }
            value if value.starts_with('-') => {
                return Err(torrentdht::Error::Session(format!(
                    "unknown flag: {value}"
                )));
            }
            _ => {
                return Err(torrentdht::Error::Session(
                    "status accepts only -c/--config".into(),
                ));
            }
        }
        idx += 1;
    }

    let cfg = Config::from_kdl_file(&config_path)?;
    let rows = scan_download_dir(&cfg).await?;
    println!("{}", format_status_table(&rows));
    Ok(())
}

#[tokio::main]
async fn main() -> torrentdht::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env().add_directive(Level::INFO.into()))
        .init();

    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.is_empty() {
        print_usage();
        return Ok(());
    }

    match args[0].as_str() {
        "create" => cmd_create(&args[1..]).await,
        "verify" => cmd_verify(&args[1..]).await,
        "download" => cmd_download(&args[1..]).await,
        "run" => cmd_run(&args[1..]).await,
        "daemon" => cmd_daemon(&args[1..]).await,
        "status" => cmd_status(&args[1..]).await,
        "seed" => cmd_seed(&args[1..]).await,
        "magnet" => cmd_magnet(&args[1..]).await,
        "env-check" => cmd_env_check(),
        "help" | "--help" | "-h" => {
            print_usage();
            Ok(())
        }
        _ => {
            print_usage();
            Err(torrentdht::Error::Session(
                "unknown command; use `torrentdht download --config <file.kdl> <torrent|magnet>` (legacy `torrentdht <config.kdl> <torrent>` is removed)"
                    .into(),
            ))
        }
    }
}

async fn cmd_create(args: &[String]) -> torrentdht::Result<()> {
    let mut config_path = PathBuf::from("config/default.kdl");
    let mut output = None;
    let mut announce = None;
    let mut piece_length = None;
    let mut name = None;
    let mut sign_key = None;
    let mut no_integrity_image = false;
    let mut v2_hybrid = false;
    let mut v2_only = false;
    let mut input = None;

    let mut idx = 0;
    while idx < args.len() {
        match args[idx].as_str() {
            "-c" | "--config" => {
                idx += 1;
                config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
            }
            "-o" | "--output" => {
                idx += 1;
                output = Some(PathBuf::from(args.get(idx).ok_or_else(missing("output path"))?));
            }
            "--announce" => {
                idx += 1;
                announce = Some(args.get(idx).ok_or_else(missing("announce url"))?.clone());
            }
            "--piece-length" => {
                idx += 1;
                piece_length = Some(
                    args.get(idx)
                        .ok_or_else(missing("piece length"))?
                        .parse::<u32>()
                        .map_err(|_| torrentdht::Error::Torrent("invalid piece length".into()))?,
                );
            }
            "--name" => {
                idx += 1;
                name = Some(args.get(idx).ok_or_else(missing("name"))?.clone());
            }
            "--sign-key" => {
                idx += 1;
                sign_key = Some(PathBuf::from(
                    args.get(idx).ok_or_else(missing("signing key path"))?,
                ));
            }
            "--no-integrity-image" => no_integrity_image = true,
            "--v2" => v2_hybrid = true,
            "--v2-only" => v2_only = true,
            value if value.starts_with('-') => {
                return Err(torrentdht::Error::Session(format!(
                    "unknown flag: {value}"
                )));
            }
            value => {
                if input.is_some() {
                    return Err(torrentdht::Error::Session(
                        "create accepts a single input path".into(),
                    ));
                }
                input = Some(PathBuf::from(value));
            }
        }
        idx += 1;
    }

    if v2_hybrid && v2_only {
        return Err(torrentdht::Error::Session(
            "create: use only one of --v2 (hybrid) or --v2-only".into(),
        ));
    }

    let input = input.ok_or_else(|| torrentdht::Error::Session("create requires input path".into()))?;
    let cfg = Config::from_kdl_file(&config_path)?;

    let mut builder = TorrentBuilder::new(&input);
    if let Some(url) = announce {
        builder = builder.announce(url);
    }
    if let Some(len) = piece_length {
        builder = builder.piece_length(len);
    }
    if let Some(display) = name {
        builder = builder.name(display);
    }
    if let Some(path) = sign_key {
        builder = builder.signing_key(load_signing_key(&path)?);
    } else if cfg.integrity_sign_torrents {
        if let Some(path) = &cfg.integrity_signing_key_file {
            builder = builder.signing_key(load_signing_key(path)?);
        }
    }
    if v2_hybrid {
        builder = builder.v2_hybrid(true);
    }
    if v2_only {
        builder = builder.v2_only(true);
    }

    let torrent = builder.build().await?;
    let output = output.unwrap_or_else(|| {
        PathBuf::from(format!("{}.torrent", torrent.info.name.replace('/', "_")))
    });
    torrent.write_to(&output).await?;

    if cfg.integrity_create_image && !no_integrity_image {
        let layout =
            ContentLayout::from_path(&input, Some(torrent.info.name.clone()))?;
        let integrity =
            IntegrityConfig::from_app_config(&cfg, torrent.info.info_hash.as_bytes())?;
        let sidecar_root = sidecar_root_for_config(&cfg, &torrent.info);
        let report = build_integrity_image_async(
            &layout,
            &torrent.info,
            &sidecar_root,
            cfg.block_size,
            &integrity,
        )
        .await?;
        info!(
            sidecar = %sidecar_root.display(),
            pieces = report.pieces_sha1_ok,
            blocks = report.blocks_crc_ok,
            parity = report.parity_ok,
            valid = report.is_valid(),
            "created integrity image"
        );
        if !report.is_valid() {
            return Err(torrentdht::Error::Integrity(
                "integrity image build reported errors".into(),
            ));
        }
    }

    info!(
        path = %output.display(),
        hash = %torrent.info.info_hash.to_hex(),
        signed = torrent.signature.is_some(),
        magnet = %torrent_to_magnet(&torrent),
        "created torrent"
    );
    Ok(())
}

async fn cmd_verify(args: &[String]) -> torrentdht::Result<()> {
    let mut config_path = PathBuf::from("config/default.kdl");
    let mut torrent_path = None;
    let mut content_path = None;
    let mut sidecar_root = None;

    let mut idx = 0;
    while idx < args.len() {
        match args[idx].as_str() {
            "-c" | "--config" => {
                idx += 1;
                config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
            }
            "--content" => {
                idx += 1;
                content_path = Some(PathBuf::from(
                    args.get(idx).ok_or_else(missing("content path"))?,
                ));
            }
            "--sidecar-root" => {
                idx += 1;
                sidecar_root = Some(PathBuf::from(
                    args.get(idx).ok_or_else(missing("sidecar root"))?,
                ));
            }
            value if value.starts_with('-') => {
                return Err(torrentdht::Error::Session(format!(
                    "unknown flag: {value}"
                )));
            }
            value => {
                if torrent_path.is_some() {
                    return Err(torrentdht::Error::Session(
                        "verify accepts a single torrent file".into(),
                    ));
                }
                torrent_path = Some(PathBuf::from(value));
            }
        }
        idx += 1;
    }

    let torrent_path = torrent_path
        .ok_or_else(|| torrentdht::Error::Session("verify requires a .torrent file".into()))?;
    let cfg = Config::from_kdl_file(&config_path)?;
    let torrent_data = tokio::fs::read(&torrent_path).await?;
    let torrent = load_torrent_file(&torrent_data, &cfg).await?;

    let layout_paths = cfg.torrent_layout(&torrent.info.info_hash.to_hex());
    let sidecar_root = sidecar_root.unwrap_or_else(|| layout_paths.state_root.clone());

    let layout = if let Some(content) = content_path {
        ContentLayout::from_path(content, Some(torrent.info.name.clone()))?
    } else {
        ContentLayout::from_torrent_at(&layout_paths.content_root, &torrent.info)?
    };

    let integrity = IntegrityConfig::from_app_config(&cfg, torrent.info.info_hash.as_bytes())?;
    let report = validate_integrity_image(
        &layout,
        &torrent.info,
        &sidecar_root,
        cfg.block_size,
        &integrity,
    )
    .await?;

    info!(
        hash = %torrent.info.info_hash.to_hex(),
        pieces = report.pieces_sha1_ok,
        piece_total = report.piece_count,
        blocks = report.blocks_crc_ok,
        block_total = report.block_count,
        parity = report.parity_ok,
        parity_total = report.parity_count,
        valid = report.is_valid(),
        errors = report.errors.len(),
        "integrity verification"
    );

    if !report.is_valid() {
        for err in &report.errors {
            tracing::error!(%err, "integrity error");
        }
        return Err(torrentdht::Error::Integrity(
            "content failed integrity verification".into(),
        ));
    }
    Ok(())
}

async fn cmd_download(args: &[String]) -> torrentdht::Result<()> {
    let (opts, target) = SessionOptions::parse(
        args,
        true,
        "download requires torrent file or magnet URI",
    )?;
    cmd_download_target(&opts, &target.expect("target checked")).await
}

async fn cmd_seed(args: &[String]) -> torrentdht::Result<()> {
    let (opts, target) = SessionOptions::parse(args, true, "seed requires a .torrent file")?;
    let target = target.expect("target checked");
    let mut cfg = Config::from_kdl_file(&opts.config_path)?;
    opts.apply_to_config(&mut cfg)?;
    let torrent_data = tokio::fs::read(&target).await?;
    let torrent = load_torrent_file(&torrent_data, &cfg).await?;
    info!(name = %torrent.info.name, hash = %torrent.info.info_hash.to_hex(), "loaded torrent for seeding");

    let session = Session::from_torrent(cfg, torrent).await?;
    session.add_static_peers(opts.static_peers).await;
    session.seed().await
}

async fn cmd_download_target(opts: &SessionOptions, target: &str) -> torrentdht::Result<()> {
    let mut cfg = Config::from_kdl_file(&opts.config_path)?;
    opts.apply_to_config(&mut cfg)?;
    cfg.download_files = opts.download_files.clone();
    let session = if target.starts_with("magnet:?") {
        let magnet = torrentdht::parse_magnet(target)?;
        info!(hash = %magnet.info_hash.to_hex(), "loaded magnet link");
        let session = Session::from_magnet(cfg, magnet).await?;
        session.add_static_peers(opts.static_peers.clone()).await;
        session
    } else {
        let torrent_data = tokio::fs::read(target).await?;
        let torrent = load_torrent_file(&torrent_data, &cfg).await?;
        info!(name = %torrent.info.name, hash = %torrent.info.info_hash.to_hex(), "loaded torrent");
        let session = Session::from_torrent(cfg, torrent).await?;
        session.add_static_peers(opts.static_peers.clone()).await;
        session.bootstrap_dht().await?;
        session
    };

    let progress = session.download().await?;
    info!(
        pieces = progress.pieces_complete,
        total = progress.piece_count,
        bytes = progress.bytes_downloaded,
        "download complete"
    );
    Ok(())
}

async fn cmd_magnet(args: &[String]) -> torrentdht::Result<()> {
    let mut config_path = PathBuf::from("config/default.kdl");
    let mut torrent_path = None;
    let mut idx = 0;
    while idx < args.len() {
        match args[idx].as_str() {
            "-c" | "--config" => {
                idx += 1;
                config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
            }
            value if value.starts_with('-') => {
                return Err(torrentdht::Error::Session(format!(
                    "unknown flag: {value}"
                )));
            }
            value => {
                if torrent_path.is_some() {
                    return Err(torrentdht::Error::Session(
                        "magnet accepts a single torrent file".into(),
                    ));
                }
                torrent_path = Some(PathBuf::from(value));
            }
        }
        idx += 1;
    }
    let torrent_path = torrent_path
        .ok_or_else(|| torrentdht::Error::Session("magnet requires a .torrent file".into()))?;
    let cfg = Config::from_kdl_file(&config_path)?;
    let torrent_data = tokio::fs::read(&torrent_path).await?;
    let torrent = load_torrent_file(&torrent_data, &cfg).await?;
    println!("{}", torrent_to_magnet(&torrent));
    Ok(())
}

fn cmd_env_check() -> torrentdht::Result<()> {
    torrentdht::SecureEnv::check_required()?;
    println!("secure-session environment OK");
    println!(
        "network id present; remember NETWORK_ID is capability-bearing (SHA-1 announced on public DHT)"
    );
    Ok(())
}

fn print_usage() {
    eprintln!(
        "torrentdht — pure Rust BitTorrent client\n\
         \n\
         Usage:\n\
           torrentdht create [options] <input-path>\n\
           torrentdht verify [options] <file.torrent>\n\
           torrentdht download [options] <file.torrent|magnet:?...>\n\
           torrentdht run [options] <torrent...>   Download multiple torrents in one client\n\
           torrentdht daemon [options]             Long-running secure client (optional RPC)\n\
           torrentdht status [options]             List download-dir resume state\n\
           torrentdht seed [options] <file.torrent>\n\
           torrentdht magnet <file.torrent>\n\
           torrentdht env-check                    Validate TORRENTDHT_* TLS/network env\n\
         \n\
         Secure session (required for download/seed/run/daemon):\n\
           TORRENTDHT_CA_CERT=/path/to/ca.pem\n\
           TORRENTDHT_CERT=/path/to/node.pem\n\
           TORRENTDHT_KEY=/path/to/node-key.pem\n\
           TORRENTDHT_NETWORK_ID=<high-entropy private network name>\n\
           TORRENTDHT_HANDSHAKE_KEY=<shared secret for this network>\n\
           Optional: TORRENTDHT_PEER_STORE, TORRENTDHT_LISTEN_ADDR\n\
           Note: NETWORK_ID is capability-bearing (SHA-1 announced on public DHT).\n\
                 Membership is network-wide across torrents on this Client.\n\
         \n\
         Create options:\n\
           -c, --config <kdl>       Config file (default: config/default.kdl)\n\
           -o, --output <path>      Output .torrent path\n\
           --announce <url>         Tracker announce URL\n\
           --piece-length <bytes>   Piece size (default: 262144)\n\
           --name <name>            Torrent display name override\n\
           --sign-key <path>        Ed25519 signing key (32-byte seed file)\n\
           --no-integrity-image     Skip ECC manifest + parity sidecar generation\n\
           --v2                     Create hybrid BEP 52 torrent (v1 SHA1 + v2 file tree)\n\
           --v2-only                Create pure BEP 52 v2 torrent (btmh magnets; no v1 pieces)\n\
         \n\
         Verify options:\n\
           -c, --config <kdl>       Config file (default: config/default.kdl)\n\
           --content <path>         Content root (default: download-dir/info-hash)\n\
           --sidecar-root <path>    Sidecar root (default: state-dir/torrents/hash or download-dir/hash)\n\
         \n\
         Download/seed options:\n\
           -c, --config <kdl>       Config file (default: config/default.kdl)\n\
           --dht-only               Discover peers via DHT only\n\
           --tracker-only           Discover peers via tracker(s) only\n\
           --peer <host:port>       Static peer (repeatable)\n\
           --files <pattern>        Selective download file pattern (repeatable)\n"
    );
}

fn missing(label: &'static str) -> impl FnOnce() -> torrentdht::Error {
    move || torrentdht::Error::Session(format!("missing {label}"))
}