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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
use std::path::PathBuf;

use kdl::KdlDocument;
use zeroize::Zeroizing;

use crate::error::{Error, Result};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PeerDiscoveryMode {
    Hybrid,
    Tracker,
    Dht,
}

impl PeerDiscoveryMode {
    pub fn parse(raw: &str) -> Result<Self> {
        match raw {
            "hybrid" => Ok(Self::Hybrid),
            "tracker" | "tracker-only" => Ok(Self::Tracker),
            "dht" | "dht-only" => Ok(Self::Dht),
            other => Err(Error::Config(format!(
                "peer-discovery must be hybrid, tracker, or dht (got {other})"
            ))),
        }
    }

    pub fn uses_tracker(self) -> bool {
        matches!(self, Self::Hybrid | Self::Tracker)
    }

    pub fn uses_dht(self) -> bool {
        matches!(self, Self::Hybrid | Self::Dht)
    }
}

/// Peer wire security layer after discovery (selectable; unimplemented modes fail closed).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SwarmSecurity {
    /// Default: mTLS 1.3 handoff, then BitTorrent messages on the TLS stream.
    #[default]
    Mtls,
    /// Reserved: MSE/PE (BEP 17/27) for public swarms — not implemented.
    Mse,
}

impl SwarmSecurity {
    pub fn parse(raw: &str) -> Result<Self> {
        match raw {
            "mtls" | "tls" => Ok(Self::Mtls),
            "mse" | "mse-pe" | "pe" => Ok(Self::Mse),
            other => Err(Error::Config(format!(
                "swarm-security must be mtls or mse (got {other})"
            ))),
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Mtls => "mtls",
            Self::Mse => "mse",
        }
    }

    pub fn is_implemented(self) -> bool {
        match self {
            Self::Mtls | Self::Mse => true,
        }
    }
}

/// Peer transport under the chosen security layer (selectable; uTP fails closed today).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SwarmTransport {
    #[default]
    Tcp,
    /// Peer transport under the chosen security layer (`tcp` or `utp`).
    /// uTP requires `swarm-security "mse"` (mTLS is TCP-only).
    Utp,
}

impl SwarmTransport {
    pub fn parse(raw: &str) -> Result<Self> {
        match raw {
            "tcp" => Ok(Self::Tcp),
            "utp" | "uTP" => Ok(Self::Utp),
            other => Err(Error::Config(format!(
                "swarm-transport must be tcp or utp (got {other})"
            ))),
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Tcp => "tcp",
            Self::Utp => "utp",
        }
    }

    pub fn is_implemented(self) -> bool {
        matches!(self, Self::Tcp | Self::Utp)
    }
}

/// DHT bootstrap host (hostname or literal IP) + UDP port.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BootstrapNode {
    pub host: String,
    pub port: u16,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResilienceConfig {
    pub heal_interval_secs: u64,
    pub stale_peer_secs: u64,
    pub stalled_download_secs: u64,
    pub peer_ban_secs: u64,
    pub checkpoint_interval_secs: u64,
    pub max_peer_failures: u32,
    pub run_retry_initial_secs: u64,
    pub run_retry_max_secs: u64,
}

impl Default for ResilienceConfig {
    fn default() -> Self {
        Self {
            heal_interval_secs: 15,
            stale_peer_secs: 45,
            stalled_download_secs: 120,
            peer_ban_secs: 300,
            checkpoint_interval_secs: 30,
            max_peer_failures: 5,
            run_retry_initial_secs: 3,
            run_retry_max_secs: 60,
        }
    }
}

impl ResilienceConfig {
    pub fn heal_interval(&self) -> std::time::Duration {
        std::time::Duration::from_secs(self.heal_interval_secs.max(1))
    }

    pub fn checkpoint_interval(&self) -> std::time::Duration {
        std::time::Duration::from_secs(self.checkpoint_interval_secs.max(1))
    }
}

