irontide-session 0.165.0

BitTorrent session management: peers, torrents, and piece selection
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;

use bitflags::bitflags;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use tokio::sync::oneshot;

use irontide_storage::Bitfield;
use irontide_wire::ExtHandshake;

use crate::choker::{ChokingAlgorithm, SeedChokingAlgorithm};

/// Configurable parameters for a torrent session.
#[derive(Debug, Clone)]
pub struct TorrentConfig {
    /// TCP listen port for incoming peer connections.
    pub listen_port: u16,
    /// Maximum number of peer connections per torrent.
    pub max_peers: usize,
    /// Number of outstanding piece requests to maintain per peer.
    pub target_request_queue: usize,
    /// Directory where downloaded files are stored.
    pub download_dir: PathBuf,
    /// Enable DHT for peer discovery.
    pub enable_dht: bool,
    /// Enable Peer Exchange (BEP 11) for peer discovery.
    pub enable_pex: bool,
    /// Enable Fast Extension (BEP 6) for reject/suggest/allowed-fast messages.
    pub enable_fast: bool,
    /// Stop seeding after reaching this upload/download ratio (None = unlimited).
    pub seed_ratio_limit: Option<f64>,
    /// In end game mode, cancel duplicate requests when a piece completes.
    pub strict_end_game: bool,
    /// Upload rate limit in bytes/sec (0 = unlimited).
    pub upload_rate_limit: u64,
    /// Download rate limit in bytes/sec (0 = unlimited).
    pub download_rate_limit: u64,
    /// Connection encryption mode (MSE/PE).
    pub encryption_mode: irontide_wire::mse::EncryptionMode,
    /// Enable uTP (micro Transport Protocol) for peer connections.
    pub enable_utp: bool,
    /// Enable HTTP/web seeding (BEP 19, BEP 17).
    pub enable_web_seed: bool,
    /// Enable BEP 55 holepunch extension for NAT traversal.
    pub enable_holepunch: bool,
    /// Enable BEP 40 canonical peer priority for connection eviction.
    pub enable_bep40_eviction: bool,
    /// Maximum concurrent web seed connections.
    pub max_web_seeds: usize,
    /// BEP 16: super seeding mode — reveal pieces one-per-peer for maximum diversity.
    pub super_seeding: bool,
    /// BEP 21: advertise upload-only status via extension handshake when seeding.
    pub upload_only_announce: bool,
    /// Number of concurrent piece verifications during torrent checking.
    pub hashing_threads: usize,
    /// Enable sequential (in-order) piece downloading.
    pub sequential_download: bool,
    /// Completed piece count below which the picker uses random selection to promote diversity.
    pub initial_picker_threshold: u32,
    /// Seconds below which a fast peer downloads a whole piece; if under this, picker grants
    /// exclusive assignment (no block splitting).
    pub whole_pieces_threshold: u32,
    /// Seconds without data from a peer before marking it as snubbed.
    pub snub_timeout_secs: u32,
    /// Number of pieces ahead of the streaming cursor to prioritize.
    pub readahead_pieces: u32,
    /// When true, escalate streaming piece requests that exceed the mean RTT.
    pub streaming_timeout_escalation: bool,
    /// Maximum concurrent file stream readers per torrent.
    pub max_concurrent_stream_reads: usize,
    /// Proxy configuration for outbound peer connections.
    pub proxy: crate::proxy::ProxyConfig,
    /// Anonymous mode: suppress client identity in peer handshakes.
    pub anonymous_mode: bool,
    /// Share mode: relay pieces in memory without writing to disk.
    /// Requires `enable_fast` for RejectRequest when evicting pieces.
    pub share_mode: bool,
    /// Whether this torrent should use I2P for peer connections.
    pub enable_i2p: bool,
    /// Whether to allow mixing I2P and clearnet peers.
    pub allow_i2p_mixed: bool,
    /// SSL listen port for SSL torrent connections (0 = disabled).
    pub ssl_listen_port: u16,
    /// Algorithm for ranking peers during seed-mode choking.
    pub seed_choking_algorithm: SeedChokingAlgorithm,
    /// Algorithm for determining the number of unchoke slots.
    pub choking_algorithm: ChokingAlgorithm,
    /// Prefer grouping piece requests within the same 4 MiB disk extent.
    pub piece_extent_affinity: bool,
    /// Enable sending SuggestPiece messages for cached pieces.
    pub suggest_mode: bool,
    /// Maximum number of pieces to suggest per peer.
    pub max_suggest_pieces: usize,
    /// Delay (ms) before announcing Have for a piece still being written to disk (0 = disabled).
    pub predictive_piece_announce_ms: u64,
    /// Mixed-mode TCP/uTP bandwidth allocation algorithm.
    pub mixed_mode_algorithm: crate::rate_limiter::MixedModeAlgorithm,
    /// Enable automatic sequential mode switching on partial-piece explosion.
    pub auto_sequential: bool,
    /// Storage allocation mode for disk I/O.
    pub storage_mode: irontide_core::StorageMode,
    /// Override pre-allocation strategy. `None` = derive from `storage_mode`.
    pub preallocate_mode: Option<irontide_storage::PreallocateMode>,
    /// Block request timeout in seconds before re-issuing (0 = disabled).
    pub block_request_timeout_secs: u32,
    /// Enable Local Service Discovery (BEP 14) for this torrent.
    pub enable_lsd: bool,
    /// Force all connections through the configured proxy.
    pub force_proxy: bool,
    /// Steal blocks from peers this many times slower than the requesting peer (0.0 = disabled).
    pub steal_threshold_ratio: f64,
    /// M149: Steal threshold multiplier when >90% complete.
    pub steal_threshold_endgame: f64,
    /// M133: Seconds without any wire message before disconnecting a peer (0 = disabled).
    pub peer_read_timeout_secs: u64,
    /// M133: Seconds before a stalled outgoing write disconnects a peer (0 = disabled).
    pub peer_write_timeout_secs: u64,
    /// M137: Seconds without Piece data before disconnecting a peer (0 = disabled).
    pub data_contribution_timeout_secs: u64,
    /// M138: Maximum peers to evict per choke rotation tick (0 = disabled).
    pub choke_rotation_max_evictions: u32,
    /// M138: Maximum concurrent outbound peer connections.
    pub max_concurrent_connects: u16,
    /// M147: Seconds without TCP SYN-ACK before soft reap disconnects.
    pub connect_soft_timeout: u64,
    /// URL security configuration for SSRF mitigation and IDNA checking.
    pub url_security: crate::url_guard::UrlSecurityConfig,
    /// Timeout in seconds for outbound TCP peer connections (0 = OS default).
    pub peer_connect_timeout: u64,
    /// DSCP (Differentiated Services Code Point) value for peer traffic sockets.
    pub peer_dscp: u8,
    /// Fixed per-peer request queue depth for the lifetime of the connection.
    pub initial_queue_depth: usize,
    /// Maximum per-peer request queue depth.
    pub max_request_queue_depth: usize,
    /// Deprecated — unused in the fixed-depth pipeline model. Retained for API
    /// compatibility; was formerly used to scale BDP-based queue depth.
    pub request_queue_time: f64,
    /// Maximum BEP 9 metadata size in bytes accepted from peers.
    pub max_metadata_size: u64,
    /// Maximum wire protocol message size in bytes for the codec.
    pub max_message_size: usize,
    /// Maximum accepted piece length when adding a torrent.
    pub max_piece_length: u64,
    /// Maximum outstanding incoming requests per peer.
    pub max_outstanding_requests: usize,
    /// Maximum number of pieces simultaneously in-flight (downloaded but not
    /// yet verified).
    pub max_in_flight_pieces: usize,
    /// M149: Minimum per-peer pipeline depth (requests in flight).
    pub min_pipeline_depth: u32,
    /// M149: Maximum per-peer pipeline depth (requests in flight).
    pub max_pipeline_depth: u32,
    /// M149: Seconds of data to buffer in the pipeline per peer.
    pub target_buffer_secs: f64,
    /// M103: Enable block-level stealing for partially-downloaded pieces.
    pub use_block_stealing: bool,
    /// M132: Seconds between steal-queue population scans (0 = disabled).
    pub steal_stale_piece_secs: u64,
    /// M104: Fixed per-peer pipeline depth (concurrent requests per peer).
    pub fixed_pipeline_depth: usize,
    /// M120: Lock timing warning threshold in milliseconds (0 = disabled).
    pub lock_warn_threshold_ms: u64,
    /// M127: Enable direct I/O for filesystem storage (O_DIRECT / F_NOCACHE).
    pub filesystem_direct_io: bool,
}

