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
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
use crate::channel::{ChannelReceiver, ChannelSender, Reply};
use crate::config::TorrentConfig;
#[cfg(feature = "dht")]
use crate::dht::DhtTracker;
use crate::file::File;
use crate::operation::{Operation, TorrentOperationResult};
use crate::peer::extension::PeerExtension;
use crate::peer::{
BitTorrentPeer, ChokeState, CloseReason, ConnectionProtocol, InterestState, Peer,
PeerDiscovery, PeerEntry, PeerId, PeerState, ProtocolExtensionFlags,
};
use crate::peer_pool::PeerPool;
use crate::piece_picker::strategy::{
PriorityStrategy, RarestFirstStrategy, SequentialStrategy, SuggestedOnlyStrategy,
};
use crate::piece_picker::{FxPiecePicker, PickerOptions, PiecePicker};
use crate::storage::{Storage, StorageParams};
use crate::torrent_data::DataPool;
use crate::tracker::{AnnounceEvent, AnnouncementResult, TrackerClient};
#[cfg(feature = "lsd")]
use crate::LocalServiceDiscovery;
use crate::{BitVec, Result};
use crate::{
FileAttributeFlags, FileIndex, InfoHash, Metrics, Piece, PieceBlock, PieceIndex, PiecePriority,
Sha1Hash, Sha256Hash, TorrentError, TorrentFlags, TorrentMetadata, TorrentMetadataInfo,
DEFAULT_TORRENT_PROTOCOL_EXTENSIONS,
};
use crate::{FilePriority, TorrentTracker};
use crate::{FileStream, TorrentHandle};
use derive_more::Display;
use futures::future::BoxFuture;
use futures::stream::FuturesUnordered;
use futures::{FutureExt, StreamExt};
use fx_callback::{Callback, MultiThreadedCallback, Subscription};
use itertools::Itertools;
use log::{debug, info, log, trace, warn, Level};
use std::collections::{BTreeMap, HashMap};
use std::fmt::{Debug, Display, Formatter};
use std::io;
use std::net::{Ipv4Addr, SocketAddr};
use std::ops::Range;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::oneshot::Sender;
use tokio::sync::Notify;
use tokio::task::JoinSet;
use tokio::time::timeout;
use tokio::{select, time};
use tokio_util::sync::{
CancellationToken, WaitForCancellationFuture, WaitForCancellationFutureOwned,
};
use url::Url;
const TICK_INTERVAL: Duration = Duration::from_secs(1);
/// A [Torrent] extension factory.
/// This factory will create a new instance of an [Extension] for each new torrent.
pub type ExtensionFactory = fn() -> PeerExtension;
/// Factory type for creating a new [Storage] instance.
pub type StorageFactory = dyn FnOnce(StorageParams) -> Storage + Send + Sync;
/// Factory type for creating a new [PiecePicker] instance.
pub type PiecePickerFactory =
dyn Fn(TorrentHandle, usize, DataPool, Storage, PickerOptions) -> PiecePicker + Send + Sync;
/// The states of the torrent
#[derive(Debug, Display, Copy, Clone, PartialEq)]
pub enum TorrentState {
/// The torrent is being initialized
#[display("initializing")]
Initializing,
/// The torrent is trying to retrieve the metadata from peers.
#[display("retrieving metadata")]
RetrievingMetadata,
/// The torrent has not started its download yet, and is currently checking existing files.
#[display("validating files")]
CheckingFiles,
/// The torrent is being downloaded. This is the state most torrents will be in most of the time.
#[display("downloading")]
Downloading,
/// In this state the torrent has finished downloading but still doesn't have the entire torrent.
#[display("finished")]
Finished,
/// In this state the torrent has finished downloading and is a pure seeder.
#[display("seeding")]
Seeding,
/// The torrent is currently paused and no longer executing any operations.
#[display("paused")]
Paused,
/// The torrent encountered an unrecoverable error.
#[display("error")]
Error,
/// The torrent has been stopped and is no longer executing any operations.
#[display("stopped")]
Stopped,
}
impl TorrentState {
/// Check if the current state is an initialization phase state.
pub fn is_initializing_phase(&self) -> bool {
self == &TorrentState::Initializing
|| self == &TorrentState::RetrievingMetadata
|| self == &TorrentState::CheckingFiles
}
}
impl Default for TorrentState {
fn default() -> Self {
Self::Initializing
}
}
/// Requests a new torrent creation based on the given data.
/// This is the **recommended** way to create new torrents.
///
/// # Examples
///
/// ```rust,no_run
/// # use fx_torrent::ExtensionFactory;
/// # use fx_torrent::Result;
/// # use fx_torrent::peer::{PeerDiscovery, TcpPeerDiscovery};
/// # use fx_torrent::storage::{DiskStorage};
/// # use fx_torrent::tracker::TrackerClient;
/// # use fx_torrent::{Torrent, TorrentFlags, TorrentMetadata, TorrentRequest, MagnetResult, CompactResult};
/// # use std::time::Duration;
///
/// # async fn create_new_torrent(
/// # metadata: TorrentMetadata,
/// # extensions: Vec<ExtensionFactory>,
/// # ) -> Result<Torrent> {
/// // create a tcp peer discovery for dialing and accepting tpc connections
/// let peer_discovery = TcpPeerDiscovery::new().await.unwrap();
/// // create a new tracker client for discovering peer addresses
/// let tracker = TrackerClient::new(Duration::from_secs(6));
///
/// Torrent::request()
/// .metadata(metadata)
/// .options(TorrentFlags::AutoManaged)
/// .extensions(extensions)
/// .storage(|params| {
/// DiskStorage::new(params.info_hash, params.path, params.data_pool).into()
/// })
/// .peer_discovery(peer_discovery.into())
/// .tracker(tracker.into())
/// .build()
/// # }
/// ```
#[derive(Default)]
pub struct TorrentRequest {
/// The torrent metadata information
metadata: Option<TorrentMetadata>,
/// The torrent options
options: Option<TorrentFlags>,
/// The torrent configuration
config: Option<TorrentConfig>,
/// The discovery strategies for peer connections.
peer_discoveries: Vec<PeerDiscovery>,
/// The protocol extensions that should be enabled
protocol_extensions: Option<ProtocolExtensionFlags>,
/// The factories for creating the peer extensions that should be enabled for this torrent
extensions: Vec<ExtensionFactory>,
/// The storage strategy to use for the torrent data
storage: Option<Box<StorageFactory>>,
/// The operations used by the torrent for processing data
operations: Option<Vec<Operation>>,
/// The trackers of the torrent to use.
trackers: Vec<TorrentTracker>,
/// The piece picker factory to use for the torrent.
piece_picker: Option<Box<PiecePickerFactory>>,
}
impl TorrentRequest {
/// Set the torrent metadata
pub fn metadata(&mut self, metadata: TorrentMetadata) -> &mut Self {
self.metadata = Some(metadata);
self
}
/// Set the torrent options
pub fn options(&mut self, options: TorrentFlags) -> &mut Self {
self.options = Some(options);
self
}
/// Set the torrent configuration
pub fn config(&mut self, config: TorrentConfig) -> &mut Self {
self.config = Some(config);
self
}
/// Add the given peer dialer to the torrent.
///
/// ## Remark
///
/// The order in which the dialers are added are important for outgoing connections.
pub fn peer_discovery(&mut self, dialer: PeerDiscovery) -> &mut Self {
self.peer_discoveries.push(dialer);
self
}
/// Set the given peer dialers of the torrent.
/// This overrides any existing configured peer dialers.
///
/// ## Remark
///
/// The order of the dialers are important for outgoing connections.
pub fn peer_discoveries(&mut self, discoveries: Vec<PeerDiscovery>) -> &mut Self {
self.peer_discoveries = discoveries;
self
}
/// Set the protocol extensions that should be enabled
pub fn protocol_extensions(&mut self, extensions: ProtocolExtensionFlags) -> &mut Self {
self.protocol_extensions = Some(extensions);
self
}
/// Add the given extension factory that should be activated.
pub fn extension(&mut self, extension: ExtensionFactory) -> &mut Self {
self.extensions.push(extension);
self
}
/// Set the extension factories that should be activated for this torrent.
/// This overrides any previously set extensions.
pub fn extensions(&mut self, extensions: Vec<ExtensionFactory>) -> &mut Self {
self.extensions = extensions;
self
}
/// Set the underlying storage for storing the torrent file data.
pub fn storage<F>(&mut self, storage: F) -> &mut Self
where
F: FnOnce(StorageParams) -> Storage + Send + Sync + 'static,
{
self.storage = Some(Box::new(storage));
self
}
/// Add the operation to the torrent for processing data.
pub fn operation(&mut self, operation: Operation) -> &mut Self {
self.operations.get_or_insert(Vec::new()).push(operation);
self
}
/// Set the operations used by the torrent for processing data
pub fn operations(&mut self, operations: Vec<Operation>) -> &mut Self {
self.operations = Some(operations);
self
}
/// Add the given tracker to the torrent.
pub fn tracker(&mut self, tracker: TorrentTracker) -> &mut Self {
self.trackers.push(tracker);
self
}
/// Set the trackers of the torrent to use.
/// This will override any existing configured trackers.
pub fn trackers(&mut self, trackers: Vec<TorrentTracker>) -> &mut Self {
self.trackers = trackers;
self
}
/// Set the piece picker factory to use for the torrent.
pub fn piece_picker<F>(&mut self, picker: F) -> &mut Self
where
F: Fn(TorrentHandle, usize, DataPool, Storage, PickerOptions) -> PiecePicker
+ Send
+ Sync
+ 'static,
{
self.piece_picker = Some(Box::new(picker));
self
}
/// Build the torrent from the given data.
/// This is the same as calling `Torrent::try_from(self)`.
pub fn build(&mut self) -> Result<Torrent> {
Torrent::try_from(self)
}
/// Get the list of default operations for the torrent.
pub fn default_operations() -> Vec<Operation> {
Operation::default_operations()
}
}
impl Debug for TorrentRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TorrentRequest")
.field("metadata", &self.metadata)
.field("options", &self.options)
.field("config", &self.config)
.field("peer_discoveries", &self.peer_discoveries)
.field("protocol_extensions", &self.protocol_extensions)
.field("extensions", &self.extensions)
.field("operations", &self.operations)
.field("trackers", &self.trackers)
.finish()
}
}
impl TryFrom<&mut TorrentRequest> for Torrent {
type Error = TorrentError;
fn try_from(request: &mut TorrentRequest) -> Result<Self> {
let metadata = request.metadata.take().ok_or(TorrentError::InvalidRequest(
"metadata is missing".to_string(),
))?;
let peer_discoveries = std::mem::take(&mut request.peer_discoveries);
let protocol_extensions = request
.protocol_extensions
.unwrap_or_else(DEFAULT_TORRENT_PROTOCOL_EXTENSIONS);
let extensions = std::mem::take(&mut request.extensions);
let options = request.options.unwrap_or(TorrentFlags::default());
let config = request
.config
.take()
.unwrap_or_else(|| TorrentConfig::builder().build());
let data_pool = DataPool::new();
let storage = request.storage.take().ok_or(TorrentError::InvalidRequest(
"file storage is missing".to_string(),
))?;
let storage_params = StorageParams {
info_hash: metadata.info_hash.clone(),
path: config.path().to_path_buf(),
data_pool: data_pool.clone(),
};
let operations = request
.operations
.take()
.unwrap_or_else(TorrentRequest::default_operations);
let trackers = std::mem::take(&mut request.trackers);
let piece_picker = std::mem::take(&mut request.piece_picker).unwrap_or_else(|| {
Box::new(
|handle: TorrentHandle,
max_outstanding_pieces: usize,
data_pool: DataPool,
storage: Storage,
options: PickerOptions| {
FxPiecePicker::new(
handle,
data_pool,
storage,
vec![
RarestFirstStrategy::new().into(),
SuggestedOnlyStrategy::new().into(),
SequentialStrategy::new().into(),
PriorityStrategy::new().into(),
],
32 * 1024 * 1024, // 32MB, TODO: make this configurable
max_outstanding_pieces,
options,
)
.into()
},
)
});
Ok(Self::new(
metadata,
peer_discoveries,
protocol_extensions,
extensions,
options,
config,
data_pool,
storage(storage_params),
operations,
trackers,
piece_picker,
))
}
}
/// The result metrics from a tracker scrape.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct ScrapeMetrics {
/// The number of active peers that have completed downloading.
pub complete: u32,
/// The number of active peers that have not completed downloading.
pub incomplete: u32,
/// The number of peers that have ever completed downloading.
pub downloaded: u32,
}
impl FromIterator<ScrapeMetrics> for ScrapeMetrics {
fn from_iter<T: IntoIterator<Item = ScrapeMetrics>>(iter: T) -> Self {
let mut result = Self::default();
for metrics in iter {
result.complete += metrics.complete;
result.incomplete += metrics.incomplete;
result.downloaded += metrics.downloaded;
}
result
}
}
#[derive(Debug, Display, Clone, PartialEq)]
pub enum TorrentEvent {
/// Invoked when the status of the torrent has changed
#[display("torrent state has changed to {}", _0)]
StateChanged(TorrentState),
/// Invoked when the torrent metadata has been changed
#[display("torrent metadata has been changed")]
MetadataChanged(TorrentMetadata),
/// Invoked when a new peer connection has been established
#[display("peer {} has been connected", _0)]
PeerConnected(SocketAddr),
/// Invoked when an existing peer connection has closed.
#[display("peer {} has been disconnected", _0)]
PeerDisconnected(SocketAddr),
/// Invoked when the active trackers have been changed
#[display("trackers have changed")]
TrackersChanged,
/// Invoked when the pieces have changed of the torrent
#[display("torrent pieces have changed to {}", _0)]
PiecesChanged(usize),
/// Invoked when the priorities of the torrent pieces have changed
#[display("torrent piece priorities have changed")]
PiecePrioritiesChanged,
/// Invoked when a piece has been completed.
#[display("piece {} has been completed", _0)]
PieceCompleted(PieceIndex),
/// Invoked when the files have changed of the torrent
#[display("torrent files have changed")]
FilesChanged,
/// Invoked when the options of the torrent have been changed
#[display("torrent options have changed")]
OptionsChanged,
/// Invoked when the torrent metrics have been updated
#[display("torrent stats changed {:?}", _0)]
Stats(Metrics),
}
/// A torrent is an actual tracked torrent which is communicating with one or more trackers and peers.
///
/// Use [TorrentMetadata] if you only want to retrieve the metadata of a torrent.
#[derive(Debug, Display, Clone)]
#[display("{}", inner)]
pub struct Torrent {
/// The unique peer id of this torrent
/// This id is used as our client id when connecting to peers
peer_id: PeerId,
metrics: Metrics,
pub(crate) inner: InnerTorrent,
instance_counter: Arc<()>,
cancellation_token: CancellationToken,
}
impl Torrent {
/// Create a new request builder for creating a new torrent.
/// See [TorrentRequest] for more information.
pub fn request() -> TorrentRequest {
TorrentRequest::default()
}
fn new(
metadata: TorrentMetadata,
peer_discoveries: Vec<PeerDiscovery>,
protocol_extensions: ProtocolExtensionFlags,
extensions: Vec<ExtensionFactory>,
options: TorrentFlags,
config: TorrentConfig,
data_pool: DataPool,
storage: Storage,
operations: Vec<Operation>,
trackers: Vec<TorrentTracker>,
piece_picker: Box<PiecePickerFactory>,
) -> Self {
let handle = TorrentHandle::new();
let callbacks = MultiThreadedCallback::new();
let info_hash = metadata.info_hash.clone();
let (command_sender, command_receiver) = channel!(1024);
let location = config.path().to_path_buf();
let mut piece_picker = piece_picker(
handle,
config.max_in_flight_pieces,
data_pool.clone(),
storage.clone(),
PickerOptions::Priority,
);
piece_picker.set_max_outstanding(config.max_in_flight_pieces);
let mut context = TorrentContext::new(
handle,
metadata,
config,
peer_discoveries.first().map(|e| e.addr().port()),
protocol_extensions,
extensions,
options,
data_pool,
trackers,
storage,
piece_picker,
command_sender,
callbacks,
);
let torrent = Self {
peer_id: context.peer_id,
metrics: context.metrics.clone(),
inner: InnerTorrent::new(
context.handle,
context.command_sender().clone(),
context.callbacks.clone(),
),
instance_counter: Arc::new(Default::default()),
cancellation_token: context.cancellation_token.clone(),
};
spawn!("TorrentContext::run", async move {
context
.run(operations, command_receiver, peer_discoveries)
.await;
});
info!(
"Torrent {} (info hash {}) created with storage location {:?}",
torrent, info_hash, location
);
torrent
}
/// Returns the unique handle of the torrent.
pub fn handle(&self) -> TorrentHandle {
self.inner.handle()
}
/// Returns `true` if the torrent is still valid, else `false` if it has been closed/stopped.
pub fn is_valid(&self) -> bool {
self.inner.is_valid()
}
/// Returns the unique peer id of this torrent.
/// This ID is used within the peer clients to identify with remote peers.
pub fn peer_id(&self) -> PeerId {
self.peer_id
}
/// Returns the port number on which the torrent is listening for incoming connections,
/// or [None] if the torrent is not listening for incoming peer connections.
pub async fn peer_port(&self) -> Option<u16> {
self.inner
.sender
.send(|tx| TorrentCommand::PeerPort { response: tx })
.await
.await
.unwrap_or_default()
}
/// Add a new peer address for this torrent.
///
/// The address is added to the peer pool. A new connection may be established
/// when additional peers are needed.
///
/// # Errors
///
/// When the torrent is invalid or stopped, it returns [TorrentError::InvalidHandle].
pub async fn add_peer(&self, addr: SocketAddr) -> Result<()> {
self.inner.add_peer(addr).await
}
/// Get the absolute filesystem path to a given file in the torrent.
///
/// This combines the torrent's storage path with the file's [`torrent_path`]
/// to produce a full path on the local filesystem.
///
/// # Errors
///
/// When the torrent is invalid or stopped, it returns [TorrentError::InvalidHandle].
pub async fn absolute_file_path(&self, file: &File) -> Result<PathBuf> {
Ok(self
.inner
.sender
.send(|tx| TorrentCommand::GetFilePath {
file: file.clone(),
response: tx,
})
.await
.await?)
}
/// Get the absolute path to the torrent location.
/// This can either be a file or directory to the torrent depending on the type of the torrent.
///
/// The path is only available when the `metadata` of the torrent is known.
/// See [Torrent::is_metadata_known].
///
/// # Returns
///
/// It returns the location of the torrent if the metadata is known, else [None].
pub async fn path(&self) -> Option<PathBuf> {
self.inner
.sender
.send(|tx| TorrentCommand::GetPath { response: tx })
.await
.await
.unwrap_or_default()
}
/// Returns the info hash of the torrent.
///
/// # Errors
///
/// When the torrent is invalid or stopped, it returns [TorrentError::InvalidHandle].
pub async fn info_hash(&self) -> Result<InfoHash> {
self.inner.info_hash().await
}
/// Returns the state of the torrent.
pub async fn state(&self) -> TorrentState {
self.inner.state().await
}
/// Returns the enabled protocol extensions of the torrent.
///
/// # Errors
///
/// When the torrent is invalid or stopped, it returns [TorrentError::InvalidHandle].
pub async fn protocol_extensions(&self) -> Result<ProtocolExtensionFlags> {
self.inner.protocol_extensions().await
}
/// Get the metric statics of the torrent.
/// These are collected from each active peer connection within the torrent and are periodically scraped.
///
/// # Returns
///
/// It returns the statics of this torrent.
pub fn metrics(&self) -> &Metrics {
&self.metrics
}
/// Returns the metadata of the torrent, or [TorrentError::InvalidHandle] when the torrent is invalid.
pub async fn metadata(&self) -> Result<TorrentMetadata> {
self.inner.metadata().await
}
/// Returns `true` when the metadata of the torrent is known, else `false` when it's still being retrieved.
pub async fn is_metadata_known(&self) -> bool {
self.inner.is_metadata_known().await
}
/// Returns the active options of the torrent.
pub async fn options(&self) -> Result<TorrentFlags> {
self.inner.options().await
}
/// Add the given options to the torrent.
///
/// It triggers the [TorrentEvent::OptionsChanged] event if the options changed.
/// If the options are already present, this will be a no-op.
pub async fn add_options(&self, options: TorrentFlags) {
let _ = self
.inner
.sender
.send(|tx| TorrentCommand::AddOptions {
options,
response: tx,
})
.await
.await;
}
/// Remove the given options to the torrent.
///
/// It triggers the [TorrentEvent::OptionsChanged] event if the options changed.
/// If none of the given options are present, this will be a no-op.
pub async fn remove_options(&self, options: TorrentFlags) {
let _ = self
.inner
.sender
.send(|tx| TorrentCommand::RemoveOptions {
options,
response: tx,
})
.await
.await;
}
/// Return the total amount of pieces for this torrent.
/// If the metadata is still being retrieved, the total pieces cannot yet be known and this will result in 0.
pub async fn total_pieces(&self) -> usize {
self.inner.total_pieces().await
}
/// Get the total number of completed pieces for this torrent.
///
/// # Returns
///
/// It returns the total amount of completed pieces of this torrent when known.
pub async fn total_completed_pieces(&self) -> usize {
self.inner
.sender
.send(|tx| TorrentCommand::NumOfCompletedPieces { response: tx })
.await
.await
.unwrap_or_default()
}
/// Retrieve the torrent pieces, if known.
/// If the metadata is still being retrieved, the pieces cannot yet be created and will result in [None].
///
/// # Returns
///
/// Returns the current torrent pieces when known, else [None].
pub async fn pieces(&self) -> Option<Vec<Piece>> {
self.inner
.sender
.send(|tx| TorrentCommand::GetPieces { response: tx })
.await
.await
.ok()
}
/// Returns the information about a specific piece within the torrent.
/// If the pieces are not yet known, in case the metadata is still being retrieved, then it returns [None].
///
/// If a piece index is requested out-of-bounds of the pieces, [None] will also be returned.
pub async fn piece(&self, piece: &PieceIndex) -> Option<Piece> {
self.inner.piece(piece).await
}
/// Get the priorities of the pieces.
/// It might return an empty array if the metadata is still being retrieved.
pub async fn piece_priorities(&self) -> BTreeMap<PieceIndex, PiecePriority> {
self.inner
.sender
.send(|tx| TorrentCommand::GetPiecePriorities { response: tx })
.await
.await
.unwrap_or_default()
}
/// Set the priorities of the pieces.
/// Use [Torrent::piece_priorities] to get the current priorities with its [PieceIndex].
///
/// Providing all piece indexes of the torrent is not required.
pub async fn prioritize_pieces(&self, priorities: Vec<(PieceIndex, PiecePriority)>) {
let _ = self
.inner
.sender
.send(|tx| TorrentCommand::PrioritizePieces {
priorities,
response: tx,
})
.await
.await;
}
/// Returns `true` if the piece index has been downloaded, validated, and written to storage.
pub async fn has_piece(&self, piece: &PieceIndex) -> bool {
self.inner
.sender
.send(|tx| TorrentCommand::HasPiece {
piece: *piece,
response: tx,
})
.await
.await
.unwrap_or_default()
}
/// Prioritize the given bytes within the torrent.
/// This will match the bytes against the relevant pieces, and prioritize those pieces.
pub async fn prioritize_bytes(&self, bytes: &Range<usize>, priority: PiecePriority) {
self.inner.prioritize_bytes(bytes, priority).await;
}
/// Returns `true` if the given byte range is available in the torrent, else `false`.
/// This means that the bytes have been downloaded, written, and validated.
pub async fn has_bytes(&self, range: &Range<usize>) -> bool {
self.inner.has_bytes(range).await
}
/// Returns the total of connected peers have the given piece available.
pub async fn availability(&self, index: PieceIndex) -> usize {
self.inner.availability(index).await
}
/// Returns the availability of all pieces.
pub async fn availabilities(&self) -> BTreeMap<PieceIndex, usize> {
self.inner.availabilities().await
}
/// Get the total files of the torrent.
/// If the metadata is still being retrieved, the files cannot yet be created and will result in [None].
///
/// # Returns
///
/// Returns the total files of the torrent when known, else [None].
pub async fn total_files(&self) -> Option<usize> {
self.inner
.sender
.send(|tx| TorrentCommand::NumOfFiles { response: tx })
.await
.await
.ok()
}
/// Returns the files of the torrent, if the metadata is known (see [Torrent::is_metadata_known]).
/// If the metadata is still being retrieved, the returned files array will be empty.
pub async fn files(&self) -> Vec<File> {
self.inner.files().await
}
/// Returns the [File] for the given torrent file index, if found.
pub async fn file(&self, file: &FileIndex) -> Option<File> {
self.inner.file(file).await
}
/// Returns the [File] for the given torrent file name, if found.
pub async fn file_by_name(&self, name: &str) -> Option<File> {
self.inner.file_by_name(name).await
}
/// Stream the given file from the torrent.
/// It returns an error if the file stream couldn't be started.
pub async fn stream(&self, file: &File) -> Result<FileStream> {
self.inner.stream(&file.index).await
}
/// Set the priorities of the torrent files.
/// Use [Torrent::files] to get the current files with their respective [FileIndex].
///
/// Providing all file indexes of the torrent is not required.
pub async fn prioritize_files(&self, priorities: Vec<(FileIndex, FilePriority)>) {
let _ = self
.inner
.sender
.send(|tx| TorrentCommand::PrioritizeFiles {
priorities,
response: tx,
})
.await
.await;
}
/// Returns the number of healthy peer connections in the torrent.
pub async fn active_peer_connections(&self) -> usize {
self.inner
.sender
.send(|tx| TorrentCommand::NumOfActivePeerConnections { response: tx })
.await
.await
.unwrap_or_default()
}
/// Returns the number of active tracker connections in the torrent.
pub async fn active_tracker_connections(&self) -> usize {
self.inner
.sender
.send(|tx| TorrentCommand::NumOfActiveTrackerConnections { response: tx })
.await
.await
.unwrap_or_default()
}
/// Check if the torrent has completed downloading all wanted pieces.
pub async fn is_completed(&self) -> bool {
self.inner
.sender
.send(|tx| TorrentCommand::IsCompleted { response: tx })
.await
.await
.unwrap_or_default()
}
/// Returns `true` when the torrent is currently paused.
pub async fn is_paused(&self) -> bool {
self.inner
.sender
.send(|tx| TorrentCommand::IsPaused { response: tx })
.await
.await
.unwrap_or_default()
}
/// Announce this torrent to the known trackers.
/// This will retrieve the announcement information from the trackers.
///
/// # Returns
///
/// Returns the announcement information, or [TorrentError::InvalidHandle] when the torrent is invalid.
pub async fn announce(&self) -> Result<AnnouncementResult> {
if !self.is_valid() {
return Err(TorrentError::InvalidHandle(self.inner.handle));
}
// try to wait for at least 2 connections
if self.active_tracker_connections().await == 0 {
self.wait_for_trackers(2).await;
}
Ok(self
.inner
.sender
.send(|tx| TorrentCommand::AnnounceAll { response: tx })
.await
.await?)
}
/// Scrape the trackers of the torrent to retrieve the metrics.
pub async fn scrape(&self) -> Result<ScrapeMetrics> {
if !self.is_valid() {
return Err(TorrentError::InvalidHandle(self.inner.handle));
}
// try to wait for at least 2 connections
if self.active_tracker_connections().await == 0 {
self.wait_for_trackers(2).await;
}
Ok(self
.inner
.sender
.send(|tx| TorrentCommand::ScrapeAll { response: tx })
.await
.await?)
}
/// Returns an existing peer from the peer pool.
/// The returned instance is a weak reference that can be dropped by the pool at any time.
///
/// ## Remark
///
/// Before calling a method,
/// make sure to check if the reference is still valid by calling [Peer::is_valid].
pub async fn peer(&self, addr: &SocketAddr) -> Option<Peer> {
self.inner.peer(addr).await
}
/// Returns an existing peer from the peer pool by the given address.
/// The returned instance is a weak reference that can be dropped by the pool at any time.
///
/// ## Remark
///
/// Before calling a method,
/// make sure to check if the reference is still valid by calling [Peer::is_valid].
pub async fn peer_by_addr(&self, addr: &SocketAddr) -> Option<Peer> {
self.inner.peer_by_addr(addr).await
}
/// Resume the downloading of the torrent data.
pub async fn resume(&self) {
let _ = self
.inner
.sender
.send(|tx| TorrentCommand::Resume { response: tx })
.await
.await;
}
/// Pause the current torrent.
pub async fn pause(&self) {
let _ = self
.inner
.sender
.send(|tx| TorrentCommand::Pause { response: tx })
.await
.await;
}
/// Returns the torrent data for the given piece, if available.
/// This doesn't verify if the bytes are valid and completed.
pub async fn read_piece(&self, piece: &PieceIndex) -> Result<Vec<u8>> {
self.inner.read_piece(piece).await
}
/// Returns the torrent data for the given piece byte range, if available.
/// This doesn't verify if the bytes are valid and completed.
pub async fn read_piece_bytes(
&self,
piece: &PieceIndex,
range: Range<usize>,
) -> Result<Vec<u8>> {
self.inner.read_piece_bytes(piece, range).await
}
/// Try to read the bytes from the given torrent file.
/// This reads all available bytes of the file stored within the [StorageExtension].
///
/// Returns the amount of bytes read and the byte buffer.
///
/// ## Remarks
///
/// This doesn't verify if the bytes are valid and completed.
pub async fn read_file_to_end(&self, file: &FileIndex) -> Result<(usize, Vec<u8>)> {
self.inner
.sender
.send(|tx| TorrentCommand::ReadFileToEnd {
file: *file,
response: tx,
})
.await
.await
}
/// Wait for the given number of active trackers.
async fn wait_for_trackers(&self, num_of_trackers: usize) {
let notifier = Arc::new(Notify::new());
let mut receiver = self.subscribe();
let cancellation_token = CancellationToken::new();
let inner_cancel = cancellation_token.clone();
let inner_notifier = notifier.clone();
tokio::spawn(async move {
loop {
select! {
_ = inner_cancel.cancelled() => break,
Ok(event) = receiver.recv() => {
if let TorrentEvent::TrackersChanged = *event {
inner_notifier.notify_one();
}
}
}
}
});
loop {
notifier.notified().await;
if self.active_tracker_connections().await >= num_of_trackers {
break;
}
}
cancellation_token.cancel();
}
}
impl Callback<TorrentEvent> for Torrent {
fn subscribe(&self) -> Subscription<TorrentEvent> {
self.inner.subscribe()
}
}
impl PartialEq for Torrent {
fn eq(&self, other: &Self) -> bool {
self.inner.handle == other.inner.handle && self.peer_id == other.peer_id
}
}
impl Drop for Torrent {
fn drop(&mut self) {
if Arc::strong_count(&self.instance_counter) == 1 {
self.cancellation_token.cancel();
}
}
}
#[derive(Debug, Display, Clone)]
#[display("{}", handle)]
pub struct InnerTorrent {
handle: TorrentHandle,
sender: ChannelSender<TorrentCommand>,
callbacks: MultiThreadedCallback<TorrentEvent>,
}
impl InnerTorrent {
pub fn new(
handle: TorrentHandle,
sender: ChannelSender<TorrentCommand>,
callbacks: MultiThreadedCallback<TorrentEvent>,
) -> Self {
Self {
handle,
sender,
callbacks,
}
}
/// Returns the unique handle of the torrent.
pub fn handle(&self) -> TorrentHandle {
self.handle
}
/// Returns `true` if the torrent is still valid, else `false` if it has been closed.
pub fn is_valid(&self) -> bool {
!self.sender.is_closed()
}
/// Returns the info hash of the torrent.
pub async fn info_hash(&self) -> Result<InfoHash> {
Ok(self
.sender
.send(|tx| TorrentCommand::InfoHash { response: tx })
.await
.await?)
}
/// Returns the state of the torrent.
pub async fn state(&self) -> TorrentState {
self.sender
.send(|tx| TorrentCommand::State { response: tx })
.await
.await
.unwrap_or(TorrentState::Error)
}
/// Returns the port on which the torrent is listening for incoming connections.
pub async fn peer_port(&self) -> Option<u16> {
self.sender
.send(|tx| TorrentCommand::PeerPort { response: tx })
.await
.await
.ok()
.flatten()
}
/// Returns an existing peer from the pool by the given handle.
/// The returned instance is a weak reference that can be dropped by the pool at any time.
pub async fn peer(&self, addr: &SocketAddr) -> Option<Peer> {
self.sender
.send(|tx| TorrentCommand::GetPeer {
addr: *addr,
response: tx,
})
.await
.await
.ok()
.flatten()
}
/// Returns an existing peer from the pool by the given address.
/// The returned instance is a weak reference that can be dropped by the pool at any time.
pub async fn peer_by_addr(&self, addr: &SocketAddr) -> Option<Peer> {
self.sender
.send(|tx| TorrentCommand::GetPeerByAddr {
addr: *addr,
response: tx,
})
.await
.await
.ok()
.flatten()
}
/// Add the given peer address to the torrent pool for establishing a connection.
pub async fn add_peer(&self, addr: SocketAddr) -> Result<()> {
Ok(self
.sender
.send(|tx| TorrentCommand::AddPeer { addr, response: tx })
.await
.await?)
}
/// Add the given peer addresses to the torrent pool for establishing connections.
pub async fn add_peers(&self, addrs: Vec<SocketAddr>) {
self.sender
.fire_and_forget(TorrentCommand::AddPeers { addrs })
.await;
}
/// Returns the total number of peer addresses known in the peer pool.
pub async fn peer_addrs_len(&self) -> usize {
self.sender
.send(|tx| TorrentCommand::NumOfPeerAddrs { response: tx })
.await
.await
.unwrap_or_default()
}
/// Notify the torrent that a peer has connected.
pub async fn peer_connected(&self, peer: Peer) {
self.sender
.fire_and_forget(TorrentCommand::PeerConnected { peer })
.await
}
/// Decrease the priority of the given peer addresses in the torrent pool.
pub async fn decrease_peer_priority(&self, addrs: Vec<SocketAddr>) {
self.sender
.fire_and_forget(TorrentCommand::DecreasePeerPriority { addrs })
.await;
}
/// Returns the enabled protocol extensions of the torrent.
/// It can return [Err] when the torrent has been closed (see [Torrent::is_valid]).
pub async fn protocol_extensions(&self) -> Result<ProtocolExtensionFlags> {
Ok(self
.sender
.send(|tx| TorrentCommand::ProtocolExtensions { response: tx })
.await
.await?)
}
/// Returns the metadata of the torrent, or [TorrentError::InvalidHandle] when the torrent is invalid.
pub async fn metadata(&self) -> Result<TorrentMetadata> {
Ok(self
.sender
.send(|tx| TorrentCommand::Metadata { response: tx })
.await
.await?)
}
/// Update the metadata of the torrent.
pub async fn set_metadata(&self, metadata: TorrentMetadataInfo) {
self.sender
.fire_and_forget(TorrentCommand::SetMetadata { metadata })
.await
}
/// Returns the completed pieces bitfield of the torrent.
pub async fn bitfield(&self) -> Result<BitVec> {
Ok(self
.sender
.send(|tx| TorrentCommand::Bitfield { response: tx })
.await
.await?)
}
/// Returns `true` when the metadata of the torrent is known, else `false` when it's still being retrieved.
pub async fn is_metadata_known(&self) -> bool {
self.sender
.send(|tx| TorrentCommand::IsMetadataKnown { response: tx })
.await
.await
.unwrap_or_default()
}
/// Returns the active options of the torrent.
pub async fn options(&self) -> Result<TorrentFlags> {
Ok(self
.sender
.send(|tx| TorrentCommand::GetOptions { response: tx })
.await
.await?)
}
/// Returns the configuration used by the torrent.
/// This is a snapshot and might be modified in the future.
pub async fn config(&self) -> Result<TorrentConfig> {
Ok(self
.sender
.send(|tx| TorrentCommand::GetConfig { response: tx })
.await
.await?)
}
/// Returns the information about a specific piece within the torrent.
/// If the pieces are not yet known, in case the metadata is still being retrieved, then it returns [None].
///
/// If a piece index is requested out-of-bounds of the pieces, [None] will also be returned.
pub async fn piece(&self, piece: &PieceIndex) -> Option<Piece> {
self.sender
.send(|tx| TorrentCommand::GetPiece {
piece: *piece,
response: tx,
})
.await
.await
.ok()
.flatten()
}
/// Return the total amount of pieces for this torrent.
/// If the metadata is still being retrieved, the total pieces cannot yet be known and this will result in 0.
pub async fn total_pieces(&self) -> usize {
self.sender
.send(|tx| TorrentCommand::NumOfPieces { response: tx })
.await
.await
.unwrap_or_default()
}
/// Returns the wanted pieces of the torrent.
pub async fn wanted_pieces(&self) -> Result<Vec<Piece>> {
Ok(self
.sender
.send(|tx| TorrentCommand::WantedPieces { response: tx })
.await
.await?)
}
/// Update the availability of the given pieces for the torrent.
pub async fn piece_availabilities(&self, pieces: Vec<PieceIndex>, available: bool) {
self.sender
.fire_and_forget(TorrentCommand::PieceAvailabilities { pieces, available })
.await
}
/// Prioritize the given bytes within the torrent.
pub async fn prioritize_bytes(&self, bytes: &Range<usize>, priority: PiecePriority) {
let _ = self
.sender
.send(|tx| TorrentCommand::PrioritizeBytes {
bytes: bytes.clone(),
priority,
response: tx,
})
.await
.await;
}
/// Returns `true` if the given byte range is available in the torrent, else `false`.
pub async fn has_bytes(&self, range: &Range<usize>) -> bool {
self.sender
.send(|tx| TorrentCommand::HasBytes {
bytes: range.clone(),
response: tx,
})
.await
.await
.unwrap_or_default()
}
/// Read the given torrent byte range.
pub async fn read_bytes(&self, range: &Range<usize>) -> Result<Vec<u8>> {
self.sender
.send(|tx| TorrentCommand::ReadBytes {
range: range.clone(),
response: tx,
})
.await
.await
}
/// Returns the total of connected peers have the given piece available.
pub async fn availability(&self, piece: PieceIndex) -> usize {
self.sender
.send(|tx| TorrentCommand::Availability {
piece,
response: tx,
})
.await
.await
.unwrap_or_default()
}
/// Returns the availability of all pieces.
pub async fn availabilities(&self) -> BTreeMap<PieceIndex, usize> {
self.sender
.send(|tx| TorrentCommand::Availabilities { response: tx })
.await
.await
.unwrap_or_default()
}
/// Returns the files of the torrent, if the metadata is known (see [Torrent::is_metadata_known]).
/// If the metadata is still being retrieved, the returned files array will be empty.
pub async fn files(&self) -> Vec<File> {
self.sender
.send(|tx| TorrentCommand::Files { response: tx })
.await
.await
.unwrap_or_default()
}
/// Returns the torrent file for the given index, if available.
pub async fn file(&self, file: &FileIndex) -> Option<File> {
self.sender
.send(|tx| TorrentCommand::File {
file: *file,
response: tx,
})
.await
.await
.ok()
.flatten()
}
/// Returns the torrent file for the given index, if available.
pub async fn file_by_name(&self, name: &str) -> Option<File> {
self.sender
.send(|tx| TorrentCommand::FileByName {
name: name.to_string(),
response: tx,
})
.await
.await
.ok()
.flatten()
}
/// Returns the [FileIndex] for the starting byte of the given piece.
pub async fn file_index_for(&self, piece: &PieceIndex) -> Option<FileIndex> {
self.sender
.send(|tx| TorrentCommand::FileIndexFor {
piece: *piece,
response: tx,
})
.await
.await
.ok()
.flatten()
}
/// Stream the given file from the torrent.
pub async fn stream(&self, file: &FileIndex) -> Result<FileStream> {
self.sender
.send(|tx| TorrentCommand::FileStream {
file: *file,
response: tx,
})
.await
.await
}
/// Request the torrent piece picker to pick pieces for the given peer.
pub async fn pick_pieces(&self, peer_addr: &SocketAddr) {
self.sender
.fire_and_forget(TorrentCommand::PickPieces {
peer_addr: *peer_addr,
})
.await;
}
/// Process a received piece block from a peer.
pub async fn piece_block_received<T: Into<Vec<u8>>>(
&self,
peer_addr: &SocketAddr,
block: &PieceBlock,
data: T,
) {
self.sender
.fire_and_forget(TorrentCommand::PieceBlockReceived {
peer_addr: *peer_addr,
block: *block,
data: data.into(),
})
.await;
}
/// Inform the torrent that a piece block request has been rejected by the peer.
pub async fn piece_block_rejected(&self, peer_addr: &SocketAddr, block: &PieceBlock) {
self.sender
.fire_and_forget(TorrentCommand::PieceBlockRejected {
peer_addr: *peer_addr,
block: *block,
})
.await
}
/// Returns the torrent data for the given piece, if available.
/// This doesn't verify if the bytes are valid and completed.
pub async fn read_piece(&self, piece: &PieceIndex) -> Result<Vec<u8>> {
self.sender
.send(|tx| TorrentCommand::ReadPiece {
piece: *piece,
response: tx,
})
.await
.await
}
/// Returns the torrent data for the given piece byte range, if available.
/// This doesn't verify if the bytes are valid and completed.
pub async fn read_piece_bytes(
&self,
piece: &PieceIndex,
range: Range<usize>,
) -> Result<Vec<u8>> {
self.sender
.send(|tx| TorrentCommand::ReadPieceBytes {
piece: *piece,
bytes: range,
response: tx,
})
.await
.await
}
/// Calculate the hash for the given piece stored in the storage.
pub async fn hash_v1(&self, piece: &PieceIndex) -> Result<Sha1Hash> {
self.sender
.send(|tx| TorrentCommand::HashV1Data {
piece: *piece,
response: tx,
})
.await
.await
}
/// Calculate the hash for the given piece stored in the storage.
pub async fn hash_v2(&self, piece: &PieceIndex) -> Result<Sha256Hash> {
self.sender
.send(|tx| TorrentCommand::HashV2Data {
piece: *piece,
response: tx,
})
.await
.await
}
/// Returns `true` if the torrent is in the end-game phase, else `false`.
pub async fn is_end_game(&self) -> bool {
self.sender
.send(|tx| TorrentCommand::IsEndGame { response: tx })
.await
.await
.unwrap_or_default()
}
/// Notify the torrent that a peer's connection is closed.
pub(crate) async fn peer_closed(&self, addr: SocketAddr, reason: CloseReason) {
self.sender
.fire_and_forget(TorrentCommand::PeerClosed { addr, reason })
.await;
}
/// Returns the data pool of the torrent.
#[cfg(test)]
pub async fn data_pool(&self) -> Result<DataPool> {
Ok(self
.sender
.send(|tx| TorrentCommand::DataPool { response: tx })
.await
.await?)
}
/// Returns the storage of the torrent.
#[cfg(test)]
pub async fn storage(&self) -> Result<Storage> {
Ok(self
.sender
.send(|tx| TorrentCommand::Storage { response: tx })
.await
.await?)
}
}
impl Callback<TorrentEvent> for InnerTorrent {
fn subscribe(&self) -> Subscription<TorrentEvent> {
self.callbacks.subscribe()
}
}
/// The reason why a pending request was rejected
#[derive(Debug, Clone, PartialEq)]
pub enum RequestRejectedReason {
/// Indicates that the received piece data was invalid
InvalidDataResponse,
/// Indicates that the remote peer rejected the request
RejectedByRemotePeer,
}
/// The command sender to interact with the [TorrentContext] main task loop.
#[derive(Debug)]
pub enum TorrentCommand {
PeerPort {
response: Reply<Option<u16>>,
},
AddPeer {
addr: SocketAddr,
response: Reply<()>,
},
AddPeers {
addrs: Vec<SocketAddr>,
},
/// Returns an existing peer from the torrent by the given handle.
GetPeer {
addr: SocketAddr,
response: Reply<Option<Peer>>,
},
/// Returns an existing peer from the torrent by the given peer address.
GetPeerByAddr {
addr: SocketAddr,
response: Reply<Option<Peer>>,
},
/// Inform that a new peer connection has been established.
PeerConnected {
peer: Peer,
},
DecreasePeerPriority {
addrs: Vec<SocketAddr>,
},
PeerClosed {
addr: SocketAddr,
reason: CloseReason,
},
State {
response: Reply<TorrentState>,
},
GetConfig {
response: Reply<TorrentConfig>,
},
Metadata {
response: Reply<TorrentMetadata>,
},
SetMetadata {
metadata: TorrentMetadataInfo,
},
IsMetadataKnown {
response: Reply<bool>,
},
InfoHash {
response: Reply<InfoHash>,
},
GetOptions {
response: Reply<TorrentFlags>,
},
AddOptions {
options: TorrentFlags,
response: Reply<()>,
},
RemoveOptions {
options: TorrentFlags,
response: Reply<()>,
},
NumOfPieces {
response: Reply<usize>,
},
NumOfFiles {
response: Reply<usize>,
},
/// Returns the total number of completed pieces in the torrent.
NumOfCompletedPieces {
response: Reply<usize>,
},
/// Returns the total number of known peer addresses in the peer pool.
NumOfPeerAddrs {
response: Reply<usize>,
},
/// Returns the total number of active peer connections in the peer pool.
NumOfActivePeerConnections {
response: Reply<usize>,
},
NumOfActiveTrackerConnections {
response: Reply<usize>,
},
GetPath {
response: Reply<Option<PathBuf>>,
},
GetFilePath {
file: File,
response: Reply<PathBuf>,
},
GetPieces {
response: Reply<Vec<Piece>>,
},
GetPiece {
piece: PieceIndex,
response: Reply<Option<Piece>>,
},
/// Returns all wanted pieces of the torrent that have not yet been completed.
WantedPieces {
response: Reply<Vec<Piece>>,
},
/// Update the availability of the given pieces for the torrent.
PieceAvailabilities {
pieces: Vec<PieceIndex>,
available: bool,
},
Files {
response: Reply<Vec<File>>,
},
File {
file: FileIndex,
response: Reply<Option<File>>,
},
FileByName {
name: String,
response: Reply<Option<File>>,
},
FileIndexFor {
piece: PieceIndex,
response: Reply<Option<FileIndex>>,
},
FileStream {
file: FileIndex,
response: Reply<Result<FileStream>>,
},
HasPiece {
piece: PieceIndex,
response: Reply<bool>,
},
HasBytes {
bytes: Range<usize>,
response: Reply<bool>,
},
GetPiecePriorities {
response: Reply<BTreeMap<PieceIndex, PiecePriority>>,
},
PrioritizePieces {
priorities: Vec<(PieceIndex, PiecePriority)>,
response: Reply<()>,
},
PrioritizeFiles {
priorities: Vec<(FileIndex, PiecePriority)>,
response: Reply<()>,
},
PrioritizeBytes {
bytes: Range<usize>,
priority: PiecePriority,
response: Reply<()>,
},
IsCompleted {
response: Reply<bool>,
},
IsPaused {
response: Reply<bool>,
},
Pause {
response: Reply<()>,
},
Resume {
response: Reply<()>,
},
AnnounceAll {
response: Reply<AnnouncementResult>,
},
ScrapeAll {
response: Reply<ScrapeMetrics>,
},
ReadPiece {
piece: PieceIndex,
response: Reply<Result<Vec<u8>>>,
},
ReadPieceBytes {
piece: PieceIndex,
bytes: Range<usize>,
response: Reply<Result<Vec<u8>>>,
},
ReadFileToEnd {
file: FileIndex,
response: Reply<Result<(usize, Vec<u8>)>>,
},
ReadBytes {
range: Range<usize>,
response: Reply<Result<Vec<u8>>>,
},
Availability {
piece: PieceIndex,
response: Reply<usize>,
},
Availabilities {
response: Reply<BTreeMap<PieceIndex, usize>>,
},
HashV1Data {
piece: PieceIndex,
response: Reply<Result<Sha1Hash>>,
},
HashV2Data {
piece: PieceIndex,
response: Reply<Result<Sha256Hash>>,
},
ProtocolExtensions {
response: Reply<ProtocolExtensionFlags>,
},
Bitfield {
response: Reply<BitVec>,
},
PickPieces {
peer_addr: SocketAddr,
},
PieceBlockReceived {
peer_addr: SocketAddr,
block: PieceBlock,
data: Vec<u8>,
},
PieceBlockRejected {
peer_addr: SocketAddr,
block: PieceBlock,
},
IsEndGame {
response: Reply<bool>,
},
#[cfg(test)]
DataPool {
response: Reply<DataPool>,
},
#[cfg(test)]
Storage {
response: Reply<Storage>,
},
}
/// The torrent context data.
/// This context can be shared by multiple [Torrent] instances, but only one [Torrent] instance can own the context.
#[derive(Debug)]
pub struct TorrentContext {
/// The unique immutable handle of the torrent
handle: TorrentHandle,
/// The unique immutable peer id of the torrent
peer_id: PeerId,
/// The peer address port on which the torrent is listening for incoming peer connections
peer_port: Option<u16>,
/// The torrent metadata information of the torrent
/// This might still be incomplete if the torrent was created from a magnet link
metadata: TorrentMetadata,
/// The trackers of the torrent
trackers: Vec<TorrentTracker>,
/// The pool of peer connections
peer_pool: PeerPool,
/// The pieces of the torrent, these are only known if the metadata is available
data_pool: DataPool,
/// The data storage of the torrent.
storage: Storage,
/// The piece picker of the torrent.
piece_picker: PiecePicker,
/// The immutable enabled protocol extensions for this torrent
protocol_extensions: ProtocolExtensionFlags,
/// The immutable peer extension factories for this torrent.
/// These factories create the extensions for each established peer connection.
extensions: Vec<ExtensionFactory>,
/// The verification tasks validating piece data.
verify_tasks: JoinSet<VerifyTaskResult>,
/// The state of the torrent
state: TorrentState,
/// The torrent options that are set for this torrent
options: TorrentFlags,
/// The torrent configuration
config: TorrentConfig,
/// The metrics of the torrent
metrics: Metrics,
/// The main task loop command sender of the torrent
command_sender: ChannelSender<TorrentCommand>,
/// The callbacks for the torrent events
callbacks: MultiThreadedCallback<TorrentEvent>,
/// The main loop cancellation token
cancellation_token: CancellationToken,
}
impl TorrentContext {
pub(crate) fn new(
handle: TorrentHandle,
metadata: TorrentMetadata,
config: TorrentConfig,
peer_port: Option<u16>,
protocol_extensions: ProtocolExtensionFlags,
extensions: Vec<ExtensionFactory>,
options: TorrentFlags,
data_pool: DataPool,
trackers: Vec<TorrentTracker>,
storage: Storage,
piece_picker: PiecePicker,
command_sender: ChannelSender<TorrentCommand>,
callbacks: MultiThreadedCallback<TorrentEvent>,
) -> Self {
Self {
handle,
metadata,
peer_id: PeerId::new(),
peer_port,
trackers,
peer_pool: PeerPool::new(handle, config.peers_upper_limit),
data_pool,
storage,
piece_picker,
verify_tasks: Default::default(),
protocol_extensions,
extensions,
state: Default::default(),
options,
config,
metrics: Metrics::new(),
command_sender,
callbacks,
cancellation_token: CancellationToken::new(),
}
}
/// Run the main task loop of the torrent context.
/// This process is automatically terminated when the `command_receiver` has no more active sender channels.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub(crate) async fn run(
&mut self,
mut operations: Vec<Operation>,
mut command_receiver: ChannelReceiver<TorrentCommand>,
peer_discoveries: Vec<PeerDiscovery>,
) {
let mut operations_tick = time::interval(TICK_INTERVAL);
let mut peer_connections: FuturesUnordered<BoxFuture<'_, (usize, Option<PeerEntry>)>> =
FuturesUnordered::new();
for (idx, discovery) in peer_discoveries.iter().enumerate() {
peer_connections.push(Box::pin(async move {
let entry = discovery.recv().await;
(idx, entry)
}));
}
loop {
select! {
_ = self.cancellation_token.cancelled() => break,
command = command_receiver.recv() => match command {
Some(command) => self.on_command(command).await,
None => break,
},
Some((idx, entry)) = peer_connections.next() => {
if let Some(entry) = entry {
self.on_incoming_peer_connection(entry).await;
let discovery = &peer_discoveries[idx];
peer_connections.push(Box::pin(async move {
let entry = discovery.recv().await;
(idx, entry)
}));
}
},
_ = operations_tick.tick() => self.on_tick(&mut operations, peer_discoveries.as_slice()).await,
}
}
// shutdown the peer pool
self.peer_pool.shutdown().await;
// inform the trackers that the torrent has been stopped
for tracker in self.trackers.iter() {
tracker
.announce(
&self.metadata.info_hash,
self.peer_port().cloned().unwrap_or(6881),
AnnounceEvent::Stopped,
)
.await;
}
self.cancellation_token.cancel();
self.update_state(TorrentState::Stopped);
trace!("Torrent {} main loop ended", self);
}
/// Get the unique handle of the torrent.
/// It returns an owned instance of the torrent handle.
pub fn handle(&self) -> TorrentHandle {
self.handle
}
/// Get the address on which the torrent is listening for new incoming connections.
pub fn addr(&self) -> Option<SocketAddr> {
self.peer_port
.as_ref()
.map(|port| SocketAddr::from((Ipv4Addr::UNSPECIFIED, *port)))
}
/// Returns a reference to the peer pool of the torrent.
pub fn peer_pool(&self) -> &PeerPool {
&self.peer_pool
}
/// Returns a mutable reference to the peer pool of the torrent.
pub fn peer_pool_mut(&mut self) -> &mut PeerPool {
&mut self.peer_pool
}
/// Get the peer id of the torrent.
/// This is the unique peer ID that is used within the communication with remote peers for this torrent.
pub fn peer_id(&self) -> PeerId {
self.peer_id
}
/// Returns the port number on which the torrent is listening.
/// Or [None] if the torrent is not listening for incoming peer connections.
pub fn peer_port(&self) -> Option<&u16> {
self.peer_port.as_ref()
}
/// Returns `true` if the torrent is canceled.
pub fn is_cancelled(&self) -> bool {
self.cancellation_token.is_cancelled()
}
/// Returns a Future that gets fulfilled when the torrent is being cancelled/stopped.
/// The future will complete immediately if the torrenbt is already cancelled when this method is called.
pub fn cancelled(&self) -> WaitForCancellationFuture<'_> {
self.cancellation_token.cancelled()
}
/// Returns a Future that gets fulfilled when the torrent is being cancelled/stopped.
/// The future will complete immediately if the torrenbt is already cancelled when this method is called.
pub fn cancelled_owned(&self) -> WaitForCancellationFutureOwned {
self.cancellation_token.clone().cancelled_owned()
}
/// Get the enabled protocol extensions for the torrent.
pub fn protocol_extensions(&self) -> ProtocolExtensionFlags {
self.protocol_extensions
}
/// Returns the peer extensions, enabled within the torrent, that support the given protocol.
/// These extensions should be activated for each established peer connection of the torrent.
pub fn extensions(&self, protocol: ConnectionProtocol) -> Vec<PeerExtension> {
self.extensions
.iter()
.map(|e| e())
.filter(|e| e.supports(protocol))
.collect()
}
/// Returns `true` if the specified extension is enabled for the torrent, else `false`.
pub fn is_extension_enabled(&self, extension: &str) -> bool {
self.extensions.iter().any(|e| e().name() == extension)
}
/// Returns the configured trackers for the torrent.
pub fn trackers(&self) -> &[TorrentTracker] {
self.trackers.as_slice()
}
/// Returns the DHT tracker for the torrent, if one is configured.
#[cfg(feature = "dht")]
pub fn dht(&self) -> Option<&DhtTracker> {
self.trackers.iter().find_map(|tracker| {
if let TorrentTracker::Dht(dht) = tracker {
Some(dht)
} else {
None
}
})
}
/// Returns the local service discovery for the torrent, if one is configured.
#[cfg(feature = "lsd")]
pub fn lsd(&self) -> Option<&LocalServiceDiscovery> {
self.trackers.iter().find_map(|tracker| {
if let TorrentTracker::Lsd(lsd) = tracker {
Some(lsd)
} else {
None
}
})
}
/// Returns the tracker client for the torrent, if one is configured.
pub fn tracker(&self) -> Option<&TrackerClient> {
self.trackers.iter().find_map(|tracker| {
if let TorrentTracker::TrackerClient(client) = tracker {
Some(client)
} else {
None
}
})
}
/// Returns the currently active trackers of the torrent.
pub async fn active_trackers(&self) -> Vec<Url> {
match self.tracker() {
Some(client) => client.tracker_urls().await,
None => vec![],
}
}
/// Returns the total amount of active tracker connections.
/// This only counts trackers which have at least made one successful announcement.
pub async fn active_tracker_connections(&self) -> usize {
match self.tracker() {
Some(client) => client.trackers_len().await,
None => 0,
}
}
/// Returns the absolute path to the torrent location, if the metadata is known.
/// This can either be a file or directory to the torrent depending on the type of the torrent.
pub fn path(&self) -> Option<PathBuf> {
match &self.metadata.info {
None => None,
Some(info) => Some(self.config.path().join(info.name())),
}
}
/// Get the state of the torrent.
pub fn state(&self) -> &TorrentState {
&self.state
}
/// Get the known torrent transfer stats.
pub fn metrics(&self) -> &Metrics {
&self.metrics
}
/// Get the options of the torrent.
pub fn options(&self) -> &TorrentFlags {
&self.options
}
/// Get an owned instance of the options of the torrent.
pub fn options_owned(&self) -> TorrentFlags {
self.options.clone()
}
/// Get the configuration of the torrent.
pub fn config(&self) -> &TorrentConfig {
&self.config
}
/// Get an owned instance of the metadata from the torrent.
/// It returns an owned instance of the metadata.
pub fn metadata(&self) -> &TorrentMetadata {
&self.metadata
}
/// Check if the metadata of the torrent is known.
/// It returns false when the torrent is still retrieving the metadata, else true.
pub fn is_metadata_known(&self) -> bool {
self.metadata.info.is_some()
}
/// Get the total amount of actively connected peers.
/// This only counts peers that have not been closed yet, so it can be smaller than the peer pool.
pub fn active_peer_connections(&self) -> usize {
self.peer_pool.active_peer_connections()
}
/// Returns a reference to the data pool of the torrent.
pub fn data_pool(&self) -> &DataPool {
&self.data_pool
}
/// Returns a reference to the underlying storage layer of the torrent.
pub fn storage(&self) -> &Storage {
&self.storage
}
/// Returns a reference to the command sender of the torrent.
/// This allowed for delegating tasks to the main task of the torrent context.
pub fn command_sender(&self) -> &ChannelSender<TorrentCommand> {
&self.command_sender
}
/// Returns a reference to the event callbacks of the torrent.
pub fn callbacks(&self) -> &MultiThreadedCallback<TorrentEvent> {
&self.callbacks
}
/// Get the total amount of wanted pieces by the torrent.
pub async fn total_wanted_pieces(&self) -> usize {
self.data_pool.wanted_pieces().await.len()
}
/// Returns `true` if all bytes are completed, validated, and written to the storage, else `false`.
pub async fn has_bytes(&self, range: &Range<usize>) -> bool {
self.data_pool.has_bytes(range.clone()).await
}
/// Prioritize the given pieces within this torrent.
async fn prioritize_pieces(&mut self, priorities: Vec<(PieceIndex, PiecePriority)>) {
self.data_pool
.set_piece_priorities(priorities.as_slice())
.await;
priorities
.iter()
.for_each(|(piece, priority)| self.piece_picker.set_priority(piece, *priority));
self.update_interested_pieces_stats().await;
debug!("Torrent {} piece priorities have been changed", self);
self.invoke_event(TorrentEvent::PiecePrioritiesChanged);
// update the state of the torrent based on the new priorities
// this can only be done after the init phase to not disrupt the init operations
let is_not_init_state = !self.state.is_initializing_phase();
if is_not_init_state {
let new_state = self.determine_state().await;
self.update_state(new_state);
}
}
/// Prioritize the given files within this torrent.
async fn prioritize_files(&mut self, priorities: Vec<(FileIndex, FilePriority)>) {
let file_priorities =
futures::future::join_all(priorities.into_iter().map(|(file, priority)| {
let data_pool = self.data_pool.clone();
async move {
let file = data_pool.file(&file).await?;
Some((file, priority))
}
}))
.await;
let mut piece_priorities = HashMap::new();
for (file, priority) in file_priorities.into_iter().flatten() {
for piece in file.pieces {
piece_priorities
.entry(piece)
.and_modify(|p: &mut PiecePriority| *p = (*p).max(priority))
.or_insert(priority);
}
}
self.prioritize_pieces(piece_priorities.into_iter().collect())
.await;
}
/// Prioritize the given bytes within the torrent.
/// This will match the bytes against the relevant pieces, and prioritize those pieces.
async fn prioritize_bytes(&mut self, bytes: &Range<usize>, priority: PiecePriority) {
let piece_priorities = self
.find_relevant_pieces_for_bytes(bytes)
.await
.into_iter()
.map(|piece| (piece.index, priority))
.collect();
self.prioritize_pieces(piece_priorities).await;
}
/// Check if the torrent has completed downloading all wanted pieces.
pub async fn is_completed(&self) -> bool {
self.data_pool.is_completed().await
}
/// Check if downloading piece data is allowed by the torrent.
pub fn is_download_allowed(&self) -> bool {
let is_download_mode = self.options.contains(TorrentFlags::DownloadMode);
let is_not_paused = !self.options.contains(TorrentFlags::Paused);
let is_not_init_state = !self.state.is_initializing_phase();
is_download_mode && is_not_paused && is_not_init_state
}
/// Check if uploading piece data is allowed by the torrent.
pub fn is_upload_allowed(&self) -> bool {
let is_not_paused = !self.options.contains(TorrentFlags::Paused);
let is_uploading_mode = self.options.contains(TorrentFlags::UploadMode)
|| self.options.contains(TorrentFlags::SeedMode);
is_uploading_mode && is_not_paused
}
/// Check if the torrent is currently paused.
pub fn is_paused(&self) -> bool {
self.options.contains(TorrentFlags::Paused)
}
/// Determines the number of additional peer connections needed for the torrent.
///
/// This function calculates how many more peer connections are required based on the
/// current torrent state, configuration limits, and active connections. It ensures
/// the number of connections stays within defined thresholds.
///
/// # Returns
///
/// It returns a number of additionally wanted connection, ensuring the total
/// stays within the configured peer connection limits.
pub async fn remaining_peer_connections_needed(&self) -> usize {
// if the torrent is trying to retrieve the metadata,
// then allow at least the lower limit during paused state
if self.options.contains(TorrentFlags::Paused) {
return if self.state == TorrentState::RetrievingMetadata {
self.config.peers_lower_limit
} else {
0
};
}
// if the torrent is validating files, then don't open any new peer connections during the process
// if the torrent is finished, then don't actively reach out to new peers
if matches!(
self.state,
TorrentState::CheckingFiles | TorrentState::Finished | TorrentState::Seeding
) {
return 0;
}
let currently_active_peers = self.active_peer_connections();
let is_retrieving_data = self.options.contains(TorrentFlags::DownloadMode);
let is_retrieving_metadata = self.options.contains(TorrentFlags::Metadata)
&& self.state == TorrentState::RetrievingMetadata;
let peer_lower_bound = self.config.peers_lower_limit;
let peer_upper_bound = self.config.peers_upper_limit;
// if we're downloading or retrieving metadata, aim for the upper bound
if is_retrieving_metadata || is_retrieving_data {
return peer_upper_bound.saturating_sub(currently_active_peers);
}
// if we're not actively requesting any data, aim for the lower bound
peer_lower_bound.saturating_sub(currently_active_peers)
}
/// Get all relevant pieces for the given torrent byte range.
///
/// # Arguments
///
/// * `torrent_bytes` - The torrent byte range to retrieve the relevant pieces of.
///
/// # Returns
///
/// It returns all pieces with at least 1 byte overlapping with the given range.
pub async fn find_relevant_pieces_for_bytes(&self, torrent_bytes: &Range<usize>) -> Vec<Piece> {
self.data_pool
.pieces()
.await
.into_iter()
.filter(|e| e.contains(torrent_bytes))
.collect()
}
/// Try to find the [PieceBlock] for the given piece and offset.
/// The offset will be matched against the blocks within the piece.
pub async fn find_piece_block(&self, piece: PieceIndex, offset: usize) -> Option<PieceBlock> {
self.data_pool.find_piece_block(&piece, offset).await
}
/// Get the pieces for the given file.
/// This will retrieve all overlapping pieces with the file.
/// The last piece can be longer than the actual file if the piece overlaps with multiple files.
///
/// # Returns
///
/// Returns the cloned pieces for the given file.
pub async fn file_pieces(&self, file: &File) -> Vec<Piece> {
self.data_pool
.pieces()
.await
.into_iter()
.filter(|piece| file.contains(&piece.torrent_range()))
.collect()
}
/// Get the list of non-padding files contained in the torrent.
///
/// This method filters out any files marked with the [`FileAttributeFlags::PaddingFile`] attribute,
/// so padding files will **not** be included in the returned list.
///
/// ## Remarks
///
/// If the torrent's metadata has not yet been fully retrieved, this method will return an empty vector.
pub async fn files(&self) -> Vec<File> {
self.data_pool
.files()
.await
.into_iter()
// filter out any padding files
.filter_map(|file| {
if !file.attributes().contains(FileAttributeFlags::PaddingFile) {
Some(file)
} else {
None
}
})
.collect()
}
/// Stream the given torrent file.
async fn stream(&self, file: &FileIndex) -> Result<FileStream> {
let file = match self.data_pool.file(file).await {
None => {
return Err(TorrentError::Io(io::Error::new(
io::ErrorKind::NotFound,
"torrent file not found",
)))
}
Some(file) => file,
};
let buffer_len = match self.metadata.info.as_ref() {
None => {
return Err(TorrentError::InvalidMetadata(
"metadata unknown".to_string(),
))
}
Some(info) => info.piece_length as usize,
};
Ok(FileStream::new(
file,
buffer_len,
buffer_len,
self.storage.clone(),
self.data_pool.clone(),
self.command_sender.clone(),
self.subscribe(),
))
}
/// Get the number of non-padding files currently known in the torrent.
///
/// Files marked with the [`FileAttributeFlags::PaddingFile`] attribute are excluded from the count.
///
/// ## Remarks
///
/// If the torrent's metadata has not yet been fully retrieved, this method will return `0`.
pub async fn total_files(&self) -> usize {
self.data_pool.num_of_files().await
}
/// Get the absolute filesystem path to a given file in the torrent.
///
/// This combines the torrent's storage path with the file's [`torrent_path`]
/// to produce a full path on the local filesystem.
pub fn absolute_file_path(&self, file: &File) -> PathBuf {
self.config.path().join(file.torrent_path.as_path())
}
/// Returns sum of bytes of all files within the torrent.
pub fn len(&self) -> Option<usize> {
self.metadata.info.as_ref().map(|e| e.len())
}
/// Returns a list of peer address within the peer pool of the torrent.
pub async fn discovered_peers(&self) -> Vec<SocketAddr> {
self.peer_pool.peer_addrs().cloned().collect_vec()
}
/// Add the given peer to this torrent.
/// Duplicate peers will be ignored and dropped.
async fn add_peer(&mut self, peer: Peer) {
trace!("Torrent {} is trying to add new peer {}", self, peer);
let peer_addr = *peer.addr();
match self.peer_pool.add_peer(peer).await {
Ok(_) => {
debug!("Torrent {} added peer {}", self, peer_addr);
self.metrics.peers.inc();
self.invoke_event(TorrentEvent::PeerConnected(peer_addr));
}
Err(e) => {
debug!("Torrent {} failed to add peer {}, {}", self, peer_addr, e);
}
}
}
/// Handle a closed torrent peer connection.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn on_peer_closed(&mut self, addr: SocketAddr, reason: CloseReason) {
trace!(
"Torrent {} peer connection closed {:?}, reason: {:?}",
self,
addr,
reason
);
let peer = match self.peer_pool.peer_closed(&addr, reason) {
None => return,
Some(peer) => peer,
};
match timeout(Duration::from_millis(200), peer.remote_piece_bitfield()).await {
Ok(bitfield) => {
// decrease the availability of the pieces that the peer had
for (piece_index, _) in bitfield.iter().enumerate().filter(|(_, value)| **value) {
self.update_availability(&piece_index, -1).await;
}
}
Err(e) => {
debug!("Torrent {} failed to collect peer bitfield, {}", self, e);
}
}
self.metrics.peers.dec();
self.invoke_event(TorrentEvent::PeerDisconnected(*peer.addr()));
}
/// Update the given metadata to the torrent.
/// This method can be used by extensions to update the torrent metadata when the current
/// connection is based on a magnet link.
///
/// If the data was already known, this method does nothing.
pub(crate) fn set_metadata(&mut self, metadata_info: TorrentMetadataInfo) {
// verify if the metadata of the torrent is already known
// if so, we ignore this update
if self.metadata.info.is_some() {
return;
}
// validate the received metadata against our info hash
let info_hash = self.metadata.info_hash.clone();
let is_metadata_invalid = metadata_info
.info_hash()
.map(|metadata_info_hash| metadata_info_hash != info_hash)
.map_err(|e| {
debug!(
"Failed to calculate the info hash from the received metadata of {}, {}",
self, e
);
})
.unwrap_or(true);
if is_metadata_invalid {
debug!("Torrent {} received invalid metadata", self);
return;
}
self.metadata.info = Some(metadata_info);
debug!("Torrent {} updated metadata of {}", self, info_hash);
self.invoke_event(TorrentEvent::MetadataChanged(self.metadata.clone()));
}
/// Returns the announce event for the current torrent state.
pub fn announce_event(&self) -> AnnounceEvent {
match self.state {
TorrentState::Paused => AnnounceEvent::Paused,
TorrentState::Seeding | TorrentState::Finished => AnnounceEvent::Completed,
TorrentState::Stopped => AnnounceEvent::Stopped,
_ => AnnounceEvent::Started,
}
}
/// Announce the torrent to all trackers.
pub fn announce_all(&self, response: Option<Sender<AnnouncementResult>>) {
let event = self.announce_event();
let peer_port = self.peer_port().cloned().unwrap_or(6881);
let info_hash = self.metadata.info_hash.clone();
let trackers = self.trackers.clone();
// move the operation to a separate task
trace!("Torrent {} is announcing {}", self, event);
tokio::spawn(async move {
let futures = trackers
.iter()
.map(|tracker| tracker.announce(&info_hash, peer_port, event))
.collect_vec();
let announcement_result = futures::future::join_all(futures)
.await
.into_iter()
.collect();
if let Some(response) = response {
let _ = response.send(announcement_result);
}
});
}
/// Get the scrape metrics result from scraping all trackers for this torrent.
pub fn scrape(&self, response: Option<Sender<ScrapeMetrics>>) {
let handle = self.handle;
let info_hash = self.metadata.info_hash.clone();
let trackers = self.trackers.clone();
// move the operation to a separate task
trace!("Torrent {} is scraping trackers", self);
tokio::spawn(async move {
let futures = trackers
.iter()
.map(|tracker| tracker.scrape(&info_hash))
.collect_vec();
let scrape_metrics = futures::future::join_all(futures).await.into_iter()
.filter_map(|result| {
match result {
Ok(scrape_metrics) => Some(scrape_metrics),
Err(e) => {
debug!("Torrent {} failed to scrape tracker, {}", handle, e);
None
}
}
})
.filter_map(|mut result| {
match result.files.remove(&info_hash) {
None => {
debug!("Torrent {} failed to scrape tracker, info hash {} not found in scrape result", handle, info_hash);
None
}
Some(metrics) => Some(ScrapeMetrics {
complete: metrics.complete,
incomplete: metrics.incomplete,
downloaded: metrics.downloaded,
})
}
})
.collect();
if let Some(response) = response {
let _ = response.send(scrape_metrics);
}
});
}
/// Add the given options to the torrent.
///
/// It triggers the [TorrentEvent::OptionsChanged] event if the options changed.
/// If the options are already present, this will be a no-op.
pub fn add_options(&mut self, options: TorrentFlags) {
// check if all the given options are already present
// of so, this is a no-op
if self.options.contains(options) {
return;
}
self.options |= options;
if self.options.contains(TorrentFlags::SequentialDownload) {
self.piece_picker.add_options(PickerOptions::Sequential);
}
self.invoke_event(TorrentEvent::OptionsChanged);
}
/// Remove the given options from the torrent.
///
/// It triggers the [TorrentEvent::OptionsChanged] event if the options changed.
/// If none of the given options are present, this will be a no-op.
pub fn remove_options(&mut self, options: TorrentFlags) {
// check if any of the given options is actually present
// of not, this is a no-op
if !self.options.intersects(options) {
return;
}
self.options &= !options;
if !self.options.contains(TorrentFlags::SequentialDownload) {
self.piece_picker.remove_options(PickerOptions::Sequential);
}
self.invoke_event(TorrentEvent::OptionsChanged);
}
/// Update the state of this torrent.
/// If the torrent is already in the given state, this will be a no-op.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub fn update_state(&mut self, state: TorrentState) {
// check if we're already in the expected state
// if so, ignore this update
if self.state == state {
return;
}
self.state = state;
// inform the trackers about the new state
self.announce_all(None);
debug!("Torrent {} state updated to {:?}", self, state);
self.invoke_event(TorrentEvent::StateChanged(state));
}
/// Update the availability of the given piece indexes.
/// This will increase or decrease the availability of the torrent pieces.
///
/// This method can be used ot both increase and decrease the availability information
/// to correctly establish the rarity of pieces.
///
/// # Arguments
///
/// * `pieces` - The piece indexes that need to be updated.
///* `available` - Indicates if the pieces become available or unavailable.
pub async fn update_piece_availabilities(&mut self, pieces: Vec<PieceIndex>, available: bool) {
// check if the metadata is known and the pieces have been created
if !self.is_metadata_known() || self.data_pool().num_of_pieces().await == 0 {
trace!(
"Torrent {} is unable to update piece availabilities, metadata or pieces are unknown",
self
);
return;
}
for piece in pieces {
let change = if available { 1 } else { -1 };
self.update_availability(&piece, change).await;
}
}
/// Modify the availability of the given piece in both the data pool and the piece picker.
async fn update_availability(&mut self, piece: &PieceIndex, change: i32) {
self.piece_picker.update_availability(piece, change);
self.data_pool.update_availability(piece, change).await;
}
/// Set the pieces of the torrent.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub(crate) async fn update_pieces(&mut self, pieces: Vec<Piece>) {
let start_time = Instant::now();
let total_pieces = pieces.len();
self.piece_picker.set_pieces(pieces.as_slice());
self.data_pool.set_pieces(pieces).await;
// update the piece availability based on the current peer connections
let mut availability: BTreeMap<PieceIndex, u32> = BTreeMap::new();
let mut peer_count = 0u32;
for peer in self.peer_pool.peers() {
peer_count += 1;
match timeout(Duration::from_millis(200), peer.remote_piece_bitfield()).await {
Ok(bitfield) => {
for (piece_index, _) in
bitfield.into_iter().enumerate().filter(|(_, value)| *value)
{
*availability.entry(piece_index).or_insert(0) += 1;
}
}
Err(e) => {
debug!("Torrent {} failed to collect peer bitfield, {}", self, e);
}
}
}
let availability_len = availability.len();
if availability_len > 0 {
for (piece, availability) in availability {
self.update_availability(&piece, availability as i32).await;
}
debug!(
"Torrent {} updated {} piece availabilities from {} peers",
self, availability_len, peer_count
);
}
let elapsed = start_time.elapsed();
debug!(
"Torrent {} updated {} pieces in {:.3}ms",
self,
total_pieces,
elapsed.as_secs_f64() * 1000.0
);
self.update_interested_pieces_stats().await;
self.invoke_event(TorrentEvent::PiecesChanged(total_pieces));
}
/// Set the files of the torrent, replacing any existing files.
pub(crate) async fn update_files(&self, files: Vec<File>) {
let total_files = files.len();
self.data_pool.set_files(files).await;
debug!("Torrent {} updated {} file(s)", self, total_files);
self.invoke_event(TorrentEvent::FilesChanged);
}
/// Pick pieces for the given peer.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn on_pick_pieces(&mut self, peer_addr: SocketAddr) {
// early exit if downloading pieces is not allowed
if !self.is_download_allowed() {
return;
}
let peer = match self.peer_pool.get(&peer_addr) {
None => return,
Some(peer) => peer,
};
self.piece_picker.pick_pieces(peer).await;
}
/// Verify the given hash of the piece.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub async fn on_piece_verified(
&mut self,
piece_index: &PieceIndex,
v1_hash: Option<Sha1Hash>,
v2_hash: Option<Sha256Hash>,
) {
self.on_pieces_verified(vec![(*piece_index, v1_hash, v2_hash)])
.await;
}
/// Verify the given hashes of the pieces in a single batch.
/// The completed pieces are stored in the data pool with a single update.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub async fn on_pieces_verified(
&mut self,
results: Vec<(PieceIndex, Option<Sha1Hash>, Option<Sha256Hash>)>,
) {
let mut completed_pieces = Vec::with_capacity(results.len());
for (piece_index, v1_hash, v2_hash) in results {
// early exit if the piece couldn't be hashed
// this is most of the time due to missing data in the storage
if v1_hash.is_none() && v2_hash.is_none() {
self.piece_picker.set_failed(&piece_index);
continue;
}
let piece = match self.data_pool.piece(&piece_index).await {
None => {
warn!(
"Torrent {} failed to verify piece {}, piece not found",
self, piece_index
);
continue;
}
Some(piece) => piece,
};
let expected_v1 = piece.hash.hash_v1();
let expected_v2 = piece.hash.hash_v2();
let validation_result = match (expected_v1, expected_v2) {
(Some(_), Some(hash_v2)) | (None, Some(hash_v2)) => {
v2_hash.map(|hash| hash_v2 == hash).unwrap_or(false)
}
(Some(hash_v1), None) => v1_hash.map(|hash| hash == hash_v1).unwrap_or(false),
(None, None) => {
debug!(
"Torrent {} is unable to verify piece {}, piece hash is missing or invalid",
self, piece_index
);
continue;
}
};
if validation_result {
completed_pieces.push(piece);
} else {
trace!("Torrent {} piece {} validation failed", self, piece_index);
self.piece_picker.set_failed(&piece_index);
if self.state != TorrentState::CheckingFiles {
self.metrics.wasted.inc_by(piece.length as u64);
}
}
}
self.on_pieces_completed(&completed_pieces).await;
}
/// Process the completed pieces.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn on_pieces_completed(&mut self, pieces: &[Piece]) {
if pieces.is_empty() {
return;
}
// mark the pieces as completed
let indexes = pieces.iter().map(|piece| piece.index).collect::<Vec<_>>();
self.data_pool.set_completed(&indexes, true).await;
for piece in pieces {
self.piece_picker.set_completed(&piece.index);
// update the metrics
if piece.priority != PiecePriority::None {
self.metrics
.wanted_completed_size
.inc_by(piece.length as u64);
self.metrics.wanted_completed_pieces.inc();
}
self.metrics.completed_pieces.inc();
self.metrics.completed_size.inc_by(piece.length as u64);
// inform the subscribers
debug!("Torrent {} piece {} has been completed", self, piece.index);
self.invoke_event(TorrentEvent::PieceCompleted(piece.index));
}
// check if the all wanted pieces have been completed
// this is skipped while checking files, as the state is determined once all files have been validated
if self.state != TorrentState::CheckingFiles && self.is_completed().await {
// offload the state change to the main loop
self.update_state(TorrentState::Finished);
}
}
/// Update the stats info of all interested pieces by the torrent.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn update_interested_pieces_stats(&self) {
let start_time = Instant::now();
let interested_pieces = self.data_pool.interested_pieces().await;
let len = interested_pieces.len() as u64;
// calculate the wanted metrics
self.metrics.wanted_pieces.set(len);
let wanted_size = self.data_pool.interested_size().await as u64;
self.metrics.wanted_size.set(wanted_size);
// calculate the completed metrics
let wanted_completed_pieces = self
.data_pool
.completed_pieces()
.await
.into_iter()
.filter(|piece| interested_pieces.contains(piece))
.count() as u64;
self.metrics
.wanted_completed_pieces
.set(wanted_completed_pieces);
let remaining_size = self
.data_pool
.wanted_pieces()
.await
.into_iter()
.map(|e| e.length as u64)
.sum();
// calculate the wanted completed size,
// by subtracting the remaining size from the wanted size
self.metrics
.wanted_completed_size
.set(wanted_size.saturating_sub(remaining_size));
let elapsed = start_time.elapsed();
trace!(
"Torrent {} updated interested pieces stats in {:.3}ms",
self,
elapsed.as_secs_f64() * 1000.0
);
}
/// Resume the torrent.
/// This will put the torrent back into [TorrentFlags::DownloadMode], trying to download any missing pieces.
pub(crate) async fn resume(&mut self) {
self.add_options(TorrentFlags::DownloadMode | TorrentFlags::Metadata);
self.remove_options(TorrentFlags::Paused);
// announce to the trackers if we don't know any peers
if self.peer_pool.num_connect_candidates() == 0 {
self.announce_all(None);
}
let wanted_pieces = self.total_wanted_pieces().await;
debug!(
"Torrent {} is resuming with {} wanted remaining pieces",
self, wanted_pieces
);
}
/// Pause the torrent operations.
pub(crate) async fn pause(&mut self) {
self.add_options(TorrentFlags::Paused);
}
/// Add the specified peer addresses to the peer pool of the torrent.
///
/// These peers will be considered as potential connection targets in the future,
/// particularly when the torrent requires additional connections.
/// The provided addresses are queued for possible use; there is no immediate
/// guarantee that connections will be attempted right away.
pub fn add_peer_addresses(&mut self, peer_addrs: Vec<SocketAddr>) {
self.peer_pool.add_peer_addresses(peer_addrs, self.addr());
}
/// Process the given command for the torrent context.
/// It returns `true` when the main loop of the context needs to be stopped, else `false`.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub(crate) async fn on_command(&mut self, command: TorrentCommand) {
match command {
TorrentCommand::PeerPort { response } => {
response.send(self.peer_port);
}
TorrentCommand::AddPeer { addr, response } => {
response.send(self.add_peer_addresses(vec![addr]));
}
TorrentCommand::AddPeers { addrs } => {
self.add_peer_addresses(addrs);
}
TorrentCommand::GetPeer { addr, response } => {
response.send(self.peer_pool.get(&addr).cloned());
}
TorrentCommand::GetPeerByAddr { addr, response } => {
response.send(self.peer_pool.get(&addr).cloned())
}
TorrentCommand::PeerConnected { peer } => self.add_peer(peer).await,
TorrentCommand::DecreasePeerPriority { addrs } => {
self.decrease_peer_addr_priority(addrs)
}
TorrentCommand::PeerClosed { addr, reason } => {
self.on_peer_closed(addr, reason).await;
}
TorrentCommand::Metadata { response } => {
response.send(self.metadata.clone());
}
TorrentCommand::SetMetadata { metadata } => self.set_metadata(metadata),
TorrentCommand::IsMetadataKnown { response } => {
response.send(self.is_metadata_known());
}
TorrentCommand::InfoHash { response } => {
response.send(self.metadata.info_hash.clone());
}
TorrentCommand::GetOptions { response } => {
response.send(self.options);
}
TorrentCommand::AddOptions { options, response } => {
self.add_options(options);
response.send(());
self.options_changed().await;
}
TorrentCommand::RemoveOptions { options, response } => {
self.remove_options(options);
response.send(());
self.options_changed().await;
}
TorrentCommand::State { response } => {
response.send(*self.state());
}
TorrentCommand::GetConfig { response } => {
response.send(self.config.clone());
}
TorrentCommand::NumOfPieces { response } => {
response.send(self.data_pool().num_of_pieces().await);
}
TorrentCommand::NumOfFiles { response } => {
response.send(self.data_pool().num_of_files().await);
}
TorrentCommand::NumOfCompletedPieces { response } => {
response.send(self.data_pool().num_completed_pieces().await);
}
TorrentCommand::NumOfPeerAddrs { response } => response.send(self.peer_pool.len()),
TorrentCommand::NumOfActivePeerConnections { response } => {
response.send(self.peer_pool.active_peer_connections());
}
TorrentCommand::NumOfActiveTrackerConnections { response } => {
response.send(self.active_tracker_connections().await);
}
TorrentCommand::GetPath { response } => {
response.send(self.path().clone());
}
TorrentCommand::GetFilePath { file, response } => {
response.send(self.absolute_file_path(&file));
}
TorrentCommand::GetPieces { response } => {
response.send(self.data_pool.pieces().await);
}
TorrentCommand::GetPiece { piece, response } => {
response.send(self.data_pool.piece(&piece).await);
}
TorrentCommand::WantedPieces { response } => {
response.send(self.data_pool.wanted_pieces().await);
}
TorrentCommand::PieceAvailabilities { pieces, available } => {
self.update_piece_availabilities(pieces, available).await;
}
TorrentCommand::Files { response } => {
response.send(self.data_pool.files().await);
}
TorrentCommand::File { file, response } => {
response.send(self.data_pool.file(&file).await);
}
TorrentCommand::FileByName { name, response } => {
response.send(self.data_pool.file_by_name(name).await);
}
TorrentCommand::FileIndexFor { piece, response } => {
response.send(self.data_pool.file_index_for(&piece).await)
}
TorrentCommand::FileStream { file, response } => {
response.send(self.stream(&file).await)
}
TorrentCommand::HasPiece { piece, response } => {
response.send(self.data_pool.is_piece_completed(&piece).await);
}
TorrentCommand::HasBytes { bytes, response } => {
response.send(self.has_bytes(&bytes).await)
}
TorrentCommand::GetPiecePriorities { response } => {
response.send(self.data_pool.piece_priorities().await)
}
TorrentCommand::PickPieces { peer_addr } => {
self.on_pick_pieces(peer_addr).await;
}
TorrentCommand::PrioritizePieces {
priorities,
response,
} => {
response.send(self.prioritize_pieces(priorities).await);
}
TorrentCommand::PrioritizeFiles {
priorities,
response,
} => {
response.send(self.prioritize_files(priorities).await);
}
TorrentCommand::PrioritizeBytes {
bytes,
priority,
response,
} => {
response.send(self.prioritize_bytes(&bytes, priority).await);
}
TorrentCommand::IsCompleted { response } => {
response.send(self.is_completed().await);
}
TorrentCommand::IsPaused { response } => {
response.send(self.is_paused());
}
TorrentCommand::Pause { response } => {
response.send(self.pause().await);
}
TorrentCommand::Resume { response } => {
response.send(self.resume().await);
}
TorrentCommand::AnnounceAll { response } => {
self.announce_all(Some(response.take()));
}
TorrentCommand::ScrapeAll { response } => {
self.scrape(Some(response.take()));
}
TorrentCommand::ReadPiece { piece, response } => {
response.send(self.read_piece(&piece).await);
}
TorrentCommand::ReadPieceBytes {
piece,
bytes,
response,
} => response.send(self.read_piece_bytes(&piece, bytes).await),
TorrentCommand::ReadFileToEnd { file, response } => {
response.send(self.read_file_to_end(&file).await);
}
TorrentCommand::ReadBytes { range, response } => {
response.send(self.read_bytes(range).await);
}
TorrentCommand::Availability { piece, response } => {
response.send(self.piece_picker.availability(&piece))
}
TorrentCommand::Availabilities { response } => {
response.send(self.piece_picker.availabilities())
}
TorrentCommand::HashV1Data { piece, response } => {
response.send(self.storage().hash_v1(&piece).await.map_err(Into::into));
}
TorrentCommand::HashV2Data { piece, response } => {
response.send(self.storage().hash_v2(&piece).await.map_err(Into::into));
}
TorrentCommand::ProtocolExtensions { response } => {
response.send(self.protocol_extensions())
}
TorrentCommand::Bitfield { response } => response.send(self.data_pool.bitfield().await),
TorrentCommand::PieceBlockReceived {
peer_addr,
block,
data,
} => self.on_piece_block_received(peer_addr, block, data).await,
TorrentCommand::PieceBlockRejected { peer_addr, block } => {
self.on_piece_block_rejected(&peer_addr, block).await
}
TorrentCommand::IsEndGame { response } => {
response.send(self.piece_picker.is_end_game());
}
#[cfg(test)]
TorrentCommand::DataPool { response } => response.send(self.data_pool.clone()),
#[cfg(test)]
TorrentCommand::Storage { response } => response.send(self.storage.clone()),
}
}
#[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
async fn on_incoming_peer_connection(&mut self, entry: PeerEntry) {
trace!(
"Torrent {} is trying to accept incoming {} peer connection",
self,
entry.socket_addr
);
let timeout = self.config.peer_connection_timeout;
let handle = self.handle;
let peer_id = self.peer_id;
let peer_port = self.peer_port().copied();
let peer_client_name = self.config.client_name().to_string();
let metadata = self.metadata.clone();
let data_pool = self.data_pool.clone();
let storage = self.storage.clone();
let protocol_extensions = self.protocol_extensions();
let extensions = self.extensions(entry.protocol());
let command_sender = self.command_sender.clone();
let callbacks = self.callbacks.clone();
spawn!("TorrentContext::on_incoming_peer_connection", async move {
match BitTorrentPeer::new_inbound(
peer_id,
entry.socket_addr,
peer_port,
peer_client_name,
entry.stream,
InnerTorrent {
handle,
sender: command_sender.clone(),
callbacks,
},
metadata,
data_pool,
storage,
protocol_extensions,
extensions,
timeout,
)
.await
{
Ok(peer) => {
debug!(
"Torrent {} established connection with peer {}",
handle, peer
);
command_sender
.fire_and_forget(TorrentCommand::PeerConnected { peer: peer.into() })
.await;
}
Err(e) => debug!(
"Torrent {} failed to accept incoming peer connection {}, {}",
handle, entry.socket_addr, e
),
}
});
}
fn decrease_peer_addr_priority(&mut self, peers: Vec<SocketAddr>) {
for peer in peers {
self.peer_pool.update_peer_rank(&peer, -1);
}
}
/// Process the received data for a piece block.
async fn on_piece_block_received(
&mut self,
peer_addr: SocketAddr,
block: PieceBlock,
data: Vec<u8>,
) {
let piece = block.piece;
let peer = match self.peer_pool.get(&peer_addr) {
None => {
debug!(
"Torrent {} received block from unknown peer {}",
self, peer_addr
);
return;
}
Some(peer) => peer,
};
self.piece_picker.block_received(peer, block, data).await;
if self.piece_picker.is_piece_finished(&piece) {
self.verify_piece(&piece).await;
}
}
/// Process a rejected piece block request.
async fn on_piece_block_rejected(&mut self, peer_addr: &SocketAddr, block: PieceBlock) {
self.piece_picker.block_rejected(peer_addr, block).await;
}
/// Start the verification process for the given piece.
async fn verify_piece(&mut self, piece: &PieceIndex) {
let piece = match self.data_pool.piece(piece).await {
Some(piece) => piece,
None => {
debug!(
"Torrent {} is unable to verify piece {}, piece not found",
self, piece
);
return;
}
};
let handle = self.handle;
let storage = self.storage.clone();
self.verify_tasks.spawn(async move {
match (piece.hash.has_v1(), piece.hash.has_v2()) {
(true, true) | (false, true) => {
VerifyTaskResult {
piece: piece.index,
v1_hash: None,
v2_hash: storage.hash_v2(&piece.index).await.ok(),
}
}
(true, false) => {
VerifyTaskResult {
piece: piece.index,
v1_hash: storage.hash_v1(&piece.index).await.ok(),
v2_hash: None,
}
}
(false, false) => {
debug!(
"Torrent {} is unable to validate piece {}, piece hash is missing or invalid",
handle, piece.index
);
VerifyTaskResult {
piece: piece.index,
v1_hash: None,
v2_hash: None,
}
}
}
});
}
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn on_verify_task_tick(&mut self) {
let start_time = Instant::now();
while let Some(result) = self.verify_tasks.join_next().now_or_never().flatten() {
match result {
Ok(result) => {
self.on_piece_verified(&result.piece, result.v1_hash, result.v2_hash)
.await
}
Err(_) => break,
}
if start_time.elapsed() > TICK_INTERVAL {
break;
}
}
}
/// Process the new options of the torrent.
async fn options_changed(&mut self) {
// update the state of the torrent based on the new options
// this can only be done after the init phase to not disrupt the init operations
let is_not_init_state = !self.state.is_initializing_phase();
if is_not_init_state {
let state = self.determine_state().await;
self.update_state(state);
}
}
/// Try to determine the state the torrent currently has.
/// It returns the expected state of the torrent without actually updating the state.
pub async fn determine_state(&self) -> TorrentState {
let is_paused = self.options.contains(TorrentFlags::Paused);
let is_download_mode = self.options.contains(TorrentFlags::DownloadMode);
if is_paused {
return TorrentState::Paused;
}
let total_pieces = self.data_pool.num_of_pieces().await;
if total_pieces == 0 {
return TorrentState::Initializing;
}
if is_download_mode {
return TorrentState::Downloading;
}
if self.is_upload_allowed() {
return TorrentState::Seeding;
}
TorrentState::Finished
}
/// Get the piece part of the torrent based on the piece and the offset within the piece.
/// It returns [None] if the piece part is unknown to this torrent.
///
/// # Arguments
///
/// * `piece` - The index of the piece.
/// * `begin` - The offset within the piece.
pub async fn piece_block(&self, piece: PieceIndex, begin: usize) -> Option<PieceBlock> {
self.find_piece_block(piece, begin).await
}
/// Get the total amount of completed pieces for the torrent.
pub async fn total_completed_pieces(&self) -> usize {
self.data_pool.num_completed_pieces().await
}
/// Try to read the bytes from the given torrent file.
/// This reads all available bytes of the file stored within the [StorageExtension].
///
/// ## Remarks
///
/// This doesn't verify if the bytes are valid and completed.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub async fn read_file_to_end(&self, file: &FileIndex) -> Result<(usize, Vec<u8>)> {
let file = self
.data_pool
.file(file)
.await
.ok_or(TorrentError::DataUnavailable)?;
if let Some(piece) = self.data_pool.piece(&file.pieces.start).await {
let len = file.len();
let mut buffer = vec![0; len];
let file_offset = file.torrent_offset.saturating_sub(piece.offset);
let bytes_read = self
.storage
.read(&mut buffer, &piece.index, file_offset)
.await?;
return Ok((bytes_read, buffer[..bytes_read].to_vec()));
}
Err(TorrentError::DataUnavailable)
}
/// Try to read the given piece bytes.
/// It will read the bytes from all relevant files which overlap with the given piece.
///
/// ## Remarks
///
/// This doesn't verify if the bytes are valid and completed.
#[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
pub(crate) async fn read_piece(&self, piece: &PieceIndex) -> Result<Vec<u8>> {
match self.data_pool.piece(piece).await {
None => Err(TorrentError::DataUnavailable),
Some(piece) => {
self.internal_read_bytes(piece.offset..piece.offset + piece.length, false)
.await
}
}
}
/// Try to read the given piece bytes range.
///
/// ## Remarks
///
/// This doesn't verify if the bytes are valid and completed.
#[cfg_attr(feature = "tracing", tracing::instrument(skip(self, range)))]
pub(crate) async fn read_piece_bytes(
&self,
piece: &PieceIndex,
range: Range<usize>,
) -> Result<Vec<u8>> {
self.read_piece(piece).await.map(|e| e[range].to_vec())
}
/// Try to read the given bytes from the torrent.
/// This reads all available bytes of one or more files from the torrent stored within the [Storage].
/// The returned bytes will be padded with 0 if the available data is smaller than the requested range.
///
/// # Arguments
///
/// * `torrent_range` - The byte range within the torrent to read.
///
/// # Returns
///
/// It returns the bytes read from the torrent, padding the bytes with `0` if the data was not available.
pub async fn read_bytes_with_padding(&self, torrent_range: Range<usize>) -> Result<Vec<u8>> {
self.internal_read_bytes(torrent_range, true).await
}
/// Try to read the given bytes from the torrent.
/// This reads all bytes of one or more files from the torrent stored within the [Storage].
///
/// # Arguments
///
/// * `byte_range` - The torrent byte range to be read.
///
/// # Returns
///
/// It returns the bytes read from the torrent, returning a [TorrentError] if data was not available.
pub async fn read_bytes(&self, byte_range: Range<usize>) -> Result<Vec<u8>> {
self.internal_read_bytes(byte_range, false).await
}
async fn internal_read_bytes(
&self,
byte_range: Range<usize>,
with_padding: bool,
) -> Result<Vec<u8>> {
// early exit if an empty bytes range is given
if byte_range.is_empty() {
return Err(TorrentError::Io(io::Error::new(
io::ErrorKind::InvalidInput,
"range cannot be empty",
)));
}
let metadata = match self.metadata.info.as_ref() {
None => return Err(TorrentError::DataUnavailable),
Some(info) => info,
};
// early exit if the given byte range is out-of-bounds
let total_len = metadata.len();
if byte_range.end > total_len {
return Err(TorrentError::Io(io::Error::new(
io::ErrorKind::InvalidInput,
format!("range {:?} is out-of-bounds", byte_range),
)));
}
let mut buffer = vec![0u8; byte_range.len()];
let start_piece_index = byte_range.start / metadata.piece_length as usize;
let bytes_read = self
.storage
.read(
&mut buffer,
&start_piece_index,
byte_range.start % metadata.piece_length as usize,
)
.await?;
if bytes_read < byte_range.len() && !with_padding {
return Err(TorrentError::DataUnavailable);
}
Ok(buffer)
}
/// Invoke the given torrent event for all registered callbacks.
pub(crate) fn invoke_event(&self, event: TorrentEvent) {
self.callbacks.invoke(event)
}
/// Execute a periodic torrent context tick.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn on_tick(
&mut self,
operations: &mut Vec<Operation>,
peer_discoveries: &[PeerDiscovery],
) {
self.execute_operations_chain(operations, peer_discoveries)
.await;
self.peer_pool.tick().await;
self.piece_picker_tick().await;
self.on_verify_task_tick().await;
self.on_upload_tick().await;
}
/// Execute the torrent operations chain.
///
/// This will execute the operations in order as defined by the chain.
/// If an operation returns [None], the execution chain will be interrupted.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn execute_operations_chain(
&mut self,
operations: &mut Vec<Operation>,
peer_discoveries: &[PeerDiscovery],
) {
for operation in operations.iter_mut() {
let start_time = Instant::now();
let execution_result = operation.execute(self, peer_discoveries).await;
let elapsed_time = start_time.elapsed();
log!(
if elapsed_time > TICK_INTERVAL {
Level::Warn
} else {
Level::Trace
},
"Torrent {} \"{}\" took {:.3}ms",
self,
operation.name(),
elapsed_time.as_secs_f64() * 1000.0
);
if execution_result == TorrentOperationResult::Stop {
break;
}
}
}
/// Execute a tick operation within the piece picker.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn piece_picker_tick(&mut self) {
if !self.is_download_allowed() || self.state == TorrentState::CheckingFiles {
return;
}
trace!("Torrent {} is picking pieces", self);
self.piece_picker
.tick(self.peer_pool.peers_with(|conn| {
!matches!(
conn.state(),
PeerState::Handshake | PeerState::Error | PeerState::Closed
)
}))
.await;
}
/// Execute an upload tick, managing the upload slots of the torrent.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
async fn on_upload_tick(&mut self) {
// early exit if uploading is currently not allowed
if !self.is_upload_allowed() {
return;
}
let remaining_upload_slots = self
.config
.peers_upload_slots
.saturating_sub(self.peer_pool.upload_slots_len());
let peer_addrs = futures::future::join_all(
self.peer_pool
.peers_with(|conn| {
!matches!(
conn.state(),
PeerState::Handshake | PeerState::Error | PeerState::Closed
)
})
.map(|peer| async {
let remote_interest_state =
timeout(Duration::from_millis(250), peer.remote_interest_state())
.await
.unwrap_or(InterestState::NotInterested);
if remote_interest_state == InterestState::NotInterested {
return None;
}
let choke_state =
match timeout(Duration::from_millis(250), peer.choke_state()).await {
Ok(state) => state,
Err(_) => return None,
};
if choke_state == ChokeState::UnChoked {
return None;
}
Some(peer.addr().clone())
}),
)
.await;
for addr in peer_addrs
.into_iter()
.filter_map(|e| e)
.take(remaining_upload_slots)
{
self.peer_pool.unchoke_peer(&addr).await;
}
}
}
impl Callback<TorrentEvent> for TorrentContext {
fn subscribe(&self) -> Subscription<TorrentEvent> {
self.callbacks.subscribe()
}
}
impl Display for TorrentContext {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.handle)
}
}
impl PartialEq for TorrentContext {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
#[derive(Debug)]
struct VerifyTaskResult {
piece: PieceIndex,
v1_hash: Option<Sha1Hash>,
v2_hash: Option<Sha256Hash>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operation::{
ConnectPeersOperation, CreatePiecesAndFilesOperation, FileValidationOperation,
StatsOperation,
};
use crate::peer::TcpPeerDiscovery;
use crate::storage::{DiskStorage, MemoryStorage};
use crate::tests::helpers::wait_for_torrent_pieces;
use crate::tests::{copy_test_file, read_test_file_to_bytes};
use crate::{InfoHash, Magnet};
use std::net::Ipv4Addr;
use std::str::FromStr;
use tempfile::tempdir;
use tokio::sync::mpsc::unbounded_channel;
mod drop {
use super::*;
use tokio::sync::oneshot;
use tokio::time::timeout;
#[tokio::test]
async fn test_drop_last_torrent() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let (tx, rx) = oneshot::channel();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![],
vec![]
);
let command_sender = torrent.inner.sender.clone();
let mut receiver = torrent.subscribe();
tokio::spawn(async move {
while let Ok(event) = receiver.recv().await {
if let TorrentEvent::StateChanged(state) = &*event {
if state == &TorrentState::Stopped {
let _ = tx.send(());
break;
}
}
}
});
// drop the last torrent reference
drop(torrent);
// wait for the torrent to reach the stopped state
timeout(Duration::from_millis(250), rx)
.await
.expect("timeout waiting for TorrentState::Stopped")
.unwrap();
// verify that the context run task is stopped
assert!(
command_sender.is_closed(),
"context run task should be stopped"
);
}
}
mod tracker {
use super::*;
use crate::tracker::{TrackerEntry, TrackerServer};
#[tokio::test]
async fn test_announce() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build()
);
let result = torrent.announce().await.unwrap();
assert_ne!(
0, result.total_seeders,
"expected seeders to have been found"
);
assert_ne!(0, result.peers.len(), "expected peers to have been found");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_scrape() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let tracker_server = TrackerServer::new().await.unwrap();
let tracker_manager = TrackerClient::new(Duration::from_secs(3));
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![],
vec![],
|_| MemoryStorage::new().into(),
None,
tracker_manager.clone()
);
// add the server to the tracker client
match tracker_manager
.add_tracker_entry(TrackerEntry {
tier: 0,
url: Url::parse(
format!("http://localhost:{}/announce", tracker_server.addr().port())
.as_str(),
)
.unwrap(),
})
.await
{
Ok(_) => {}
Err(e) => assert!(
false,
"expected the tracker entry to have been added, {}",
e
),
}
// add a dummy peer
let info_hash = torrent.info_hash().await.unwrap();
tracker_server
.add_peer(
info_hash.clone(),
(Ipv4Addr::LOCALHOST, 8000).into(),
PeerId::new(),
6881,
true,
)
.await;
let result = torrent.scrape().await.unwrap();
assert_ne!(
0, result.downloaded,
"expected scrape results to have been returned"
)
}
}
mod availability {
use super::*;
#[tokio::test]
async fn test_piece_availabilities() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()]
);
assert_timeout!(
Duration::from_secs(5),
torrent.total_pieces().await > 0,
"expected the pieces to have been created"
);
torrent.inner.piece_availabilities(vec![0, 1], true).await;
assert_timeout!(
Duration::from_secs(2),
torrent.availability(0).await == 1,
"expected the piece availability to have been increased"
);
assert_eq!(1, torrent.availabilities().await[&1]);
torrent.inner.piece_availabilities(vec![0], false).await;
assert_timeout!(
Duration::from_secs(2),
torrent.availability(0).await == 0,
"expected the piece availability to have been decreased"
);
}
}
mod metadata {
use super::*;
use crate::operation::MetadataOperation;
#[tokio::test]
async fn test_metadata_available() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let filename = "debian-udp.torrent";
let torrent_info_data = read_test_file_to_bytes(filename);
let torrent_info = TorrentMetadata::try_from(torrent_info_data.as_slice()).unwrap();
let torrent = torrent!(
filename,
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()]
);
let metadata = torrent.metadata().await.unwrap();
assert_eq!(torrent_info, metadata);
assert!(
metadata.info.is_some(),
"expected the torremt metadata info to have been known"
);
}
#[tokio::test]
async fn test_retrieve_metadata() {
init_logger!();
let filename = "debian.torrent";
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
copy_test_file(temp_path, filename, None);
let info =
TorrentMetadata::try_from(read_test_file_to_bytes(filename).as_slice()).unwrap();
let magnet_uri = Magnet::try_from(&info).unwrap().to_string();
let (tx, mut rx) = unbounded_channel();
let source_torrent = torrent!(
filename,
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![],
vec![TcpPeerDiscovery::new().await.unwrap().into()]
);
let torrent = torrent!(
magnet_uri.as_str(),
temp_path,
TorrentFlags::Metadata,
TorrentConfig::builder().build(),
vec![
StatsOperation::new().into(),
ConnectPeersOperation::new(false).into(),
MetadataOperation::new(None).into(),
],
vec![TcpPeerDiscovery::new().await.unwrap().into()],
|_| { MemoryStorage::new().into() },
None
);
// listen for the metadata changed event
let torrent_handle = torrent.handle();
let mut receiver = torrent.subscribe();
tokio::spawn(async move {
while let Ok(event) = receiver.recv().await {
match &*event {
TorrentEvent::MetadataChanged(_) => {
let _ = tx.send(());
break;
}
TorrentEvent::Stats(stats) => {
debug!("Torrent {} stats: {}", torrent_handle, stats);
}
_ => {}
}
}
});
// connect the torrent to the source torrent, which has the metadata
let port = source_torrent
.peer_port()
.await
.expect("expected the source torrent peer port");
torrent
.add_peer((Ipv4Addr::LOCALHOST, port).into())
.await
.unwrap();
timeout!(
Duration::from_secs(10),
rx.recv(),
"expected to receive a MetadataChanged event"
)
.unwrap();
let result = torrent.metadata().await.unwrap();
assert_ne!(
None, result.info,
"expected the metadata to have been present"
);
}
#[tokio::test]
async fn test_info_hash() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let info_hash = InfoHash::from_str("EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()]
);
let result = torrent.info_hash().await.unwrap();
assert_eq!(info_hash, result, "expected the info hash to match");
}
}
mod pieces {
use super::*;
#[tokio::test]
async fn test_create_pieces() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()]
);
let (tx, mut rx) = unbounded_channel();
let mut receiver = torrent.subscribe();
tokio::spawn(async move {
while let Ok(event) = receiver.recv().await {
if let TorrentEvent::PiecesChanged(_) = *event {
tx.send(()).unwrap();
}
}
});
// wait for the pieces changed event
timeout!(
Duration::from_millis(750),
rx.recv(),
"expected the pieces to be created"
)
.unwrap();
let pieces = torrent.pieces().await.unwrap();
assert_ne!(0, pieces.len(), "expected the pieces to have been created");
}
#[tokio::test]
async fn test_get_piece() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
Operation::default_operations(),
vec![],
|_| MemoryStorage::new().into(),
None
);
// wait for the pieces to have been create
wait_for_torrent_pieces(&torrent).await;
let result = torrent
.piece(&0)
.await
.expect("expected a piece to have been returned");
assert_eq!(0, result.index, "expected the piece index to match");
}
#[tokio::test]
async fn test_piece_part() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let expected_piece_part = PieceBlock {
piece: 0,
block: 1,
begin: 16384,
length: 16384,
};
let (mut context, _) = torrent_context!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build()
);
// create the torrent pieces
let mut operation = CreatePiecesAndFilesOperation::new();
let result = operation.execute(&mut context).await;
assert_eq!(TorrentOperationResult::Continue, result);
// request an invalid piece part
let result = context.piece_block(0, 16000).await;
assert_eq!(
None, result,
"expected no piece part to be returned for invalid begin"
);
// request a valid piece part
let result = context.piece_block(0, 16384).await;
assert_eq!(Some(expected_piece_part), result, "expected the piece part");
}
#[tokio::test]
async fn test_total_wanted_pieces() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let expected_result = 75;
let mut operation = CreatePiecesAndFilesOperation::new();
let (mut context, _) = torrent_context!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![]
);
// create the torrent pieces
operation.execute(&mut context).await;
// only request the first piece
let total_pieces = context.data_pool().num_of_pieces().await;
let priorities = (0..total_pieces)
.into_iter()
.map(|i| {
if i < expected_result {
(i, PiecePriority::Normal)
} else {
(i, PiecePriority::None)
}
})
.collect();
context.prioritize_pieces(priorities).await;
// check the total wanted pieces
let result = context.total_wanted_pieces().await;
assert_eq!(expected_result, result);
}
}
mod files {
use super::*;
#[tokio::test]
async fn test_create_files() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()]
);
let (tx, mut rx) = unbounded_channel();
// wait for the pieces changed event
let mut receiver = torrent.subscribe();
tokio::spawn(async move {
while let Ok(event) = receiver.recv().await {
if let TorrentEvent::FilesChanged = *event {
tx.send(()).unwrap();
}
}
});
let _ = timeout!(
Duration::from_millis(750),
rx.recv(),
"expected the files to be created"
)
.unwrap();
let files = torrent.files().await;
assert_eq!(1, files.len(), "expected the files to have been created");
}
#[tokio::test]
async fn test_file() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
Operation::default_operations(),
vec![],
|_| { MemoryStorage::new().into() },
None
);
// wait for the pieces to have been create
wait_for_torrent_pieces(&torrent).await;
let result = torrent.file(&0).await.unwrap();
assert_eq!(0, result.index, "expected the file index to match");
assert_eq!(
"debian-12.4.0-amd64-DVD-1.iso",
result.filename(),
"expected the filename to match"
);
}
#[tokio::test]
async fn test_file_by_name() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
Operation::default_operations(),
vec![],
|_| { MemoryStorage::new().into() },
None
);
// wait for the pieces to have been create
wait_for_torrent_pieces(&torrent).await;
let result = torrent
.file_by_name("debian-12.4.0-amd64-DVD-1.iso")
.await
.unwrap();
assert_eq!(0, result.index, "expected the file index to match");
assert_eq!(
"debian-12.4.0-amd64-DVD-1.iso",
result.filename(),
"expected the filename to match"
);
}
#[tokio::test]
async fn test_prioritize_files() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"multifile.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()],
vec![],
|_| MemoryStorage::new().into(),
None
);
let data_pool = torrent.inner.data_pool().await.unwrap();
// wait for the pieces to be created
wait_for_torrent_pieces(&torrent).await;
// prioritize the second file
torrent
.prioritize_files(vec![
(0, FilePriority::None),
(1, FilePriority::Normal),
(2, FilePriority::None),
])
.await;
// verify the 1st file
let file = data_pool.file(&0).await.unwrap();
assert_eq!(
FilePriority::None,
file.priority,
"expected file 0 to not be wanted"
);
let last_piece = data_pool.piece(&(file.pieces.end - 1)).await.unwrap();
assert_eq!(
PiecePriority::Normal,
last_piece.priority,
"expected the last overlapping piece to be wanted"
);
// verify the 2nd file
let file = data_pool.file(&1).await.unwrap();
assert_eq!(
FilePriority::Normal,
file.priority,
"expected file 1 to be wanted"
);
// make sure that all pieces are wanted of the 2nd file
for piece_index in file.pieces {
let piece = data_pool.piece(&piece_index).await.unwrap();
assert_eq!(
PiecePriority::Normal,
piece.priority,
"expected piece {} of file 1 to be wanted",
piece_index
);
}
// verify the 3th file
let file_2 = data_pool.file(&2).await.unwrap();
assert_eq!(
FilePriority::None,
file_2.priority,
"expected file 2 to not be wanted"
);
// file 1 fully ends with piece 725, so there is no overlap with file 2
let first_piece = data_pool.piece(&(file_2.pieces.end - 1)).await.unwrap();
assert_eq!(
PiecePriority::None,
first_piece.priority,
"expected the 1st piece of file 2 to not be wanted",
);
}
}
mod bytes {
use super::*;
use tokio::sync::oneshot;
#[tokio::test]
async fn test_prioritize_bytes() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()],
vec![],
|params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
None
);
let piece_len = torrent
.metadata()
.await
.ok()
.and_then(|e| e.info)
.map(|info| info.piece_length as usize)
.unwrap();
// wait for the pieces to be created
wait_for_torrent_pieces(&torrent).await;
// check the current priority of the pieces
let priorities = torrent.piece_priorities().await;
assert_eq!(priorities[&1], PiecePriority::Normal);
assert_eq!(priorities[&2], PiecePriority::Normal);
// set the byte priorities
torrent
.prioritize_bytes(&(piece_len..(piece_len * 2) + 1), PiecePriority::Now)
.await;
// check the new priority of pieces
let priorities = torrent.piece_priorities().await;
assert_eq!(priorities[&0], PiecePriority::Normal);
assert_eq!(priorities[&1], PiecePriority::Now);
assert_eq!(priorities[&2], PiecePriority::Now);
assert_eq!(priorities[&3], PiecePriority::Normal);
}
#[tokio::test]
async fn test_has_bytes() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()],
vec![],
|params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
None
);
let (peer, _peer2) = tcp_peer_pair!(&torrent, vec![]);
torrent.inner.peer_connected(peer.clone().into()).await;
let piece_len = torrent
.metadata()
.await
.ok()
.and_then(|e| e.info)
.map(|info| info.piece_length as usize)
.unwrap();
let (tx, rx) = oneshot::channel();
let mut receiver = torrent.subscribe();
tokio::spawn(async move {
while let Ok(event) = receiver.recv().await {
if let TorrentEvent::PieceCompleted(piece) = &*event {
if *piece == 2 {
tx.send(()).unwrap();
break;
}
}
}
});
// wait for the pieces to be created
wait_for_torrent_pieces(&torrent).await;
// check if the bytes are available
let bytes = piece_len..piece_len * 2;
let result = torrent.has_bytes(&bytes).await;
assert_eq!(
false, result,
"expected the bytes to not have been completed"
);
// set the pieces as completed
mark_piece_completed!(&torrent.inner.sender, 1, peer.addr(), "piece-1_30.iso");
mark_piece_completed!(&torrent.inner.sender, 2, peer.addr(), "piece-1_30.iso");
assert_timeout!(Duration::from_secs(2), torrent.has_piece(&2).await); // TODO: improve test performance
// wait for the pieces to be completed internally
let _ = timeout!(
Duration::from_millis(500),
rx,
"expected a TorrentEvent::PieceCompleted"
);
// check if the bytes are available
let result = torrent.has_bytes(&bytes).await;
assert_eq!(true, result, "expected the bytes to have been completed");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_torrent_resume_internal() {
init_logger!(LevelFilter::Debug);
let temp_dir_source = tempdir().unwrap();
let temp_path_source = temp_dir_source.path().to_str().unwrap();
let temp_dir_target = tempdir().unwrap();
let temp_path_target = temp_dir_target.path().to_str().unwrap();
let num_of_pieces = 30;
copy_test_file(
temp_path_source,
"piece-1_30.iso",
Some("debian-12.4.0-amd64-DVD-1.iso"),
);
let expected_file_data = read_test_file_to_bytes("piece-1_30.iso");
let (tx_state, mut rx_state) = unbounded_channel();
let source_torrent = torrent!(
"debian-udp.torrent",
temp_path_source,
TorrentFlags::UploadMode | TorrentFlags::SeedMode,
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into(),],
vec![TcpPeerDiscovery::new().await.unwrap().into()],
|params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
None
);
let target_torrent = torrent!(
"debian-udp.torrent",
temp_path_target,
TorrentFlags::DownloadMode | TorrentFlags::Paused,
TorrentConfig::builder().build(),
vec![
StatsOperation::new().into(),
CreatePiecesAndFilesOperation::new().into(),
],
vec![TcpPeerDiscovery::new().await.unwrap().into()],
|params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
None
);
let (source_peer, target_peer) = tcp_peer_pair!(
&source_torrent,
&target_torrent,
vec![],
vec![],
ProtocolExtensionFlags::none()
);
// initialize the source torrent
wait_for_torrent_pieces(&source_torrent).await;
source_torrent
.inner
.peer_connected(source_peer.clone().into())
.await;
for piece in 0..num_of_pieces {
mark_piece_completed!(
&source_torrent.inner.sender,
piece,
source_peer.addr(),
"piece-1_30.iso"
);
}
let source_data_pool = source_torrent.inner.data_pool().await.unwrap();
assert_timeout!(
Duration::from_secs(2), // TODO: improve test performance
source_data_pool.is_piece_completed(&29).await
);
// initialize the target torrent
wait_for_torrent_pieces(&target_torrent).await;
// only request the first X amount of pieces
let total_pieces = target_torrent.total_pieces().await;
target_torrent
.prioritize_pieces(
(num_of_pieces..total_pieces)
.into_iter()
.map(|piece| (piece, PiecePriority::None))
.collect(),
)
.await;
target_torrent
.inner
.peer_connected(target_peer.into())
.await;
// resume the target torrent to fetch data from the source torrent
target_torrent.resume().await;
// listen to the finished event
let target_handle = target_torrent.handle();
let mut receiver = target_torrent.subscribe();
tokio::spawn(async move {
while let Ok(event) = receiver.recv().await {
match &*event {
TorrentEvent::StateChanged(state) => {
if state == &TorrentState::Finished {
let _ = tx_state.send(());
break;
}
}
TorrentEvent::Stats(stats) => {
debug!("Torrent {} stats: {}", target_handle, stats);
}
_ => {}
}
}
});
// connect the target torrent to the source torrent
// do not connect the source torrent to the target, as the source torrent is seeding and won't actively create new connections
target_torrent
.add_peer(SocketAddr::from((
[127, 0, 0, 1],
source_torrent.peer_port().await.unwrap(),
)))
.await
.expect("expected the peer address to have been added");
// wait for all pieces to be completed (finished state)
timeout!(
Duration::from_secs(90),
rx_state.recv(),
"expected the torrent to enter the FINISHED state"
)
.unwrap();
// validate the pieces and received data
let data_pool = target_torrent.inner.data_pool().await.unwrap();
let pieces_bitfield = data_pool.bitfield().await;
for piece_index in 0..num_of_pieces {
assert_eq!(
Some(true),
pieces_bitfield.get(piece_index).map(|e| *e),
"expected piece bitfield bit {} to be set",
piece_index
);
}
// read the torrent file
match target_torrent.read_file_to_end(&0).await {
Ok((bytes_read, bytes)) => {
assert_eq!(
expected_file_data.len(),
bytes_read,
"expected the available data to have been read"
);
assert_eq!(
expected_file_data, bytes,
"expected the available data to have been read"
);
}
Err(e) => assert!(false, "failed to read torrent data, {}", e),
}
}
#[tokio::test]
async fn test_torrent_is_completed() {
init_logger!(LevelFilter::Info);
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
copy_test_file(
temp_path,
"piece-1_30.iso",
Some("debian-12.4.0-amd64-DVD-1.iso"),
);
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()],
vec![]
);
// wait for the pieces to be created
wait_for_torrent_pieces(&torrent).await;
// mark all pieces as completed
let data_pool = torrent.inner.data_pool().await.unwrap();
let pieces = torrent.pieces().await.unwrap();
data_pool
.set_completed(&(0..pieces.len()).into_iter().collect_vec(), true)
.await;
let result = torrent.is_completed().await;
assert_eq!(true, result, "expected the torrent to be completed");
}
#[tokio::test]
async fn test_torrent_is_download_allowed() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let (mut context, _) = torrent_context!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build()
);
// create the pieces and files for the torrent
let mut operation = CreatePiecesAndFilesOperation::new();
operation.execute(&mut context).await;
let mut receiver = context.subscribe();
// reset the state to Initializing
context.update_state(TorrentState::Initializing);
let result = context.is_download_allowed();
assert_eq!(false, result, "expected downloading to not be allowed");
let result = async {
context.add_options(TorrentFlags::DownloadMode);
// wait for the state change event
let _ = receiver.recv().await;
context.is_download_allowed()
}
.await;
assert_eq!(false, result, "expected downloading to not be allowed");
let result = async {
context.update_state(TorrentState::Finished);
context.is_download_allowed()
}
.await;
assert_eq!(true, result, "expected downloading to be allowed");
let result = async {
context.add_options(TorrentFlags::Paused);
context.is_download_allowed()
}
.await;
assert_eq!(false, result, "expected downloading to not be allowed");
}
#[tokio::test]
async fn test_torrent_is_upload_allowed() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let (mut context, _) = torrent_context!(
"debian-udp.torrent",
temp_path,
TorrentFlags::UploadMode,
TorrentConfig::builder().build()
);
// create pieces and files for the torrent
let mut operation = CreatePiecesAndFilesOperation::new();
operation.execute(&mut context).await;
// validate the existing files
let mut operation = FileValidationOperation::new();
operation.execute(&mut context).await;
let result = context.is_upload_allowed();
assert_eq!(true, result, "expected uploading to be allowed");
context.add_options(TorrentFlags::Paused);
let result = context.is_upload_allowed();
assert_eq!(false, result, "expected uploading to not be allowed");
context.remove_options(TorrentFlags::Paused | TorrentFlags::UploadMode);
let result = context.is_upload_allowed();
assert_eq!(false, result, "expected uploading to not be allowed");
}
#[tokio::test]
async fn test_torrent_is_end_game() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()],
vec![],
|params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
None
);
let (peer, _peer2) = tcp_peer_pair!(&torrent, vec![]);
torrent.inner.peer_connected(peer.clone().into()).await;
// wait for the torrent pieces to be created
wait_for_torrent_pieces(&torrent).await;
// set only the first 30 pieces as wanted
let num_of_pieces = torrent.total_pieces().await;
torrent
.prioritize_pieces(
(30..num_of_pieces)
.into_iter()
.map(|piece| (piece, PiecePriority::None))
.collect_vec(),
)
.await;
// mark the first 90% of the wanted pieces as completed
for piece in 0..27 {
mark_piece_completed!(&torrent.inner.sender, piece, peer.addr(), "piece-1_30.iso");
}
assert_timeout!(
Duration::from_secs(2), // TODO: improve test performance
torrent.has_piece(&26).await,
"expected piece 26 to be completed"
);
let result = torrent.inner.is_end_game().await;
assert_eq!(
false, result,
"expected the torrent to not be in the end-game phase"
);
// mark the remaining wanted pieces as completed
for piece in 27..30 {
mark_piece_completed!(&torrent.inner.sender, piece, peer.addr(), "piece-1_30.iso");
}
assert_timeout!(
Duration::from_secs(2), // TODO: improve test performance
torrent.has_piece(&29).await,
"expected piece 29 to be completed"
);
// wait for all pieces to be processed and check the bitfield result
let bitfield = torrent.inner.bitfield().await.unwrap();
assert_eq!(
30,
bitfield.count_ones(),
"expected 30 pieces to have been marked as completed"
);
let result = torrent.inner.is_end_game().await;
assert_eq!(
true, result,
"expected the torrent to be in the end-game phase"
);
}
#[tokio::test]
async fn test_torrent_determine_state() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let pieces = vec![Piece::new(
InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap(),
0,
0,
1024,
)];
let (mut context, _) = torrent_context!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build()
);
let result = context.determine_state().await;
assert_eq!(TorrentState::Initializing, result);
context.update_pieces(pieces).await;
let result = context.determine_state().await;
assert_eq!(TorrentState::Finished, result);
context.add_options(TorrentFlags::UploadMode);
let result = context.determine_state().await;
assert_eq!(TorrentState::Seeding, result);
context.remove_options(TorrentFlags::UploadMode);
context.add_options(TorrentFlags::DownloadMode);
context.update_state(TorrentState::Paused);
let result = context.determine_state().await;
assert_eq!(TorrentState::Downloading, result);
}
#[tokio::test]
async fn test_torrent_wanted_pieces() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let (mut context, _) = torrent_context!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build()
);
// create the torrent pieces
let mut operation = CreatePiecesAndFilesOperation::new();
operation.execute(&mut context).await;
// retrieve the pieces from the data pool
let pieces = context.data_pool().pieces().await;
let total_pieces = pieces.len();
assert_ne!(0, total_pieces, "expected the pieces to have been created");
context
.prioritize_pieces(
(30..total_pieces)
.into_iter()
.map(|piece| (piece, PiecePriority::None))
.collect(),
)
.await;
let expected_result: Vec<PieceIndex> = (0..30)
.into_iter()
.map(|piece| piece as PieceIndex)
.collect();
let result = context
.data_pool
.wanted_pieces()
.await
.into_iter()
.map(|e| e.index)
.collect::<Vec<_>>();
assert_eq!(expected_result, result);
context.on_pieces_completed(&pieces[0..2]).await;
let expected_result: Vec<PieceIndex> = (2..30)
.into_iter()
.map(|piece| piece as PieceIndex)
.collect();
let result = context
.data_pool
.wanted_pieces()
.await
.into_iter()
.map(|e| e.index)
.collect::<Vec<_>>();
assert_eq!(expected_result, result);
}
#[tokio::test]
async fn test_torrent_update_state() {
init_logger!();
let expected_state = TorrentState::Paused;
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let (tx, mut rx) = unbounded_channel();
let (mut context, _) = torrent_context!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![]
);
// subscribe to the events of the torrent
let mut receiver = context.subscribe();
tokio::spawn(async move {
while let Ok(event) = receiver.recv().await {
if let TorrentEvent::StateChanged(state) = &*event {
tx.send(state.clone()).unwrap();
break;
}
}
});
context.update_state(expected_state);
let result = timeout!(
Duration::from_millis(200),
rx.recv(),
"expected a state change event"
)
.unwrap();
assert_eq!(
expected_state, result,
"expected the state change event to match the new state"
);
let result = context.state();
assert_eq!(
&expected_state, result,
"expected the state function to match the new state"
);
}
mod prioritize {
use super::*;
use crate::tests::helpers::wait_for_torrent_pieces;
use crate::FilePriority;
#[tokio::test]
async fn test_torrent_prioritize_pieces() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()]
);
// create the pieces
wait_for_torrent_pieces(&torrent).await;
// only request the first piece
let mut priorities = torrent.piece_priorities().await;
priorities.insert(8, PiecePriority::High);
priorities.insert(9, PiecePriority::High);
let priorities = priorities
.into_iter()
.map(|(i, priority)| {
if i < 10 {
(i, priority)
} else {
(i, PiecePriority::None)
}
})
.collect();
torrent.prioritize_pieces(priorities).await;
// check the new priorities of the pieces
let result = torrent
.pieces()
.await
.expect("expected the pieces to be present");
for piece in 0..8 {
let priority = PiecePriority::Normal;
assert_eq!(
priority, result[piece].priority,
"expected piece {} to have priority {:?}",
piece, priority
);
}
for piece in 9..10 {
let priority = PiecePriority::High;
assert_eq!(
priority, result[piece].priority,
"expected piece {} to have priority {:?}",
piece, priority
);
}
for piece in 10..20 {
let priority = PiecePriority::None;
assert_eq!(
priority, result[piece].priority,
"expected piece {} to have priority {:?}",
piece, priority
);
}
// check the wanted pieces
let expected_wanted_pieces = vec![8, 9, 0, 1, 2, 3, 4, 5, 6, 7];
let data_pool = torrent.inner.data_pool().await.unwrap();
let result = data_pool
.wanted_pieces()
.await
.into_iter()
.map(|e| e.index)
.collect::<Vec<_>>();
assert_eq!(
expected_wanted_pieces, result,
"expected only piece 0 to be wanted"
);
// check the interested pieces
let expected_interested_pieces = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = data_pool.interested_pieces().await;
assert_eq!(
expected_interested_pieces, result,
"expected only piece 0 to be interested"
);
}
#[tokio::test]
async fn test_prioritize_bytes() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let mut operation = CreatePiecesAndFilesOperation::new();
let (mut context, _) = torrent_context!(
"debian-udp.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![]
);
let piece_length = context
.metadata()
.info
.as_ref()
.map(|e| e.piece_length)
.unwrap() as usize;
let range = 0usize..(2 * piece_length);
// create the torrent pieces
operation.execute(&mut context).await;
// prioritize the first 2 pieces through the bytes
context.prioritize_bytes(&range, PiecePriority::High).await;
let priorities = context.data_pool.piece_priorities().await;
assert_eq!(Some(&PiecePriority::High), priorities.get(&0));
assert_eq!(Some(&PiecePriority::High), priorities.get(&1));
assert_eq!(Some(&PiecePriority::Normal), priorities.get(&2));
}
#[tokio::test]
async fn test_prioritize_files() {
init_logger!();
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().to_str().unwrap();
let torrent = torrent!(
"multifile.torrent",
temp_path,
TorrentFlags::none(),
TorrentConfig::builder().build(),
vec![CreatePiecesAndFilesOperation::new().into()]
);
// create the pieces and files of the torrent
wait_for_torrent_pieces(&torrent).await;
// prioritize only the 2nd file
let file_priorities = torrent
.files()
.await
.into_iter()
.map(|file| {
if file.index == 1 {
(file.index, FilePriority::Normal)
} else {
(file.index, FilePriority::None)
}
})
.collect();
torrent.prioritize_files(file_priorities).await;
let priorities = torrent.piece_priorities().await;
// verify that file 0 is ignored, except for the last piece
for piece in 0usize..401usize {
assert_eq!(
Some(&PiecePriority::None),
priorities.get(&piece),
"expected the first file (piece {}) to be ignored",
piece
);
}
assert_eq!(Some(&PiecePriority::Normal), priorities.get(&401));
// check that file 1 is wanted
for piece in 402usize..725usize {
assert_eq!(
Some(&PiecePriority::Normal),
priorities.get(&piece),
"expected the second file (piece {}) to be wanted",
piece
);
}
// check that the remaining files are ignored
for piece in 725usize..priorities.len() {
assert_eq!(
Some(&PiecePriority::None),
priorities.get(&piece),
"expected the remaining files (piece {}) to be ignored",
piece
);
}
}
}
}