#[derive(Debug, Clone)]
pub struct Config {
    pub listen_port: u16,
    pub download_dir: PathBuf,
    /// Host-owned state root for peer ledger store, DHT routing, and per-torrent
    /// resume/integrity sidecars. When unset, state stays under `download_dir`
    /// (`.torrentdht/` beside content — legacy layout).
    pub state_dir: Option<PathBuf>,
    pub dht_enabled: bool,
    pub peer_discovery: PeerDiscoveryMode,
    pub max_peers: usize,
    pub block_size: u32,
    pub memory_cache_mb: usize,
    pub flush_workers: usize,
    pub flush_batch_size: usize,
    pub integrity_verify_blocks: bool,
    pub integrity_ecc_enabled: bool,
    pub integrity_ecc_data_shards: usize,
    pub integrity_ecc_parity_shards: usize,
    pub integrity_encrypt_sidecars: bool,
    pub integrity_key_file: Option<PathBuf>,
    pub integrity_passphrase: Option<Zeroizing<String>>,
    /// Injected by `Client` from the network handshake key (system ACL). Not a KDL field.
    pub integrity_access_secret: Option<Zeroizing<Vec<u8>>>,
    pub integrity_sign_torrents: bool,
    pub integrity_signing_key_file: Option<PathBuf>,
    pub integrity_create_image: bool,
    pub integrity_require_signed_torrents: bool,
    /// Ed25519 verifying keys (32 bytes) allowed when require-signed-torrents is set.
    pub integrity_trusted_signing_keys: Vec<[u8; 32]>,
    pub tracker_block_private: bool,
    pub max_upload_slots: usize,
    pub upload_rotate_secs: u64,
    pub nat_enabled: bool,
    pub nat_map_tcp: bool,
    pub nat_map_udp: bool,
    pub nat_upnp: bool,
    pub nat_natpmp: bool,
    /// Reserved: uTP transport is not implemented; prefer `swarm-transport`.
    /// Kept in sync with [`Self::swarm_transport`] (`true` iff `Utp`).
    pub utp_enabled: bool,
    /// Peer wire security: `mtls` (default, implemented) or `mse` (reserved).
    pub swarm_security: SwarmSecurity,
    /// Peer transport: `tcp` (default, implemented) or `utp` (reserved).
    pub swarm_transport: SwarmTransport,
    pub end_game_threshold: u32,
    /// Host opt-in: BEP 11 peer exchange (default off; also forced off for private torrents).
    pub pex_enabled: bool,
    /// Host opt-in: super-seeding mode when uploading (default off).
    pub super_seed_enabled: bool,
    /// Host opt-in: fetch pieces from torrent `url-list` (default off).
    pub web_seed_enabled: bool,
    /// Host opt-in: allow `ftp://` web seeds when web seeds are enabled (default off).
    pub web_seed_ftp_enabled: bool,
    /// When true (default), seeding only advertises/serves hash-verified pieces.
    pub seed_require_verified: bool,
    pub listen_dual_stack: bool,
    pub announce_ip: Option<std::net::Ipv4Addr>,
    pub announce_ipv6: Option<std::net::Ipv6Addr>,
    pub download_rate_kbps: u64,
    pub upload_rate_kbps: u64,
    pub dht_persist: bool,
    /// DHT bootstrap nodes. Empty = public Mainline routers (`router.bittorrent.com`, …).
    pub dht_bootstrap: Vec<BootstrapNode>,
    /// How long announced peers stay in the local DHT peer store (seconds).
    pub dht_peer_announce_ttl_secs: u64,
    /// Host opt-in: enable the line RPC control plane (default off).
    pub rpc_enabled: bool,
    /// Bind address when RPC is enabled (e.g. `127.0.0.1:7600`).
    pub rpc_listen: Option<String>,
    /// Shared secret for RPC `auth <token>` (or env `TORRENTDHT_RPC_TOKEN`).
    pub rpc_auth_token: Option<Zeroizing<String>>,
    /// Allow non-loopback RPC binds (default off).
    pub rpc_allow_non_loopback: bool,
    /// Jail for `add_torrent` paths (default: `download_dir`).
    pub rpc_torrent_root: Option<PathBuf>,
    pub download_files: Vec<String>,
    pub resilience: ResilienceConfig,
    /// Secure dial TCP connect timeout (seconds).
    pub secure_connect_timeout_secs: u64,
    /// Secure dial TLS handshake timeout (seconds).
    pub secure_tls_timeout_secs: u64,
    /// Secure application handshake + credential exchange timeout (seconds).
    pub secure_handshake_timeout_secs: u64,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            listen_port: 6881,
            download_dir: PathBuf::from("./downloads"),
            state_dir: None,
            dht_enabled: true,
            peer_discovery: PeerDiscoveryMode::Hybrid,
            max_peers: 55,
            block_size: 16 * 1024,
            memory_cache_mb: 256,
            flush_workers: 2,
            flush_batch_size: 32,
            integrity_verify_blocks: true,
            integrity_ecc_enabled: true,
            integrity_ecc_data_shards: 4,
            integrity_ecc_parity_shards: 1,
            integrity_encrypt_sidecars: true,
            integrity_key_file: None,
            integrity_passphrase: None,
            integrity_access_secret: None,
            integrity_sign_torrents: false,
            integrity_signing_key_file: None,
            integrity_create_image: true,
            integrity_require_signed_torrents: false,
            integrity_trusted_signing_keys: Vec::new(),
            tracker_block_private: true,
            max_upload_slots: 8,
            upload_rotate_secs: 30,
            nat_enabled: false,
            nat_map_tcp: true,
            nat_map_udp: true,
            nat_upnp: true,
            nat_natpmp: true,
            utp_enabled: false,
            swarm_security: SwarmSecurity::Mtls,
            swarm_transport: SwarmTransport::Tcp,
            end_game_threshold: 4,
            pex_enabled: false,
            super_seed_enabled: false,
            web_seed_enabled: false,
            web_seed_ftp_enabled: false,
            seed_require_verified: true,
            listen_dual_stack: true,
            announce_ip: None,
            announce_ipv6: None,
            download_rate_kbps: 0,
            upload_rate_kbps: 0,
            dht_persist: true,
            dht_bootstrap: Vec::new(),
            dht_peer_announce_ttl_secs: 1800,
            rpc_enabled: false,
            rpc_listen: None,
            rpc_auth_token: None,
            rpc_allow_non_loopback: false,
            rpc_torrent_root: None,
            download_files: Vec::new(),
            resilience: ResilienceConfig::default(),
            secure_connect_timeout_secs: 5,
            secure_tls_timeout_secs: 10,
            secure_handshake_timeout_secs: 15,
        }
    }
}