impl Default for TorrentConfig {
    fn default() -> Self {
        Self {
            listen_port: 6881,
            max_peers: 128,
            target_request_queue: 5,
            download_dir: PathBuf::from("."),
            enable_dht: true,
            enable_pex: true,
            enable_fast: false,
            seed_ratio_limit: None,
            strict_end_game: true,
            upload_rate_limit: 0,
            download_rate_limit: 0,
            encryption_mode: irontide_wire::mse::EncryptionMode::Disabled,
            enable_utp: true,
            enable_web_seed: true,
            enable_holepunch: true,
            enable_bep40_eviction: true,
            max_web_seeds: 4,
            super_seeding: false,
            upload_only_announce: true,
            hashing_threads: {
                let cores = std::thread::available_parallelism()
                    .map(|n| n.get())
                    .unwrap_or(4);
                (cores / 4).clamp(2, 8)
            },
            sequential_download: false,
            initial_picker_threshold: 4,
            whole_pieces_threshold: 20,
            snub_timeout_secs: 15,
            readahead_pieces: 8,
            streaming_timeout_escalation: true,
            max_concurrent_stream_reads: 8,
            proxy: crate::proxy::ProxyConfig::default(),
            anonymous_mode: false,
            share_mode: false,
            enable_i2p: false,
            allow_i2p_mixed: false,
            ssl_listen_port: 0,
            seed_choking_algorithm: SeedChokingAlgorithm::FastestUpload,
            choking_algorithm: ChokingAlgorithm::FixedSlots,
            piece_extent_affinity: true,
            suggest_mode: false,
            max_suggest_pieces: 10,
            predictive_piece_announce_ms: 0,
            mixed_mode_algorithm: crate::rate_limiter::MixedModeAlgorithm::PeerProportional,
            auto_sequential: true,
            storage_mode: irontide_core::StorageMode::Auto,
            preallocate_mode: None,
            block_request_timeout_secs: 60,
            enable_lsd: true,
            force_proxy: false,
            steal_threshold_ratio: 10.0,
            steal_threshold_endgame: 3.0,
            min_pipeline_depth: 16,
            max_pipeline_depth: 512,
            target_buffer_secs: 2.0,
            peer_read_timeout_secs: 10,
            peer_write_timeout_secs: 10,
            data_contribution_timeout_secs: 0,
            choke_rotation_max_evictions: 0,
            max_concurrent_connects: 128,
            connect_soft_timeout: 3,
            url_security: crate::url_guard::UrlSecurityConfig::default(),
            peer_connect_timeout: 10,
            peer_dscp: 0x08,
            initial_queue_depth: 128,
            max_request_queue_depth: 250,
            request_queue_time: 3.0,
            max_metadata_size: 4 * 1024 * 1024,
            max_message_size: 16 * 1024 * 1024,
            max_piece_length: 32 * 1024 * 1024,
            max_outstanding_requests: 500,
            max_in_flight_pieces: 512,
            use_block_stealing: true,
            steal_stale_piece_secs: 2,
            fixed_pipeline_depth: 128,
            lock_warn_threshold_ms: 50,
            filesystem_direct_io: false,
        }
    }
}

impl From<&crate::settings::Settings> for TorrentConfig {
    fn from(s: &crate::settings::Settings) -> Self {
        Self {
            listen_port: 0, // Each torrent gets a random port (matches make_torrent_config)
            max_peers: s.max_peers_per_torrent,
            target_request_queue: 5,
            download_dir: s.download_dir.clone(),
            enable_dht: s.enable_dht,
            enable_pex: s.enable_pex,
            enable_fast: s.enable_fast_extension,
            seed_ratio_limit: s.seed_ratio_limit,
            strict_end_game: s.strict_end_game,
            upload_rate_limit: s.upload_rate_limit,
            download_rate_limit: s.download_rate_limit,
            encryption_mode: s.encryption_mode,
            enable_utp: s.enable_utp,
            enable_web_seed: s.enable_web_seed,
            enable_holepunch: s.enable_holepunch,
            enable_bep40_eviction: s.enable_bep40_eviction,
            max_web_seeds: s.max_web_seeds,
            super_seeding: s.default_super_seeding,
            upload_only_announce: s.upload_only_announce,
            hashing_threads: s.hashing_threads,
            sequential_download: false,
            initial_picker_threshold: s.initial_picker_threshold,
            whole_pieces_threshold: s.whole_pieces_threshold,
            snub_timeout_secs: s.snub_timeout_secs,
            readahead_pieces: s.readahead_pieces,
            streaming_timeout_escalation: s.streaming_timeout_escalation,
            max_concurrent_stream_reads: s.max_concurrent_stream_reads,
            proxy: s.proxy.clone(),
            anonymous_mode: s.anonymous_mode,
            share_mode: s.default_share_mode,
            enable_i2p: s.enable_i2p,
            allow_i2p_mixed: s.allow_i2p_mixed,
            ssl_listen_port: s.ssl_listen_port,
            seed_choking_algorithm: s.seed_choking_algorithm,
            choking_algorithm: s.choking_algorithm,
            piece_extent_affinity: s.piece_extent_affinity,
            suggest_mode: s.suggest_mode,
            max_suggest_pieces: s.max_suggest_pieces,
            predictive_piece_announce_ms: s.predictive_piece_announce_ms,
            mixed_mode_algorithm: s.mixed_mode_algorithm,
            auto_sequential: s.auto_sequential,
            storage_mode: s.storage_mode,
            preallocate_mode: s.preallocate_mode,
            block_request_timeout_secs: s.block_request_timeout_secs,
            enable_lsd: s.enable_lsd,
            force_proxy: s.force_proxy,
            steal_threshold_ratio: s.steal_threshold_ratio,
            steal_threshold_endgame: s.steal_threshold_endgame,
            min_pipeline_depth: s.min_pipeline_depth,
            max_pipeline_depth: s.max_pipeline_depth,
            target_buffer_secs: s.target_buffer_secs,
            peer_read_timeout_secs: s.peer_read_timeout_secs,
            peer_write_timeout_secs: s.peer_write_timeout_secs,
            data_contribution_timeout_secs: s.data_contribution_timeout_secs,
            choke_rotation_max_evictions: s.choke_rotation_max_evictions,
            max_concurrent_connects: s.max_concurrent_connects,
            connect_soft_timeout: s.connect_soft_timeout,
            url_security: crate::url_guard::UrlSecurityConfig::from(s),
            peer_connect_timeout: s.peer_connect_timeout,
            peer_dscp: s.peer_dscp,
            initial_queue_depth: s.initial_queue_depth,
            max_request_queue_depth: s.max_request_queue_depth,
            request_queue_time: s.request_queue_time,
            max_metadata_size: s.max_metadata_size,
            max_message_size: s.max_message_size,
            max_piece_length: s.max_piece_length,
            max_outstanding_requests: s.max_outstanding_requests,
            max_in_flight_pieces: s.max_in_flight_pieces,
            use_block_stealing: s.use_block_stealing,
            steal_stale_piece_secs: s.steal_stale_piece_secs,
            fixed_pipeline_depth: s.fixed_pipeline_depth,
            lock_warn_threshold_ms: s.lock_warn_threshold_ms,
            filesystem_direct_io: s.filesystem_direct_io,
        }
    }
}

