fx-torrent 0.10.3

FX Torrent is a feature rich Bittorrent protocol implementation written in rust supporting Linux, MacOS and Windows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
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
use crate::channel::{ChannelReceiver, ChannelSender, Reply, Response};
use crate::merkle::LEAF_BLOCK_SIZE;
use crate::metrics::Metric;
use crate::peer::extension::{ExtensionNumber, ExtensionRegistry, PeerExtension};
use crate::peer::peer_connection::PeerConnection;
use crate::peer::peer_context::PeerContext;
use crate::peer::protocol::{CloseReason, UtpStream};
use crate::peer::protocol::{ExtendedHandshake, Handshake, HashRequest, Message, Piece, Request};
use crate::peer::{
    extension, ChokeState, Error, InterestState, Metrics, PeerEvent, PeerId, Result,
};
use crate::storage::Storage;
use crate::torrent::InnerTorrent;
use crate::torrent_data::DataPool;
use crate::{
    BitVec, CompactIp, PieceBlock, PieceIndex, TorrentEvent, TorrentMetadata, TorrentMetadataInfo,
};
use bitmask_enum::bitmask;
use byteorder::BigEndian;
use byteorder::ByteOrder;
use derive_more::Display;
use fx_callback::{Callback, MultiThreadedCallback, Subscription};
use log::{debug, error, log, trace, warn, Level};
use std::cmp::max;
use std::collections::{HashSet, VecDeque};
use std::fmt::{Debug, Display, Formatter};
use std::net::SocketAddr;
use std::time::{Duration, Instant};
use std::{io, result};
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio::{select, time};
use tokio_util::sync::CancellationToken;

const KEEP_ALIVE_SECONDS: u64 = 90;
const PEER_TICK_INTERVAL: Duration = Duration::from_secs(1);
const MIN_TARGET_QUEUE_LEN: usize = 2;
const MAX_TARGET_QUEUE_LEN: usize = 500;
const REQUEST_QUEUE_TIME: Duration = Duration::from_secs(3);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

/// The response of a remote peer connection.
#[derive(Debug, PartialEq)]
pub(crate) enum PeerResponse {
    /// The remote peer sent a handshake.
    Handshake(Handshake),
    /// The remote peer sent a message.
    Message(Message),
    /// The remote peer connection encountered an error.
    Error(Error),
    /// The remote peer has closed the connection.
    Closed,
}

/// The underlying stream implementation of a peer connection.
/// This stream is used to connect with, or receive from, a remote peer.
#[derive(Debug)]
pub enum PeerStream {
    /// The peer is a TCP stream
    Tcp(TcpStream),
    /// The peer is a UTP stream
    Utp(UtpStream),
}

impl From<TcpStream> for PeerStream {
    fn from(stream: TcpStream) -> Self {
        Self::Tcp(stream)
    }
}

impl From<UtpStream> for PeerStream {
    fn from(stream: UtpStream) -> Self {
        Self::Utp(stream)
    }
}

/// The underlying network protocol used by the peer to communicate with the remote peer.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum ConnectionProtocol {
    Tcp,
    Utp,
    Http,
    Other,
}

impl Display for ConnectionProtocol {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// The connection direction type of the peer.
/// This indicates if the initial established connection with the remote peer was an inbound or outbound connection.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConnectionDirection {
    Inbound = 0,
    Outbound = 1,
}

/// The state that a peer is in
#[derive(Debug, Display, Copy, Clone, PartialEq)]
pub enum PeerState {
    /// The peer is currently exchanging the handshake
    #[display("performing peer handshake")]
    Handshake,
    /// The peer is currently trying to retrieve the metadata
    #[display("retrieving metadata")]
    RetrievingMetadata,
    /// The peer is currently paused
    #[display("paused")]
    Paused,
    /// The peer is currently idle
    #[display("idle")]
    Idle,
    #[display("downloading")]
    Downloading,
    #[display("uploading")]
    Uploading,
    #[display("error")]
    Error,
    #[display("closed")]
    Closed,
}

/// The extension flags of the protocol.
/// See BEP4 (<https://www.bittorrent.org/beps/bep_0004.html>) for more info.
///
/// _The known collisions mentioned in BEP4, are ignored within these flags._
#[bitmask(u16)]
#[bitmask_config(vec_debug, flags_iter)]
pub enum ProtocolExtensionFlags {
    /// Azureus Messaging Protocol
    Azureus,
    /// Libtorrent Extension Protocol, aka Extensions
    LTEP,
    /// Extension Negotiation Protocol
    ENP,
    /// BitTorrent DHT
    Dht,
    /// XBT Peer Exchange
    XbtPeerExchange,
    /// suggest, haveall, havenone, reject request, and allow fast extensions
    Fast,
    /// NAT Traversal
    Nat,
    /// hybrid torrent legacy to v2 upgrade
    SupportV2,
}

impl Display for ProtocolExtensionFlags {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut extensions = Vec::new();

        if self.contains(Self::Azureus) {
            extensions.push("Azureus");
        }
        if self.contains(Self::LTEP) {
            extensions.push("LTEP");
        }
        if self.contains(Self::ENP) {
            extensions.push("ENP");
        }
        if self.contains(Self::Dht) {
            extensions.push("DHT");
        }
        if self.contains(Self::XbtPeerExchange) {
            extensions.push("XBT");
        }
        if self.contains(Self::Fast) {
            extensions.push("Fast");
        }
        if self.contains(Self::Nat) {
            extensions.push("Nat");
        }
        if self.contains(Self::SupportV2) {
            extensions.push("SupportV2");
        }

        write!(f, "{}", extensions.join(" | "))
    }
}

/// The remote peer information
#[derive(Debug, Clone, PartialEq)]
pub struct RemotePeer {
    pub peer_id: PeerId,
    pub protocol_extensions: ProtocolExtensionFlags,
    pub extensions: ExtensionRegistry,
    pub client_name: Option<String>,
    /// Indicates if the extended handshake has been received from the remote peer.
    pub extended_handshake: bool,
    /// Indicates that the connection has been upgraded to v2
    pub is_v2: bool,
}

#[derive(Debug, Default, Clone)]
pub struct PeerStats {
    /// The bytes that have been transferred to the peer.
    pub upload: usize,
    /// The bytes that contain actual piece data transferred to the peer.
    pub upload_useful: usize,
    /// The bytes that have been transferred from the peer.
    pub download: usize,
    /// The bytes that contain actual piece data transferred from the peer.
    pub download_useful: usize,
}

/// The BitTorrent peer protocol implementation.
/// This [TorrentPeer] exchanges torrent data with remote peers through the specified BEP3 BitTorrent protocol.
///
/// It communicates with remote peers over TCP or uTP, see [PeerConn] for more info.
#[derive(Debug, Display, Clone)]
#[display("{}", context)]
pub struct BitTorrentPeer {
    context: PeerContext,
    sender: ChannelSender<PeerCommand>,
    callbacks: MultiThreadedCallback<PeerEvent>,
    cancellation_token: CancellationToken,
}

impl BitTorrentPeer {
    /// Create a new outgoing BitTorrent peer connection for the given network stream.
    pub(crate) async fn new_outbound(
        peer_id: PeerId,
        peer_addr: SocketAddr,
        peer_port: Option<u16>,
        peer_client_name: String,
        stream: PeerStream,
        torrent: InnerTorrent,
        metadata: TorrentMetadata,
        data_pool: DataPool,
        storage: Storage,
        protocol_extensions: ProtocolExtensionFlags,
        extensions: Vec<PeerExtension>,
        timeout: Duration,
    ) -> Result<Self> {
        trace!(
            "Torrent {} is trying to create outgoing peer connection to {}",
            torrent,
            peer_addr
        );
        let metrics = Metrics::new();
        let connection = match stream {
            PeerStream::Tcp(stream) => {
                PeerConnection::new_tcp(peer_id, peer_addr, stream, metrics.clone())
            }
            PeerStream::Utp(stream) => {
                PeerConnection::new_utp(peer_id, peer_addr, stream, metrics.clone())
            }
        };

        Self::process_connection_stream(
            PeerContext::builder()
                .id(peer_id)
                .addr(peer_addr)
                .connection_type(ConnectionDirection::Outbound)
                .protocol(connection.protocol())
                .state(PeerState::Handshake)
                .metrics(metrics)
                .build(),
            peer_port,
            peer_client_name,
            connection,
            torrent,
            metadata,
            data_pool,
            storage,
            protocol_extensions,
            extensions,
            timeout,
        )
        .await
    }

    /// Try to accept a new incoming BitTorrent peer connection for the given network stream.
    pub(crate) async fn new_inbound(
        peer_id: PeerId,
        peer_addr: SocketAddr,
        peer_port: Option<u16>,
        peer_client_name: String,
        stream: PeerStream,
        torrent: InnerTorrent,
        metadata: TorrentMetadata,
        data_pool: DataPool,
        storage: Storage,
        protocol_extensions: ProtocolExtensionFlags,
        extensions: Vec<PeerExtension>,
        timeout: Duration,
    ) -> Result<Self> {
        let metrics = Metrics::new();
        let connection = match stream {
            PeerStream::Tcp(stream) => {
                PeerConnection::new_tcp(peer_id, peer_addr, stream, metrics.clone())
            }
            PeerStream::Utp(stream) => {
                PeerConnection::new_utp(peer_id, peer_addr, stream, metrics.clone())
            }
        };

        trace!(
            "Torrent {} is trying to receive incoming peer connection from {}",
            torrent,
            peer_addr
        );
        tokio::time::timeout(
            timeout,
            Self::process_connection_stream(
                PeerContext::builder()
                    .id(peer_id)
                    .addr(peer_addr)
                    .connection_type(ConnectionDirection::Inbound)
                    .protocol(connection.protocol())
                    .state(PeerState::Handshake)
                    .metrics(metrics)
                    .build(),
                peer_port,
                peer_client_name,
                connection,
                torrent,
                metadata,
                data_pool,
                storage,
                protocol_extensions,
                extensions,
                timeout,
            ),
        )
        .await
        .map_err(|_| {
            Error::Io(io::Error::new(
                io::ErrorKind::TimedOut,
                format!("connection from {} timed out", peer_addr),
            ))
        })
        .flatten()
    }

    /// Returns the unique peer identifier within the torrent network.
    pub fn id(&self) -> &PeerId {
        self.context.id()
    }

    /// Returns the address of the remote peer.
    pub fn addr(&self) -> &SocketAddr {
        self.context.addr()
    }

    /// Returns the connection type of the peer.
    pub fn connection_type(&self) -> &ConnectionDirection {
        self.context.connection_type()
    }

    /// Returns the underlying protocol used by the peer connection.
    pub fn protocol(&self) -> &ConnectionProtocol {
        self.context.protocol()
    }

    /// Returns the metrics of the peer.
    pub fn metrics(&self) -> &Metrics {
        self.context.metrics()
    }

    /// Retrieve the remote peer id.
    /// This is only available after the handshake with the peer has been completed.
    ///
    /// # Returns
    ///
    /// Returns the remote peer id when the handshake has been completed, else `None`.
    pub async fn remote_id(&self) -> Option<PeerId> {
        self.sender
            .send(|tx| PeerCommand::GetRemoteId { response: tx })
            .await
            .await
            .ok()
            .flatten()
    }

    /// Get the remote peer information.
    /// This is only available after the handshake with the peer has been completed.
    ///
    /// # Returns
    ///
    /// Returns the remote peer information when the handshake has been completed, else `None`.
    pub async fn remote_peer(&self) -> Option<RemotePeer> {
        self.sender
            .send(|tx| PeerCommand::GetRemotePeer { response: tx })
            .await
            .await
            .ok()
            .flatten()
    }