impl Config {
    /// Locked-down defaults for embedding in a commercial host application.
    ///
    /// Optional protocol extensions (PEX, webseed/FTP, NAT, uTP, RPC, super-seed)
    /// are off. Seed upload requires verified pieces. Sidecar encryption is on
    /// (requires handshake key / passphrase / key-file at runtime).
    ///
    /// Swarm stack defaults to mTLS + TCP (`swarm-security` / `swarm-transport`).
    ///
    /// Signed torrents are required; call [`Self::with_trusted_signing_keys`] before
    /// opening a client (empty allowlist fails closed at validate / open).
    pub fn for_commercial_host(download_dir: impl Into<PathBuf>, listen_port: u16) -> Self {
        Self {
            listen_port,
            download_dir: download_dir.into(),
            dht_enabled: true,
            peer_discovery: PeerDiscoveryMode::Hybrid,
            nat_enabled: false,
            utp_enabled: false,
            swarm_security: SwarmSecurity::Mtls,
            swarm_transport: SwarmTransport::Tcp,
            pex_enabled: false,
            super_seed_enabled: false,
            web_seed_enabled: false,
            web_seed_ftp_enabled: false,
            seed_require_verified: true,
            rpc_enabled: false,
            rpc_listen: None,
            rpc_auth_token: None,
            rpc_allow_non_loopback: false,
            rpc_torrent_root: None,
            integrity_encrypt_sidecars: true,
            integrity_require_signed_torrents: true,
            tracker_block_private: true,
            ..Self::default()
        }
    }

    /// Pin Ed25519 verifying keys for `require-signed-torrents`.
    pub fn with_trusted_signing_keys(mut self, keys: Vec<[u8; 32]>) -> Self {
        self.integrity_trusted_signing_keys = keys;
        self
    }