/// Current state of a torrent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TorrentState {
    /// Waiting for peers to send torrent metadata via BEP 9.
    FetchingMetadata,
    /// Verifying existing data on disk against piece hashes.
    Checking,
    /// Actively downloading pieces from peers.
    Downloading,
    /// All pieces downloaded, awaiting transition to seeding.
    Complete,
    /// Upload-only: all pieces verified, serving to other peers.
    Seeding,
    /// Manually paused by the user. No peer connections maintained.
    Paused,
    /// Removed from the session. Terminal state.
    Stopped,
    /// Share mode: relay pieces in memory without writing to disk.
    Sharing,
}

/// Aggregate statistics for a torrent.
#[derive(Debug, Clone, Serialize)]
pub struct TorrentStats {
    // ── Original fields (unchanged) ──
    /// Current torrent state.
    pub state: TorrentState,
    /// Total bytes downloaded (payload only).
    pub downloaded: u64,
    /// Total bytes uploaded (payload only).
    pub uploaded: u64,
    /// Number of pieces that have been verified.
    pub pieces_have: u32,
    /// Total number of pieces in the torrent.
    pub pieces_total: u32,
    /// Number of currently connected peers.
    pub peers_connected: usize,
    /// Number of known peers (connected + available).
    pub peers_available: usize,
    /// Progress of piece checking (0.0–1.0), meaningful when state is `Checking`.
    pub checking_progress: f32,
    /// Number of connected peers broken down by discovery source.
    pub peers_by_source: HashMap<crate::peer_state::PeerSource, usize>,

    // ── Identity ──
    /// Info hashes (v1 SHA-1 and/or v2 SHA-256) for this torrent.
    pub info_hashes: irontide_core::InfoHashes,
    /// Display name from the torrent metadata.
    pub name: String,

    // ── State flags ──
    /// Whether metadata has been received (always true for .torrent adds).
    pub has_metadata: bool,
    /// Whether we have all pieces and are seeding.
    pub is_seeding: bool,
    /// Whether all wanted pieces are downloaded (may differ from is_seeding with file priorities).
    pub is_finished: bool,
    /// Whether the torrent is paused.
    pub is_paused: bool,
    /// Whether the torrent is auto-managed by the session queuing system.
    pub auto_managed: bool,
    /// Whether sequential piece downloading is enabled.
    pub sequential_download: bool,
    /// Whether BEP 16 super seeding mode is active.
    pub super_seeding: bool,
    /// Whether the user explicitly toggled seed-only mode (M159).
    ///
    /// Distinct from `is_seeding` which reflects download completion.
    /// When `true`, the engine stops scheduling new block requests but
    /// continues to serve uploads to interested peers.
    #[serde(default)]
    pub user_seed_mode: bool,
    /// Whether we have accepted any incoming peer connections.
    pub has_incoming: bool,
    /// Whether resume data needs to be saved.
    pub need_save_resume: bool,
    /// Whether a storage move operation is in progress.
    pub moving_storage: bool,

    // ── Progress ──
    /// Download progress as a fraction (0.0–1.0).
    pub progress: f32,
    /// Download progress in parts per million (0–1_000_000).
    pub progress_ppm: u32,
    /// Total bytes of verified (downloaded and hash-checked) data.
    pub total_done: u64,
    /// Total size of the torrent in bytes.
    pub total: u64,
    /// Total bytes of wanted data that have been verified.
    pub total_wanted_done: u64,
    /// Total bytes of wanted data (respecting file priorities).
    pub total_wanted: u64,
    /// Block (sub-piece request) size in bytes.
    pub block_size: u32,

    // ── Transfer (session counters) ──
    /// Total bytes downloaded this session (including protocol overhead).
    pub total_download: u64,
    /// Total bytes uploaded this session (including protocol overhead).
    pub total_upload: u64,
    /// Total payload bytes downloaded this session.
    pub total_payload_download: u64,
    /// Total payload bytes uploaded this session.
    pub total_payload_upload: u64,
    /// Total bytes of data that failed hash check.
    pub total_failed_bytes: u64,
    /// Total bytes of redundant (duplicate) data received.
    pub total_redundant_bytes: u64,

    // ── Transfer (all-time, persisted) ──
    /// All-time total bytes downloaded (persisted across sessions via resume data).
    pub all_time_download: u64,
    /// All-time total bytes uploaded (persisted across sessions via resume data).
    pub all_time_upload: u64,

    // ── Rates ──
    /// Current download rate in bytes/sec (including protocol overhead).
    pub download_rate: u64,
    /// Current upload rate in bytes/sec (including protocol overhead).
    pub upload_rate: u64,
    /// Current payload download rate in bytes/sec.
    pub download_payload_rate: u64,
    /// Current payload upload rate in bytes/sec.
    pub upload_payload_rate: u64,

    // ── Connection details ──
    /// Number of peers connected (including half-open).
    pub num_peers: usize,
    /// Number of connected peers that are seeds.
    pub num_seeds: usize,
    /// Number of complete copies known from tracker scrape (-1 = unknown).
    pub num_complete: i32,
    /// Number of incomplete copies known from tracker scrape (-1 = unknown).
    pub num_incomplete: i32,
    /// Total number of seeds across all trackers.
    pub list_seeds: usize,
    /// Total number of peers across all trackers.
    pub list_peers: usize,
    /// Number of peers available to connect to (not yet connected).
    pub connect_candidates: usize,
    /// Number of active peer connections (TCP + uTP).
    pub num_connections: usize,
    /// Number of unchoked peers we are uploading to.
    pub num_uploads: usize,
    /// M133: Total unique peer connection attempts during this session.
    pub unique_peers_attempted: u64,
    /// M137: Peer pipeline lifecycle snapshot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pipeline: Option<crate::peer_states::PeerPipelineSnapshot>,
    /// M138: Total peers evicted by proactive choke rotation.
    pub choke_rotations: u64,
    /// M149: Total number of piece-level steals performed.
    pub piece_steals: u64,

    // ── Limits ──
    /// Maximum number of connections for this torrent.
    pub connections_limit: usize,
    /// Maximum number of unchoke slots for this torrent.
    pub uploads_limit: usize,

    // ── Distributed copies ──
    /// Number of full distributed copies available in the swarm.
    pub distributed_full_copies: u32,
    /// Fractional part of distributed copies (0–999).
    pub distributed_fraction: u32,
    /// Distributed copies as a float (full + fraction/1000).
    pub distributed_copies: f32,

    // ── Tracker ──
    /// URL of the tracker we most recently announced to.
    pub current_tracker: String,
    /// Whether we are currently announcing to any tracker.
    pub announcing_to_trackers: bool,
    /// Whether we are currently announcing to LSD (Local Service Discovery).
    pub announcing_to_lsd: bool,
    /// Whether we are currently announcing to DHT.
    pub announcing_to_dht: bool,

    // ── Timestamps (POSIX seconds) ──
    /// Time when the torrent was added to the session.
    pub added_time: i64,
    /// Time when the torrent completed downloading (0 = not completed).
    pub completed_time: i64,
    /// Last time a complete copy was seen in the swarm (0 = never).
    pub last_seen_complete: i64,
    /// Time of last upload activity (0 = never).
    pub last_upload: i64,
    /// Time of last download activity (0 = never).
    pub last_download: i64,

    // ── Durations (cumulative seconds) ──
    /// Total seconds the torrent has been active (downloading or seeding).
    pub active_duration: i64,
    /// Total seconds the torrent has been in finished state.
    pub finished_duration: i64,
    /// Total seconds the torrent has been seeding.
    pub seeding_duration: i64,

    // ── Storage ──
    /// Current save path for the torrent data.
    pub save_path: String,

    // ── Queue ──
    /// Position in the session queue (-1 = not queued).
    pub queue_position: i32,