    /// Get the known supported extensions of the remote peer.
    /// This might still be `None` when the handshake with the peer has not been completed yet.
    ///
    /// # Returns
    ///
    /// Returns the supported extensions of the remote peer.
    pub async fn remote_supported_extensions(&self) -> ProtocolExtensionFlags {
        self.sender
            .send(|tx| PeerCommand::GetRemoteSupportedExtensions { response: tx })
            .await
            .await
            .ok()
            .flatten()
            .unwrap_or(ProtocolExtensionFlags::none())
    }

    /// Set the choke state of the client peer.
    pub async fn set_choke_state(&self, state: ChokeState) {
        self.sender
            .fire_and_forget(PeerCommand::SetChokeState { state })
            .await
    }

    /// Returns the choke state of the client peer,
    /// indicating if data can be sent to the remote peer or not.
    pub async fn choke_state(&self) -> ChokeState {
        self.sender
            .send(|tx| PeerCommand::GetChokeState { response: tx })
            .await
            .await
            .ok()
            .unwrap_or(ChokeState::Choked)
    }

    /// Get the remote peer choke state.
    pub async fn remote_choke_state(&self) -> ChokeState {
        self.sender
            .send(|tx| PeerCommand::GetRemoteChokeState { response: tx })
            .await
            .await
            .ok()
            .unwrap_or(ChokeState::Choked)
    }

    /// Get the interested state of the remote peer.
    pub async fn remote_interest_state(&self) -> InterestState {
        self.sender
            .send(|tx| PeerCommand::GetRemoteInterestState { response: tx })
            .await
            .await
            .ok()
            .unwrap_or(InterestState::NotInterested)
    }