    /// Host-owned torrent payload root (`{download_dir}/{info_hash}/…`).
    pub fn with_download_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.download_dir = dir.into();
        self
    }

    /// Host-owned state/ledger root (peers, DHT routing, resume, integrity sidecars).
    pub fn with_state_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.state_dir = Some(dir.into());
        self
    }

    /// Select swarm wire security (`mtls` implemented; `mse` reserved / fail-closed).
    pub fn with_swarm_security(mut self, security: SwarmSecurity) -> Self {
        self.swarm_security = security;
        self
    }

    /// Select swarm transport (`tcp` implemented; `utp` reserved / fail-closed).
    pub fn with_swarm_transport(mut self, transport: SwarmTransport) -> Self {
        self.swarm_transport = transport;
        self.utp_enabled = matches!(transport, SwarmTransport::Utp);
        self
    }

    /// Enable loopback RPC for a host control plane (token must be >= 32 chars).
    pub fn with_loopback_rpc(mut self, listen: impl Into<String>, auth_token: impl Into<String>) -> Self {
        self.rpc_enabled = true;
        self.rpc_listen = Some(listen.into());
        self.rpc_auth_token = Some(Zeroizing::new(auth_token.into()));
        self.rpc_allow_non_loopback = false;
        self
    }

    pub fn from_kdl_str(input: &str) -> Result<Self> {
        let doc = input
            .parse::<KdlDocument>()
            .map_err(|err| Error::Config(err.to_string()))?;
        let mut cfg = Self::default();

        if let Some(port) = node_arg_integer(&doc, "listen-port") {
            cfg.listen_port = u16_from_kdl(port, "listen-port")?;
        }
        if let Some(dir) = node_arg_string(&doc, "download-dir") {
            cfg.download_dir = PathBuf::from(dir);
        }
        if let Some(dir) = node_arg_string(&doc, "state-dir") {
            cfg.state_dir = Some(PathBuf::from(dir));
        }
        if let Some(enabled) = node_arg_bool(&doc, "dht-enabled") {
            cfg.dht_enabled = enabled;
        }
        if let Some(mode) = node_arg_string(&doc, "peer-discovery") {
            cfg.peer_discovery = PeerDiscoveryMode::parse(&mode)?;
        }
        let mut utp_flag: Option<bool> = None;
        let mut transport_explicit: Option<SwarmTransport> = None;
        if let Some(mode) = node_arg_string(&doc, "swarm-security") {
            cfg.swarm_security = SwarmSecurity::parse(&mode)?;
        }
        if let Some(mode) = node_arg_string(&doc, "swarm-transport") {
            transport_explicit = Some(SwarmTransport::parse(&mode)?);
        }
        if let Some(max_peers) = node_arg_integer(&doc, "max-peers") {
            cfg.max_peers = max_peers as usize;
        }
        if let Some(block_size) = node_arg_integer(&doc, "block-size") {
            cfg.block_size = u32_from_kdl(block_size, "block-size")?;
        }
        if let Some(cache) = node_arg_integer(&doc, "memory-cache-mb") {
            cfg.memory_cache_mb = cache as usize;
        }
        if let Some(workers) = node_arg_integer(&doc, "flush-workers") {
            cfg.flush_workers = workers as usize;
        }
        if let Some(batch) = node_arg_integer(&doc, "flush-batch-size") {
            cfg.flush_batch_size = batch as usize;
        }

        if let Some(integrity) = doc.get("integrity").and_then(|node| node.children()) {
            if let Some(value) = child_bool(integrity, "verify-blocks") {
                cfg.integrity_verify_blocks = value;
            }
            if let Some(value) = child_bool(integrity, "ecc") {
                cfg.integrity_ecc_enabled = value;
            }
            if let Some(value) = child_integer(integrity, "ecc-data-shards") {
                cfg.integrity_ecc_data_shards = value as usize;
            }
            if let Some(value) = child_integer(integrity, "ecc-parity-shards") {
                cfg.integrity_ecc_parity_shards = value as usize;
            }
            if let Some(value) = child_bool(integrity, "encrypt-sidecars") {
                cfg.integrity_encrypt_sidecars = value;
            }
            if let Some(value) = child_string(integrity, "encryption-key-file") {
                cfg.integrity_key_file = Some(PathBuf::from(value));
            }
            if let Some(value) = child_string(integrity, "passphrase") {
                cfg.integrity_passphrase = Some(Zeroizing::new(value));
            }
            if let Some(value) = child_bool(integrity, "sign-torrents") {
                cfg.integrity_sign_torrents = value;
            }
            if let Some(value) = child_string(integrity, "signing-key-file") {
                cfg.integrity_signing_key_file = Some(PathBuf::from(value));
            }
            if let Some(value) = child_bool(integrity, "create-image") {
                cfg.integrity_create_image = value;
            }
            if let Some(value) = child_bool(integrity, "require-signed-torrents") {
                cfg.integrity_require_signed_torrents = value;
            }
            cfg.integrity_trusted_signing_keys =
                parse_trusted_signing_keys(integrity)?;
        }

        if let Some(slots) = node_arg_integer(&doc, "max-upload-slots") {
            cfg.max_upload_slots = slots.max(1) as usize;
        }
        if let Some(secs) = node_arg_integer(&doc, "upload-rotate-secs") {
            cfg.upload_rotate_secs = secs.max(0) as u64;
        }
        if let Some(enabled) = node_arg_bool(&doc, "nat-enabled") {
            cfg.nat_enabled = enabled;
        }
        if let Some(enabled) = node_arg_bool(&doc, "utp-enabled") {
            utp_flag = Some(enabled);
        }
        if let Some(threshold) = node_arg_integer(&doc, "end-game-threshold") {
            cfg.end_game_threshold = threshold.max(0) as u32;
        }
        if let Some(enabled) = node_arg_bool(&doc, "pex-enabled") {
            cfg.pex_enabled = enabled;
        }
        if let Some(enabled) = node_arg_bool(&doc, "super-seed-enabled") {
            cfg.super_seed_enabled = enabled;
        }
        if let Some(enabled) = node_arg_bool(&doc, "web-seed-enabled") {
            cfg.web_seed_enabled = enabled;
        }
        if let Some(enabled) = node_arg_bool(&doc, "web-seed-ftp-enabled") {
            cfg.web_seed_ftp_enabled = enabled;
        }
        if let Some(enabled) = node_arg_bool(&doc, "seed-require-verified") {
            cfg.seed_require_verified = enabled;
        }
        if let Some(enabled) = node_arg_bool(&doc, "listen-dual-stack") {
            cfg.listen_dual_stack = enabled;
        }
        if let Some(ip) = node_arg_string(&doc, "announce-ip") {
            cfg.announce_ip = Some(
                ip.parse()
                    .map_err(|_| Error::Config(format!("invalid announce-ip: {ip}")))?,
            );
        }
        if let Some(ip) = node_arg_string(&doc, "announce-ipv6") {
            cfg.announce_ipv6 = Some(
                ip.parse()
                    .map_err(|_| Error::Config(format!("invalid announce-ipv6: {ip}")))?,
            );
        }
        if let Some(rate) = node_arg_integer(&doc, "download-rate-kbps") {
            cfg.download_rate_kbps = rate.max(0) as u64;
        }
        if let Some(rate) = node_arg_integer(&doc, "upload-rate-kbps") {
            cfg.upload_rate_kbps = rate.max(0) as u64;
        }
        if let Some(enabled) = node_arg_bool(&doc, "dht-persist") {
            cfg.dht_persist = enabled;
        }
        if let Some(ttl) = node_arg_integer(&doc, "dht-peer-announce-ttl-secs") {
            cfg.dht_peer_announce_ttl_secs = ttl.max(60) as u64;
        }
        if let Some(bootstrap) = doc.get("dht-bootstrap").and_then(|node| node.children()) {
            cfg.dht_bootstrap.clear();
            for entry in bootstrap.nodes() {
                if entry.name().value() != "node" {
                    continue;
                }
                let host = entry
                    .entries()
                    .first()
                    .and_then(|e| e.value().as_string())
                    .ok_or_else(|| Error::Config("dht-bootstrap node missing host".into()))?;
                let port = entry
                    .entries()
                    .get(1)
                    .and_then(|e| e.value().as_integer())
                    .ok_or_else(|| {
                        Error::Config("dht-bootstrap node missing port integer".into())
                    })?;
                cfg.dht_bootstrap.push(BootstrapNode {
                    host: host.to_string(),
                    port: u16_from_kdl(port, "dht-bootstrap node port")?,
                });
            }
        }
        if let Some(enabled) = node_arg_bool(&doc, "rpc-enabled") {
            cfg.rpc_enabled = enabled;
        }
        if let Some(addr) = node_arg_string(&doc, "rpc-listen") {
            cfg.rpc_listen = Some(addr);
        }
        if let Some(token) = node_arg_string(&doc, "rpc-auth-token") {
            cfg.rpc_auth_token = Some(Zeroizing::new(token));
        }
        if let Some(enabled) = node_arg_bool(&doc, "rpc-allow-non-loopback") {
            cfg.rpc_allow_non_loopback = enabled;
        }
        if let Some(path) = node_arg_string(&doc, "rpc-torrent-root") {
            cfg.rpc_torrent_root = Some(PathBuf::from(path));
        }
        if let Some(files) = doc.get("download-files").and_then(|node| node.children()) {
            cfg.download_files.clear();
            for entry in files.nodes() {
                if entry.name().value() != "file" {
                    continue;
                }
                if let Some(path) = entry.entries().first().and_then(|e| e.value().as_string()) {
                    cfg.download_files.push(path.to_string());
                }
            }
        }

        if let Some(nat) = doc.get("nat").and_then(|node| node.children()) {
            if let Some(value) = child_bool(nat, "map-tcp") {
                cfg.nat_map_tcp = value;
            }
            if let Some(value) = child_bool(nat, "map-udp") {
                cfg.nat_map_udp = value;
            }
            if let Some(value) = child_bool(nat, "upnp") {
                cfg.nat_upnp = value;
            }
            if let Some(value) = child_bool(nat, "natpmp") {
                cfg.nat_natpmp = value;
            }
        }

        if let Some(value) = node_arg_bool(&doc, "tracker-block-private") {
            cfg.tracker_block_private = value;
        }

        if let Some(secure) = doc.get("secure").and_then(|node| node.children()) {
            if let Some(value) = child_integer(secure, "connect-timeout-secs") {
                cfg.secure_connect_timeout_secs = value.max(1) as u64;
            }
            if let Some(value) = child_integer(secure, "tls-timeout-secs") {
                cfg.secure_tls_timeout_secs = value.max(1) as u64;
            }
            if let Some(value) = child_integer(secure, "handshake-timeout-secs") {
                cfg.secure_handshake_timeout_secs = value.max(1) as u64;
            }
        }
        if let Some(value) = node_arg_integer(&doc, "secure-connect-timeout-secs") {
            cfg.secure_connect_timeout_secs = value.max(1) as u64;
        }
        if let Some(value) = node_arg_integer(&doc, "secure-tls-timeout-secs") {
            cfg.secure_tls_timeout_secs = value.max(1) as u64;
        }
        if let Some(value) = node_arg_integer(&doc, "secure-handshake-timeout-secs") {
            cfg.secure_handshake_timeout_secs = value.max(1) as u64;
        }

        if let Some(resilience) = doc.get("resilience").and_then(|node| node.children()) {
            if let Some(value) = child_integer(resilience, "heal-interval-secs") {
                cfg.resilience.heal_interval_secs = value.max(1) as u64;
            }
            if let Some(value) = child_integer(resilience, "stale-peer-secs") {
                cfg.resilience.stale_peer_secs = value.max(1) as u64;
            }
            if let Some(value) = child_integer(resilience, "stalled-download-secs") {
                cfg.resilience.stalled_download_secs = value.max(1) as u64;
            }
            if let Some(value) = child_integer(resilience, "peer-ban-secs") {
                cfg.resilience.peer_ban_secs = value.max(1) as u64;
            }
            if let Some(value) = child_integer(resilience, "checkpoint-interval-secs") {
                cfg.resilience.checkpoint_interval_secs = value.max(1) as u64;
            }
            if let Some(value) = child_integer(resilience, "max-peer-failures") {
                cfg.resilience.max_peer_failures = value.max(1) as u32;
            }
            if let Some(value) = child_integer(resilience, "run-retry-initial-secs") {
                cfg.resilience.run_retry_initial_secs = value.max(1) as u64;
            }
            if let Some(value) = child_integer(resilience, "run-retry-max-secs") {
                cfg.resilience.run_retry_max_secs = value.max(1) as u64;
            }
        }

        crate::rpc::validate_rpc_config(&cfg)?;
        crate::torrent::validate_signed_torrent_config(&cfg)?;
        reconcile_swarm_transport(&mut cfg, utp_flag, transport_explicit)?;
        crate::swarm::validate_swarm_stack(&cfg)?;
        Ok(cfg)
    }

    pub fn from_kdl_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let data = std::fs::read_to_string(path)?;
        Self::from_kdl_str(&data)
    }

    pub fn memory_cache_bytes(&self) -> usize {
        self.memory_cache_mb.saturating_mul(1024 * 1024)
    }
}