    // ── Error ──
    /// Human-readable error message (empty = no error).
    pub error: String,
    /// Index of the file that caused the error (-1 = not file-specific).
    pub error_file: i32,
}

impl Default for TorrentStats {
    fn default() -> Self {
        Self {
            // Original fields
            state: TorrentState::Paused,
            downloaded: 0,
            uploaded: 0,
            pieces_have: 0,
            pieces_total: 0,
            peers_connected: 0,
            peers_available: 0,
            checking_progress: 0.0,
            peers_by_source: HashMap::new(),

            // Identity
            info_hashes: irontide_core::InfoHashes::v1_only(irontide_core::Id20::from([0u8; 20])),
            name: String::new(),

            // State flags
            has_metadata: false,
            is_seeding: false,
            is_finished: false,
            is_paused: false,
            auto_managed: false,
            sequential_download: false,
            super_seeding: false,
            user_seed_mode: false,
            has_incoming: false,
            need_save_resume: false,
            moving_storage: false,

            // Progress
            progress: 0.0,
            progress_ppm: 0,
            total_done: 0,
            total: 0,
            total_wanted_done: 0,
            total_wanted: 0,
            block_size: 16384,

            // Transfer (session counters)
            total_download: 0,
            total_upload: 0,
            total_payload_download: 0,
            total_payload_upload: 0,
            total_failed_bytes: 0,
            total_redundant_bytes: 0,

            // Transfer (all-time)
            all_time_download: 0,
            all_time_upload: 0,

            // Rates
            download_rate: 0,
            upload_rate: 0,
            download_payload_rate: 0,
            upload_payload_rate: 0,

            // Connection details
            num_peers: 0,
            num_seeds: 0,
            num_complete: -1,
            num_incomplete: -1,
            list_seeds: 0,
            list_peers: 0,
            connect_candidates: 0,
            num_connections: 0,
            num_uploads: 0,
            unique_peers_attempted: 0,
            pipeline: None,
            choke_rotations: 0,
            piece_steals: 0,

            // Limits
            connections_limit: 0,
            uploads_limit: 0,

            // Distributed copies
            distributed_full_copies: 0,
            distributed_fraction: 0,
            distributed_copies: 0.0,

            // Tracker
            current_tracker: String::new(),
            announcing_to_trackers: false,
            announcing_to_lsd: false,
            announcing_to_dht: false,

            // Timestamps
            added_time: 0,
            completed_time: 0,
            last_seen_complete: 0,
            last_upload: 0,
            last_download: 0,

            // Durations
            active_duration: 0,
            finished_duration: 0,
            seeding_duration: 0,

            // Storage
            save_path: String::new(),

            // Queue
            queue_position: -1,

            // Error
            error: String::new(),
            error_file: -1,
        }
    }
}

/// Lightweight summary of a torrent for the HTTP API.
///
/// A reduced view of [`TorrentStats`] with only the fields needed for list views.
/// Constructed via `From<&TorrentStats>`.
#[derive(Debug, Clone, Serialize)]
pub struct TorrentSummary {
    /// Hex-encoded v1 info hash (empty string for v2-only torrents).
    pub info_hash: String,
    /// Display name from the torrent metadata.
    pub name: String,
    /// Current torrent state.
    pub state: TorrentState,
    /// Download progress as a fraction (0.0–1.0).
    pub progress: f64,
    /// Current download rate in bytes/sec.
    pub download_rate: u64,
    /// Current upload rate in bytes/sec.
    pub upload_rate: u64,
    /// Total size of the torrent in bytes.
    pub total_size: u64,
    /// Number of connected peers.
    pub num_peers: usize,
    /// Number of connected seeders.
    pub num_seeds: usize,
    /// Total bytes uploaded across all sessions.
    pub all_time_upload: u64,
    /// Total bytes downloaded across all sessions.
    pub all_time_download: u64,
    /// Time when the torrent was added (POSIX seconds).
    pub added_time: i64,
    /// Whether the user has enabled seed-only mode for this torrent.
    pub user_seed_mode: bool,
    /// Progress of piece checking (0.0–1.0), meaningful when state is `Checking`.
    pub checking_progress: f32,
}

impl From<&TorrentStats> for TorrentSummary {
    fn from(s: &TorrentStats) -> Self {
        Self {
            info_hash: s.info_hashes.v1.map(|h| h.to_hex()).unwrap_or_default(),
            name: s.name.clone(),
            state: s.state,
            progress: s.progress as f64,
            download_rate: s.download_rate,
            upload_rate: s.upload_rate,
            total_size: s.total,
            num_peers: s.num_peers,
            num_seeds: s.num_seeds,
            all_time_upload: s.all_time_upload,
            all_time_download: s.all_time_download,
            added_time: s.added_time,
            user_seed_mode: s.user_seed_mode,
            checking_progress: s.checking_progress,
        }
    }
}

/// Lightweight record of a single block write completion,
/// carried in `PeerEvent::PieceBlocksBatch`.
#[derive(Debug, Clone)]
pub(crate) struct BlockEntry {
    pub index: u32,  // piece index
    pub begin: u32,  // byte offset within piece
    pub length: u32, // block size (usually 16384)
}

/// Events sent from a `PeerTask` back to the `TorrentActor`.
#[derive(Debug)]
#[allow(dead_code)] // consumed by peer/torrent modules (not yet implemented)
pub(crate) enum PeerEvent {
    Bitfield {
        peer_addr: SocketAddr,
        bitfield: Bitfield,
    },
    Have {
        peer_addr: SocketAddr,
        index: u32,
    },
    /// BEP 54: Peer no longer has a piece (lt_donthave extension).
    DontHave {
        peer_addr: SocketAddr,
        index: u32,
    },
    PieceData {
        peer_addr: SocketAddr,
        index: u32,
        begin: u32,
        data: Bytes,
    },
    /// Block completion from a peer task's direct disk write.
    /// Sent immediately on each block write for real-time TorrentActor visibility.
    PieceBlocksBatch {
        peer_addr: SocketAddr,
        blocks: Vec<BlockEntry>,
    },
    PeerChoking {
        peer_addr: SocketAddr,
        choking: bool,
    },
    PeerInterested {
        peer_addr: SocketAddr,
        interested: bool,
    },
    ExtHandshake {
        peer_addr: SocketAddr,
        handshake: ExtHandshake,
    },
    MetadataPiece {
        peer_addr: SocketAddr,
        piece: u32,
        data: Bytes,
        total_size: u64,
    },
    MetadataReject {
        peer_addr: SocketAddr,
        piece: u32,
    },
    PexPeers {
        new_peers: Vec<SocketAddr>,
    },
    TrackersReceived {
        tracker_urls: Vec<String>,
    },
    IncomingRequest {
        peer_addr: SocketAddr,
        index: u32,
        begin: u32,
        length: u32,
    },
    RejectRequest {
        peer_addr: SocketAddr,
        index: u32,
        begin: u32,
        length: u32,
    },
    AllowedFast {
        peer_addr: SocketAddr,
        index: u32,
    },
    SuggestPiece {
        peer_addr: SocketAddr,
        index: u32,
    },
    /// Peer successfully connected with a specific transport.
    TransportIdentified {
        peer_addr: SocketAddr,
        transport: crate::rate_limiter::PeerTransport,
    },
    /// M140: BT handshake completed successfully — peer is now truly live.
    /// Sent from `run_peer` after BT protocol handshake exchange validates
    /// info_hash and peer_id. Triggers `mark_live()` in the actor.
    HandshakeComplete {
        peer_addr: SocketAddr,
    },
    Disconnected {
        peer_addr: SocketAddr,
        reason: Option<String>,
    },
    WebSeedPieceData {
        url: String,
        index: u32,
        data: Bytes,
    },
    WebSeedError {
        url: String,
        piece: u32,
        message: String,
    },
    /// BEP 52: Received hash response from peer.
    HashesReceived {
        peer_addr: SocketAddr,
        request: irontide_core::HashRequest,
        hashes: Vec<irontide_core::Id32>,
    },
    /// BEP 52: Peer rejected our hash request.
    HashRequestRejected {
        peer_addr: SocketAddr,
        request: irontide_core::HashRequest,
    },
    /// BEP 52: Peer sent a hash request to us.
    IncomingHashRequest {
        peer_addr: SocketAddr,
        request: irontide_core::HashRequest,
    },
    /// BEP 55: Received a Rendezvous request (we are the relay).
    HolepunchRendezvous {
        peer_addr: SocketAddr,
        target: SocketAddr,
    },
    /// BEP 55: Received a Connect message (we should initiate simultaneous connect).
    HolepunchConnect {
        peer_addr: SocketAddr,
        target: SocketAddr,
    },
    /// BEP 55: Received an Error message from the relay.
    HolepunchError {
        peer_addr: SocketAddr,
        target: SocketAddr,
        error_code: u32,
    },
    /// MSE handshake failed — peer is being retried with a different encryption mode.
    /// Carries the new command channel sender so the TorrentActor can
    /// update its PeerState.
    MseRetry {
        peer_addr: SocketAddr,
        cmd_tx: tokio::sync::mpsc::Sender<PeerCommand>,
    },
    /// Peer released a piece it was downloading (choke, error, disconnect).
    PieceReleased {
        peer_addr: SocketAddr,
        piece: u32,
    },
}