    /// Verify if the remote peer has the given piece.
    ///
    /// # Arguments
    ///
    /// * `piece` - The piece index that should be checked.
    ///
    /// # Returns
    ///
    /// Returns true when the remote peer has the piece available, else false.
    pub async fn remote_has_piece(&self, piece: &PieceIndex) -> bool {
        self.sender
            .send(|tx| PeerCommand::GetRemoteHasPiece {
                piece: *piece,
                response: tx,
            })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the bitfield of the pieces that have been completed by the client.
    pub async fn client_piece_bitfield(&self) -> BitVec {
        self.sender
            .send(|tx| PeerCommand::GetClientBitfield { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the bitfield of the pieces that the remote peer has.
    pub async fn remote_piece_bitfield(&self) -> BitVec {
        self.sender
            .send(|tx| PeerCommand::GetRemoteBitfield { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the bitfield of the fast pieces for the remote peer.
    ///
    /// This bitfield indicates the pieces which are allowed to be downloaded,
    /// even when [Peer::remote_choke_state] returns [ChokeState::Choked].
    pub async fn remote_fast_bitfield(&self) -> BitVec {
        self.sender
            .send(|tx| PeerCommand::GetRemoteFastBitfield { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns `true` if the remote peer has pieces that are wanted by the torrent
    /// and are not yet being requested.
    pub async fn has_wanted_pieces(&self) -> bool {
        self.sender
            .send(|tx| PeerCommand::HasWantedPieces { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Check if the remote peer is a seed.
    /// This means that the remote peer has all pieces available and is seeding the torrent.
    pub async fn is_seed(&self) -> bool {
        self.sender
            .send(|tx| PeerCommand::IsSeed { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the active state of the peer.
    pub async fn state(&self) -> PeerState {
        if self.sender.is_closed() {
            return PeerState::Closed;
        }

        self.context.state().await
    }

    /// Verify if the peer supports the given extension name with the remote peer.
    /// There is a plausibility for a "false-negative" when the extended handshake has not yet been executed.
    ///
    /// # Arguments
    ///
    /// * `extension_name` - The name of the extension to check for
    ///
    /// # Returns
    ///
    /// Returns true when the extension is supported, else false
    pub async fn supports_extension<S: Into<String>>(&self, extension_name: S) -> bool {
        // both the remote peer and this peer should support the given extension name
        self.sender
            .send(|tx| PeerCommand::IsExtensionSupported {
                name: extension_name.into(),
                response: tx,
            })
            .await
            .await
            .unwrap_or_default()
    }

    /// Return the remote [ExtensionNumber] for the given extension name, if found.
    /// Returns [None] when the extension is not supported by the remote peer.
    ///
    /// Related [BitTorrentPeer::supports_extension].
    pub async fn remote_extension_number<S: Into<String>>(
        &self,
        extension_name: S,
    ) -> Option<ExtensionNumber> {
        self.sender
            .send(|tx| PeerCommand::FindExtensionNumber {
                name: extension_name.into(),
                response: tx,
            })
            .await
            .await
            .ok()
            .flatten()
    }

    /// Returns the total number of pending requests to the remote peer.
    pub async fn client_pending_requests_len(&self) -> usize {
        self.sender
            .send(|tx| PeerCommand::GetClientPendingRequestsLen { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the total number of pending requests from the remote peer.
    pub async fn remote_pending_requests_len(&self) -> usize {
        self.sender
            .send(|tx| PeerCommand::GetRemotePendingRequestsLen { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the suggested pieces by the remote peer for downloading.
    pub async fn suggested_pieces(&self) -> Vec<PieceIndex> {
        self.sender
            .send(|tx| PeerCommand::SuggestedPieces { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Request one or more piece blocks from the remote peer.
    pub async fn request(&self, blocks: &[PieceBlock]) {
        self.sender
            .fire_and_forget(PeerCommand::Request {
                blocks: blocks.to_vec(),
            })
            .await
    }

    /// Returns the target number of requests which should be queued for the remote peer.
    pub async fn target_request_queue_len(&self) -> usize {
        self.sender
            .send(|tx| PeerCommand::TargetRequestQueueLen { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Try to HolePunch the given target peer address.
    /// The response is completed once a `connect` message has been received from the relaying peer.
    pub(crate) async fn holepunch(
        &self,
        addr: SocketAddr,
    ) -> Response<SocketAddr, extension::Error> {
        self.sender
            .send(|tx| PeerCommand::SendHolePunch {
                target: addr,
                response: tx,
            })
            .await
    }

    /// Send the given message to the remote peer.
    pub(crate) async fn send(&self, message: Message) -> Result<()> {
        self.sender
            .send(|tx| PeerCommand::SendMessage {
                message,
                response: tx,
            })
            .await
            .await
    }

    /// Close the peer connection.
    pub(crate) async fn close(&self) {
        let _ = self
            .sender
            .send(|tx| PeerCommand::Close { response: tx })
            .await
            .await;
    }

    async fn process_connection_stream(
        context: PeerContext,
        peer_port: Option<u16>,
        peer_client_name: String,
        connection: PeerConnection,
        torrent: InnerTorrent,
        metadata: TorrentMetadata,
        data_pool: DataPool,
        storage: Storage,
        protocol_extensions: ProtocolExtensionFlags,
        extensions: Vec<PeerExtension>,
        timeout: Duration,
    ) -> Result<Self> {
        let (command_sender, command_receiver) = channel!(128);
        context.metrics().client_choked.set(true);
        context.metrics().remote_choked.set(true);

        let torrent_event_receiver = torrent.subscribe();
        let mut context = BitTorrentPeerContext::new(
            context,
            peer_port,
            peer_client_name,
            connection,
            torrent,
            metadata,
            data_pool,
            storage,
            protocol_extensions,
            extensions.as_slice(),
            timeout,
        )
        .await?;
        let peer = Self {
            context: context.context.clone(),
            sender: command_sender,
            callbacks: context.callbacks.clone(),
            cancellation_token: context.cancellation_token.clone(),
        };

        // exchange the handshake with the remote peer
        context.exchange_handshake().await?;

        // run the peer context in a separate task
        spawn!("PeerContext::run", async move {
            context
                .run(command_receiver, torrent_event_receiver, extensions)
                .await
        });

        Ok(peer)
    }
}

impl Callback<PeerEvent> for BitTorrentPeer {
    fn subscribe(&self) -> Subscription<PeerEvent> {
        self.callbacks.subscribe()
    }
}

impl PartialEq for BitTorrentPeer {
    fn eq(&self, other: &Self) -> bool {
        self.context == other.context
    }
}

/// The internal peer commands executed on the main loop of the peer.
#[derive(Debug)]
enum PeerCommand {
    /// Returns the remote peer id, if known.
    GetRemoteId {
        response: Reply<Option<PeerId>>,
    },
    /// Returns the remote peer information, if known.
    GetRemotePeer {
        response: Reply<Option<RemotePeer>>,
    },
    /// Returns the supported extensions of the remote peer, if known.
    GetRemoteSupportedExtensions {
        response: Reply<Option<ProtocolExtensionFlags>>,
    },
    SetChokeState {
        state: ChokeState,
    },
    /// Returns the choke state of the client peer.
    GetChokeState {
        response: Reply<ChokeState>,
    },
    /// Returns the remote peer choke state, if known.
    GetRemoteChokeState {
        response: Reply<ChokeState>,
    },
    /// Returns the remote peer interested state, if known.
    GetRemoteInterestState {
        response: Reply<InterestState>,
    },
    /// Returns `true` if the remote peer has the given piece, else `false`.
    GetRemoteHasPiece {
        piece: PieceIndex,
        response: Reply<bool>,
    },
    /// Returns `true` if the remote peer has pieces which are wanted by the torrent, else `false`.
    HasWantedPieces {
        response: Reply<bool>,
    },
    /// Returns the bitfield (pieces) of the remote peer, if known.
    GetRemoteBitfield {
        response: Reply<BitVec>,
    },
    /// Returns the bitfield (pieces) of the fast pieces for the remote peer, if known.
    GetRemoteFastBitfield {
        response: Reply<BitVec>,
    },
    /// Returns `true` if the remote peer is a seed, else `false`.
    IsSeed {
        response: Reply<bool>,
    },
    /// Returns the bitfield of the client pieces that have been completed.
    GetClientBitfield {
        response: Reply<BitVec>,
    },
    /// Returns `true` if the peer and remote peer support the given extension, else `false`.
    IsExtensionSupported {
        name: String,
        response: Reply<bool>,
    },
    /// Returns the extension number of the given extension name if found, else `None`.
    FindExtensionNumber {
        name: String,
        response: Reply<Option<ExtensionNumber>>,
    },
    /// Returns the total number of pending requests to the remote peer.
    GetClientPendingRequestsLen {
        response: Reply<usize>,
    },
    /// Returns the total number of pending requests from the remote peer.
    GetRemotePendingRequestsLen {
        response: Reply<usize>,
    },
    /// Returns the suggested pieces of the remote peer.
    SuggestedPieces {
        response: Reply<Vec<PieceIndex>>,
    },
    /// Request one or more piece blocks from the remote peer.
    Request {
        blocks: Vec<PieceBlock>,
    },
    TargetRequestQueueLen {
        response: Reply<usize>,
    },
    /// Send the given message to the remote peer.
    SendMessage {
        message: Message,
        response: Reply<Result<()>>,
    },
    /// Send a holepunch request to the remote peer.
    SendHolePunch {
        target: SocketAddr,
        response: Reply<extension::Result<SocketAddr>>,
    },
    /// Close the peer connection.
    Close {
        response: Reply<()>,
    },
}

#[derive(Debug, Display)]
#[display("{}", context)]
pub struct BitTorrentPeerContext {
    /// The core context information of the peer.
    context: PeerContext,
    /// The remote peer information, known after the initial handshake.
    remote: Option<RemotePeer>,
    /// The peer port on which the torrent is listening for incoming connections.
    peer_port: Option<u16>,
    /// The name of the peer client.
    peer_client_name: String,
    torrent: InnerTorrent,
    /// The metadata of the torrent
    metadata: TorrentMetadata,
    /// The data pool of the torrent
    data_pool: DataPool,
    /// The storage of the torrent
    storage: Storage,
    /// The peer client supported/enabled protocol extensions
    protocol_extensions: ProtocolExtensionFlags,

    /// The client choke state
    client_choke_state: ChokeState,
    /// The choke state of the remote peer
    remote_choke_state: ChokeState,

    /// The client interest state for the pieces of the remote peer
    client_interest_state: InterestState,
    /// The interest state of the remote peer for our available pieces
    remote_interest_state: InterestState,

    /// The extensions which are support by the application
    /// These are immutable once the peer has been created
    extension_registry: ExtensionRegistry,

    /// The torrent pieces
    client_pieces: BitVec,
    /// The pieces of the remote peer
    remote_pieces: BitVec,
    /// The allowed fast pieces of the remote peer
    remote_fast_pieces: HashSet<PieceIndex>,
    /// The pieces which have been suggested by the remote peer for downloading
    remote_suggested_pieces: HashSet<PieceIndex>,

    /// The number of requests we should queue up for the remote peer
    target_queue_len: usize,
    /// The queue of requests which should be sent to the remote peer
    download_queue: VecDeque<PieceBlock>,
    /// The client peer pending requests to the remote torrent.
    /// These have been requested, but not yet received.
    pending_requests: Vec<PendingRequest>,
    /// The remote pending requests for this client.
    /// These are the requests the remote peer is interested in
    remote_pending_requests: Vec<Request>,

    /// The underlying peer connection
    connection: PeerConnection,

    /// The callbacks which are triggered by this peer when an event is raised
    callbacks: MultiThreadedCallback<PeerEvent>,
    /// The timeout duration of the connection.
    timeout: Duration,
    /// The cancellation token to cancel any async task within this peer on closure
    cancellation_token: CancellationToken,
}

impl BitTorrentPeerContext {
    /// Create a new peer context instance.
    pub(crate) async fn new(
        context: PeerContext,
        peer_port: Option<u16>,
        peer_client_name: String,
        connection: PeerConnection,
        torrent: InnerTorrent,
        metadata: TorrentMetadata,
        data_pool: DataPool,
        storage: Storage,
        protocol_extensions: ProtocolExtensionFlags,
        extensions: &[PeerExtension],
        timeout: Duration,
    ) -> Result<Self> {
        let total_pieces = data_pool.num_of_pieces().await;
        let extension_registry = Self::create_extension_registry(extensions);

        Ok(Self {
            context,
            // the remote information is unknown until the handshake has been completed
            remote: None,
            torrent,
            metadata,
            peer_port,
            peer_client_name,
            data_pool,
            storage,
            protocol_extensions,
            // connections should always start in the choked state
            client_choke_state: ChokeState::Choked,
            remote_choke_state: ChokeState::Choked,
            // connections should always start in the not interested state
            client_interest_state: InterestState::NotInterested,
            remote_interest_state: InterestState::NotInterested,
            extension_registry,
            client_pieces: BitVec::repeat(false, total_pieces),
            remote_pieces: BitVec::repeat(false, total_pieces),
            remote_fast_pieces: Default::default(),
            remote_suggested_pieces: Default::default(),
            target_queue_len: 4,
            download_queue: VecDeque::new(),
            pending_requests: vec![],
            remote_pending_requests: Vec::new(),
            connection,
            callbacks: MultiThreadedCallback::new(),
            cancellation_token: CancellationToken::new(),
            timeout,
        })
    }

    /// Run the main loop of peer.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn run(
        &mut self,
        mut command_receiver: ChannelReceiver<PeerCommand>,
        mut torrent_event_receiver: Subscription<TorrentEvent>,
        mut extensions: Vec<PeerExtension>,
    ) {
        // Try to send the initial message to the remote peer
        if let Err(e) = self.send_initial_messages().await {
            debug!("Peer {} failed to send initial messages, {}", self, e);
            self.update_state(PeerState::Error).await;
            return;
        }

        let mut interval = time::interval(PEER_TICK_INTERVAL);

        loop {
            select! {
                _ = self.cancellation_token.cancelled() => break,
                _ = time::sleep(Duration::from_secs(KEEP_ALIVE_SECONDS)) => self.send_keep_alive().await,
                Some(event) = self.connection.recv() => self.on_reader_event(event, extensions.as_mut_slice()).await,
                command = command_receiver.recv() => match command {
                    Some(command) => self.on_command(command, extensions.as_mut_slice()).await,
                    None => break,
                },
                Ok(event) = torrent_event_receiver.recv() => self.on_torrent_event(&*event).await,
                _ = interval.tick() => self.on_tick(extensions.as_mut_slice(), PEER_TICK_INTERVAL).await,
            }
        }

        self.update_state(PeerState::Closed).await;
        trace!("Peer {} main loop ended", self);
    }

    /// Try to exchange the handshake with the remote peer.
    /// Returns an error if the handshake failed to by exchanged with the remote peer.
    async fn exchange_handshake(&mut self) -> Result<()> {
        if self.context.connection_type() == &ConnectionDirection::Outbound {
            // as this is an outgoing connection, we're the once who initiate the handshake
            self.send_handshake().await?;
        }

        // retrieve the incoming handshake from the reader
        // as the handshake is always 68 bytes long, we request a buffer of 68 bytes from the reader
        trace!("Peer {} is awaiting the remote handshake", self);
        let handshake = self.try_receive_handshake().await?;
        if let Err(reason) = self.validate_handshake(handshake).await {
            self.close(reason).await;
            return Err(Error::Handshake(
                *self.context.addr(),
                format!("{:?}", reason),
            ));
        };

        if self.context.connection_type() == &ConnectionDirection::Inbound {
            // as this is an incoming connection, we need to send our own handshake after receiving the peer handshake
            self.send_handshake().await?;
        }

        Ok(())
    }

    /// Returns the address of the remote peer.
    pub fn addr(&self) -> &SocketAddr {
        self.context.addr()
    }

    /// Returns the protocol used by the connection to the peer.
    pub fn connection_protocol(&self) -> ConnectionProtocol {
        self.connection.protocol()
    }

    /// Returns a reference the torrent this peer belongs to.
    pub(crate) fn torrent(&self) -> &InnerTorrent {
        &self.torrent
    }

    /// Returns the client choke state of the peer.
    pub fn choke_state(&self) -> &ChokeState {
        &self.client_choke_state
    }

    /// Returns the remote peer id, if known.
    pub fn remote_id(&self) -> Option<PeerId> {
        self.remote.as_ref().map(|e| e.peer_id.clone())
    }

    /// Returns the remote peer information, if known.
    ///
    /// The data of the remote peer is only known after the handshake has been exchanged
    /// and validated.
    pub fn remote_peer(&self) -> Option<&RemotePeer> {
        self.remote.as_ref()
    }

    /// Get the supported extension registry of the remote peer.
    ///
    /// # Returns
    ///
    /// Returns the extension registry of the remote peer if known, else `None`.
    pub fn remote_extension_registry(&self) -> Option<ExtensionRegistry> {
        self.remote.as_ref().map(|e| e.extensions.clone())
    }

    /// Get the supported protocol extensions of the remote peer.
    /// This might still be `None` when the handshake with the peer has not been completed yet.
    pub fn remote_protocol_extensions(&self) -> Option<ProtocolExtensionFlags> {
        self.remote.as_ref().map(|e| e.protocol_extensions.clone())
    }

    /// Returns the available pieces of the remote peer as a bit vector.
    /// It might return an empty bit vector when the handshake has not been completed yet.
    pub fn remote_piece_bitfield(&self) -> &BitVec {
        &self.remote_pieces
    }

    /// Returns the bitfield of pieces which are allowed to be downloaded, even when choked.
    pub fn remote_fast_bitfield(&self) -> BitVec {
        let mut bitfield = BitVec::repeat(false, self.remote_pieces.len());

        // early exit, if the fast protocol is not supported
        if !self.is_protocol_enabled(ProtocolExtensionFlags::Fast) {
            return bitfield;
        }

        for piece in &self.remote_fast_pieces {
            bitfield.set(*piece, true);
        }

        bitfield
    }

    /// Check if the remote has all pieces available.
    /// The remote has all pieces if either an `HaveAll` message or completed `Bitfield` has been received by the remote.
    ///
    /// It returns true when the remote has all pieces and the metadata is known, else false.
    pub async fn remote_has_all_pieces(&self) -> bool {
        let torrent_total_pieces = self.data_pool.num_of_pieces().await;
        // the received bitfield can be greater than the actual total pieces due to byte alignment
        self.remote_pieces.len() > 0
            && self.remote_pieces.len() >= torrent_total_pieces
            && self.remote_pieces.all()
    }

    /// Check if a specific protocol extension is supported by the remote peer.
    /// If the client or the remote peer don't support the given extension, `false` is returned.
    pub fn is_protocol_enabled(&self, extension: ProtocolExtensionFlags) -> bool {
        self.protocol_extensions.contains(extension)
            && self
                .remote
                .as_ref()
                .map(|e| e.protocol_extensions.contains(extension))
                .unwrap_or(false)
    }

    /// Check if the client peer is currently interested in pieces from the remote peer.
    pub fn is_client_interested(&self) -> bool {
        self.client_interest_state == InterestState::Interested
    }

    /// Check if fast requests are allowed for the given piece.
    /// It returns true when fast requests are allowed for the given piece, else false.
    fn is_fast_allowed(&self, piece: &PieceIndex) -> bool {
        self.remote_fast_pieces.contains(piece)
    }

    /// Get the known metadata from the torrent.
    /// This info is requested from the torrent that created this peer.
    pub fn metadata(&self) -> &TorrentMetadata {
        &self.metadata
    }

    /// Returns the completed pieces bitfield of the torrent.
    pub async fn torrent_bitfield(&self) -> BitVec {
        self.data_pool.bitfield().await
    }

    /// Check if the remote peer supports v2.
    pub fn is_v2_supported(&self) -> bool {
        if let Some(remote) = self.remote.as_ref() {
            return remote.is_v2.clone();
        }

        false
    }

    /// Update the underlying torrent metadata.
    /// This method can be used by extensions to update the torrent metadata when the current
    /// connection is based on a magnet link.
    pub async fn set_torrent_metadata(&self, metadata: TorrentMetadataInfo) {
        self.torrent.set_metadata(metadata).await;
    }

    /// Get the client peer extensions registry.
    /// This is the registry of our own client.
    ///
    /// # Returns
    ///
    /// Returns a reference to the client extension registry.
    pub fn client_extension_registry(&self) -> &ExtensionRegistry {
        &self.extension_registry
    }

    /// Check if the remote peer has wanted piece data that are not yet being requested.
    /// If it least one piece is available by the remote peer and wanted by the torrent, it returns `true`.
    pub async fn has_wanted_piece(&self) -> bool {
        let remote_has_all_pieces = self.remote_has_all_pieces().await;
        let wanted_pieces = self.data_pool.wanted_pieces().await;

        wanted_pieces.into_iter().any(|piece| {
            // check if the remote peer has this piece
            let has_piece = remote_has_all_pieces
                || self
                    .remote_pieces
                    .get(piece.index)
                    .map(|e| *e)
                    .unwrap_or_default();
            if !has_piece {
                return false;
            }

            // check if at least one wanted piece is not in the download queue and pending requests
            let in_queue = self.download_queue.iter().any(|e| &e.piece == &piece.index);
            let in_pending = self
                .pending_requests
                .iter()
                .any(|e| &e.request.index == &piece.index);
            !in_queue && !in_pending
        })
    }

    /// Process an incoming peer reader event.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_reader_event(&mut self, event: PeerResponse, extensions: &mut [PeerExtension]) {
        match event {
            PeerResponse::Closed => self.close(CloseReason::None).await,
            PeerResponse::Message(message) => {
                if let Message::ExtendedPayload(extension_number, payload) = message {
                    trace!(
                        "Trying to find extension for extended payload number {}",
                        extension_number
                    );
                    if let Some(extension) = self
                        .find_extension_by_number(extension_number, extensions)
                        .await
                    {
                        trace!(
                            "Peer {} is processing extension {} message payload",
                            self,
                            extension.name(),
                        );
                        let start_time = Instant::now();
                        if let Err(e) = extension.on_message(payload.as_ref(), self).await {
                            error!(
                                "Peer {} failed to process extension {} message, {}",
                                self,
                                extension.name(),
                                e
                            );
                        }
                        let elapsed = start_time.elapsed();
                        log!(
                            if elapsed > PEER_TICK_INTERVAL {
                                Level::Warn
                            } else {
                                Level::Trace
                            },
                            "Peer {} extension {} on_message took {:.3}ms",
                            self,
                            extension.name(),
                            elapsed.as_secs_f64() * 1000.0
                        )
                    } else {
                        warn!(
                            "Peer {} received unsupported extension message for extension number {}",
                            self, extension_number
                        );
                    }
                } else {
                    self.on_message_received(message).await
                }
            }
            PeerResponse::Error(e) => {
                debug!("Peer {} encountered an error, {}", self, e);
                self.update_state(PeerState::Error).await;
            }
            _ => {}
        }
    }

    async fn on_message_received(&mut self, message: Message) {
        debug!("Peer {} received remote message {:?}", self, message);
        match message {
            Message::KeepAlive => {
                trace!("Peer {} received keep alive", self);
            }
            Message::Choke => {
                self.update_remote_peer_choke_state(ChokeState::Choked)
                    .await
            }
            Message::Unchoke => {
                self.update_remote_peer_choke_state(ChokeState::UnChoked)
                    .await
            }
            Message::Interested => {
                self.update_remote_peer_interest_state(InterestState::Interested)
                    .await
            }
            Message::NotInterested => {
                self.update_remote_peer_interest_state(InterestState::NotInterested)
                    .await
            }
            Message::Have(piece) => self.set_remote_has_piece(piece as PieceIndex, true).await,
            Message::HaveAll => self.update_remote_fast_have(true).await,
            Message::HaveNone => self.update_remote_fast_have(false).await,
            Message::Bitfield(pieces) => self.update_remote_pieces(pieces).await,
            Message::Request(request) => self.add_remote_pending_request(request).await,
            Message::RejectRequest(request) => self.handle_rejected_client_request(request).await,
            Message::Cancel(request) => self.cancel_remote_pending_request(request).await,
            Message::Suggest(piece) => self.on_piece_suggested(piece as PieceIndex).await,
            Message::AllowedFast(piece) => self.remote_fast_piece(piece as PieceIndex).await,
            Message::Piece(piece) => self.on_piece_data_received(piece).await,
            Message::ExtendedHandshake(handshake) => {
                self.update_extended_handshake(handshake).await
            }
            Message::HashRequest(request) => self.handle_hash_request(request).await,
            _ => warn!("Message not yet implemented for {:?}", message),
        }
    }

    /// Process a pending request requested by the remote peer.
    /// This tries to retrieve the requested data from the torrent.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_remote_pending_request(&mut self, request: Request) {
        // check if the client is choked, if so, we reject the request
        // this can happen if the client choke's while the request was still queued in the command channel
        if self.client_choke_state == ChokeState::Choked {
            self.send_reject_request(request).await;
            return;
        }

        // check if the piece request is valid
        // if not, reject the request
        if !self.validate_piece_request(&request).await {
            debug!("Peer {} received invalid piece request {:?}", self, request);
            self.send_reject_request(request).await;
            return;
        }

        if self.context.state().await != PeerState::Uploading {
            self.update_state(PeerState::Uploading).await;
        }

        let mut buffer = vec![0u8; request.length];
        match self
            .storage
            .read(&mut buffer, &request.index, request.begin)
            .await
        {
            Ok(len) => {
                if len != request.length {
                    warn!("Peer {} failed to read piece {} data", self, request.index);
                    self.send_reject_request(request).await;
                    return;
                }

                match self
                    .send(Message::Piece(Piece {
                        index: request.index,
                        begin: request.begin,
                        data: buffer,
                    }))
                    .await
                {
                    Ok(_) => {
                        debug!(
                            "Peer {} sent piece {} data block (offset {}, size {}) to remote peer",
                            self, request.index, request.begin, len
                        );
                        self.context.metrics().bytes_out_useful.inc_by(len as u64);
                    }
                    Err(e) => warn!(
                        "Peer {} failed to sent piece {} data part (size {}) to remote peer, {}",
                        self, request.index, len, e
                    ),
                }
            }
            Err(e) => {
                warn!(
                    "Peer {} failed read piece {} data, {}",
                    self, request.index, e
                );
                self.send_reject_request(request).await;
            }
        }
    }

    /// Handle an event that has been triggered by the [Torrent].
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_torrent_event(&mut self, event: &TorrentEvent) {
        match event {
            TorrentEvent::MetadataChanged(metadata) => {
                self.metadata = metadata.clone();
            }
            TorrentEvent::PiecesChanged(_) => {
                trace!("Peer {} updating client piece bitfield", self);
                // retrieve the torrent pieces bitfield and store it as the client bitfield
                let piece_bitfield = self.data_pool.bitfield().await;
                let bitfield_len = piece_bitfield.len();
                self.client_pieces = piece_bitfield;

                // extend the remote pieces bitfield if needed
                if self.remote_pieces.len() < bitfield_len {
                    self.remote_pieces.resize(bitfield_len, false);
                }

                self.determine_client_interest_state().await;
            }
            TorrentEvent::PiecePrioritiesChanged => {
                self.determine_client_interest_state().await;
            }
            TorrentEvent::OptionsChanged => {
                self.determine_client_interest_state().await;
            }
            TorrentEvent::PieceCompleted(piece) => {
                self.update_client_piece_availability(piece).await;
            }
            _ => {}
        }
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_tick(&mut self, extensions: &mut [PeerExtension], interval: Duration) {
        let start = Instant::now();

        self.on_stats_update(interval);
        self.on_extensions_tick(extensions, interval).await;
        self.send_queued_requests(interval).await;
        self.process_remote_pending_requests(interval).await;
        self.cleanup_pending_requests(interval).await;

        let elapsed = start.elapsed();
        log!(
            if elapsed > interval {
                Level::Warn
            } else {
                Level::Trace
            },
            "Peer {} tick took {:.3}ms",
            self,
            elapsed.as_secs_f64() * 1000.0
        );
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn process_remote_pending_requests(&mut self, interval: Duration) {
        let start_time = Instant::now();
        let len = self.remote_pending_requests.len().min(4);

        let mut num_of_pending_requests_sent = 0;
        while !self.remote_pending_requests.is_empty()
            && start_time.elapsed() < interval
            && num_of_pending_requests_sent < len
        {
            let pending_request = self.remote_pending_requests.remove(0);
            self.on_remote_pending_request(pending_request).await;
            num_of_pending_requests_sent += 1;
        }

        let elapsed = start_time.elapsed();
        log!(
            if elapsed > interval {
                Level::Warn
            } else {
                Level::Trace
            },
            "Peer {} processed {} remote pending requests in {:.3}ms",
            self,
            num_of_pending_requests_sent,
            elapsed.as_secs_f64() * 1000.0
        );
    }

    /// Clean up timed-out block requests sent to the remote peer.
    async fn cleanup_pending_requests(&mut self, interval: Duration) {
        let start_time = Instant::now();
        let mut timed_out_blocks = vec![];
        self.pending_requests.retain_mut(|pending| {
            if pending.sent.elapsed() > REQUEST_TIMEOUT {
                timed_out_blocks.push(pending.block);
                return false;
            }

            true
        });

        let num_of_timed_out_blocks = timed_out_blocks.len();
        for block in timed_out_blocks {
            self.torrent
                .piece_block_rejected(self.context.addr(), &block)
                .await;
        }

        let elapsed = start_time.elapsed();
        log!(
            if elapsed > interval {
                Level::Warn
            } else {
                Level::Trace
            },
            "Peer {} cleaned {} timed-out requests in {:.3}ms",
            self,
            num_of_timed_out_blocks,
            elapsed.as_secs_f64() * 1000.0
        )
    }

    /// Process a request which has been rejected by the remote peer.
    /// This can be the case when we've request piece data that is no longer available, or the remote peer cannot serve it at the moment.
    async fn handle_rejected_client_request(&mut self, request: Request) {
        debug!("Peer {} remote rejected request {:?}", self, request);
        self.remove_client_pending_request(&request).await;

        if let Some(block) = self
            .data_pool
            .find_piece_block(&request.index, request.begin)
            .await
        {
            self.torrent
                .piece_block_rejected(self.context.addr(), &block)
                .await;
        }
    }

    /// Handle a received piece data message
    async fn on_piece_data_received(&mut self, piece: Piece) {
        let request = if let Some(request) = self
            .remove_client_pending_request(&Request::from(&piece))
            .await
        {
            request
        } else {
            debug!(
                "Received piece {} data from peer {} for an unwanted (not queued) request",
                piece.index, self
            );
            return;
        };

        self.context
            .metrics()
            .bytes_in_useful
            .inc_by(piece.data.len() as u64);
        trace!("Received piece data for {:?} from {}", request, self);
        if let Some(block) = self
            .data_pool
            .find_piece_block(&piece.index, piece.begin)
            .await
        {
            let data_size = piece.data.len();
            if block.length == data_size {
                self.torrent
                    .piece_block_received(self.context.addr(), &block, piece.data)
                    .await;
            } else {
                debug!(
                "Peer {} received invalid piece part {:?} data, received data length {}, expected length {}",
                    self,
                    block,
                    piece.data.len(),
                    data_size
                );

                self.torrent
                    .piece_block_rejected(self.context.addr(), &block)
                    .await;
            }
        } else {
            debug!(
                "Received piece {} data from peer {} for a part that is unknown to the torrent",
                piece.index, self
            );
        }

        // recalculate the target requests queue length of the peer
        self.update_target_request_queue_len();

        // check if the download queue is empty and the remote client is still unchoked
        // if so, request additional pieces to be picked for this peer connection
        if self.remote_choke_state == ChokeState::UnChoked && self.download_queue.is_empty() {
            self.torrent.pick_pieces(self.context.addr()).await;
        }
    }

    /// Handle a received hash request from the remote peer.
    async fn handle_hash_request(&self, _request: HashRequest) {
        // check if the torrent hash is a v2
        let metadata_version = self.metadata.metadata_version().unwrap_or(0);
        if metadata_version != 2 {
            warn!(
                "Peer {} is unable to handle hash request for torrent with metadata version {}",
                self, metadata_version
            );
            return;
        }
    }

    /// Handle an internal peer command event.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_command(&mut self, command: PeerCommand, extensions: &mut [PeerExtension]) {
        match command {
            PeerCommand::GetRemoteId { response } => response.send(self.remote_id()),
            PeerCommand::GetRemotePeer { response } => response.send(self.remote_peer().cloned()),
            PeerCommand::GetRemoteSupportedExtensions { response } => {
                response.send(self.remote.as_ref().map(|e| e.protocol_extensions))
            }
            PeerCommand::SetChokeState { state } => self.update_client_choke_state(state).await,
            PeerCommand::GetChokeState { response } => response.send(self.client_choke_state),
            PeerCommand::GetRemoteChokeState { response } => response.send(self.remote_choke_state),
            PeerCommand::GetRemoteInterestState { response } => {
                response.send(self.remote_interest_state)
            }
            PeerCommand::GetRemoteHasPiece { piece, response } => response.send(
                self.remote_pieces
                    .get(piece)
                    .map(|bit| *bit)
                    .unwrap_or_default(),
            ),
            PeerCommand::HasWantedPieces { response } => {
                response.send(self.has_wanted_piece().await)
            }
            PeerCommand::GetRemoteBitfield { response } => {
                response.send(self.remote_piece_bitfield().clone())
            }
            PeerCommand::GetRemoteFastBitfield { response } => {
                response.send(self.remote_fast_bitfield())
            }
            PeerCommand::IsSeed { response } => response.send(self.remote_has_all_pieces().await),
            PeerCommand::GetClientBitfield { response } => {
                response.send(self.client_pieces.clone())
            }
            PeerCommand::IsExtensionSupported { name, response } => {
                response.send(self.is_extension_supported(name.as_str()))
            }
            PeerCommand::FindExtensionNumber { name, response } => {
                response.send(self.find_remote_extension_number(name.as_str()))
            }
            PeerCommand::GetClientPendingRequestsLen { response } => {
                response.send(self.download_queue.len() + self.pending_requests.len())
            }
            PeerCommand::GetRemotePendingRequestsLen { response } => {
                response.send(self.remote_pending_requests.len())
            }
            PeerCommand::SuggestedPieces { response } => {
                response.send(self.remote_suggested_pieces.iter().cloned().collect())
            }
            PeerCommand::Request { blocks } => self.on_request(blocks).await,
            PeerCommand::TargetRequestQueueLen { response } => {
                response.send(self.target_request_queue_len())
            }
            PeerCommand::SendMessage { message, response } => {
                response.send(self.send(message).await)
            }
            PeerCommand::SendHolePunch { target, response } => {
                self.send_holepunch(target, response, extensions).await
            }
            PeerCommand::Close { response } => {
                response.send(self.close(CloseReason::None).await);
            }
        }
    }

    /// Returns `true` if the extension is supported by both the client- and remote peer.
    pub fn is_extension_supported(&self, name: &str) -> bool {
        self.extension_registry.contains_key(name)
            && self
                .remote
                .as_ref()
                .map_or(false, |e| e.extensions.contains_key(name))
    }

    /// Check if v2 hashes should be requested for the current torrent.
    async fn should_request_hashes(&self) -> bool {
        if let Some(metadata_version) = self.metadata.metadata_version() {
            return metadata_version == 2 && self.is_v2_supported();
        }

        false
    }

    /// Request any missing hashes from the remote peer.
    async fn request_missing_hashes(&self) {
        if let Some(info) = self.metadata.info.as_ref() {
            trace!("Peer {} is requesting missing v2 hashes", self);
            let piece_length = info.piece_length as usize;
            let _base_layer = (piece_length + LEAF_BLOCK_SIZE - 1) / LEAF_BLOCK_SIZE;
        } else {
            warn!(
                "Peer {} is unable to request missing hashes, torrent metadata info is unknown",
                self
            );
        }
    }

    /// Determine if our peer client is interested in pieces from the remote peer.
    async fn determine_client_interest_state(&mut self) {
        let state: InterestState;
        // FIXME: torrent should inform the peer about the state
        let is_download_allowed = true;

        // check if downloading is allowed by the torrent
        if is_download_allowed {
            let has_wanted_pieces = self.has_wanted_piece().await;
            if has_wanted_pieces {
                state = InterestState::Interested;
            } else {
                state = InterestState::NotInterested;
            }
        } else {
            state = InterestState::NotInterested;
        }

        self.update_client_interest_state(state).await;
    }

    /// Try to receive/read the incoming handshake from the remote peer.
    async fn try_receive_handshake(&mut self) -> Result<Handshake> {
        select! {
            _ = time::sleep(self.timeout) => Err(Error::Handshake(
                *self.addr(),
                format!(
                    "handshake has timed out after {}.{:03} seconds",
                    self.timeout.as_secs(), self.timeout.subsec_millis()
                )
            )),
            result = self.connection.recv() => {
                if let Some(message) = result {
                    match message {
                        PeerResponse::Handshake(handshake) => Ok(handshake),
                        PeerResponse::Error(e) => Err(e),
                        PeerResponse::Closed => Err(Error::Closed),
                        _ => Err(Error::Handshake(*self.addr(), "invalid handshake received".to_string())),
                    }
                } else {
                    Err(Error::Closed)
                }
            },
        }
    }

    async fn validate_handshake(
        &mut self,
        handshake: Handshake,
    ) -> result::Result<(), CloseReason> {
        let mut v2_enabled = false;
        let mut is_valid = false;
        trace!("Peer {} received handshake {:?}", self, handshake);

        // check if v2 support is enabled
        if self
            .protocol_extensions
            .contains(ProtocolExtensionFlags::SupportV2)
            && handshake
                .supported_extensions
                .contains(ProtocolExtensionFlags::SupportV2)
        {
            // use the v2 info hash for validation
            if let Some(v2_hash) = self.metadata.info_hash.v2_as_short() {
                trace!("Peer {} is validating v2 handshake {:?}", self, v2_hash);
                if v2_hash == handshake.info_hash.short_info_hash_bytes() {
                    debug!("Peer {} has successfully upgraded to v2", self);
                    v2_enabled = true;
                    is_valid = true;
                } else {
                    debug!(
                        "Peer {} failed to upgrade to v2, invalid v2 handshake, falling back to v1 handshake validation",
                        self
                    );
                }
            } else {
                warn!(
                    "Peer {} is unable to upgrade to v2, metadata v2 hash is missing",
                    self
                )
            }
        }

        // check if the v2 handshake didn't succeed and we're using v1 handshake validation
        if !is_valid && self.metadata.info_hash != handshake.info_hash {
            self.update_state(PeerState::Error).await;
            return Err(CloseReason::InvalidInfoHash);
        }

        // store the remote peer information
        trace!(
            "Peer {} is updating remote peer information with {:?}",
            self,
            handshake
        );
        {
            self.remote = Some(RemotePeer {
                peer_id: handshake.peer_id,
                protocol_extensions: handshake.supported_extensions,
                extensions: ExtensionRegistry::default(),
                client_name: None,
                extended_handshake: false,
                is_v2: v2_enabled,
            });
        }

        debug!(
            "Peer {} handshake has been validated, {:?}",
            self, handshake
        );
        Ok(())
    }

    /// Updates the choke state of the client peer.
    pub async fn update_client_choke_state(&mut self, state: ChokeState) {
        // check if we're already in the expected state
        if self.client_choke_state == state {
            return;
        }

        self.client_choke_state = state;
        self.context
            .metrics()
            .client_choked
            .set(state == ChokeState::Choked);

        let send_result: Result<()>;
        if state == ChokeState::Choked {
            send_result = self.send(Message::Choke).await;
            self.reject_remote_pending_requests().await;
        } else {
            send_result = self.send(Message::Unchoke).await;
        }

        if let Err(e) = send_result {
            debug!(
                "Peer {} failed to sent {:?} state update, {}",
                self, state, e
            );
            self.update_state(PeerState::Error).await;
            return;
        }

        self.callbacks
            .invoke(PeerEvent::ClientChokeStateChanged(self.client_choke_state));
        debug!("Peer {} client entered {} state", self, state);
    }

    /// Updates the choke state of the remote peer.
    async fn update_remote_peer_choke_state(&mut self, state: ChokeState) {
        if self.remote_choke_state == state {
            return;
        }

        // update the choke state of the remote peer
        self.remote_choke_state = state;
        self.context
            .metrics()
            .remote_choked
            .set(state == ChokeState::Choked);

        if state == ChokeState::Choked {
            // if the remote is choked and the fast protocol is disabled,
            // then all pending requests are implicitly rejected
            if !self.is_protocol_enabled(ProtocolExtensionFlags::Fast) {
                self.reject_pending_requests().await;
            }

            // reject the whole downloading queue for this peer
            self.reject_download_queue().await;
        } else {
            self.send_queued_requests(PEER_TICK_INTERVAL).await;
            self.torrent.pick_pieces(self.context.addr()).await;
        }

        self.callbacks
            .invoke(PeerEvent::RemoteChokeStateChanged(self.client_choke_state));
        trace!("Peer {} remote entered {} state", self, state);
    }

    /// Updates the interest state of the client peer.
    /// This will notify the remote peer about the new interest state of our client if it changed.
    pub async fn update_client_interest_state(&mut self, state: InterestState) {
        // check if we're already in the expected state
        if self.client_interest_state == state {
            return;
        }

        self.client_interest_state = state;
        self.context
            .metrics()
            .client_interested
            .set(state == InterestState::Interested);

        let send_result: Result<()>;
        if state == InterestState::NotInterested {
            send_result = self.send(Message::NotInterested).await;
        } else {
            send_result = self.send(Message::Interested).await;
        }

        if let Err(e) = send_result {
            debug!(
                "Failed to send state {} to remote peer {}, {}",
                state, self, e
            );
        } else {
            debug!("Peer {} client entered {} state", self, state);
        }
    }

    /// Updates the interest state of the remote peer.
    async fn update_remote_peer_interest_state(&mut self, state: InterestState) {
        if self.remote_interest_state == state {
            return;
        }

        self.remote_interest_state = state;
        self.context
            .metrics()
            .remote_interested
            .set(state == InterestState::Interested);
    }

    /// Updates the state of the peer.
    pub async fn update_state(&mut self, new_state: PeerState) {
        if self.context.state().await == new_state {
            return;
        }

        self.context.set_state(new_state).await;
        debug!("Peer {} state updated to {:?}", self, new_state);
        self.invoke_event(PeerEvent::StateChanged(new_state));
    }

    /// Set the client peer as having the given pieces.
    /// This updates the peer client bitfield availability and informs the remote peer about the newly available pieces.
    async fn update_client_piece_availability(&mut self, piece: &PieceIndex) {
        // we might not have the bitfield stored if it was unknown when this peer was created
        // if that's the case, copy the whole bitfield from the torrent instead
        if self.client_pieces.len() <= *piece {
            self.client_pieces = self.data_pool.bitfield().await;
        } else {
            self.client_pieces.set(piece.clone(), true);
        }

        match self.send(Message::Have(*piece as u32)).await {
            Ok(_) => trace!(
                "Peer {} notified remote about {} piece availability",
                self,
                piece
            ),
            Err(e) => warn!(
                "Peer {} failed to notify remote peer about {} piece availability, {}",
                self, piece, e
            ),
        }
    }

    /// Update the remote piece availabilities with given piece.
    ///
    /// The range of the piece will be checked against the known pieces of the torrent, if known.
    /// If the piece is out-of-range, the update will be ignored.
    pub(crate) async fn set_remote_has_piece(&mut self, piece: PieceIndex, has_piece: bool) {
        let total_pieces = self.data_pool.num_of_pieces().await;
        let is_metadata_known = self.metadata.info.is_some();

        // ensure the BitVec is large enough to accommodate the piece index
        if piece >= self.remote_pieces.len() {
            let is_piece_bounds_known = is_metadata_known && total_pieces != 0;
            // check if the given piece index is out of bounds
            if is_piece_bounds_known && total_pieces < piece {
                warn!(
                    "Peer {} received remote has piece index {} out of bounds ({})",
                    self,
                    piece,
                    self.remote_pieces.len()
                );
                return;
            }

            // increase the size of the BitVec if metadata is still being retrieved
            self.remote_pieces.resize(piece + 1, false);
        }

        self.remote_pieces.set(piece, has_piece);

        self.context
            .metrics()
            .available_pieces
            .set(self.remote_pieces.count_ones() as u64);

        if has_piece {
            if !self.is_client_interested() {
                self.determine_client_interest_state().await;
            }
            self.torrent.piece_availabilities(vec![piece], true).await;
            if self.remote_has_all_pieces().await {
                self.invoke_event(PeerEvent::SeedStateChanged(true));
            }
        } else {
            self.torrent.piece_availabilities(vec![piece], false).await;
            self.invoke_event(PeerEvent::SeedStateChanged(false));
        }
    }

    /// Update the remote piece availability based on the supplied [BitVec].
    async fn update_remote_pieces(&mut self, pieces: BitVec) {
        self.remote_pieces = pieces.clone();
        debug!(
            "Peer {} updated {}/{} remote available pieces",
            self,
            pieces.count_ones(),
            pieces.len()
        );

        // notify subscribers about each available piece
        let piece_indexes: Vec<_> = pieces
            .into_iter()
            .enumerate()
            .filter(|(_, v)| *v)
            .map(|(piece, _)| piece as PieceIndex)
            .collect();

        if !piece_indexes.is_empty() {
            self.torrent.piece_availabilities(piece_indexes, true).await;
            if !self.is_client_interested() {
                self.determine_client_interest_state().await;
            }
        }

        if self.remote_has_all_pieces().await {
            self.invoke_event(PeerEvent::SeedStateChanged(true));
        }
    }

    async fn update_remote_fast_have(&mut self, have_all: bool) {
        // if the fast protocol is disabled, we should close the connection
        if !self
            .protocol_extensions
            .contains(ProtocolExtensionFlags::Fast)
        {
            warn!(
                "Fast protocol is disabled, closing connection with peer {}",
                self
            );
            self.close(CloseReason::InvalidAllowFastMessage).await;
            return;
        }

        let bitfield_len = self.data_pool.num_of_pieces().await;
        self.update_remote_pieces(BitVec::repeat(have_all, bitfield_len))
            .await;
        self.context
            .metrics()
            .available_pieces
            .set(bitfield_len as u64);
        self.determine_client_interest_state().await;
    }

    /// Add a pending request which is being requested by the remote peer.
    /// This request can however still be rejected on several conditions.
    async fn add_remote_pending_request(&mut self, request: Request) {
        let mut reject_request = false;
        // check if the request is a duplicate
        if self.remote_pending_requests.contains(&request) {
            warn!("Peer {} requested duplicate request {:?}", self, request);
            if self.is_protocol_enabled(ProtocolExtensionFlags::Fast) {
                self.close(CloseReason::InvalidAllowFastMessage).await;
            }

            return;
        }
        // check if the client peer is choked, if so, reject the request
        if self.client_choke_state == ChokeState::Choked {
            debug!(
                "Peer {} received request for piece {} data while being choked",
                self, request.index
            );
            reject_request = true;
        }
        // check if the request chunk is larger than the allowed chunk size, if so, reject the request
        if request.length > PieceBlock::MAX_LEN {
            debug!(
                "Peer {} requested too large piece {} part, max length {}, requested length {}",
                self,
                request.index,
                PieceBlock::MAX_LEN,
                request.length
            );
            reject_request = true;
        }

        if reject_request {
            self.send_reject_request(request).await;
            return;
        }

        self.on_remote_pending_request(request).await;
    }

    /// Try to cancel a remote pending request.
    /// This will remove the pending request from the queue if found.
    async fn cancel_remote_pending_request(&mut self, request: Request) {
        if let Some(position) = self
            .remote_pending_requests
            .iter()
            .position(|e| e == &request)
        {
            let request = self.remote_pending_requests.remove(position);
            debug!("Cancelled remote pending {:?} for {}", request, self);
        } else {
            debug!(
                "Unable to cancel remote pending {:?} for {}, pending request not found",
                request, self
            );
        }
    }

    /// Reject any remaining pending requests of the remote peer.
    /// This should be called when our client peer enters the [ChokeState::Choked].
    async fn reject_remote_pending_requests(&mut self) {
        if self.is_protocol_enabled(ProtocolExtensionFlags::Fast) {
            // reject any remaining pending requests as specified in BEP6 when entering the choked state
            // this should prevent race conditions in which case we're still sending some piece data while
            // the client is entering the choked state
            for request in std::mem::take(&mut self.remote_pending_requests) {
                if self.connection.is_closed() {
                    break;
                }

                self.send_reject_request(request).await;
            }
        } else {
            // clear any remaining pending requests as specified in BEP3 when entering the choked state
            self.remote_pending_requests.clear();
        }
    }

    /// Add the given piece to be executed as fast request.
    async fn remote_fast_piece(&mut self, piece: PieceIndex) {
        // When the fast extension is disabled, if a peer receives an Allowed Fast message then the peer MUST close the connection.
        if !self.is_protocol_enabled(ProtocolExtensionFlags::Fast) {
            self.close(CloseReason::InvalidAllowFastMessage).await;
            return;
        }

        // resize the remote bitfield, if needed
        if self.remote_pieces.len() < piece {
            self.remote_pieces.resize(piece, false);
        }

        self.remote_fast_pieces.insert(piece);
    }

    /// Process an incoming piece suggestion from the remote peer.
    /// This will request the given piece if the fast protocol is enabled, downloading is allowed and the piece is wanted by the torrent.
    async fn on_piece_suggested(&mut self, piece: PieceIndex) {
        // When the fast extension is disabled, if a peer receives a Suggest Piece message, the peer MUST close the connection.
        if !self.is_protocol_enabled(ProtocolExtensionFlags::Fast) {
            self.close(CloseReason::InvalidAllowFastMessage).await;
            return;
        }

        self.remote_suggested_pieces.insert(piece);
    }

    async fn update_extended_handshake(&mut self, handshake: ExtendedHandshake) {
        if let Some(remote) = self.remote.as_mut() {
            remote.extensions = handshake.m;
            remote.client_name = handshake.client;
            remote.extended_handshake = true;
            let remote_info = format!("{:?}", remote);

            debug!(
                "Peer {} updated extended handshake information, {}",
                self, remote_info
            );
        } else {
            warn!(
                "Peer {} received extended handshake before the initial handshake was completed",
                self
            );
            self.close(CloseReason::None).await;
        }
    }

    /// Process piece block requests, which need to be queued for downloading from the remote peer.
    async fn on_request(&mut self, blocks: Vec<PieceBlock>) {
        // early exit if the peer is being closed
        if self.cancellation_token.is_cancelled() {
            self.reject_block_requests(blocks.into_iter()).await;
            return;
        }

        let mut requests_added = 0usize;
        for block in blocks {
            // filter out any duplicate piece blocks
            if self.download_queue.contains(&block) {
                trace!("Peer {} has already queued piece block {:?}", self, block);
                continue;
            }
            if self.pending_requests.iter().any(|pending| {
                pending.request.index == block.piece && pending.request.begin == block.begin
            }) {
                trace!(
                    "Peer {} is already downloading piece block {:?}",
                    self,
                    block
                );
                continue;
            }

            self.download_queue.push_back(block);
            requests_added += 1;
        }

        trace!(
            "Peer {} is adding {} request(s) to the download queue",
            self,
            requests_added
        );
    }

    fn target_request_queue_len(&self) -> usize {
        self.target_queue_len
            .saturating_sub(self.download_queue.len())
            .saturating_sub(self.pending_requests.len())
    }

    fn update_target_request_queue_len(&mut self) {
        let download_rate = self.context.metrics().bytes_in_useful.rate();
        let target_queue_len = max(
            (REQUEST_QUEUE_TIME.as_secs() * download_rate as u64) as usize / PieceBlock::MAX_LEN,
            MIN_TARGET_QUEUE_LEN,
        );

        self.target_queue_len = target_queue_len.min(MAX_TARGET_QUEUE_LEN);
    }

    /// Reject the given piece block requests.
    /// This informs the piece picker that the peer was unable to fulfill the requests.
    async fn reject_block_requests(&self, blocks: impl Iterator<Item = PieceBlock>) {
        for block in blocks {
            self.torrent
                .piece_block_rejected(self.context.addr(), &block)
                .await
        }
    }

    /// Reject the current in-flight block requests to the remote peer.
    async fn reject_pending_requests(&mut self) {
        let blocks = std::mem::take(&mut self.pending_requests)
            .into_iter()
            .map(|e| e.block);
        self.reject_block_requests(blocks).await;
    }

    /// Reject the queued piece blocks within the download queue.
    async fn reject_download_queue(&mut self) {
        let blocks = std::mem::take(&mut self.download_queue).into_iter();
        self.reject_block_requests(blocks).await;
    }

    /// Try to sent one or more queued requests to the remote peer.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn send_queued_requests(&mut self, interval: Duration) {
        const REQUEST_LIMIT: usize = 20;

        // early exit if there are no queued requests
        if self.download_queue.is_empty() {
            return;
        }

        let start_time = Instant::now();
        let mut num_of_requests_sent = 0;
        while !self.download_queue.is_empty()
            && start_time.elapsed() < interval
            && self.pending_requests.len() < self.target_queue_len
            && num_of_requests_sent < REQUEST_LIMIT
        {
            let block = match self.download_queue.pop_front() {
                None => break,
                Some(request) => request,
            };
            // if the remote peer is choked, but the fast protocol allows this piece
            // we continue sending the request as it's still valid
            let is_remote_choked = self.remote_choke_state == ChokeState::Choked;
            let is_fast_allowed = self.is_fast_allowed(&block.piece);
            if is_remote_choked && !is_fast_allowed {
                // the block is not allowed within the fast protocol,
                // put it back into the download queue
                self.download_queue.push_back(block);
                continue;
            }

            // if the block is already in the pending requests,
            // drop it and continue with the next one
            if self.pending_requests.iter().any(|pending| {
                pending.request.index == block.piece && pending.request.begin == block.begin
            }) {
                trace!(
                    "Peer {} is already downloading piece block {:?}",
                    self,
                    block
                );
                continue;
            }

            if let Err(e) = self.send_pending_request(block.clone().into()).await {
                trace!(
                    "Peer {} failed to sent request ({}:{}), {}",
                    self,
                    block.piece,
                    block.begin,
                    e
                );
                self.torrent
                    .piece_block_rejected(self.context.addr(), &block)
                    .await;
                break;
            }

            num_of_requests_sent += 1;
        }

        let elapsed = start_time.elapsed();
        log!(
            if elapsed > interval {
                Level::Warn
            } else {
                Level::Trace
            },
            "Peer {} sent {} queued request(s) in {:.3}ms",
            self,
            num_of_requests_sent,
            elapsed.as_secs_f64() * 1000.0
        );
    }

    /// Try to send the handshake information of our client peer to the remote peer.
    async fn send_handshake(&mut self) -> Result<()> {
        self.update_state(PeerState::Handshake).await;
        let handshake = Handshake::new(
            self.metadata.info_hash.clone(),
            *self.context.id(),
            self.protocol_extensions,
        );
        debug!("Peer {} is sending handshake {:?}", self, handshake);
        match self
            .send_raw_bytes(TryInto::<Vec<u8>>::try_into(handshake)?)
            .await
        {
            Ok(_) => Ok(()),
            Err(e) => {
                debug!("Peer {} failed to send handshake, {}", self, e);
                self.update_state(PeerState::Error).await;
                Err(e)
            }
        }
    }

    async fn send_extended_handshake(&self) -> Result<()> {
        let extension_registry = self.extension_registry.clone();
        let is_partial_seed = self.data_pool.is_partial_seed().await;
        let message = Message::ExtendedHandshake(ExtendedHandshake {
            m: extension_registry,
            upload_only: is_partial_seed,
            client: self.peer_client_name.clone().into(),
            regg: None,
            encryption: false,
            metadata_size: None,
            port: self.peer_port.map(|e| e as u32),
            your_ip: Some(CompactIp::from(self.context.addr())),
            ipv4: None,
            ipv6: None,
        });

        debug!("Peer {} is sending extended handshake {:?}", self, message);
        self.send(message).await
    }

    async fn send_initial_messages(&mut self) -> Result<()> {
        let mut is_fast_have_sent = false;

        // the extended handshake should be sent immediately after the standard bittorrent handshake to any peer that supports the extension protocol
        if self.is_protocol_enabled(ProtocolExtensionFlags::LTEP) {
            trace!("Peer {} exchanging extended handshake", self);
            self.update_state(PeerState::Handshake).await;
            if let Err(e) = self.send_extended_handshake().await {
                warn!("Peer {} failed to send extended handshake, {}", self, e);
                // remove the LTEP extension flag from the remote peer
                // as the extended handshake has failed to complete
                if let Some(remote) = self.remote.as_mut() {
                    remote.protocol_extensions &= !ProtocolExtensionFlags::LTEP;
                }
            }
        }

        // check if the fast protocol is enabled
        // if so, we send the initial fast messages to the remote peer
        let bitfield = self.torrent_bitfield().await;
        let is_bitfield_known = bitfield.len() > 0;
        let is_fast_enabled = self.is_protocol_enabled(ProtocolExtensionFlags::Fast);
        if is_fast_enabled && is_bitfield_known {
            let mut message: Option<Message> = None;
            let is_metadata_known = self.metadata.info.is_some();

            if is_metadata_known && bitfield.all() {
                message = Some(Message::HaveAll);
            } else if !is_metadata_known || bitfield.not_any() {
                message = Some(Message::HaveNone);
            }

            if let Some(message) = message {
                let message_type = format!("{:?}", message);
                match self.send(message).await {
                    Ok(_) => {
                        is_fast_have_sent = true;
                        debug!("Peer {} sent message {}", self, message_type);
                    }
                    Err(e) => {
                        warn!(
                            "Peer {} failed to send message {}, {}",
                            self, message_type, e
                        );
                        self.update_state(PeerState::Error).await;
                    }
                }
            }
        }

        // we try to send the bitfield with completed pieces if none of the initial fast messages have been sent
        // this is only done if at least one piece is completed
        if !is_fast_have_sent && is_bitfield_known && bitfield.any() {
            let message = Message::Bitfield(bitfield.clone());
            let message_type = format!("{:?}", message);
            match self.send(message).await {
                Ok(_) => debug!("Peer {} sent message {}", self, message_type),
                Err(e) => {
                    warn!("Peer {} failed to send bitfield message, {}", self, e);
                    self.update_state(PeerState::Error).await;
                }
            }
        }

        // store the bitfield of the torrent as initial state
        self.client_pieces = bitfield;

        // request missing hashes if needed
        if self.should_request_hashes().await {
            self.request_missing_hashes().await;
        }

        self.update_state(PeerState::Idle).await;
        Ok(())
    }

    /// Try to send a HolePunch request to the remote peer.
    /// This is done through the HolePunch extension, if available.
    async fn send_holepunch(
        &self,
        target: SocketAddr,
        response: Reply<extension::Result<SocketAddr>>,
        extensions: &mut [PeerExtension],
    ) {
        let extension = match extensions.iter_mut().find_map(|e| match e {
            PeerExtension::Holepunch(e) => Some(e),
            _ => None,
        }) {
            None => {
                response.send(Err(extension::Error::Unsupported));
                return;
            }
            Some(e) => e,
        };

        trace!("Peer {} is starting holepunch for {}", self, target);
        extension.send_rendezvous(target, response, self).await;
    }

    /// Send the reject request to the remote peer.
    /// This is only executed if the fast protocol is enabled.
    async fn send_reject_request(&mut self, request: Request) {
        self.context.metrics().rejects.inc();

        // if the fast protocol is disabled, then we don't send a reject
        if !self.is_protocol_enabled(ProtocolExtensionFlags::Fast) {
            return;
        }

        let piece = request.index;
        match self.send(Message::RejectRequest(request)).await {
            Ok(_) => trace!("Peer {} rejected remote request {}", self, piece),
            Err(e) => {
                warn!(
                    "Peer {} failed to reject remote request {}, {}",
                    self, piece, e
                );
                if let Error::Io(e) = e {
                    if matches!(
                        e.kind(),
                        io::ErrorKind::Interrupted
                            | io::ErrorKind::ConnectionReset
                            | io::ErrorKind::ConnectionAborted
                            | io::ErrorKind::ConnectionRefused
                    ) {
                        self.close(CloseReason::TimedOutRequest).await
                    }
                }
            }
        }
    }

    /// Try to send the given message to the remote peer.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn send(&self, message: Message) -> Result<()> {
        trace!("Peer {} trying to send message {:?}", self, message);
        let message_bytes = TryInto::<Vec<u8>>::try_into(message)?;
        self.send_bytes(message_bytes).await
    }

    /// Send the given message to the remote peer.
    /// This method will prefix the message bytes with the BigEndian length bytes of the given message.
    pub async fn send_bytes<T: AsRef<[u8]>>(&self, message: T) -> Result<()> {
        let msg_length = message.as_ref().len();
        let mut buffer = vec![0u8; 4];

        // write the length of the given message as BigEndian in the first 4 bytes
        BigEndian::write_u32(&mut buffer[..4], msg_length as u32);
        // append the given message bytes to the buffer
        buffer.extend_from_slice(message.as_ref());

        self.send_raw_bytes(buffer).await
    }

    /// Send the given message bytes AS-IS to the remote peer.
    /// The given bytes should be a valid BitTorrent protocol message.
    async fn send_raw_bytes<T: AsRef<[u8]>>(&self, bytes: T) -> Result<()> {
        let msg_length = bytes.as_ref().len();

        timeout(self.timeout, self.connection.write(bytes.as_ref())).await??;

        self.context.metrics().bytes_out.inc_by(msg_length as u64);
        Ok(())
    }

    /// Request piece data which is available from the remote peer.
    async fn send_pending_request(&mut self, block: PieceBlock) -> Result<()> {
        if self.context.state().await != PeerState::Downloading {
            self.update_state(PeerState::Downloading).await;
        }

        self.send(Message::Request(block.clone().into())).await?;

        // add the request to the pending requests queue
        self.pending_requests.push(PendingRequest {
            request: block.clone().into(),
            block,
            sent: Instant::now(),
        });
        Ok(())
    }

    /// Send the keep alive message to the remote peer.
    pub async fn send_keep_alive(&self) {
        let message = Message::KeepAlive;

        match TryInto::<Vec<u8>>::try_into(message) {
            Ok(bytes) => {
                if let Err(e) = self.send_bytes(bytes).await {
                    warn!("Failed to send keep alive to peer {}, {}", self, e);
                }
            }
            Err(e) => warn!("Failed to parse keep alive message, {}", e),
        }
    }

    /// Try to remove the given request from the pending requests.
    /// This function should be called when piece data has been received or rejected for the given request.
    async fn remove_client_pending_request(&mut self, request: &Request) -> Option<Request> {
        self.pending_requests
            .iter()
            .position(|e| &e.request == request)
            .map(|pos| self.pending_requests.remove(pos).request)
    }

    /// Verify that the given piece request is valid to be processed.
    /// This will check that the requested range is within the piece range and that the piece is completed.
    async fn validate_piece_request(&self, request: &Request) -> bool {
        let is_piece_completed = self.data_pool.is_piece_completed(&request.index).await;

        if is_piece_completed {
            if let Some(piece) = self.data_pool.piece(&request.index).await {
                let piece_len = piece.length;
                let request_end = request.begin + request.length;

                return request.begin < piece_len && request_end <= piece_len;
            } else {
                warn!(
                    "Peer {} failed to retrieve piece data of {}",
                    self, request.index
                );
            }
        } else {
            debug!(
                "Peer {} received piece request for incomplete piece {}",
                self, request.index
            );
        }

        false
    }

    /// Find the supported extension from our own client extensions through the extensions number.
    /// This should be used when we've received an extended message from the remote peer.
    pub async fn find_extension_by_number<'a>(
        &self,
        extension_number: ExtensionNumber,
        extensions: &'a mut [PeerExtension],
    ) -> Option<&'a mut PeerExtension> {
        // search for the given extension, by extensions number, in our own supported extensions
        let extension_registry = self.client_extension_registry();
        if let Some(extension_name) = extension_registry
            .iter()
            .find(|(_, number)| extension_number == **number)
            .map(|(name, _)| name.clone())
        {
            return extensions.iter_mut().find(|e| e.name() == extension_name);
        } else {
            let extensions = self.remote_extension_registry();
            debug!(
                "Extension number {} is not support by {}, supported remote {:?}",
                extension_number, self, extensions
            )
        }

        None
    }

    /// Returns the extension number of the remote peer for the given extension name.
    pub fn find_remote_extension_number(&self, extension_name: &str) -> Option<ExtensionNumber> {
        self.remote
            .as_ref()
            .and_then(|remote| remote.extensions.get(extension_name).copied())
    }

    /// Invoke the extension tick function for all enabled extensions.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_extensions_tick(&mut self, extensions: &mut [PeerExtension], interval: Duration) {
        for extension in extensions {
            let start = Instant::now();
            extension.tick(self).await;
            let elapsed = start.elapsed();
            log!(
                if elapsed > interval {
                    Level::Warn
                } else {
                    Level::Trace
                },
                "Peer {} extension \"{}\" tick took {:.3}ms",
                self,
                extension.name(),
                elapsed.as_secs_f64() * 1000.0
            );
        }
    }

    /// Update the statistics of the peer.
    fn on_stats_update(&self, interval: Duration) {
        let event_stats = self.context.metrics().snapshot();
        self.context.metrics().tick(interval);
        self.callbacks.invoke(PeerEvent::Stats(event_stats));
    }

    /// Invoke an event on the peer instance.
    /// This will trigger the event for all enabled extensions.
    pub fn invoke_event(&self, event: PeerEvent) {
        self.callbacks.invoke(event);
    }

    /// Close the connection of the peer.
    /// This cancels the main loop of the peer and notifies the parent torrent of the closure.
    pub(crate) async fn close(&mut self, reason: CloseReason) {
        debug!("Peer {} is closing, {:?}", self, reason);
        // cancel the main loop of the peer to stop any ongoing operation
        self.cancellation_token.cancel();
        // reject any pending requests and queued block downloads
        self.reject_pending_requests().await;
        self.reject_download_queue().await;
        // close underlying connection
        let _ = self.connection.close().await;
        // notify any subscribers
        self.update_state(PeerState::Closed).await;

        // notify the torrent that this peer is being closed
        if self.torrent.is_valid() {
            self.torrent.peer_closed(*self.context.addr(), reason).await;
        }

        self.invoke_event(PeerEvent::Closed(reason));
    }

    /// Return the extension registry for the given extensions.
    fn create_extension_registry(extensions: &[PeerExtension]) -> ExtensionRegistry {
        let mut extension_index = 0u8;

        extensions
            .iter()
            .map(|e| {
                extension_index += 1;
                (e.name().to_string(), extension_index)
            })
            .collect()
    }
}

impl Callback<PeerEvent> for BitTorrentPeerContext {
    fn subscribe(&self) -> Subscription<PeerEvent> {
        self.callbacks.subscribe()
    }
}

impl Drop for BitTorrentPeerContext {
    fn drop(&mut self) {
        self.cancellation_token.cancel();
        trace!("Peer {} is being dropped", self)
    }
}

#[derive(Debug)]
struct PendingRequest {
    /// The piece block belonging to this request.
    block: PieceBlock,
    /// The outgoing request that is pending a response.
    request: Request,
    /// The time the request was sent to the remote peer.
    sent: Instant,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::operation::{CreatePiecesAndFilesOperation, FileValidationOperation};
    use crate::peer::protocol::UtpPacketCapture;
    use crate::peer::tests::create_utp_peer_pair;
    use crate::storage::{DiskStorage, MemoryStorage};
    use crate::tests::copy_test_file;
    use crate::tests::helpers::wait_for_torrent_pieces;
    use crate::DEFAULT_TORRENT_PROTOCOL_EXTENSIONS;
    use std::cmp::Ordering;
    use tempfile::tempdir;

    mod new {
        use super::*;

        #[tokio::test]
        async fn test_new_tcp() {
            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![],
                vec![]
            );
            let (outgoing, incoming) = tcp_peer_pair!(&torrent, vec![]);

            let result = incoming.state().await;
            assert_ne!(PeerState::Error, result);
            assert_ne!(PeerState::Closed, result);

            incoming.close().await;
            let result = incoming.state().await;
            assert_eq!(PeerState::Closed, result);
            assert_timeout!(
                Duration::from_secs(1),
                PeerState::Closed == outgoing.state().await,
                "expected the outgoing connection to be closed"
            );
        }

        #[tokio::test]
        async fn test_new_utp() {
            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![],
                vec![]
            );
            let incoming_capture = UtpPacketCapture::new();
            let outgoing_capture = UtpPacketCapture::new();
            let (incoming_socket, outgoing_socket) = create_utp_socket_pair!(
                vec![incoming_capture.clone().into()],
                vec![outgoing_capture.clone().into()]
            );
            let (outgoing, incoming) = create_utp_peer_pair(
                &incoming_socket,
                &outgoing_socket,
                &torrent,
                &torrent,
                DEFAULT_TORRENT_PROTOCOL_EXTENSIONS(),
            )
            .await;

            let result = incoming.state().await;
            assert_ne!(PeerState::Error, result);
            assert_ne!(PeerState::Closed, result);

            // close the incoming peer connection
            incoming.close().await;
            let result = incoming.state().await;
            assert_eq!(
                PeerState::Closed,
                result,
                "expected the incoming connection to be closed"
            );

            // wait for the outgoing peer connection to reach the closed state
            assert_timeout!(
                Duration::from_secs(1),
                PeerState::Closed == outgoing.state().await,
                "expected the outgoing connection to be closed"
            );
        }
    }

    mod handshake {
        use super::*;
        use std::net::Ipv4Addr;
        use tokio::net::TcpListener;
        use tokio::sync::oneshot;

        #[tokio::test]
        async fn test_handshake() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let (tx, rx) = oneshot::channel();
            let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)))
                .await
                .unwrap();
            let listener_addr = (Ipv4Addr::LOCALHOST, listener.local_addr().unwrap().port()).into();
            let torrent = torrent!(
                "debian-udp.torrent",
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![],
                vec![]
            );

            // create a new outbound peer
            // this peer is responsible for starting the handshake
            let inner = torrent.inner.clone();
            let data_pool = torrent.inner.data_pool().await.unwrap();
            let storage = torrent.inner.storage().await.unwrap();

            // subscribe to the peer and listen for the handshake completed event
            let metadata = torrent.inner.metadata().await.unwrap();
            tokio::spawn(async move {
                // the peer is only returned after the handshake has been completed
                let peer = BitTorrentPeer::new_outbound(
                    PeerId::new(),
                    listener_addr,
                    Some(6881),
                    "FxTestClient".to_string(),
                    PeerStream::Tcp(TcpStream::connect(listener_addr).await.unwrap()),
                    inner,
                    metadata,
                    data_pool,
                    storage,
                    ProtocolExtensionFlags::none(),
                    vec![],
                    Duration::from_secs(5),
                )
                .await
                .expect("expected a new outbound peer");

                let _ = tx.send(peer);
            });

            // try to accept the incoming peer connection
            let (stream, addr) = timeout!(Duration::from_millis(250), listener.accept())
                .expect("expected to receive an incoming connection");
            let peer_id = PeerId::new();
            let connection = PeerConnection::new_tcp(peer_id, addr, stream, Metrics::new());

            // the outgoing connection should always send a handshake as first message
            // so wait for the incoming handshake from the peer
            let info_hash = torrent.info_hash().await.unwrap();
            let message = timeout!(
                Duration::from_millis(250),
                connection.recv(),
                "expected an incoming handshake"
            )
            .unwrap();
            let handshake = match message {
                PeerResponse::Handshake(handshake) => handshake,
                _ => {
                    assert!(false, "expected a handshake message");
                    return;
                }
            };
            assert_eq!(
                ProtocolExtensionFlags::none(),
                handshake.supported_extensions,
                "expected the handshake to have no extensions"
            );
            assert_eq!(
                info_hash, handshake.info_hash,
                "expected the handshake to have the correct info hash"
            );

            // send a response to the given handshake
            let reply_handshake = TryInto::<Vec<u8>>::try_into(Handshake {
                supported_extensions: ProtocolExtensionFlags::none(),
                info_hash,
                peer_id,
            })
            .unwrap();
            let result = connection.write(reply_handshake.as_slice()).await;
            assert!(
                result.is_ok(),
                "expected the handshake to be sent successfully, but got {:?}",
                result
            );

            // wait for the remote peer to receive and validate the handshake
            let peer = timeout!(
                Duration::from_millis(250),
                rx,
                "expected the handshake to be validated"
            )
            .unwrap();

            // verify that the peer is no longer in the handshake state
            let state = peer.state().await;
            assert_ne!(
                PeerState::Handshake,
                state,
                "expected the peer handshake to have been completed"
            );
        }
    }

    #[tokio::test]
    async fn test_peer_has_wanted_pieces() {
        init_logger!();
        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 source = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![
                CreatePiecesAndFilesOperation::new().into(),
                FileValidationOperation::new().into(),
            ],
            vec![],
            |params| DiskStorage::new(params.info_hash, params.path, params.data_pool,).into(),
            None
        );
        let target = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![CreatePiecesAndFilesOperation::new().into()],
            vec![],
            |_| MemoryStorage::new().into(),
            None
        );

        // create the pieces for the torrent
        wait_for_torrent_pieces(&source).await;
        wait_for_torrent_pieces(&target).await;

        // wait for the source torrent to validate the existing pieces
        // this should automatically inform the target peer that it has wanted pieces
        assert_timeout!(
            Duration::from_secs(2),
            source.has_piece(&29).await,
            "expected the pieces to have been validated"
        );

        // pause the source to prevent the target from starting to download the available pieces
        source.pause().await;

        // create the peer pair
        let (_source_peer, target_peer) = tcp_peer_pair!(
            &source,
            &target,
            vec![],
            vec![],
            ProtocolExtensionFlags::LTEP
        );

        // check if the target peer has wanted pieces from the source
        // as the bitfield is sent after the handshake, it might not have been received yet
        assert_timeout!(
            Duration::from_millis(500),
            target_peer.has_wanted_pieces().await == true,
            "expected the remote to have wanted pieces"
        );
    }

    #[tokio::test]
    async fn test_peer_torrent_pieces_changed() {
        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![]
        );
        let (outgoing, _incoming) = tcp_peer_pair!(&torrent, vec![]);

        // create the pieces for the torrent
        wait_for_torrent_pieces(&torrent).await;

        // check if both the client & remote piece bitfield have been updated
        let torrent_bitfield = torrent.inner.data_pool().await.unwrap().bitfield().await;
        assert_timeout!(
            Duration::from_secs(1),
            torrent_bitfield == outgoing.client_piece_bitfield().await,
            "expected the peer client bitfield to match the torrent bitfield"
        );
        assert_timeout!(
            Duration::from_millis(500),
            outgoing.remote_piece_bitfield().await.len() == torrent_bitfield.len(),
            "expected the remote bitfield to match the torrent bitfield length"
        );
    }

    #[test]
    fn test_interest_state_ordering() {
        let result = InterestState::NotInterested.cmp(&InterestState::NotInterested);
        assert_eq!(Ordering::Equal, result);

        let result = InterestState::Interested.cmp(&InterestState::NotInterested);
        assert_eq!(Ordering::Greater, result);

        let result = InterestState::NotInterested.cmp(&InterestState::Interested);
        assert_eq!(Ordering::Less, result);

        let result = InterestState::Interested.cmp(&InterestState::Interested);
        assert_eq!(Ordering::Equal, result);
    }

    mod target_request_queue_len {
        use super::*;

        #[tokio::test]
        async fn test_download_rate() {
            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![],
                |_| MemoryStorage::new().into(),
                None
            );
            let (mut peer, _target) = peer_context_pair!(&torrent.inner, &[]);

            // update the target queue len when the download rate is 0
            peer.update_target_request_queue_len();
            assert_eq!(
                MIN_TARGET_QUEUE_LEN, peer.target_queue_len,
                "expected the target_queue_len to be MIN_TARGET_QUEUE_LEN"
            );

            peer.context.metrics().bytes_in_useful.inc_by(640_000);
            peer.context.metrics().tick(Duration::from_secs(1));
            peer.context.metrics().bytes_in_useful.inc_by(1_280_000);
            peer.context.metrics().tick(Duration::from_secs(1));

            // update the target queue len when a download rate is known
            peer.update_target_request_queue_len();
            assert_eq!(
                65, peer.target_queue_len,
                "expected the target_queue_len to be calculated from the download rate"
            );
        }

        #[tokio::test]
        async fn test_max_target_queue_len() {
            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![],
                |_| MemoryStorage::new().into(),
                None
            );
            let (mut peer, _target) = peer_context_pair!(&torrent.inner, &[]);

            // set the download rate to a ridiculously high value
            peer.context.metrics().bytes_in_useful.inc_by(100_000_000);
            peer.context.metrics().tick(Duration::from_secs(1));

            peer.update_target_request_queue_len();
            assert_eq!(
                MAX_TARGET_QUEUE_LEN, peer.target_queue_len,
                "expected the target_queue_len to be MAX_TARGET_QUEUE_LEN"
            );
        }
    }
}