fn node_arg_integer(doc: &KdlDocument, name: &str) -> Option<i128> {
    doc.get(name)
        .and_then(|node| node.entries().first())
        .and_then(|entry| entry.value().as_integer())
}

fn node_arg_string(doc: &KdlDocument, name: &str) -> Option<String> {
    doc.get(name)
        .and_then(|node| node.entries().first())
        .and_then(|entry| entry.value().as_string())
        .map(str::to_string)
}

fn node_arg_bool(doc: &KdlDocument, name: &str) -> Option<bool> {
    doc.get(name)
        .and_then(|node| node.entries().first())
        .and_then(|entry| entry.value().as_bool())
}

fn child_bool(doc: &KdlDocument, name: &str) -> Option<bool> {
    doc.get(name)
        .and_then(|node| node.entries().first())
        .and_then(|entry| entry.value().as_bool())
}

fn child_integer(doc: &KdlDocument, name: &str) -> Option<i128> {
    doc.get(name)
        .and_then(|node| node.entries().first())
        .and_then(|entry| entry.value().as_integer())
}

fn child_string(doc: &KdlDocument, name: &str) -> Option<String> {
    doc.get(name)
        .and_then(|node| node.entries().first())
        .and_then(|entry| entry.value().as_string())
        .map(str::to_string)
}