/// Commands sent from the `TorrentActor` to a `PeerTask`.
#[derive(Debug)]
#[allow(dead_code)] // consumed by peer/torrent modules (not yet implemented)
pub(crate) enum PeerCommand {
    Request {
        index: u32,
        begin: u32,
        length: u32,
    },
    Cancel {
        index: u32,
        begin: u32,
        length: u32,
    },
    SetChoking(bool),
    SetInterested(bool),
    Have(u32),
    RequestMetadata {
        piece: u32,
    },
    RejectRequest {
        index: u32,
        begin: u32,
        length: u32,
    },
    AllowedFast(u32),
    SendPiece {
        index: u32,
        begin: u32,
        data: Bytes,
    },
    /// Send an updated extension handshake (e.g. BEP 21 upload-only).
    SendExtHandshake(irontide_wire::ExtHandshake),
    /// BEP 6: Suggest a piece to the peer.
    SuggestPiece(u32),
    /// BEP 52: Send a hash request to the peer.
    SendHashRequest(irontide_core::HashRequest),
    /// BEP 52: Send hashes in response to a peer's request.
    SendHashes {
        request: irontide_core::HashRequest,
        hashes: Vec<irontide_core::Id32>,
    },
    /// BEP 52: Reject a peer's hash request.
    SendHashReject(irontide_core::HashRequest),
    /// BEP 11: Send a PEX message to this peer.
    SendPex {
        message: crate::pex::PexMessage,
    },
    /// BEP 55: Send a holepunch message to this peer.
    SendHolepunch(irontide_wire::HolepunchMessage),
    /// Update the piece count after BEP 9 metadata assembly.
    UpdateNumPieces(u32),
    /// M159: Tell the peer task to stop dispatching block requests.
    ///
    /// Translated to `DispatchCommand::Stop` by the reader loop. The requester
    /// transitions back to the idle state waiting for a fresh `StartRequesting`.
    /// Uploads are unaffected.
    StopRequesting,
    /// M75: Actor sends reservation state to peer task for integrated dispatch.
    /// Sent after metadata download (magnet) or at peer connection (non-magnet).
    StartRequesting {
        atomic_states: std::sync::Arc<crate::piece_reservation::AtomicPieceStates>,
        availability_snapshot: std::sync::Arc<crate::piece_reservation::AvailabilitySnapshot>,
        piece_notify: std::sync::Arc<tokio::sync::Notify>,
        disk_handle: Option<crate::disk::DiskHandle>,
        write_error_tx: tokio::sync::mpsc::Sender<crate::disk::DiskWriteError>,
        /// Piece/chunk arithmetic for dispatch state initialization.
        lengths: irontide_core::Lengths,
        /// M103: Shared block-level request/received bitmaps for per-block stealing.
        block_maps: Option<std::sync::Arc<crate::piece_reservation::BlockMaps>>,
        /// M103: Shared queue of pieces available for block stealing.
        steal_candidates: Option<std::sync::Arc<crate::piece_reservation::StealCandidates>>,
        /// M120: Per-piece write guards to prevent steal/write races.
        piece_write_guards: Option<std::sync::Arc<crate::piece_reservation::PieceWriteGuards>>,
    },
    /// Actor sends an updated availability snapshot to the peer task.
    SnapshotUpdate {
        snapshot: std::sync::Arc<crate::piece_reservation::AvailabilitySnapshot>,
    },
    Shutdown,
}

/// Helper trait combining [`AsyncRead`] + [`AsyncWrite`] for trait-object erasure.
///
/// Rust doesn't allow `dyn AsyncRead + AsyncWrite` directly, so this trait
/// combines both into a single trait that can be used as a trait object.
pub(crate) trait AsyncReadWrite:
    tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send
{
}

impl<T> AsyncReadWrite for T where T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send {}

/// Boxed async stream (AsyncRead + AsyncWrite + Unpin + Send) with a Debug impl.
///
/// Used for incoming SSL peer connections where the concrete TLS type is erased.
pub(crate) struct BoxedAsyncStream(pub Box<dyn AsyncReadWrite>);

impl std::fmt::Debug for BoxedAsyncStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("BoxedAsyncStream(..)")
    }
}