fn u16_from_kdl(value: i128, field: &str) -> Result<u16> {
    if !(0..=u16::MAX as i128).contains(&value) {
        return Err(Error::Config(format!("{field} out of range for u16")));
    }
    Ok(value as u16)
}

fn u32_from_kdl(value: i128, field: &str) -> Result<u32> {
    if !(0..=u32::MAX as i128).contains(&value) {
        return Err(Error::Config(format!("{field} out of range for u32")));
    }
    Ok(value as u32)
}

/// Merge legacy `utp-enabled` with `swarm-transport` and keep `utp_enabled` mirrored.
fn reconcile_swarm_transport(
    cfg: &mut Config,
    utp_flag: Option<bool>,
    transport_explicit: Option<SwarmTransport>,
) -> Result<()> {
    match (utp_flag, transport_explicit) {
        (None, None) => {
            cfg.utp_enabled = matches!(cfg.swarm_transport, SwarmTransport::Utp);
        }
        (Some(true), None) => {
            cfg.swarm_transport = SwarmTransport::Utp;
            cfg.utp_enabled = true;
        }
        (Some(false), None) => {
            cfg.swarm_transport = SwarmTransport::Tcp;
            cfg.utp_enabled = false;
        }
        (None, Some(transport)) => {
            cfg.swarm_transport = transport;
            cfg.utp_enabled = matches!(transport, SwarmTransport::Utp);
        }
        (Some(want_utp), Some(transport)) => {
            let transport_is_utp = matches!(transport, SwarmTransport::Utp);
            if want_utp != transport_is_utp {
                return Err(Error::Config(format!(
                    "utp-enabled #{want_utp} conflicts with swarm-transport \"{}\"",
                    transport.as_str()
                )));
            }
            cfg.swarm_transport = transport;
            cfg.utp_enabled = want_utp;
        }
    }
    Ok(())
}

fn parse_trusted_signing_keys(integrity: &KdlDocument) -> Result<Vec<[u8; 32]>> {
    let mut keys = Vec::new();
    for node in integrity.nodes() {
        if node.name().value() != "trusted-signing-key" {
            continue;
        }
        let Some(hex) = node
            .entries()
            .first()
            .and_then(|entry| entry.value().as_string())
        else {
            return Err(Error::Config(
                "trusted-signing-key requires a hex string argument".into(),
            ));
        };
        keys.push(parse_ed25519_pubkey_hex(hex)?);
    }
    Ok(keys)
}

fn parse_ed25519_pubkey_hex(hex: &str) -> Result<[u8; 32]> {
    let hex = hex.trim();
    if hex.len() != 64 {
        return Err(Error::Config(
            "trusted-signing-key must be 64 hex characters (32-byte Ed25519 key)".into(),
        ));
    }
    let mut out = [0u8; 32];
    for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
        let s = std::str::from_utf8(chunk).map_err(|_| {
            Error::Config("trusted-signing-key hex is not valid UTF-8".into())
        })?;
        out[i] = u8::from_str_radix(s, 16).map_err(|_| {
            Error::Config("trusted-signing-key contains non-hex characters".into())
        })?;
    }
    Ok(out)
}

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

    #[test]
    fn loads_default_kdl() {
        let cfg = Config::from_kdl_str(include_str!("../config/default.kdl"))
            .unwrap_or_else(|err| {
                panic!("config: {err}");
            });
        assert_eq!(cfg.listen_port, 6881);
        assert_eq!(cfg.peer_discovery, PeerDiscoveryMode::Hybrid);
        assert!(!cfg.utp_enabled);
        assert!(!cfg.pex_enabled);
        assert!(!cfg.web_seed_enabled);
        assert!(!cfg.web_seed_ftp_enabled);
        assert!(!cfg.rpc_enabled);
        assert!(cfg.seed_require_verified);
        assert!(cfg.dht_bootstrap.is_empty());
        assert_eq!(cfg.dht_peer_announce_ttl_secs, 1800);
        assert!(cfg.state_dir.is_none());
    }

    #[test]
    fn parses_state_dir() {
        let cfg = Config::from_kdl_str(
            r#"
listen-port 6881
download-dir "./downloads"
state-dir "./var/torrentdht"
"#,
        )
        .expect("config");
        assert_eq!(
            cfg.state_dir.as_deref(),
            Some(std::path::Path::new("./var/torrentdht"))
        );
    }

    #[test]
    fn parses_dht_bootstrap_nodes() {
        let cfg = Config::from_kdl_str(
            r#"
listen-port 6881
download-dir "./downloads"
dht-bootstrap {
    node "dht.example.internal" 6881
    node "192.0.2.10" 6882
}
"#,
        )
        .expect("config");
        assert_eq!(cfg.dht_bootstrap.len(), 2);
        assert_eq!(cfg.dht_bootstrap[0].host, "dht.example.internal");
        assert_eq!(cfg.dht_bootstrap[0].port, 6881);
        assert_eq!(cfg.dht_bootstrap[1].host, "192.0.2.10");
        assert_eq!(cfg.dht_bootstrap[1].port, 6882);
    }

    #[test]
    fn rejects_utp_with_mtls_default() {
        let err = Config::from_kdl_str("utp-enabled #true\n").expect_err("utp");
        assert!(
            err.to_string().contains("TCP-only")
                || err.to_string().contains("mtls")
                || err.to_string().contains("not implemented")
        );
    }

    #[test]
    fn rejects_swarm_transport_utp_with_mtls() {
        let err = Config::from_kdl_str("swarm-transport \"utp\"\n").expect_err("utp");
        assert!(err.to_string().contains("TCP-only") || err.to_string().contains("mtls"));
    }

    #[test]
    fn accepts_mse_with_utp() {
        let cfg = Config::from_kdl_str(
            r#"
listen-port 6881
download-dir "./downloads"
swarm-security "mse"
swarm-transport "utp"
"#,
        )
        .expect("mse+utp");
        assert_eq!(cfg.swarm_security, SwarmSecurity::Mse);
        assert_eq!(cfg.swarm_transport, SwarmTransport::Utp);
        assert!(cfg.utp_enabled);
    }

    #[test]
    fn accepts_swarm_security_mse_with_tcp() {
        let cfg = Config::from_kdl_str(
            r#"
listen-port 6881
download-dir "./downloads"
swarm-security "mse"
swarm-transport "tcp"
"#,
        )
        .expect("mse+tcp");
        assert_eq!(cfg.swarm_security, SwarmSecurity::Mse);
        assert_eq!(cfg.swarm_transport, SwarmTransport::Tcp);
    }

    #[test]
    fn parses_default_swarm_stack() {
        let cfg = Config::from_kdl_str(
            r#"
listen-port 6881
download-dir "./downloads"
swarm-security "mtls"
swarm-transport "tcp"
"#,
        )
        .expect("config");
        assert_eq!(cfg.swarm_security, SwarmSecurity::Mtls);
        assert_eq!(cfg.swarm_transport, SwarmTransport::Tcp);
        assert!(!cfg.utp_enabled);
    }

    #[test]
    fn rejects_utp_flag_transport_conflict() {
        let err = Config::from_kdl_str(
            r#"
utp-enabled #true
swarm-transport "tcp"
"#,
        )
        .expect_err("conflict");
        assert!(err.to_string().contains("conflicts"));
    }

    #[test]
    fn commercial_host_profile_is_locked_down() {
        let cfg = Config::for_commercial_host("./data", 6881).with_trusted_signing_keys(vec![[9u8; 32]]);
        assert!(!cfg.rpc_enabled);
        assert!(!cfg.pex_enabled);
        assert!(!cfg.web_seed_enabled);
        assert!(!cfg.web_seed_ftp_enabled);
        assert!(!cfg.nat_enabled);
        assert!(cfg.seed_require_verified);
        assert!(cfg.integrity_encrypt_sidecars);
        assert!(cfg.integrity_require_signed_torrents);
        assert!(!cfg.integrity_trusted_signing_keys.is_empty());
        crate::torrent::validate_signed_torrent_config(&cfg).expect("keys present");
        let with_rpc = cfg.with_loopback_rpc(
            "127.0.0.1:7600",
            "a-commercial-grade-rpc-token-32b",
        );
        assert!(with_rpc.rpc_enabled);
        assert!(!with_rpc.rpc_allow_non_loopback);
    }

    #[test]
    fn require_signed_without_keys_fails_kdl_validate() {
        let err = Config::from_kdl_str(
            r#"
listen-port 6881
download-dir "./downloads"
integrity {
    require-signed-torrents #true
}
"#,
        );
        assert!(err.is_err());
    }

    #[test]
    fn parses_peer_discovery_mode() {
        assert_eq!(
            PeerDiscoveryMode::parse("hybrid").expect("hybrid"),
            PeerDiscoveryMode::Hybrid
        );
        assert_eq!(
            PeerDiscoveryMode::parse("dht-only").expect("dht"),
            PeerDiscoveryMode::Dht
        );
        assert_eq!(
            PeerDiscoveryMode::parse("tracker").expect("tracker"),
            PeerDiscoveryMode::Tracker
        );
    }

    #[test]
    fn loads_inline_kdl() {
        let cfg = Config::from_kdl_str(
            r#"
listen-port 6881
download-dir "./downloads"
dht-enabled #true
max-peers 55
block-size 16384
memory-cache-mb 256
flush-workers 2
flush-batch-size 32
"#,
        )
        .expect("inline config");
        assert_eq!(cfg.listen_port, 6881);
    }
}