/// Commands sent from a `TorrentHandle` to the `TorrentActor`.
#[derive(Debug)]
#[allow(dead_code)] // consumed by torrent module (not yet implemented)
pub(crate) enum TorrentCommand {
    AddPeers {
        peers: Vec<SocketAddr>,
        source: crate::peer_state::PeerSource,
    },
    Stats {
        reply: oneshot::Sender<TorrentStats>,
    },
    Pause,
    Resume,
    Shutdown,
    SaveResumeData {
        reply: oneshot::Sender<crate::Result<irontide_core::FastResumeData>>,
    },
    SetFilePriority {
        index: usize,
        priority: irontide_core::FilePriority,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    FilePriorities {
        reply: oneshot::Sender<Vec<irontide_core::FilePriority>>,
    },
    ForceReannounce,
    TrackerList {
        reply: oneshot::Sender<Vec<crate::tracker_manager::TrackerInfo>>,
    },
    Scrape {
        reply: oneshot::Sender<Option<(String, irontide_tracker::ScrapeInfo)>>,
    },
    /// Incoming peer routed from the session-level accept loop (TCP or uTP).
    IncomingPeer {
        stream: crate::transport::BoxedStream,
        addr: SocketAddr,
    },
    /// Open a streaming reader for a file within the torrent.
    OpenFile {
        file_index: usize,
        reply: oneshot::Sender<crate::Result<crate::streaming::FileStreamHandle>>,
    },
    /// Update the external IP for BEP 40 peer priority calculation.
    UpdateExternalIp {
        ip: std::net::IpAddr,
    },
    /// Move torrent data files to a new directory.
    MoveStorage {
        new_path: PathBuf,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Incoming SSL peer routed from the session-level SSL listener (M42).
    ///
    /// The TLS handshake has already been completed by the session actor.
    SpawnSslPeer {
        addr: SocketAddr,
        stream: BoxedAsyncStream,
    },
    /// Set the per-torrent download rate limit (bytes/sec, 0 = unlimited).
    SetDownloadLimit {
        bytes_per_sec: u64,
        reply: oneshot::Sender<()>,
    },
    /// Set the per-torrent upload rate limit (bytes/sec, 0 = unlimited).
    SetUploadLimit {
        bytes_per_sec: u64,
        reply: oneshot::Sender<()>,
    },
    /// Get the current per-torrent download rate limit (bytes/sec, 0 = unlimited).
    DownloadLimit {
        reply: oneshot::Sender<u64>,
    },
    /// Get the current per-torrent upload rate limit (bytes/sec, 0 = unlimited).
    UploadLimit {
        reply: oneshot::Sender<u64>,
    },
    /// Enable or disable sequential (in-order) piece downloading.
    SetSequentialDownload {
        enabled: bool,
        reply: oneshot::Sender<()>,
    },
    /// Query whether sequential downloading is enabled.
    IsSequentialDownload {
        reply: oneshot::Sender<bool>,
    },
    /// Enable or disable BEP 16 super seeding mode.
    SetSuperSeeding {
        enabled: bool,
        reply: oneshot::Sender<()>,
    },
    /// Query whether super seeding mode is enabled.
    IsSuperSeeding {
        reply: oneshot::Sender<bool>,
    },
    /// Enable or disable user-requested seed-only mode (M159).
    ///
    /// When enabled, the torrent stops scheduling new block requests and
    /// cancels all in-flight requests, but continues to serve uploads to
    /// interested peers. Mirrors libtorrent's `seed_mode` flag.
    SetSeedMode {
        enabled: bool,
        reply: oneshot::Sender<()>,
    },
    /// Add a new tracker URL (fire-and-forget at torrent level).
    AddTracker {
        url: String,
    },
    /// Replace all tracker URLs with a new set.
    ReplaceTrackers {
        urls: Vec<String>,
        reply: oneshot::Sender<()>,
    },
    /// Trigger a full piece verification (force recheck).
    ForceRecheck {
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Rename a file within the torrent on disk.
    RenameFile {
        file_index: usize,
        new_name: String,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Set the per-torrent maximum number of connections (0 = use global default).
    SetMaxConnections {
        limit: usize,
        reply: oneshot::Sender<()>,
    },
    /// Get the current per-torrent maximum connection limit.
    MaxConnections {
        reply: oneshot::Sender<usize>,
    },
    /// Set the per-torrent maximum number of unchoke slots (upload slots).
    SetMaxUploads {
        limit: usize,
        reply: oneshot::Sender<()>,
    },
    /// Get the current per-torrent maximum unchoke slots (upload slots).
    MaxUploads {
        reply: oneshot::Sender<usize>,
    },
    /// Get per-peer details for all connected peers.
    GetPeerInfo {
        reply: oneshot::Sender<Vec<PeerInfo>>,
    },
    /// Get in-flight piece download status (the download queue).
    GetDownloadQueue {
        reply: oneshot::Sender<Vec<PartialPieceInfo>>,
    },
    /// Check whether a specific piece has been downloaded.
    HavePiece {
        index: u32,
        reply: oneshot::Sender<bool>,
    },
    /// Get per-piece availability counts from connected peers.
    PieceAvailability {
        reply: oneshot::Sender<Vec<u32>>,
    },
    /// Get per-file bytes-downloaded progress.
    FileProgress {
        reply: oneshot::Sender<Vec<u64>>,
    },
    /// Get the torrent's identity hashes (v1 and/or v2).
    InfoHashes {
        reply: oneshot::Sender<irontide_core::InfoHashes>,
    },
    /// Get the full v1 metainfo (None for magnet links before metadata received).
    TorrentFile {
        reply: oneshot::Sender<Option<irontide_core::TorrentMetaV1>>,
    },
    /// Get the full v2 metainfo (None if not a v2/hybrid torrent or before metadata received).
    TorrentFileV2 {
        reply: oneshot::Sender<Option<irontide_core::TorrentMetaV2>>,
    },
    /// Force an immediate DHT announce (fire-and-forget at torrent level).
    ForceDhtAnnounce,
    /// Read all data for a specific piece from disk.
    ReadPiece {
        index: u32,
        reply: oneshot::Sender<crate::Result<bytes::Bytes>>,
    },
    /// Flush the disk write cache for this torrent.
    FlushCache {
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Clear the error state and resume if the torrent was paused due to error.
    ClearError,
    /// Get per-file open/mode status based on torrent state.
    FileStatus {
        reply: oneshot::Sender<Vec<crate::types::FileStatus>>,
    },
    /// Read the current torrent flags as a bitflag set.
    Flags {
        reply: oneshot::Sender<TorrentFlags>,
    },
    /// Set (enable) the specified torrent flags.
    SetFlags {
        flags: TorrentFlags,
        reply: oneshot::Sender<()>,
    },
    /// Unset (disable) the specified torrent flags.
    UnsetFlags {
        flags: TorrentFlags,
        reply: oneshot::Sender<()>,
    },
    /// Immediately initiate a peer connection to the given address.
    ConnectPeer {
        addr: SocketAddr,
    },
    /// Clear the `need_save_resume` dirty flag after a successful file save (M161).
    ClearSaveResumeFlag,
    /// Restore a piece bitmap from resume data (M161 Phase 4).
    ///
    /// Replaces the chunk tracker's bitfield with the provided raw piece bytes.
    /// The handler validates the bitfield length before applying.
    RestoreResumeBitmap {
        /// Raw piece bitfield bytes from resume data.
        pieces: Vec<u8>,
        /// Reply with `Ok(())` on success or an error if validation fails.
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// M147: Pre-resolved metadata from the background MetadataResolver.
    ///
    /// Sent by `SessionActor::spawn_metadata_resolver()` when the background
    /// resolver successfully obtains torrent metadata before the TorrentActor's
    /// own FetchingMetadata phase completes. This is a race: first to resolve
    /// wins; the other path's result is silently discarded.
    PreResolvedMetadata {
        /// Raw bencoded info dictionary bytes.
        info_bytes: Vec<u8>,
        /// Peers that were successfully connected during metadata resolution
        /// (for pre-seeding the peer pipeline).
        peers: Vec<SocketAddr>,
    },
}

/// Per-peer details exported for client UI introspection.
#[derive(Debug, Clone, Serialize)]
pub struct PeerInfo {
    /// Remote peer address (IP + port).
    pub addr: SocketAddr,
    /// Client identification string (from extension handshake `v` field, or empty).
    pub client: String,
    /// Whether the peer is choking us.
    pub peer_choking: bool,
    /// Whether the peer is interested in our data.
    pub peer_interested: bool,
    /// Whether we are choking the peer.
    pub am_choking: bool,
    /// Whether we are interested in the peer's data.
    pub am_interested: bool,
    /// Current download rate from this peer in bytes/sec.
    pub download_rate: u64,
    /// Current upload rate to this peer in bytes/sec.
    pub upload_rate: u64,
    /// Number of pieces the peer has (bitfield population count).
    pub num_pieces: u32,
    /// How the peer was discovered.
    pub source: crate::peer_state::PeerSource,
    /// Whether the peer supports BEP 6 Fast Extension.
    pub supports_fast: bool,
    /// Whether the peer declared upload-only status (BEP 21).
    pub upload_only: bool,
    /// Whether the peer is snubbed (no data for snub_timeout_secs).
    pub snubbed: bool,
    /// Seconds since the peer connection was established.
    pub connected_duration_secs: u64,
    /// Number of outstanding piece requests to this peer.
    pub num_pending_requests: usize,
    /// Number of incoming piece requests from this peer.
    pub num_incoming_requests: usize,
}

/// In-flight piece download status for the download queue.
#[derive(Debug, Clone, Serialize)]
pub struct PartialPieceInfo {
    /// Index of the piece being downloaded.
    pub piece_index: u32,
    /// Total number of blocks in this piece.
    pub blocks_in_piece: u32,
    /// Number of blocks that have been assigned to peers.
    pub blocks_assigned: u32,
}

/// Info about a file within a torrent.
#[derive(Debug, Clone, Serialize)]
pub struct FileInfo {
    /// Relative path of the file within the torrent.
    pub path: PathBuf,
    /// File size in bytes.
    pub length: u64,
}

/// Metadata about a torrent (available after metadata is fetched).
#[derive(Debug, Clone, Serialize)]
pub struct TorrentInfo {
    /// SHA-1 info hash of the torrent.
    pub info_hash: irontide_core::Id20,
    /// Display name from the torrent metadata.
    pub name: String,
    /// Total size of all files in bytes.
    pub total_length: u64,
    /// Size of each piece in bytes (last piece may be smaller).
    pub piece_length: u64,
    /// Total number of pieces in the torrent.
    pub num_pieces: u32,
    /// List of files contained in the torrent.
    pub files: Vec<FileInfo>,
    /// Whether this is a private torrent (DHT/PEX disabled).
    pub private: bool,
}

/// Aggregate statistics for the whole session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionStats {
    /// Number of non-paused torrents in the session.
    pub active_torrents: usize,
    /// Total bytes downloaded across all torrents since session start.
    pub total_downloaded: u64,
    /// Total bytes uploaded across all torrents since session start.
    pub total_uploaded: u64,
    /// Number of nodes in the DHT routing table.
    pub dht_nodes: usize,
}

/// Whether a file in a torrent is open and its I/O access mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum FileMode {
    /// File is open for reading only (e.g. seeding).
    ReadOnly,
    /// File is open for reading and writing (e.g. downloading).
    ReadWrite,
    /// File is not currently open.
    Closed,
}

/// Status of a single file within a torrent.
#[derive(Debug, Clone, Serialize)]
pub struct FileStatus {
    /// Whether the file is currently open.
    pub open: bool,
    /// The current access mode.
    pub mode: FileMode,
}

bitflags! {
    /// Bitflag convenience wrapper for common torrent state flags.
    ///
    /// These map to existing torrent actor fields; `set_flags` / `unset_flags`
    /// delegate to the underlying operations (pause/resume, set_sequential, etc.).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct TorrentFlags: u32 {
        /// Torrent is paused.
        const PAUSED = 0x1;
        /// Torrent is auto-managed by the session queuing system.
        const AUTO_MANAGED = 0x2;
        /// Sequential (in-order) piece downloading is enabled.
        const SEQUENTIAL_DOWNLOAD = 0x4;
        /// BEP 16 super seeding mode is active.
        const SUPER_SEEDING = 0x8;
        /// Upload-only status (seeding complete, no wanted pieces).
        const UPLOAD_ONLY = 0x10;
    }
}

/// Type alias for a factory that creates per-torrent storage.
pub type StorageFactory = Box<
    dyn Fn(
            &irontide_core::TorrentMetaV1,
            &std::path::Path,
        ) -> std::sync::Arc<dyn irontide_storage::TorrentStorage>
        + Send
        + Sync,
>;

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

    #[test]
    fn torrent_config_strict_end_game_default() {
        let config = TorrentConfig::default();
        assert!(config.strict_end_game);
    }

    #[test]
    fn torrent_config_bandwidth_defaults() {
        let config = TorrentConfig::default();
        assert_eq!(config.upload_rate_limit, 0);
        assert_eq!(config.download_rate_limit, 0);
    }

    #[test]
    fn torrent_config_encryption_default() {
        let cfg = TorrentConfig::default();
        assert_eq!(
            cfg.encryption_mode,
            irontide_wire::mse::EncryptionMode::Disabled
        );
    }

    #[test]
    fn torrent_config_utp_default() {
        let cfg = TorrentConfig::default();
        assert!(cfg.enable_utp);
    }

    #[test]
    fn torrent_config_web_seed_defaults() {
        let cfg = TorrentConfig::default();
        assert!(cfg.enable_web_seed);
        assert_eq!(cfg.max_web_seeds, 4);
    }

    #[test]
    fn torrent_config_super_seeding_default() {
        let cfg = TorrentConfig::default();
        assert!(!cfg.super_seeding);
        assert!(cfg.upload_only_announce);
    }

    #[test]
    fn torrent_config_picker_defaults() {
        let cfg = TorrentConfig::default();
        assert!(!cfg.sequential_download);
        assert_eq!(cfg.initial_picker_threshold, 4);
        assert_eq!(cfg.whole_pieces_threshold, 20);
        assert_eq!(cfg.snub_timeout_secs, 15);
        assert_eq!(cfg.readahead_pieces, 8);
        assert!(cfg.streaming_timeout_escalation);
    }

    #[test]
    fn torrent_stats_has_peers_by_source() {
        use crate::peer_state::PeerSource;
        use std::collections::HashMap;

        let stats = TorrentStats {
            state: TorrentState::Downloading,
            pieces_total: 10,
            ..Default::default()
        };
        assert!(stats.peers_by_source.is_empty());

        let mut map = HashMap::new();
        map.insert(PeerSource::Tracker, 5);
        map.insert(PeerSource::Dht, 3);
        let stats2 = TorrentStats {
            peers_by_source: map.clone(),
            ..stats
        };
        assert_eq!(stats2.peers_by_source[&PeerSource::Tracker], 5);
        assert_eq!(stats2.peers_by_source[&PeerSource::Dht], 3);
    }

    #[test]
    fn torrent_stats_default_values() {
        let stats = TorrentStats::default();

        // State
        assert_eq!(stats.state, TorrentState::Paused);

        // Original fields are zeroed
        assert_eq!(stats.downloaded, 0);
        assert_eq!(stats.uploaded, 0);
        assert_eq!(stats.pieces_have, 0);
        assert_eq!(stats.pieces_total, 0);
        assert_eq!(stats.peers_connected, 0);
        assert_eq!(stats.peers_available, 0);
        assert!((stats.checking_progress - 0.0).abs() < f32::EPSILON);
        assert!(stats.peers_by_source.is_empty());

        // Identity: zeroed info hash
        assert_eq!(
            stats.info_hashes,
            irontide_core::InfoHashes::v1_only(irontide_core::Id20::from([0u8; 20]))
        );
        assert!(stats.name.is_empty());

        // State flags are all false
        assert!(!stats.has_metadata);
        assert!(!stats.is_seeding);
        assert!(!stats.is_finished);
        assert!(!stats.is_paused);
        assert!(!stats.auto_managed);
        assert!(!stats.sequential_download);
        assert!(!stats.super_seeding);
        assert!(!stats.has_incoming);
        assert!(!stats.need_save_resume);
        assert!(!stats.moving_storage);

        // Progress
        assert!((stats.progress - 0.0).abs() < f32::EPSILON);
        assert_eq!(stats.progress_ppm, 0);
        assert_eq!(stats.total_done, 0);
        assert_eq!(stats.total, 0);
        assert_eq!(stats.total_wanted_done, 0);
        assert_eq!(stats.total_wanted, 0);
        assert_eq!(stats.block_size, 16384);

        // Sentinel values
        assert_eq!(stats.num_complete, -1);
        assert_eq!(stats.num_incomplete, -1);
        assert_eq!(stats.queue_position, -1);
        assert_eq!(stats.error_file, -1);

        // Strings are empty
        assert!(stats.current_tracker.is_empty());
        assert!(stats.save_path.is_empty());
        assert!(stats.error.is_empty());

        // Rates are zero
        assert_eq!(stats.download_rate, 0);
        assert_eq!(stats.upload_rate, 0);
        assert_eq!(stats.download_payload_rate, 0);
        assert_eq!(stats.upload_payload_rate, 0);

        // Distributed copies
        assert_eq!(stats.distributed_full_copies, 0);
        assert_eq!(stats.distributed_fraction, 0);
        assert!((stats.distributed_copies - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn torrent_stats_seeding_flags() {
        let stats = TorrentStats {
            state: TorrentState::Seeding,
            is_seeding: true,
            is_finished: true,
            has_metadata: true,
            progress: 1.0,
            progress_ppm: 1_000_000,
            ..Default::default()
        };
        assert_eq!(stats.state, TorrentState::Seeding);
        assert!(stats.is_seeding);
        assert!(stats.is_finished);
        assert!(stats.has_metadata);
        assert!((stats.progress - 1.0).abs() < f32::EPSILON);
        assert_eq!(stats.progress_ppm, 1_000_000);
        // Other fields remain default
        assert!(!stats.is_paused);
        assert_eq!(stats.downloaded, 0);
    }

    #[test]
    fn torrent_state_sharing_variant() {
        let state = TorrentState::Sharing;
        assert_ne!(state, TorrentState::Downloading);
        assert_ne!(state, TorrentState::Seeding);
        // Verify JSON round-trip
        let json = serde_json::to_string(&state).unwrap();
        assert_eq!(json, "\"Sharing\"");
        let decoded: TorrentState = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, TorrentState::Sharing);
    }

    #[test]
    fn torrent_config_i2p_defaults() {
        let cfg = TorrentConfig::default();
        assert!(!cfg.enable_i2p);
        assert!(!cfg.allow_i2p_mixed);
    }

    #[test]
    fn torrent_config_ssl_listen_port_default() {
        let cfg = TorrentConfig::default();
        assert_eq!(cfg.ssl_listen_port, 0);
    }

    #[test]
    fn torrent_config_ssl_listen_port_from_settings() {
        let mut s = crate::settings::Settings::default();
        s.ssl_listen_port = 4433;
        let tc = TorrentConfig::from(&s);
        assert_eq!(tc.ssl_listen_port, 4433);
    }

    #[test]
    fn torrent_config_choking_defaults() {
        let cfg = TorrentConfig::default();
        assert_eq!(
            cfg.seed_choking_algorithm,
            SeedChokingAlgorithm::FastestUpload
        );
        assert_eq!(cfg.choking_algorithm, ChokingAlgorithm::FixedSlots);
    }

    #[test]
    fn torrent_config_m44_defaults() {
        let cfg = TorrentConfig::default();
        assert!(cfg.piece_extent_affinity);
        assert!(!cfg.suggest_mode);
        assert_eq!(cfg.max_suggest_pieces, 10);
        assert_eq!(cfg.predictive_piece_announce_ms, 0);
    }

    #[test]
    fn torrent_config_from_settings_choking() {
        let mut s = crate::settings::Settings::default();
        s.seed_choking_algorithm = SeedChokingAlgorithm::RoundRobin;
        s.choking_algorithm = ChokingAlgorithm::RateBased;
        let cfg = TorrentConfig::from(&s);
        assert_eq!(cfg.seed_choking_algorithm, SeedChokingAlgorithm::RoundRobin);
        assert_eq!(cfg.choking_algorithm, ChokingAlgorithm::RateBased);
    }

    #[test]
    fn torrent_config_holepunch_default() {
        let cfg = TorrentConfig::default();
        assert!(cfg.enable_holepunch);

        // Also verify it inherits from Settings
        let s = crate::settings::Settings::default();
        let tc = TorrentConfig::from(&s);
        assert!(tc.enable_holepunch);

        // And when disabled in Settings
        let mut s2 = crate::settings::Settings::default();
        s2.enable_holepunch = false;
        let tc2 = TorrentConfig::from(&s2);
        assert!(!tc2.enable_holepunch);
    }

    #[test]
    fn torrent_config_url_security_default() {
        let cfg = TorrentConfig::default();
        assert!(cfg.url_security.ssrf_mitigation);
        assert!(!cfg.url_security.allow_idna);
        assert!(cfg.url_security.validate_https_trackers);
    }

    #[test]
    fn torrent_config_url_security_from_settings() {
        let mut s = crate::settings::Settings::default();
        s.ssrf_mitigation = false;
        s.allow_idna = true;
        s.validate_https_trackers = false;
        let cfg = TorrentConfig::from(&s);
        assert!(!cfg.url_security.ssrf_mitigation);
        assert!(cfg.url_security.allow_idna);
        assert!(!cfg.url_security.validate_https_trackers);
    }

    #[test]
    fn torrent_config_peer_dscp_default() {
        let cfg = TorrentConfig::default();
        assert_eq!(cfg.peer_dscp, 0x08);
    }

    #[test]
    fn torrent_config_peer_dscp_from_settings() {
        let mut s = crate::settings::Settings::default();
        s.peer_dscp = 0x2E;
        let cfg = TorrentConfig::from(&s);
        assert_eq!(cfg.peer_dscp, 0x2E);
    }

    // ── M121: TorrentSummary and Serialize tests ──

    #[test]
    fn summary_from_stats() {
        let v1_hash =
            irontide_core::Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap();
        let mut stats = TorrentStats::default();
        stats.info_hashes = irontide_core::InfoHashes::v1_only(v1_hash);
        stats.name = "test torrent".to_string();
        stats.state = TorrentState::Downloading;
        stats.progress = 0.75;
        stats.download_rate = 1_000_000;
        stats.upload_rate = 500_000;
        stats.total = 100_000_000;
        stats.num_peers = 42;
        stats.added_time = 1710900000;

        let summary = super::TorrentSummary::from(&stats);
        assert_eq!(
            summary.info_hash,
            "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
        );
        assert_eq!(summary.name, "test torrent");
        assert_eq!(summary.state, TorrentState::Downloading);
        assert!((summary.progress - 0.75).abs() < f64::EPSILON);
        assert_eq!(summary.download_rate, 1_000_000);
        assert_eq!(summary.upload_rate, 500_000);
        assert_eq!(summary.total_size, 100_000_000);
        assert_eq!(summary.num_peers, 42);
        assert_eq!(summary.added_time, 1710900000);
    }

    #[test]
    fn summary_from_stats_v2_only() {
        let v2_hash = irontide_core::Id32::from_hex(
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        )
        .unwrap();
        let mut stats = TorrentStats::default();
        stats.info_hashes = irontide_core::InfoHashes::v2_only(v2_hash);
        stats.name = "v2 torrent".to_string();

        let summary = super::TorrentSummary::from(&stats);
        // v2-only torrents have no v1 hash, so info_hash is empty
        assert_eq!(summary.info_hash, "");
        assert_eq!(summary.name, "v2 torrent");
    }

    #[test]
    fn stats_serializable() {
        let stats = TorrentStats::default();
        let json = serde_json::to_string(&stats).expect("TorrentStats should serialize to JSON");
        assert!(json.contains("\"state\""));
        assert!(json.contains("\"info_hashes\""));
        assert!(json.contains("\"download_rate\""));
    }

    #[test]
    fn info_hashes_serializable() {
        let v1 = irontide_core::Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap();
        let ih = irontide_core::InfoHashes::v1_only(v1);
        let json = serde_json::to_string(&ih).expect("InfoHashes should serialize to JSON");
        // Id20 serializes as raw bytes (not hex) — verify JSON structure
        assert!(json.contains("\"v1\""));
        assert!(json.contains("\"v2\":null"));
    }

    #[test]
    fn summary_serializable() {
        let mut stats = TorrentStats::default();
        stats.name = "serialize test".to_string();
        stats.state = TorrentState::Seeding;
        stats.progress = 1.0;
        let summary = super::TorrentSummary::from(&stats);
        let json =
            serde_json::to_string(&summary).expect("TorrentSummary should serialize to JSON");
        assert!(json.contains("\"name\":\"serialize test\""));
        assert!(json.contains("\"state\":\"Seeding\""));
        assert!(json.contains("\"progress\":1.0"));
    }

    #[test]
    fn test_torrent_summary_includes_seeds_and_totals() {
        let mut stats = TorrentStats::default();
        stats.num_seeds = 7;
        stats.all_time_upload = 1_500_000;
        stats.all_time_download = 3_000_000;

        let summary = super::TorrentSummary::from(&stats);
        assert_eq!(summary.num_seeds, 7);
        assert_eq!(summary.all_time_upload, 1_500_000);
        assert_eq!(summary.all_time_download, 3_000_000);
    }
}