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
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
use crate::bencode::Value;
use crate::bloom_filter::BloomFilter;
use crate::channel::{ChannelReceiver, ChannelSender, Reply, Response};
use crate::dht::compact::{CompactIPv6Nodes, CompactIpNodes};
use crate::dht::krpc::{
    AnnouncePeerRequest, AnnouncePeerResponse, ErrorMessage, FindNodeRequest, FindNodeResponse,
    GetPeersRequest, GetPeersResponse, GetRequest, GetResponse, Message, MessagePayload,
    PingMessage, PutRequest, PutResponse, QueryMessage, ResponseMessage, ResponsePayload,
    SampleInfoHashesRequest, SampleInfoHashesResponse, TransactionId, Version, WantFamily,
};
use crate::dht::observer::Observer;
use crate::dht::routing_table::RoutingTable;
use crate::dht::traversal::TraversalAlgorithm;
use crate::dht::utils::{generate_mutable_item_key, parse_mutable_item_properties};
use crate::dht::ServerNode;
use crate::dht::{
    Config, DhtMetrics, Error, ItemSignature, Mode, Node, NodeId, NodeKey, NodeState, NodeToken,
    PeerEntry, PublicKey, Result, SecretKey, DEFAULT_ROUTING_NODE_SERVERS,
};
use crate::dht::{DhtNodeHandler, QueryResult};
use crate::metrics::Metric;
use crate::{bencode, InfoHash, Sha1Hash};
use derive_more::Display;
use ed25519::SignatureBytes;
use futures::StreamExt;
use fx_callback::{Callback, MultiThreadedCallback, Subscription};
use itertools::{Either, Itertools};
use log::{debug, error, trace, warn};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter};
use std::io;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::net::{lookup_host, UdpSocket};
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::oneshot;
use tokio::time::{interval, timeout};
use tokio::{select, time};
use tokio_util::sync::CancellationToken;
use url::Url;

/// The maximum size of a single UDP packet.
const MAX_PACKET_SIZE: usize = 65_535;
const VERSION_IDENTIFIER: &str = "FX0001";
const SEND_PACKAGE_TIMEOUT: Duration = Duration::from_secs(2);
const RESPONSE_TIMEOUT: Duration = Duration::from_secs(8);
const REFRESH_TIMEOUT: Duration = Duration::from_secs(60 * 15);
const BOOTSTRAP_INTERVAL: Duration = Duration::from_secs(2);
const REFRESH_INTERVAL: Duration = Duration::from_secs(60 * 5);
const TICK_INTERVAL: Duration = Duration::from_secs(1);
const DEFAULT_BUCKET_SIZE: usize = 8;

#[derive(Debug)]
pub enum DhtEvent {
    /// Invoked when the node ID of the DHT server changes.
    IDChanged,
    /// Invoked when the external IP address of the DHT server changes.
    ExternalIpChanged(IpAddr),
    /// Invoked when a new node is added to the routing table.
    NodeAdded(NodeKey),
    /// Invoked when a new info hash is added to the DHT storage.
    InfoHashAdded(InfoHash),
    /// Invoked when a peer is updated within the DHT storage.
    PeerUpdated(InfoHash, SocketAddr),
    /// Invoked when the stats of the DHT server are updated.
    Stats(DhtMetrics),
}

/// A tracker instance for managing DHT nodes.
/// This instance can be shared between torrents by using [DhtTracker::clone].
#[derive(Debug, Display)]
#[display("DHT node [{}]", addr.port())]
pub struct DhtTracker {
    addr: SocketAddr,
    mode: Mode,
    metrics: DhtMetrics,
    pub(crate) sender: ChannelSender<TrackerCommand>,
    callbacks: MultiThreadedCallback<DhtEvent>,
    cancellation_token: CancellationToken,
}

impl DhtTracker {
    /// Create a new builder instance to create a new node server.
    pub fn builder() -> DhtTrackerBuilder {
        DhtTrackerBuilder::default()
    }

    /// Create a new node with the given ID.
    /// This function allows creating a server with a specific node id.
    pub async fn new(config: Config) -> Result<Self> {
        let socket = Arc::new(Self::bind_socket().await?);
        let socket_addr = socket.local_addr()?;
        let (command_sender, command_receiver) = channel!(256);
        let item_signature = match config.item_signature {
            None => ItemSignature::new()?,
            Some(e) => e,
        };
        let mut context = TrackerContext::new(
            config.id,
            socket,
            socket_addr,
            config.mode,
            config.info_hash_indexing_enabled,
            item_signature,
            config.max_torrents,
        );
        let metrics = context.metrics.clone();
        let callbacks = context.callbacks.clone();
        let cancellation_token = context.cancellation_token.clone();

        // create the observer and traversal algorithm for the node
        let observer = Observer::new(command_sender.clone());
        let traversal = TraversalAlgorithm::new(
            DEFAULT_BUCKET_SIZE,
            config.routing_nodes,
            command_sender.clone(),
        );

        // start the context in a separate task
        spawn!("TrackerContext::run", async move {
            context
                .run(
                    config.info_hash_indexing_interval,
                    observer,
                    traversal,
                    command_receiver,
                )
                .await;
        });

        Ok(Self {
            addr: socket_addr,
            mode: config.mode,
            metrics,
            sender: command_sender,
            callbacks,
            cancellation_token,
        })
    }

    /// Get the ID of the DHT server.
    pub async fn id(&self) -> Result<NodeId> {
        let response = self
            .sender
            .send(|tx| TrackerCommand::Id { response: tx })
            .await;
        response.await.map_err(|_| Error::Closed)
    }

    /// Returns the socket address on which this DHT node is running.
    pub fn addr(&self) -> &SocketAddr {
        &self.addr
    }

    /// Returns the port on which the DHT node is running.
    pub fn port(&self) -> u16 {
        self.addr.port()
    }

    /// Returns the DHT network metrics of the node.
    pub fn metrics(&self) -> &DhtMetrics {
        &self.metrics
    }

    /// Returns the mode of the DHT node.
    pub fn mode(&self) -> Mode {
        self.mode
    }

    /// Get the number of nodes within the routing table.
    pub async fn total_nodes(&self) -> usize {
        let response = self
            .sender
            .send(|tx| TrackerCommand::TotalNodes { response: tx })
            .await;
        response.await.unwrap_or_default()
    }

    /// Returns the node with the given key from the routing table, if found.
    pub async fn node(&self, node: &NodeKey) -> Option<Node> {
        self.sender
            .send(|tx| TrackerCommand::GetNode {
                node: *node,
                response: tx,
            })
            .await
            .await
            .ok()
            .flatten()
    }

    /// Returns the node with the given id from the routing table, if found.
    pub async fn node_by_id(&self, id: &NodeId) -> Option<Node> {
        self.sender
            .send(|tx| TrackerCommand::GetNodeById {
                id: *id,
                response: tx,
            })
            .await
            .await
            .unwrap_or_else(|_| None)
    }

    /// Returns all nodes within the routing table of the tracker.
    /// This doesn't include any router/search nodes.
    pub async fn nodes(&self) -> Vec<Node> {
        let response = self
            .sender
            .send(|tx| TrackerCommand::GetNodes { response: tx })
            .await;
        response.await.unwrap_or_default()
    }

    /// Add an unverified node to the routing table.
    /// The node will be pinged before it's actually added to the routing table.
    pub async fn add_node(&self, addr: &SocketAddr) -> Result<()> {
        let response = self
            .sender
            .send(|tx| TrackerCommand::Ping {
                addr: *addr,
                response: tx,
            })
            .await
            .await
            .map_err(|_| Error::Closed)?;

        match response {
            Ok(node) => {
                let _ = self
                    .sender
                    .fire_and_forget(TrackerCommand::AddTraversalNode((node.id, node.addr)));
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    /// Returns a list of info hashes currently known to the DHT tracker.
    pub async fn info_hashes(&self) -> Vec<InfoHash> {
        self.sender
            .send(|tx| TrackerCommand::GetStorageInfoHashes { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns a list of peers currently known to the DHT tracker.
    pub async fn peers(&self) -> HashMap<InfoHash, HashSet<PeerEntry>> {
        self.sender
            .send(|tx| TrackerCommand::GetStoragePeers { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns a list of discovered peers for the given info hash known to the DHT tracker.
    pub async fn peers_for(&self, info_hash: &InfoHash) -> HashSet<PeerEntry> {
        self.sender
            .send(|tx| TrackerCommand::GetStoragePeersByInfoHash {
                info_hash: info_hash.clone(),
                response: tx,
            })
            .await
            .await
            .unwrap_or_default()
    }

    /// Try to ping the given node address.
    /// This function waits for a response from the node, so it might be recommended to wrap this fn call in a timeout.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use std::time::Duration;
    /// # use tokio::select;
    /// # use tokio::time;
    /// # use fx_torrent::dht::DhtTracker;
    ///
    /// # async fn example() {
    ///     let target_addr = ([10, 0, 0, 99], 6881).into();
    ///     let tracker = DhtTracker::builder()
    ///         .default_routing_nodes()
    ///         .build()
    ///         .await
    ///         .unwrap();
    ///
    ///     select! {
    ///         _ = time::sleep(Duration::from_secs(10)) => return,
    ///         result = tracker.ping(&target_addr) => {
    ///            match result {
    ///                Ok(node_key) => println!("Successfully pinged node: {:?}", node_key),
    ///                Err(e) => println!("Failed to ping node: {}", e),
    ///            }
    ///         }
    ///     }
    /// # }
    /// ```
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self), err(level = tracing::Level::INFO
    )))]
    pub async fn ping(&self, addr: SocketAddr) -> Result<NodeKey> {
        self.sender
            .send(|tx| TrackerCommand::Ping { addr, response: tx })
            .await
            .await
            .map_err(|_| Error::Closed)?
    }

    /// Try to find nearby nodes for the given node id.
    /// This function waits for a response from one or more nodes within the routing table.
    /// Each queried node is limited to the given timeout.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use std::time::Duration;
    /// # use fx_torrent::dht::{DhtTracker, NodeId};
    ///
    /// # async fn example {
    ///     let target_node = NodeId::new();
    ///     let tracker = DhtTracker::builder()
    ///        .default_routing_nodes()
    ///        .build()
    ///        .await.unwrap();
    ///
    ///     match tracker.find_nodes(&target_node, Duration::from_secs(10)).await {
    ///         Ok(node_key) => println!("Successfully found nodes: {:?}", node_key),
    ///         Err(e) => println!("Failed to find nodes: {}", e),
    ///     }
    /// # }
    /// ```
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn find_nodes(&self, target_id: &NodeId, timeout: Duration) -> Result<Vec<NodeKey>> {
        let nodes = self
            .sender
            .send(|tx| TrackerCommand::GoodSearchNodes { response: tx })
            .await
            .await?;

        let futures = nodes.iter().map(|node| async {
            let response = self
                .sender
                .send(|tx| TrackerCommand::FindNode {
                    node: *node,
                    target_id: *target_id,
                    response: tx,
                })
                .await;

            select! {
                _ = time::sleep(timeout) => Err(Error::Timeout),
                result = response => result,
            }
        });

        Ok(futures::future::join_all(futures)
            .await
            .into_iter()
            .flat_map(|result| result.ok())
            .concat())
    }

    /// Returns the peer addresses for the given torrent info hash from a specific node within the network.
    /// Each queried node is limited to the given timeout.
    ///
    /// Use `n_depth` to determine the depth of the search within the network.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn get_peers_from(
        &self,
        info_hash: &InfoHash,
        node: &NodeKey,
        n_depth: usize,
        timeout: Duration,
    ) -> Result<Vec<SocketAddr>> {
        let mut peers = self
            .sender
            .send(|tx| TrackerCommand::LookupPeers {
                info_hash: info_hash.clone(),
                response: tx,
            })
            .await
            .await
            .unwrap_or_default();
        let mut found_peers = self
            .internal_get_peers(info_hash, node, n_depth, timeout)
            .await?;
        peers.append(&mut found_peers);
        Ok(peers.into_iter().unique().collect())
    }

    /// Returns the peer addresses for the given torrent info hash within the network.
    /// This function waits for a response from one oe more nodes within the routing table.
    /// Each queried node is limited to the given timeout.
    ///
    /// Use `n_depth` to determine the depth of the search within the network.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn get_peers(
        &self,
        info_hash: &InfoHash,
        n_depth: usize,
        timeout: Duration,
    ) -> Result<Vec<SocketAddr>> {
        let nodes = self
            .sender
            .send(|tx| TrackerCommand::GoodSearchNodes { response: tx })
            .await
            .await?;
        let mut peers = self
            .sender
            .send(|tx| TrackerCommand::LookupPeers {
                info_hash: info_hash.clone(),
                response: tx,
            })
            .await
            .await
            .unwrap_or_default();

        let futures = nodes.iter().map(|node| async {
            self.internal_get_peers(info_hash, node, n_depth, timeout)
                .await
        });

        let mut found_peers = futures::future::join_all(futures)
            .await
            .into_iter()
            .flat_map(|result| result.ok())
            .concat();
        peers.append(&mut found_peers);
        Ok(peers.into_iter().unique().collect())
    }

    /// Scrape the downloaders and seeders for the given info hash.
    /// Each queried node is limited to the given timeout.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn scrape_peers(
        &self,
        info_hash: &InfoHash,
        timeout: Duration,
    ) -> Result<ScrapeResult> {
        let nodes = self
            .sender
            .send(|tx| TrackerCommand::GoodSearchNodes { response: tx })
            .await
            .await?;

        let futures = nodes.iter().map(|node| async {
            let response = self
                .sender
                .send(|tx| TrackerCommand::GetPeers {
                    node: *node,
                    info_hash: info_hash.clone(),
                    scrape: true,
                    response: tx,
                })
                .await;

            select! {
                _ = time::sleep(timeout) => Err(Error::Timeout),
                result = response => result,
            }
        });

        let mut scrape_result = ScrapeResult::default();
        for result in futures::future::join_all(futures)
            .await
            .into_iter()
            .filter_map(|e| e.ok())
        {
            scrape_result.downloaders += result.downloaders;
            scrape_result.seeders += result.seeders;
        }

        Ok(scrape_result)
    }

    /// Announce the given peer to the DHT network.
    ///
    /// As defined in BEP33, the `announce_peer` supports indicating if the peer is a seeder.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn announce_peer(
        &self,
        info_hash: &InfoHash,
        peer_port: u16,
        is_seed: bool,
    ) -> Result<()> {
        self.sender
            .send(|tx| TrackerCommand::AnnouncePeer {
                info_hash: info_hash.clone(),
                peer_port,
                is_seed,
                node: None,
                response: tx,
            })
            .await
            .await
    }

    /// Announce the given peer to a specific node within the network.
    ///
    /// As defined in BEP33, the `announce_peer` supports indicating if the peer is a seeder.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self), err(level = tracing::Level::INFO
    )))]
    pub async fn announce_peer_to(
        &self,
        info_hash: &InfoHash,
        peer_port: u16,
        is_seed: bool,
        node: &NodeKey,
    ) -> Result<()> {
        self.sender
            .send(|tx| TrackerCommand::AnnouncePeer {
                info_hash: info_hash.clone(),
                peer_port,
                is_seed,
                node: Some(*node),
                response: tx,
            })
            .await
            .await
    }

    /// Returns a sample of available info hashes from the given node.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self), err(level = tracing::Level::INFO
    )))]
    pub async fn scrape_info_hashes_from(
        &self,
        target: &NodeId,
        node: &NodeKey,
    ) -> Result<Vec<InfoHash>> {
        self.sender
            .send(|tx| TrackerCommand::ScrapeInfoHashes {
                target: *target,
                node: *node,
                response: tx,
            })
            .await
            .await
    }

    /// Returns the available info hashes from the DHT network.
    /// Each queried node is limited to the given timeout.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self), err(level = tracing::Level::INFO
    )))]
    pub async fn scrape_info_hashes(
        &self,
        target: &NodeId,
        timeout: Duration,
    ) -> Result<Vec<InfoHash>> {
        let nodes = self
            .sender
            .send(|tx| TrackerCommand::GoodSearchNodes { response: tx })
            .await
            .await?;

        let futures = nodes.iter().map(|node| async {
            let response = self
                .sender
                .send(|tx| TrackerCommand::ScrapeInfoHashes {
                    target: *target,
                    node: *node,
                    response: tx,
                })
                .await;

            select! {
                _ = time::sleep(timeout) => Err(Error::Timeout),
                result = response => result,
            }
        });

        Ok(futures::future::join_all(futures)
            .await
            .into_iter()
            .flat_map(|result| result.ok())
            .concat())
    }

    /// Put an immutable item within the DHT network.
    /// Each queried node is limited to the given timeout.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn put<V>(&self, value: &V, timeout: Duration) -> Result<()>
    where
        V: Serialize,
    {
        let nodes = self
            .sender
            .send(|tx| TrackerCommand::GoodSearchNodes { response: tx })
            .await
            .await?;
        let bytes = bencode::to_bytes(value)?;
        let value = bencode::from_bytes::<Value>(bytes.as_slice())?;

        let futures = nodes.iter().map(|node| async {
            let response = self
                .sender
                .send(|tx| TrackerCommand::Put {
                    node: *node,
                    value: value.clone(),
                    sequence_nr: None,
                    signature: None,
                    public_key: None,
                    salt: None,
                    response: tx,
                })
                .await;

            select! {
                _ = time::sleep(timeout) => Err(Error::Timeout),
                result = response => result,
            }
        });

        let _ = futures::future::join_all(futures).await;
        Ok(())
    }

    /// Put a mutable item within the DHT network.
    /// Each queried node is limited to the given timeout.
    ///
    /// Returns the [PublicKey] to use for item validation.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn put_mutable<V>(
        &self,
        value: &V,
        timeout: Duration,
        sequence_nr: Option<u64>,
        salt: Option<Vec<u8>>,
        secret_key: &SecretKey,
    ) -> Result<PublicKey>
    where
        V: Serialize,
    {
        let nodes = self
            .sender
            .send(|tx| TrackerCommand::GoodSearchNodes { response: tx })
            .await
            .await?;
        let bytes = bencode::to_bytes(value)?;
        let value = bencode::from_bytes::<Value>(bytes.as_slice())?;
        let (signature, public_key) = self
            .sender
            .send(|tx| TrackerCommand::SignValue {
                value: value.clone(),
                sequence_nr: sequence_nr.unwrap_or(1),
                salt: salt.clone(),
                secret_key: secret_key.clone(),
                response: tx,
            })
            .await
            .await?;

        let futures = nodes.iter().map(|node| async {
            let response = self
                .sender
                .send(|tx| TrackerCommand::Put {
                    node: *node,
                    value: value.clone(),
                    sequence_nr: sequence_nr.clone(),
                    signature: Some(signature.clone()),
                    public_key: Some(public_key.clone()),
                    salt: salt.clone(),
                    response: tx,
                })
                .await;

            select! {
                _ = time::sleep(timeout) => Err(Error::Timeout),
                result = response => result,
            }
        });

        let _ = futures::future::join_all(futures).await;
        Ok(public_key)
    }

    /// Put an immutable item to the given node within the DHT network.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn put_to<V>(&self, value: &V, node: &NodeKey) -> Result<()>
    where
        V: Serialize,
    {
        let bytes = bencode::to_bytes(value)?;
        let value = bencode::from_bytes::<Value>(bytes.as_slice())?;
        self.sender
            .send(|tx| TrackerCommand::Put {
                node: *node,
                value,
                sequence_nr: None,
                signature: None,
                public_key: None,
                salt: None,
                response: tx,
            })
            .await
            .await
    }

    /// Get an **immutable** item from the DHT network.
    /// Each queried node is limited to the given timeout.
    ///
    /// Use `n_depth` to determine the depth of the search within the network.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn get<V>(
        &self,
        hash: Sha1Hash,
        timeout: Duration,
        n_depth: usize,
    ) -> Result<Option<V>>
    where
        V: DeserializeOwned,
    {
        let nodes = self
            .sender
            .send(|tx| TrackerCommand::GoodSearchNodes { response: tx })
            .await
            .await?;

        let mut item_stream = futures::stream::iter(nodes)
            .map(|node| async move {
                self.internal_get_item(&hash, None, None, None, &node, n_depth, timeout)
                    .await
            })
            .buffer_unordered(5);

        while let Some(item) = item_stream.next().await {
            match item {
                Ok(Some(item)) => {
                    let bytes = bencode::to_bytes(&item)?;
                    return Ok(Some(bencode::from_bytes::<V>(bytes.as_slice())?));
                }
                Err(e) => {
                    trace!("{} failed to get item, {}", self, e);
                }
                _ => {}
            }
        }

        Ok(None)
    }

    /// Get a **mutable** item from the DHT network.
    /// Each queried node is limited to the given timeout.
    ///
    /// Use `n_depth` to determine the depth of the search within the network.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn get_mutable<V>(
        &self,
        public_key: &PublicKey,
        salt: Option<Vec<u8>>,
        sequence_nr: Option<u64>,
        timeout: Duration,
        n_depth: usize,
    ) -> Result<Option<V>>
    where
        V: DeserializeOwned,
    {
        let nodes = self
            .sender
            .send(|tx| TrackerCommand::GoodSearchNodes { response: tx })
            .await
            .await?;
        let hash: Sha1Hash =
            generate_mutable_item_key(public_key, salt.as_ref().map(|e| e.as_ref()))?;

        let mut item_stream = futures::stream::iter(nodes)
            .map(|node| {
                let fn_sequence_nr = sequence_nr.as_ref();
                let fn_salt = salt.as_ref().map(|e| e.as_ref());
                async move {
                    self.internal_get_item(
                        &hash,
                        fn_sequence_nr,
                        Some(public_key),
                        fn_salt,
                        &node,
                        n_depth,
                        timeout,
                    )
                    .await
                }
            })
            .buffer_unordered(5);

        while let Some(item) = item_stream.next().await {
            match item {
                Ok(Some(item)) => {
                    let bytes = bencode::to_bytes(&item)?;
                    return Ok(Some(bencode::from_bytes::<V>(bytes.as_slice())?));
                }
                Err(e) => {
                    trace!("{} failed to get item, {}", self, e);
                }
                _ => {}
            }
        }

        Ok(None)
    }

    /// Get an immutable item from the given node within the DHT network.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, err(level = tracing::Level::INFO))
    )]
    pub async fn get_from<V>(&self, hash: Sha1Hash, node: &NodeKey) -> Result<Option<V>>
    where
        V: DeserializeOwned,
    {
        self.sender
            .send(|tx| TrackerCommand::Get {
                node: *node,
                hash,
                sequence_nr: None,
                public_key: None,
                salt: None,
                response: tx,
            })
            .await
            .await
            .map(|e: GetResult| e.value)
            .and_then(|e| {
                if let Some(value) = e {
                    let bytes = bencode::to_bytes(&value)?;
                    let item = bencode::from_bytes::<V>(bytes.as_slice())?;
                    return Ok(Some(item));
                }
                Ok(None)
            })
    }

    /// Returns `true` if the DHT tracker is closed and no longer accepts any operations.
    pub fn is_closed(&self) -> bool {
        self.cancellation_token.is_cancelled() || self.sender.is_closed()
    }

    /// Close/stop the DHT node.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub fn close(&self) {
        self.cancellation_token.cancel();
    }

    /// Retrieve peers starting from `node` going `depth_left` hops deep.
    async fn internal_get_peers(
        &self,
        info_hash: &InfoHash,
        node: &NodeKey,
        depth_left: usize,
        timeout: Duration,
    ) -> Result<Vec<SocketAddr>> {
        const MAX_IN_FLIGHT: usize = 5;
        let result = select! {
            _ = time::sleep(timeout) => return Err(Error::Timeout),
            result = self.do_get_peers(info_hash, node, false) => result?,
        };
        let mut peers: HashSet<SocketAddr> = HashSet::from_iter(result.peers);

        if depth_left == 0 || result.nodes.is_empty() {
            return Ok(peers.into_iter().collect());
        }

        let result = futures::stream::iter(result.nodes.into_iter())
            .map(|node| async move {
                let ping: Result<NodeKey> = self.ping(node.addr).await;
                if ping.is_err() {
                    return vec![];
                }

                let get_peers_result = select! {
                    _ = time::sleep(timeout) => Err(Error::Timeout),
                    result = self.do_get_peers(info_hash, &node, false) => result,
                };
                match get_peers_result {
                    Err(_) => vec![],
                    Ok(result) => {
                        let mut peers = result.peers;
                        if depth_left == 0 {
                            return peers;
                        }

                        let futures = result
                            .nodes
                            .iter()
                            .map(|node| async {
                                self.internal_get_peers(
                                    info_hash,
                                    node,
                                    depth_left.saturating_sub(1),
                                    timeout,
                                )
                                .await
                            })
                            .collect::<Vec<_>>();
                        let mut result = futures::future::join_all(futures)
                            .await
                            .into_iter()
                            .filter_map(|e| e.ok())
                            .concat();
                        peers.append(&mut result);

                        peers
                    }
                }
            })
            .buffer_unordered(MAX_IN_FLIGHT)
            .collect::<Vec<_>>()
            .await
            .concat();

        for peer in result {
            peers.insert(peer);
        }
        if peers.is_empty() {
            return Ok(vec![]);
        }

        debug!(
            "{} discovered a total of {} peers for {} from {:?}",
            self,
            peers.len(),
            info_hash,
            node.addr
        );
        Ok(peers.into_iter().collect())
    }

    /// Retrieve the peers from the given node for the [InfoHash].
    async fn do_get_peers(
        &self,
        info_hash: &InfoHash,
        node: &NodeKey,
        scrape: bool,
    ) -> Result<GetPeersResult> {
        self.sender
            .send(|tx| TrackerCommand::GetPeers {
                node: *node,
                info_hash: info_hash.clone(),
                scrape,
                response: tx,
            })
            .await
            .await
    }

    /// Try to retrieve the immutable item for the given [Sha1Hash] starting from the `node`.
    /// It goes `depth_left` level deep from the given node, trying to retrieve the information of the item.
    async fn internal_get_item(
        &self,
        hash: &Sha1Hash,
        sequence_nr: Option<&u64>,
        public_key: Option<&PublicKey>,
        salt: Option<&[u8]>,
        node: &NodeKey,
        depth_left: usize,
        timeout: Duration,
    ) -> Result<Option<Value>> {
        const MAX_IN_FLIGHT: usize = 5;
        let result = select! {
            _ = time::sleep(timeout) => Err(Error::Timeout),
            result = self.do_get_item(
                hash.clone(),
                sequence_nr.as_ref().map(|e| **e),
                public_key.map(|e| e.clone()),
                salt.map(|e| e.to_vec()),
                node,
            ) => result,
        }?;
        if let Some(value) = result.value {
            return Ok(Some(value));
        }

        if depth_left == 0 || result.nodes.is_empty() {
            return Ok(None);
        }

        let mut item_stream = futures::stream::iter(result.nodes)
            .map(|node| async move {
                let ping: Result<NodeKey> = self.ping(node.addr).await;
                if ping.is_err() {
                    return None;
                }

                self.internal_get_item(
                    hash,
                    sequence_nr,
                    public_key,
                    salt,
                    &node,
                    depth_left.saturating_sub(1),
                    timeout,
                )
                .await
                .ok()
                .flatten()
            })
            .buffer_unordered(MAX_IN_FLIGHT);

        while let Some(item) = item_stream.next().await {
            if item.is_some() {
                return Ok(item);
            }
        }

        Ok(None)
    }

    /// Retrieve the immutable item from the given node for [Sha1Hash].
    async fn do_get_item(
        &self,
        hash: Sha1Hash,
        sequence_nr: Option<u64>,
        public_key: Option<PublicKey>,
        salt: Option<Vec<u8>>,
        node: &NodeKey,
    ) -> Result<GetResult> {
        self.sender
            .send(|tx| TrackerCommand::Get {
                node: *node,
                hash,
                sequence_nr,
                public_key,
                salt,
                response: tx,
            })
            .await
            .await
    }

    /// Create a new UDP socket.
    pub(crate) async fn bind_socket() -> Result<UdpSocket> {
        match Self::bind_dual_stack().await {
            Ok(socket) => Ok(socket),
            Err(e) => {
                debug!("DHT node failed to bind dual stack socket, {}", e);
                Ok(UdpSocket::bind("0.0.0.0:0").await?)
            }
        }
    }

    /// Try to bind a dual stack IPv4 & IPv6 udp socket.
    async fn bind_dual_stack() -> Result<UdpSocket> {
        // TODO: reimplement dual stack support
        Err(Error::Io(io::Error::new(
            io::ErrorKind::Other,
            "Dual stack support is currently not implemented",
        )))
    }
}

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

impl Clone for DhtTracker {
    fn clone(&self) -> Self {
        Self {
            addr: self.addr.clone(),
            mode: self.mode,
            metrics: self.metrics.clone(),
            sender: self.sender.clone(),
            callbacks: self.callbacks.clone(),
            cancellation_token: self.cancellation_token.clone(),
        }
    }
}

#[derive(Debug, Default)]
pub struct DhtTrackerBuilder {
    id: Option<NodeId>,
    mode: Option<Mode>,
    public_ip: Option<IpAddr>,
    routing_nodes: HashSet<SocketAddr>,
    routing_node_urls: Vec<String>,
    max_torrents: Option<usize>,
    enable_indexing: Option<bool>,
    indexing_interval: Option<Duration>,
    verifier: Option<ItemSignature>,
}

impl DhtTrackerBuilder {
    /// Set the ID of the node server.
    pub fn node_id(&mut self, id: NodeId) -> &mut Self {
        self.id = Some(id);
        self
    }

    /// Set the public ip address of the dht tracker.
    pub fn public_ip(&mut self, ip: IpAddr) -> &mut Self {
        self.public_ip = Some(ip);
        self
    }

    /// Set the mode of the DHT node.
    pub fn mode(&mut self, mode: Mode) -> &mut Self {
        self.mode = Some(mode);
        self
    }

    /// Set if the default routing nodes should be enabled.
    pub fn enable_default_routing_nodes(&mut self, enabled: bool) -> &mut Self {
        if enabled {
            self.default_routing_nodes();
        } else {
            let default_routing_nodes = DEFAULT_ROUTING_NODE_SERVERS();
            self.routing_node_urls
                .retain(|e| !default_routing_nodes.contains(&e.as_str()));
        }
        self
    }

    /// Add the default routing nodes used for searching new nodes.
    pub fn default_routing_nodes(&mut self) -> &mut Self {
        self.routing_node_urls.extend(
            DEFAULT_ROUTING_NODE_SERVERS()
                .into_iter()
                .map(|e| e.to_string()),
        );
        self
    }

    /// Add the given address to the routing nodes used for searching new nodes.
    pub fn routing_node(&mut self, addr: SocketAddr) -> &mut Self {
        self.routing_nodes.insert(addr);
        self
    }

    /// Set the routing nodes to use for searching new nodes.
    /// This replaces any already existing configured routing nodes.
    pub fn routing_nodes(&mut self, nodes: Vec<SocketAddr>) -> &mut Self {
        self.routing_nodes = HashSet::from_iter(nodes);
        self
    }

    /// Add the given node url to use for searching new nodes.
    pub fn routing_node_url<S: AsRef<str>>(&mut self, url: S) -> &mut Self {
        self.routing_node_urls.push(url.as_ref().to_string());
        self
    }

    /// Set the maximum number of torrents to track within the DHT network.
    pub fn max_torrents(&mut self, max_torrents: usize) -> &mut Self {
        self.max_torrents = Some(max_torrents);
        self
    }

    /// Set if the DHT tracker should enable indexing of info hashes.
    pub fn enable_indexing(&mut self, enable: bool) -> &mut Self {
        self.enable_indexing = Some(enable);
        self
    }

    /// Set the interval at which the DHT tracker should index info hashes.
    pub fn indexing_interval(&mut self, interval: Duration) -> &mut Self {
        self.indexing_interval = Some(interval);
        self
    }

    /// Set the item verifier to use for validating mutable items stored in the DHT network.
    pub fn item_verifier(&mut self, verifier: ItemSignature) -> &mut Self {
        self.verifier = Some(verifier);
        self
    }

    /// Try to create a new DHT node from this builder.
    ///
    /// # Panics
    ///
    /// This method panics if no [ItemSignature] has been set and no crypto provider features are enabled.
    /// For more info, see [ItemSignature::new].
    pub async fn build(&mut self) -> Result<DhtTracker> {
        let defaults = Config::default();
        let id = self.id.take().unwrap_or_else(|| {
            self.public_ip
                .take()
                .map(|e| NodeId::from_ip(&e))
                .unwrap_or(defaults.id)
        });
        let mode = self.mode.take().unwrap_or(defaults.mode);
        let max_torrents = self.max_torrents.unwrap_or(defaults.max_torrents);
        let info_hash_indexing_enabled = self
            .enable_indexing
            .unwrap_or(defaults.info_hash_indexing_enabled);
        let info_hash_indexing_interval = self
            .indexing_interval
            .unwrap_or(defaults.info_hash_indexing_interval);
        let item_signature = self.verifier.take();
        let mut routing_nodes = std::mem::take(&mut self.routing_nodes);

        for node_url in self.routing_node_urls.drain(..).filter_map(Self::host) {
            match lookup_host(node_url.as_str()).await {
                Ok(addrs) => {
                    routing_nodes.extend(addrs);
                }
                Err(e) => trace!("DHT router node failed to resolve \"{}\", {}", node_url, e),
            }
        }

        DhtTracker::new(Config {
            id,
            mode,
            max_torrents,
            info_hash_indexing_enabled,
            info_hash_indexing_interval,
            item_signature,
            routing_nodes: routing_nodes.into_iter().collect::<Vec<_>>(),
        })
        .await
    }

    fn host<S: AsRef<str>>(url: S) -> Option<String> {
        let url = Url::parse(url.as_ref()).ok()?;
        if let Some(host) = url.host_str() {
            let port = url.port().unwrap_or(80);
            return Some(format!("{}:{}", host, port));
        }

        Some(url.as_ref().to_string())
    }
}

/// The information returned by a `scrape` operation within the DHT network.
#[derive(Debug, Default)]
pub struct ScrapeResult {
    pub downloaders: usize,
    pub seeders: usize,
}

/// The information returned by a `get_peers` operation within the DHT network.
#[derive(Debug)]
pub(crate) struct GetPeersResult {
    pub peers: Vec<SocketAddr>,
    pub nodes: Vec<NodeKey>,
    pub downloaders: usize,
    pub seeders: usize,
}

/// The information returned by a `get` operation within the DHT network.
#[derive(Debug)]
pub(crate) struct GetResult {
    pub value: Option<Value>,
    pub nodes: Vec<NodeKey>,
}

/// The internal DHT tracker commands executed on the main loop of the [TrackerContext].
pub(crate) enum TrackerCommand {
    Id {
        response: Reply<NodeId>,
    },
    Ping {
        addr: SocketAddr,
        response: Reply<Result<NodeKey>>,
    },
    /// Find the target node closest to the given node.
    FindNode {
        node: NodeKey,
        target_id: NodeId,
        response: Reply<Result<Vec<NodeKey>>>,
    },
    /// Find peers within the DHT storage for the given torrent info hash.
    LookupPeers {
        info_hash: InfoHash,
        response: Reply<Vec<SocketAddr>>,
    },
    /// Find peer addresses for the given torrent info hash within the network.
    GetPeers {
        node: NodeKey,
        info_hash: InfoHash,
        scrape: bool,
        response: Reply<Result<GetPeersResult>>,
    },
    /// Announce the given peer to the DHT network.
    AnnouncePeer {
        info_hash: InfoHash,
        peer_port: u16,
        is_seed: bool,
        node: Option<NodeKey>,
        response: Reply<Result<()>>,
    },
    /// Scrape the info hashes from the given node.
    ScrapeInfoHashes {
        target: NodeId,
        node: NodeKey,
        response: Reply<Result<Vec<InfoHash>>>,
    },
    /// Put an item to the DHT node.
    Put {
        node: NodeKey,
        value: Value,
        sequence_nr: Option<u64>,
        signature: Option<SignatureBytes>,
        public_key: Option<PublicKey>,
        salt: Option<Vec<u8>>,
        response: Reply<Result<()>>,
    },
    /// Sign the given value
    SignValue {
        value: Value,
        sequence_nr: u64,
        salt: Option<Vec<u8>>,
        secret_key: SecretKey,
        response: Reply<Result<(SignatureBytes, PublicKey)>>,
    },
    /// Get an item from the DHT node.
    Get {
        node: NodeKey,
        hash: Sha1Hash,
        sequence_nr: Option<u64>,
        public_key: Option<PublicKey>,
        salt: Option<Vec<u8>>,
        response: Reply<Result<GetResult>>,
    },
    TotalNodes {
        response: Reply<usize>,
    },
    /// Returns the node with the given key from the routing table, if found.
    GetNode {
        node: NodeKey,
        response: Reply<Option<Node>>,
    },
    /// Returns the node with the given id from the routing table, if found.
    GetNodeById {
        id: NodeId,
        response: Reply<Option<Node>>,
    },
    /// Returns all nodes within the routing table.
    GetNodes {
        response: Reply<Vec<Node>>,
    },
    /// Returns the info hashes stored within the [DhtStorage].
    GetStorageInfoHashes {
        response: Reply<Vec<InfoHash>>,
    },
    /// Returns the peers stored within the [DhtStorage].
    GetStoragePeers {
        response: Reply<HashMap<InfoHash, HashSet<PeerEntry>>>,
    },
    /// Returns the peers stored within the [DhtStorage] for the given info hash.
    GetStoragePeersByInfoHash {
        info_hash: InfoHash,
        response: Reply<HashSet<PeerEntry>>,
    },
    /// Returns the node keys of "good" nodes which can be used in search queries.
    GoodSearchNodes {
        response: Reply<Vec<NodeKey>>,
    },
    AddTraversalNode((NodeId, SocketAddr)),
    UpdateExternalIp(IpAddr),
}

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

/// The internal tracker context of the DHT node.
#[derive(Debug, Display)]
#[display("DHT node [{}]", socket_addr.port())]
pub(crate) struct TrackerContext {
    /// The current transaction ID of the node server
    transaction_id: u32,
    /// The underlying socket used by the server
    socket: Arc<UdpSocket>,
    /// The address on which the server is listening
    pub(crate) socket_addr: SocketAddr,
    /// The routing table of the node server
    pub(crate) routing_table: RoutingTable,
    /// The handler for processing DHT network data.
    handler: DhtNodeHandler,
    /// The currently pending requests of the server
    pending_requests: HashMap<TransactionKey, PendingRequest>,
    /// The timeout while trying to send packages to a target address
    send_timeout: Duration,
    /// Indicates if the DHT tracker should enable indexing of info hashes.
    info_hash_indexing_enabled: bool,
    /// The verifier to use for validating mutable items stored in the DHT network.
    item_signature: ItemSignature,
    /// The tracker metrics of the DHT network
    pub(crate) metrics: DhtMetrics,
    /// The channel receiver for incoming messages
    receiver: UnboundedReceiver<ReaderMessage>,
    /// The callback of the tracker
    pub(crate) callbacks: MultiThreadedCallback<DhtEvent>,
    /// The cancellation token of the server
    pub(crate) cancellation_token: CancellationToken,
}

impl TrackerContext {
    pub(crate) fn new(
        id: NodeId,
        socket: Arc<UdpSocket>,
        socket_addr: SocketAddr,
        mode: Mode,
        info_hash_indexing_enabled: bool,
        item_verifier: ItemSignature,
        max_torrents: usize,
    ) -> Self {
        let (sender, receiver) = unbounded_channel();
        let cancellation_token = CancellationToken::new();
        let metrics = DhtMetrics::new();
        let callbacks = MultiThreadedCallback::new();
        let mode = match mode {
            Mode::Client => DhtNodeHandler::client(),
            Mode::Server => DhtNodeHandler::server(ServerNode::new(
                metrics.clone(),
                socket_addr.clone(),
                callbacks.clone(),
                max_torrents,
            )),
        };

        // start the reader in a separate task
        let reader_socket = socket.clone();
        let reader_cancellation_token = cancellation_token.clone();
        spawn!("NodeReader::run", async move {
            let reader = NodeReader {
                socket: reader_socket,
                addr_port: socket_addr.port(),
                sender,
                cancellation_token: reader_cancellation_token,
            };
            reader.run().await;
        });

        Self {
            transaction_id: Default::default(),
            socket,
            socket_addr,
            routing_table: RoutingTable::new(id, DEFAULT_BUCKET_SIZE),
            handler: mode,
            pending_requests: Default::default(),
            send_timeout: SEND_PACKAGE_TIMEOUT,
            info_hash_indexing_enabled,
            item_signature: item_verifier,
            metrics,
            receiver,
            callbacks,
            cancellation_token,
        }
    }

    /// Run the task loop of the context.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub(crate) async fn run(
        &mut self,
        index_info_hashes_interval: Duration,
        mut observer: Observer,
        mut traversal: TraversalAlgorithm,
        mut command_receiver: ChannelReceiver<TrackerCommand>,
    ) {
        let mut bootstrap_interval = interval(BOOTSTRAP_INTERVAL);
        let mut refresh_interval = interval(REFRESH_INTERVAL);
        let mut index_info_hashes_interval = interval(index_info_hashes_interval);
        let mut tick_interval = interval(TICK_INTERVAL);

        debug!("{} started", self);
        loop {
            select! {
                _ = self.cancellation_token.cancelled() => break,
                Some(message) = self.receiver.recv() => self.on_message_received(message, &mut observer, &mut traversal).await,
                command = command_receiver.recv() => match command {
                    Some(command) => self.handle_command(command, &mut traversal).await,
                    None => break,
                },
                _ = refresh_interval.tick() => self.refresh_routing_table().await,
                _ = bootstrap_interval.tick() => self.bootstrap(&mut traversal).await,
                _ = index_info_hashes_interval.tick(), if self.info_hash_indexing_enabled => self.index_info_hashes().await,
                _ = tick_interval.tick() => self.tick().await,
            }
        }
        debug!("{} main loop ended", self);
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn bootstrap(&mut self, traversal: &mut TraversalAlgorithm) {
        traversal.run(self.routing_table.id, self).await;
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_message_received(
        &mut self,
        message: ReaderMessage,
        observer: &mut Observer,
        traversal: &mut TraversalAlgorithm,
    ) {
        match message {
            ReaderMessage::Message {
                message,
                message_len,
                addr,
            } => {
                self.metrics.bytes_in.inc_by(message_len as u64);
                observer.observe(addr, message.ip.as_ref(), &self).await;
                if let Err(e) = self.on_incoming_message(message, addr, traversal).await {
                    debug!(
                        "{} failed to process incoming message from {}, {}",
                        self, addr, e
                    );
                    self.metrics.errors.inc();
                }
            }
            ReaderMessage::Error {
                error,
                payload_len,
                addr,
            } => {
                debug!(
                    "{} failed to read incoming message (len {}) from {}, {}",
                    self, payload_len, addr, error
                );
                self.metrics.bytes_in.inc_by(payload_len as u64);
                self.metrics.errors.inc();
            }
        }
    }

    /// Try to process an incoming DHT message from the given node address.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all, err))]
    async fn on_incoming_message(
        &mut self,
        message: Message,
        addr: SocketAddr,
        traversal: &mut TraversalAlgorithm,
    ) -> Result<()> {
        trace!(
            "{} received message (transaction {}) from {}, {:?}",
            self,
            message
                .transaction_id_as_str()
                .map(|e| e.to_string())
                .unwrap_or_else(|| message.transaction_id_as_u32().to_string()),
            addr,
            message
        );
        let node_id = message.id().cloned();
        let transaction_id = message.transaction_id;
        let read_only = message.read_only;
        let key = TransactionKey {
            id: transaction_id.clone(),
            addr,
        };

        // check the type of the message
        match message.payload {
            MessagePayload::Query(query) => {
                self.on_incoming_query(transaction_id, query, &addr).await?
            }
            MessagePayload::Response(response_payload) => {
                if let Some(pending_request) = self.pending_requests.remove(&key) {
                    let response = response_payload.parse(pending_request.query_name.as_str())?;
                    debug!(
                        "{} received response \"{}\" from {} for {}",
                        self,
                        response.name(),
                        addr,
                        key
                    );

                    match response {
                        ResponseMessage::Ping { response } => {
                            self.on_ping_response(&key, &addr, pending_request, response)
                                .await;
                        }
                        ResponseMessage::FindNode { response } => {
                            self.on_find_node_response(&key, &addr, pending_request, response)
                                .await;
                        }
                        ResponseMessage::GetPeers { response } => {
                            self.on_get_peers_response(
                                &key,
                                &addr,
                                pending_request,
                                response,
                                traversal,
                            )
                            .await;
                        }
                        ResponseMessage::Announce { response } => {
                            self.on_announce_response(&key, &addr, pending_request, response)
                                .await;
                        }
                        ResponseMessage::SampleInfoHashes { response } => {
                            self.on_sample_info_hashes_response(
                                &key,
                                &addr,
                                pending_request,
                                response,
                                traversal,
                            )
                            .await;
                        }
                        ResponseMessage::Put { response } => {
                            self.on_put_response(&key, &addr, pending_request, response)
                                .await;
                        }
                        ResponseMessage::Get { response } => {
                            self.on_get_response(&key, &addr, pending_request, response, traversal)
                                .await;
                        }
                    }
                } else {
                    debug!(
                        "{} received response for unknown request, invalid transaction {}",
                        self, key
                    );
                    self.metrics.errors.inc();
                }
            }
            MessagePayload::Error { error } => {
                self.on_error_response(&key, &addr, error).await;
            }
        }

        if let Some(id) = node_id {
            // do not add read-only nodes to the routing
            // as they cannot be queried
            if !read_only {
                self.update_node(id, addr, traversal).await;
            }
        }
        Ok(())
    }

    /// Handle an incoming query message.
    async fn on_incoming_query(
        &mut self,
        transaction_id: TransactionId,
        query: QueryMessage,
        addr: &SocketAddr,
    ) -> Result<()> {
        let result = self
            .handler
            .on_incoming_query(query, &addr, &self.routing_table)
            .await?;

        match result {
            QueryResult::Response(message) => {
                self.send_response(transaction_id, message, addr).await
            }
            QueryResult::Error(message) => self.send_error(transaction_id, message, addr).await,
        }
    }

    /// Process the received announce_peer response.
    ///
    /// # Arguments
    ///
    /// * `key` - The transaction key of the query.
    /// * `addr`- The source address of the node.
    /// * `pending_request` - The pending request of the query.
    /// * `response` - The announce peer response of the node.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    async fn on_announce_response(
        &self,
        key: &TransactionKey,
        addr: &SocketAddr,
        pending_request: PendingRequest,
        response: AnnouncePeerResponse,
    ) {
        if !response.id.verify_id(&addr.ip()) {
            debug!("{} detected spoofed announce_peer from {}", self, key);
            Self::resolve_as_err(pending_request.request_type, Error::InvalidNodeId);
            return;
        }

        self.node_query_result(&addr, true).await;
        match pending_request.request_type {
            Some(PendingRequestType::AnnouncePeer(tx)) => {
                let _ = tx.send(Ok(()));
            }
            Some(_) => Self::resolve_as_err(
                pending_request.request_type,
                Error::InvalidMessage(format!(
                    "expected {} response, got announce_peer instead",
                    pending_request.query_name
                )),
            ),
            _ => {}
        }
    }

    /// Process the given sample info hashes response.
    ///
    /// # Arguments
    ///
    /// * `key` - The transaction key of the query.
    /// * `addr`- The source address of the node.
    /// * `pending_request` - The pending request of the query.
    /// * `response` - The received sample info hashes response.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_sample_info_hashes_response(
        &mut self,
        key: &TransactionKey,
        addr: &SocketAddr,
        pending_request: PendingRequest,
        response: SampleInfoHashesResponse,
        traversal: &mut TraversalAlgorithm,
    ) {
        if !response.id.verify_id(&addr.ip()) {
            debug!("{} detected spoofed sample_infohashes from {}", self, key);
            Self::resolve_as_err(pending_request.request_type, Error::InvalidNodeId);
            return;
        }

        // update the refresh interval for the node
        // this will allow us to index info hashes from this node in the future
        if let Some(node) = self.routing_table.find_node(&response.id) {
            node.update_indexing_interval(Duration::from_secs(response.interval as u64))
                .await;
        }

        // add the announced nodes to the traversal algorithm
        let nodes = Self::collect_nodes(&response.nodes, &response.nodes6);
        for node in nodes {
            traversal.add_node(Some(node.id), node.addr);
        }

        // add the info hashes to the peer storage
        for info_hash in &response.samples {
            self.handler.register(info_hash);
            self.callbacks
                .invoke(DhtEvent::InfoHashAdded(info_hash.clone()));
        }

        // update the metrics
        self.metrics
            .discovered_info_hashes
            .set(self.handler.torrents().count() as u64);

        match pending_request.request_type {
            Some(PendingRequestType::ScrapeInfoHashes(tx)) => {
                let _ = tx.send(Ok(response.samples));
            }
            Some(_) => Self::resolve_as_err(
                pending_request.request_type,
                Error::InvalidMessage(format!(
                    "expected {} response, got sample_infohashes instead",
                    pending_request.query_name
                )),
            ),
            _ => {}
        }
    }

    /// Process a received put response.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_put_response(
        &self,
        key: &TransactionKey,
        addr: &SocketAddr,
        pending_request: PendingRequest,
        response: PutResponse,
    ) {
        if !response.id.verify_id(&addr.ip()) {
            debug!("{} detected spoofed put from {}", self, key);
            Self::resolve_as_err(pending_request.request_type, Error::InvalidNodeId);
            return;
        }
        self.node_query_result(&addr, true).await;
        match pending_request.request_type {
            Some(PendingRequestType::Put(tx)) => {
                let _ = tx.send(Ok(()));
            }
            Some(_) => Self::resolve_as_err(
                pending_request.request_type,
                Error::InvalidMessage(format!(
                    "expected {} response, got put instead",
                    pending_request.query_name
                )),
            ),
            _ => {}
        }
    }

    /// Process a received get response.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn on_get_response(
        &mut self,
        key: &TransactionKey,
        addr: &SocketAddr,
        pending_request: PendingRequest,
        response: GetResponse,
        traversal: &mut TraversalAlgorithm,
    ) {
        if !response.id.verify_id(&addr.ip()) {
            debug!("{} detected spoofed get from {}", self, key);
            Self::resolve_as_err(pending_request.request_type, Error::InvalidNodeId);
            return;
        }
        self.node_query_result(&addr, true).await;

        // update the write token for the node
        if let Some(token) = response.token.as_ref() {
            if let Err(e) = self.update_announce_token(&response.id, token).await {
                Self::resolve_as_err(pending_request.request_type, e);
                return;
            }
        }

        // extract the mutable info from the pending request
        let (request_public_key, salt, tx) = match pending_request.request_type {
            Some(PendingRequestType::Get {
                public_key,
                salt,
                response,
            }) => (public_key, salt, response),
            Some(_) => {
                Self::resolve_as_err(
                    pending_request.request_type,
                    Error::InvalidMessage(format!(
                        "expected {} response, got get instead",
                        pending_request.query_name
                    )),
                );
                return;
            }
            _ => {
                error!("{} received get response for empty request", self);
                return;
            }
        };

        // extract response data
        let sequence_nr = response.sequence_nr;
        let public_key = match response
            .public_key
            .map(TryInto::<PublicKey>::try_into)
            .transpose()
        {
            Ok(key) => key,
            Err(e) => {
                debug!("{} failed to parse public key from {}", self, addr);
                let _ = tx.send(Err(Error::Parse(format!(
                    "failed to parse public key (len {})",
                    e.len()
                ))));
                return;
            }
        };
        let signature = response.signature;
        let value = response.value;

        // store the received value
        if let Some(value) = value.as_ref().cloned() {
            // validate that both public keys match
            if request_public_key != public_key {
                debug!("{} public keys are not matching for {}", self, addr);
                let _ = tx.send(Err(Error::InvalidMessage(
                    "public keys are not matching".to_string(),
                )));
                return;
            }

            // if the value is mutable, verify it before we store it
            if let Some(public_key) = public_key.as_ref() {
                if let Err(e) = self.verify_value(
                    &value,
                    sequence_nr.as_ref(),
                    &public_key,
                    salt.as_ref().map(AsRef::as_ref),
                    signature.as_ref().map(AsRef::as_ref),
                ) {
                    debug!("{} value validation failed for {}, {}", self, addr, e);
                    let _ = tx.send(Err(e));
                    return;
                }
            }

            let mutable_properties = match parse_mutable_item_properties(
                sequence_nr.clone(),
                public_key,
                None,
                signature.clone(),
            ) {
                Ok(properties) => properties,
                Err(e) => {
                    debug!("{} failed to parse mutable item properties, {}", self, e);
                    return;
                }
            };

            if let Err(e) = self.handler.store(value, mutable_properties) {
                if e != Error::AlreadyExists {
                    warn!("{} failed to store immutable item, {}", self, e);
                }
            }
        }

        // add the closest nodes to the traversal algorithm
        let nodes = Self::collect_nodes(&response.nodes, &response.nodes6);
        for node in nodes.iter() {
            traversal.add_node(Some(node.id), node.addr);
        }

        let _ = tx.send(Ok(GetResult { value, nodes }));
    }

    /// Process a received ping response.
    ///
    /// # Arguments
    ///
    /// * `key` - The transaction key of the query.
    /// * `addr`- The source address of the node.
    /// * `pending_request` - The pending request of the query.
    /// * `response` - The ping response of the node.
    #[cfg_attr(feature = "tracing", tracing::instrument)]
    async fn on_ping_response(
        &self,
        key: &TransactionKey,
        addr: &SocketAddr,
        pending_request: PendingRequest,
        response: PingMessage,
    ) {
        if !response.id.verify_id(&addr.ip()) {
            debug!("{} detected spoofed ping from {}", self, key);
            Self::resolve_as_err(pending_request.request_type, Error::InvalidNodeId);
            return;
        }

        self.node_query_result(&addr, true).await;
        match pending_request.request_type {
            Some(PendingRequestType::Ping(tx)) => {
                let _ = tx.send(Ok(NodeKey {
                    id: response.id,
                    addr: *addr,
                }));
            }
            Some(_) => Self::resolve_as_err(
                pending_request.request_type,
                Error::InvalidMessage(format!(
                    "expected {} response, got ping instead",
                    pending_request.query_name
                )),
            ),
            _ => {}
        }
    }

    /// Process the received find node response.
    ///
    /// # Arguments
    ///
    /// * `key` - The transaction key of the query.
    /// * `addr`- The source address of the node.
    /// * `pending_request` - The pending request of the query.
    /// * `response` - The received find node response.
    #[cfg_attr(feature = "tracing", tracing::instrument)]
    async fn on_find_node_response(
        &self,
        key: &TransactionKey,
        addr: &SocketAddr,
        pending_request: PendingRequest,
        response: FindNodeResponse,
    ) {
        if !response.id.verify_id(&addr.ip()) {
            debug!("{} detected spoofed find_node from {}", self, key);
            Self::resolve_as_err(pending_request.request_type, Error::InvalidNodeId);
            return;
        }

        self.node_query_result(&addr, true).await;
        let nodes = response
            .nodes
            .as_slice()
            .into_iter()
            .map(|e| NodeKey {
                id: e.id,
                addr: SocketAddr::from(&e.addr),
            })
            .chain(response.nodes6.as_slice().into_iter().map(|e| NodeKey {
                id: e.id,
                addr: SocketAddr::from(&e.addr),
            }))
            .collect::<Vec<_>>();

        debug!(
            "{} node {} discovered a total of {} nodes",
            self,
            addr,
            nodes.len()
        );
        match pending_request.request_type {
            Some(PendingRequestType::FindNode(tx)) => {
                let _ = tx.send(Ok(nodes));
            }
            Some(_) => Self::resolve_as_err(
                pending_request.request_type,
                Error::InvalidMessage(format!(
                    "expected {} response, got find_node instead",
                    pending_request.query_name
                )),
            ),
            _ => {}
        }
    }

    /// Process a received response message for a query.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, traversal)))]
    async fn on_get_peers_response(
        &mut self,
        key: &TransactionKey,
        addr: &SocketAddr,
        pending_request: PendingRequest,
        response: GetPeersResponse,
        traversal: &mut TraversalAlgorithm,
    ) {
        if !response.id.verify_id(&addr.ip()) {
            debug!("{} detected spoofed get_peers from {}", self, key);
            Self::resolve_as_err(pending_request.request_type, Error::InvalidNodeId);
            return;
        }

        self.node_query_result(&addr, true).await;
        if let Some(token) = response.token.as_ref() {
            if let Err(e) = self.update_announce_token(&response.id, token).await {
                Self::resolve_as_err(pending_request.request_type, e);
                return;
            }
        }

        let peers: Vec<SocketAddr> = response
            .values
            .iter()
            .map(|e| SocketAddr::from(e))
            .collect();

        let nodes = Self::collect_nodes(&response.nodes, &response.nodes6);
        for node in nodes.iter() {
            traversal.add_node(Some(node.id), node.addr);
        }

        let downloaders = response
            .downloaders
            .as_ref()
            .map(|e| e.as_bytes())
            .and_then(|e| BloomFilter::<256>::try_from(e).ok())
            .map(|e| e.len())
            .unwrap_or_default();
        let seeds = response
            .seeds
            .as_ref()
            .map(|e| e.as_bytes())
            .and_then(|e| BloomFilter::<256>::try_from(e).ok())
            .map(|e| e.len())
            .unwrap_or_default();

        match pending_request.request_type {
            Some(PendingRequestType::GetPeers {
                info_hash,
                response,
            }) => {
                for peer in &peers {
                    self.handler.update_peer(info_hash.clone(), *peer, false);
                    self.callbacks
                        .invoke(DhtEvent::PeerUpdated(info_hash.clone(), *peer));
                }

                self.metrics
                    .discovered_peers
                    .set(self.handler.peers_len() as u64);
                let _ = response.send(Ok(GetPeersResult {
                    peers,
                    nodes,
                    downloaders,
                    seeders: seeds,
                }));
            }
            Some(_) => Self::resolve_as_err(
                pending_request.request_type,
                Error::InvalidMessage(format!(
                    "expected {} response, got get_peers instead",
                    pending_request.query_name
                )),
            ),
            _ => {}
        }
    }

    /// Process a received error response message for a query.
    ///
    /// # Arguments
    ///
    /// * `key` - The transaction key of the query.
    /// * `addr` - The address of the peer that sent the error response.
    /// * `message` - The received error message.
    #[cfg_attr(feature = "tracing", tracing::instrument)]
    async fn on_error_response(
        &mut self,
        key: &TransactionKey,
        addr: &SocketAddr,
        message: ErrorMessage,
    ) {
        self.metrics.errors.inc();
        self.node_query_result(&addr, false).await;

        if let Some(pending_request) = self.pending_requests.remove(&key) {
            debug!("{} received error for {}", self, key);
            Self::resolve_as_err(pending_request.request_type, Error::from(message))
        } else {
            warn!(
                "{} received error for unknown request, invalid transaction {}",
                self, key
            );
        }
    }

    /// Process a received tracker command.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn handle_command(
        &mut self,
        command: TrackerCommand,
        traversal: &mut TraversalAlgorithm,
    ) {
        match command {
            TrackerCommand::Id { response } => {
                let id = &self.routing_table.id;
                response.send(*id);
            }
            TrackerCommand::Ping { addr, response } => {
                self.ping(&addr, response).await;
            }
            TrackerCommand::FindNode {
                node,
                target_id,
                response,
            } => match self.routing_table.find_node_by_key(&node).cloned() {
                None => response.send(Err(Error::InvalidNodeId)),
                Some(node) => {
                    self.find_node_internal(target_id, &node, Some(response.take()))
                        .await
                }
            },
            TrackerCommand::LookupPeers {
                info_hash,
                response,
            } => {
                response.send(
                    self.handler
                        .peers(&info_hash)
                        .map(|e| e.addr)
                        .collect::<Vec<_>>(),
                );
            }
            TrackerCommand::GetPeers {
                node,
                info_hash,
                scrape,
                response,
            } => {
                let node = self.find_node_or_create(&node);
                self.get_peers(info_hash, &node, false, scrape, response)
                    .await
            }
            TrackerCommand::AnnouncePeer {
                info_hash,
                peer_port,
                is_seed,
                node,
                response,
            } => match node {
                None => {
                    self.announce_peer_to_network(info_hash, peer_port, is_seed)
                        .await;
                    response.send(Ok(()));
                }
                Some(node) => match self.routing_table.find_node_by_key(&node).cloned() {
                    None => response.send(Err(Error::InvalidNodeId)),
                    Some(node) => {
                        self.announce_peer_to(info_hash, peer_port, &node, is_seed, response)
                            .await
                    }
                },
            },
            TrackerCommand::ScrapeInfoHashes {
                target,
                node,
                response,
            } => match self.routing_table.find_node_by_key(&node).cloned() {
                None => response.send(Err(Error::InvalidNodeId)),
                Some(node) => {
                    self.scrape_info_hashes(&target, &node, Some(response.take()))
                        .await
                }
            },
            TrackerCommand::Put {
                node,
                value,
                sequence_nr,
                signature,
                public_key,
                salt,
                response,
            } => match self.routing_table.find_node_by_key(&node).cloned() {
                None => response.send(Err(Error::InvalidNodeId)),
                Some(node) => {
                    self.put(
                        &node,
                        value,
                        sequence_nr,
                        signature,
                        public_key,
                        salt,
                        response,
                    )
                    .await
                }
            },
            TrackerCommand::Get {
                node,
                hash,
                sequence_nr,
                public_key,
                salt,
                response,
            } => match self.routing_table.find_node_by_key(&node).cloned() {
                None => response.send(Err(Error::InvalidNodeId)),
                Some(node) => {
                    self.get(&node, hash, sequence_nr, public_key, salt, response)
                        .await
                }
            },
            TrackerCommand::SignValue {
                value,
                sequence_nr,
                salt,
                secret_key,
                response,
            } => response.send(self.item_signature.sign(
                &value,
                &sequence_nr,
                salt.as_ref().map(|e| e.as_ref()),
                &secret_key,
            )),
            TrackerCommand::TotalNodes { response } => response.send(self.routing_table.len()),
            TrackerCommand::GetNode { node, response } => {
                match self.routing_table.find_node_by_key(&node) {
                    None => response.send(None),
                    Some(node) => response.send(Some(node.clone())),
                }
            }
            TrackerCommand::GetNodeById { id, response } => {
                response.send(self.routing_table.find_node(&id).cloned())
            }
            TrackerCommand::GetNodes { response } => {
                response.send(self.routing_table.nodes().cloned().collect::<Vec<_>>());
            }
            TrackerCommand::GetStorageInfoHashes { response } => {
                response.send(self.handler.torrents().cloned().collect());
            }
            TrackerCommand::GetStoragePeers { response } => response.send(
                self.handler
                    .torrents()
                    .map(|info_hash| {
                        (
                            info_hash.clone(),
                            self.handler.peers(&info_hash).cloned().collect(),
                        )
                    })
                    .collect::<HashMap<_, _>>(),
            ),
            TrackerCommand::GetStoragePeersByInfoHash {
                response,
                info_hash,
            } => {
                response.send(self.handler.peers(&info_hash).cloned().collect());
            }
            TrackerCommand::GoodSearchNodes { response } => {
                response.send(
                    Self::find_good_search_nodes(&self.routing_table)
                        .await
                        .map(|e| *e.key())
                        .collect(),
                );
            }
            TrackerCommand::AddTraversalNode((id, addr)) => traversal.add_node(Some(id), addr),
            TrackerCommand::UpdateExternalIp(ip) => {
                self.update_external_ip(ip).await;
                traversal.restart();
            }
        }
    }

    /// Ping the given node address.
    ///
    /// # Arguments
    ///
    /// * `addr` - the node address to ping.
    /// * `sender` - The result sender for the ping operation.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, handler)))]
    async fn ping(&mut self, addr: &SocketAddr, handler: Reply<Result<NodeKey>>) {
        self.send_query(
            QueryMessage::Ping {
                request: PingMessage {
                    id: self.routing_table.id,
                },
            },
            addr,
            Some(PendingRequestType::Ping(handler.take())),
            || async {},
        )
        .await;
    }

    /// Find the closest nodes for the given target node id.
    ///
    /// # Arguments
    ///
    /// * `target` - The target node id to retrieve the closest nodes of.
    /// * `node` - The node to which the address belongs to, if available.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, node)))]
    pub(crate) async fn find_node(
        &mut self,
        target: NodeId,
        node: &Node,
    ) -> Response<Vec<NodeKey>, Error> {
        let (tx, rx) = oneshot::channel();
        self.find_node_internal(target, node, Some(tx)).await;
        Response::from(rx)
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn find_node_internal(
        &mut self,
        target: NodeId,
        node: &Node,
        reply: Option<oneshot::Sender<Result<Vec<NodeKey>>>>,
    ) {
        self.send_query(
            QueryMessage::FindNode {
                request: FindNodeRequest {
                    id: self.routing_table.id,
                    target,
                    want: WantFamily::Ipv4 | WantFamily::Ipv6,
                },
            },
            node.addr(),
            reply.map(PendingRequestType::FindNode),
            || node.failed(),
        )
        .await;
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn get_peers(
        &mut self,
        info_hash: InfoHash,
        node: &Node,
        no_seed: bool,
        scrape: bool,
        response: Reply<Result<GetPeersResult>>,
    ) {
        self.send_query(
            QueryMessage::GetPeers {
                request: GetPeersRequest {
                    id: self.routing_table.id,
                    info_hash: info_hash.clone(),
                    no_seed,
                    scrape,
                    want: Default::default(),
                },
            },
            node.addr(),
            Some(PendingRequestType::GetPeers {
                info_hash,
                response: response.take(),
            }),
            || node.failed(),
        )
        .await
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn announce_peer_to(
        &mut self,
        info_hash: InfoHash,
        port: u16,
        node: &Node,
        is_seed: bool,
        response: Reply<Result<()>>,
    ) {
        let token = match node.announce_token().await {
            None => {
                response.send(Err(Error::InvalidToken));
                return;
            }
            Some(token) => token,
        };
        self.send_query(
            QueryMessage::AnnouncePeer {
                request: AnnouncePeerRequest {
                    id: self.routing_table.id,
                    implied_port: false,
                    info_hash: info_hash.clone(),
                    port,
                    token,
                    name: None,
                    seed: is_seed,
                },
            },
            node.addr(),
            Some(PendingRequestType::AnnouncePeer(response.take())),
            || node.failed(),
        )
        .await
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    async fn announce_peer_to_network(&mut self, info_hash: InfoHash, port: u16, is_seed: bool) {
        for node in self.routing_table.nodes().cloned().collect::<Vec<_>>() {
            if let Some(token) = node.announce_token().await {
                self.send_query(
                    QueryMessage::AnnouncePeer {
                        request: AnnouncePeerRequest {
                            id: self.routing_table.id,
                            implied_port: false,
                            info_hash: info_hash.clone(),
                            port,
                            token,
                            name: None,
                            seed: is_seed,
                        },
                    },
                    node.addr(),
                    None,
                    || node.failed(),
                )
                .await
            }
        }
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn scrape_info_hashes(
        &mut self,
        target: &NodeId,
        node: &Node,
        response: Option<oneshot::Sender<Result<Vec<InfoHash>>>>,
    ) {
        self.send_query(
            QueryMessage::SampleInfoHashes {
                request: SampleInfoHashesRequest {
                    id: self.routing_table.id,
                    target: *target,
                },
            },
            node.addr(),
            response.map(PendingRequestType::ScrapeInfoHashes),
            || node.failed(),
        )
        .await
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    async fn index_info_hashes(&mut self) {
        let node_id = self.routing_table.id;
        let search_nodes = Self::find_good_search_nodes(&self.routing_table)
            .await
            .cloned()
            .collect::<Vec<_>>();

        for node in &search_nodes {
            // check if an index interval is known for the node
            // if so, and we have a last index timestamp, check that we're allowed to index the node again
            match (node.last_indexed().await, node.indexing_interval().await) {
                (Some(last_indexed), Some(interval)) => {
                    if Instant::now().duration_since(last_indexed) < interval {
                        continue;
                    }
                }
                _ => {}
            }

            self.scrape_info_hashes(&node_id, node, None).await;
        }
    }

    /// Send an immutable `put` item request to the given node.
    /// The response will eventually be sent to the given reply channel.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn put(
        &mut self,
        node: &Node,
        value: Value,
        sequence_nr: Option<u64>,
        signature: Option<SignatureBytes>,
        public_key: Option<PublicKey>,
        salt: Option<Vec<u8>>,
        response: Reply<Result<()>>,
    ) {
        let token = match node.announce_token().await {
            None => {
                response.send(Err(Error::InvalidToken));
                return;
            }
            Some(token) => token,
        };
        let mutable_properties = match parse_mutable_item_properties(
            sequence_nr,
            public_key,
            salt.clone(),
            signature.map(|e| e.to_vec()),
        ) {
            Ok(properties) => properties,
            Err(e) => {
                response.send(Err(e));
                return;
            }
        };
        let key = match self.handler.store(value.clone(), mutable_properties) {
            Err(e) => {
                response.send(Err(e));
                return;
            }
            Ok(key) => key,
        };
        let (cas, sequence_nr, public_key, signature) = match self
            .handler
            .get(&key)
            .and_then(|e| e.mutable_properties.as_ref())
        {
            None => (None, None, None, None),
            Some(properties) => {
                let cas = if properties.sequence_nr > 0 {
                    Some(properties.sequence_nr - 1)
                } else {
                    None
                };

                (
                    cas,
                    Some(properties.sequence_nr),
                    Some(properties.public_key.to_vec()),
                    Some(properties.signature.to_vec()),
                )
            }
        };

        self.send_query(
            QueryMessage::Put {
                request: PutRequest {
                    id: self.routing_table.id,
                    token,
                    value,
                    cas,
                    sequence_nr,
                    public_key,
                    signature,
                    salt,
                },
            },
            node.addr(),
            Some(PendingRequestType::Put(response.take())),
            || node.failed(),
        )
        .await
    }

    /// Send a `get` item request to the given node.
    ///
    ///
    /// The response will eventually be sent to the given reply channel.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn get(
        &mut self,
        node: &Node,
        hash: Sha1Hash,
        sequence_nr: Option<u64>,
        public_key: Option<PublicKey>,
        salt: Option<Vec<u8>>,
        response: Reply<Result<GetResult>>,
    ) {
        // let target = hex::encode(hash);
        self.send_query(
            QueryMessage::Get {
                request: GetRequest {
                    id: self.routing_table.id,
                    target: hash,
                    sequence_nr,
                },
            },
            node.addr(),
            Some(PendingRequestType::Get {
                public_key,
                salt,
                response: response.take(),
            }),
            || node.failed(),
        )
        .await
    }

    #[cfg_attr(feature = "tracing", tracing::instrument)]
    async fn update_external_ip(&mut self, ip: IpAddr) {
        let new_node_id = NodeId::from_ip(&ip);
        let existing_nodes = self.routing_table.nodes().cloned().collect::<Vec<_>>();
        let bucket_size = self.routing_table.bucket_size;

        // replace the routing table
        self.routing_table = RoutingTable::new(new_node_id, bucket_size);
        for node in existing_nodes {
            let _ = self.routing_table.add_node(node).await;
        }

        debug!("{} detected external IP {}", self, ip);
        let _ = self.callbacks.invoke(DhtEvent::ExternalIpChanged(ip));
    }

    /// Try to send a new query to the given node address.
    /// Returns a [Response] for the send query to the given node address.
    ///
    /// # Arguments
    ///
    /// * `query` - The query to send to the node address.
    /// * `addr` - The address to send the query to.
    /// * `pending_request` - The request to resolve once a response has been received for this query.
    /// * `on_failed` - The closure to execute when the query couldn't be sent.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, on_failed)))]
    async fn send_query<'a, F>(
        &mut self,
        query: QueryMessage,
        addr: &SocketAddr,
        pending_request: Option<PendingRequestType>,
        on_failed: F,
    ) where
        F: AsyncFnOnce(),
    {
        // validate the remote node address
        if addr.ip().is_unspecified() || addr.port() == 0 {
            Self::resolve_as_err(pending_request, Error::InvalidAddr);
            return;
        }

        let name = query.name().to_string();
        let id = self.next_transaction_id();
        let message = match Message::builder()
            .transaction_id(id.clone())
            .payload(MessagePayload::Query(query))
            .read_only(self.handler.is_read_only())
            .build()
        {
            Ok(message) => message,
            Err(e) => {
                Self::resolve_as_err(pending_request, e);
                return;
            }
        };

        debug!(
            "{} is sending query \"{}\" (transaction {}) to {}",
            self, name, id, addr
        );
        match self.send(message, addr).await {
            Ok(_) => {
                self.pending_requests.insert(
                    TransactionKey { id, addr: *addr },
                    PendingRequest {
                        query_name: name,
                        request_type: pending_request,
                        timestamp_sent: Instant::now(),
                    },
                );
                self.metrics
                    .pending_queries
                    .set(self.pending_requests.len() as u64);
            }
            Err(e) => {
                on_failed().await;
                Self::resolve_as_err(pending_request, e);
            }
        }
    }

    /// Send the given response for a query message.
    ///
    /// # Arguments
    ///
    /// * `transaction_id` - The original query transaction id.
    /// * `response` - The response payload.
    /// * `addr` - The node address to send the response to.
    ///
    /// # Returns
    ///
    /// It returns an error if the response failed to send.
    async fn send_response(
        &self,
        transaction_id: TransactionId,
        message: ResponseMessage,
        addr: &SocketAddr,
    ) -> Result<()> {
        let message = Message::builder()
            .transaction_id(transaction_id)
            .version(Version::from(VERSION_IDENTIFIER))
            .payload(MessagePayload::Response(ResponsePayload::Message(message)))
            .ip((*addr).into())
            .port(addr.port())
            .build()?;

        self.send(message, addr).await
    }

    /// Send the given error response for a query message.
    ///
    /// # Arguments
    ///
    /// * `transaction_id` - The original transaction id of the message.
    /// * `error` - The error payload.
    /// * `addr` - The node address to send the response to.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all, err))]
    async fn send_error(
        &self,
        transaction_id: TransactionId,
        error: ErrorMessage,
        addr: &SocketAddr,
    ) -> Result<()> {
        let message = Message::builder()
            .transaction_id(transaction_id)
            .payload(MessagePayload::error(error))
            .ip((*addr).into())
            .port(addr.port())
            .read_only(self.handler.is_read_only())
            .build()?;

        self.send(message, addr).await
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self), err))]
    async fn send(&self, message: Message, addr: &SocketAddr) -> Result<()> {
        if self.cancellation_token.is_cancelled() {
            return Err(Error::Closed);
        }

        let bytes = bencode::to_bytes(&message)?;

        trace!(
            "{} is sending message ({} bytes, transaction {}) to {}, {:?}",
            self,
            bytes.len(),
            message
                .transaction_id_as_str()
                .map(|e| e.to_string())
                .unwrap_or_else(|| message.transaction_id_as_u32().to_string()),
            addr,
            message
        );
        let start_time = Instant::now();
        timeout(
            self.send_timeout,
            self.socket.send_to(bytes.as_slice(), addr),
        )
        .await
        .map_err(|_| {
            Error::Io(io::Error::new(
                io::ErrorKind::TimedOut,
                format!("connection to {} has timed out", addr),
            ))
        })?
        .map_err(Error::from)?;
        let elapsed = start_time.elapsed();
        trace!(
            "{} sent {} bytes to {} in {}.{:03}ms",
            self,
            bytes.len(),
            addr,
            elapsed.as_millis(),
            elapsed.as_micros()
        );

        self.metrics.bytes_out.inc_by(bytes.len() as u64);
        Ok(())
    }

    /// Find an existing node within the routing table, or create a temporary new one.
    ///
    /// The temporary new node will **not be stored** within the routing table.
    fn find_node_or_create(&self, node: &NodeKey) -> Node {
        self.routing_table
            .find_node_by_key(&node)
            .cloned()
            .unwrap_or_else(|| Node::from(*node))
    }

    /// Update the nodes information of the given node.
    async fn update_node(
        &mut self,
        id: NodeId,
        addr: SocketAddr,
        traversal: &mut TraversalAlgorithm,
    ) {
        match self.routing_table.find_node(&id) {
            Some(node) => {
                node.seen().await;
            }
            None => {
                let node = Node::new(id, addr);
                let node_key = node.key().clone();

                // traverse the node
                traversal.add_node(Some(id), addr);

                match self.routing_table.add_node(node).await {
                    Ok(bucket_index) => {
                        self.metrics.nodes.set(self.routing_table.len() as u64);
                        debug!(
                            "{} added verified node {} to bucket {}",
                            self, node_key.addr, bucket_index
                        );

                        self.callbacks.invoke(DhtEvent::NodeAdded(node_key));
                    }
                    Err(e) => {
                        trace!(
                            "{} failed to add verified node {}, {}",
                            self,
                            node_key.addr,
                            e
                        );
                    }
                }
            }
        }
    }

    async fn node_query_result(&self, node_addr: &SocketAddr, success: bool) {
        if let Some(node) = self.routing_table.nodes().find(|e| e.addr() == node_addr) {
            if success {
                node.confirmed().await;
            } else {
                node.failed().await;
            }
        };
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn tick(&mut self) {
        self.callbacks
            .invoke(DhtEvent::Stats(self.metrics.snapshot()));

        self.metrics.tick(TICK_INTERVAL);
        self.routing_table.tick(TICK_INTERVAL);
        self.handler.tick().await;
        self.cleanup_pending_requests().await;
    }

    /// Refresh the nodes within the routing table.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    async fn refresh_routing_table(&mut self) {
        trace!("{} is refreshing nodes within routing table", self);

        let mut nodes_to_query = vec![];
        for bucket in self.routing_table.buckets() {
            let nodes_last_seen =
                futures::future::join_all(bucket.nodes.iter().map(|e| e.last_seen())).await;

            // rotate all bucket node secret tokens when needed
            futures::future::join_all(bucket.nodes.iter().map(|e| e.rotate_token_secret())).await;

            // check if all nodes within the bucket need to be refreshed
            // Buckets that have not been changed in 15 minutes should be "refreshed."
            if nodes_last_seen
                .into_iter()
                .all(|e| e.elapsed() > REFRESH_TIMEOUT)
            {
                let target_node = bucket
                    .nodes
                    .first()
                    .map(|e| *e.id())
                    .unwrap_or_else(|| self.routing_table.id);
                nodes_to_query.push((target_node, bucket.nodes.clone()));
            }
        }

        for (target_node, nodes) in nodes_to_query {
            for node in nodes {
                let _ = self.find_node_internal(target_node, &node, None).await;
            }
        }
    }

    /// Cleanup pending requests which have not received a response.
    async fn cleanup_pending_requests(&mut self) {
        let now = Instant::now();
        let timed_out_request_keys: Vec<_> = self
            .pending_requests
            .iter()
            .filter(|(_, request)| now - request.timestamp_sent >= RESPONSE_TIMEOUT)
            .map(|(key, _)| key.clone())
            .collect();

        if timed_out_request_keys.is_empty() {
            return;
        }

        trace!(
            "{} is cleaning a total of {} timed-out requests",
            self,
            timed_out_request_keys.len()
        );
        for key in timed_out_request_keys {
            self.node_query_result(&key.addr, false).await;
            if let Some(request) = self.pending_requests.remove(&key) {
                Self::resolve_as_err(request.request_type, Error::Timeout);
            }
        }

        self.metrics
            .pending_queries
            .set(self.pending_requests.len() as u64);
    }

    /// Try to update the announce token for the given node ID.
    ///
    /// It returns an error when the node ID couldn't be found within the routing table or the token value is invalid.
    async fn update_announce_token(&self, id: &NodeId, token: &NodeToken) -> Result<()> {
        let node = self
            .routing_table
            .find_node(id)
            .ok_or(Error::InvalidNodeId)?;
        node.update_announce_token(token.clone()).await;
        trace!("{} updated announce token for {}", self, id);
        Ok(())
    }

    /// Get the next transaction ID for sending a new message.
    /// The transaction ID within the server will be automatically wrapped when [u32::MAX] has been reached.
    fn next_transaction_id(&mut self) -> TransactionId {
        let new = self.transaction_id.wrapping_add(1);
        self.transaction_id = new;
        let id = format!("{:02x}", new);
        id.into_bytes().into()
    }

    /// Verify the given mutable value.
    fn verify_value<V>(
        &self,
        value: &V,
        sequence_nr: Option<&u64>,
        public_key: &PublicKey,
        salt: Option<&[u8]>,
        signature: Option<&[u8]>,
    ) -> Result<()>
    where
        V: Serialize,
    {
        let signature = signature.ok_or(Error::InvalidSignature).and_then(|e| {
            TryInto::<SignatureBytes>::try_into(e).map_err(|_| Error::InvalidSignature)
        })?;
        let sequence_nr = sequence_nr.ok_or(Error::InvalidSequenceNr)?;

        self.item_signature.verify(
            &value,
            &sequence_nr,
            &public_key,
            salt.as_ref().map(AsRef::as_ref),
            &signature,
        )
    }

    fn resolve_as_err(request_type: Option<PendingRequestType>, err: Error) {
        if let Some(request_type) = request_type {
            match request_type {
                PendingRequestType::Ping(tx) => {
                    let _ = tx.send(Err(err));
                }
                PendingRequestType::FindNode(tx) => {
                    let _ = tx.send(Err(err));
                }
                PendingRequestType::AnnouncePeer(tx) => {
                    let _ = tx.send(Err(err));
                }
                PendingRequestType::GetPeers { response, .. } => {
                    let _ = response.send(Err(err));
                }
                PendingRequestType::ScrapeInfoHashes(tx) => {
                    let _ = tx.send(Err(err));
                }
                PendingRequestType::Put(tx) => {
                    let _ = tx.send(Err(err));
                }
                PendingRequestType::Get { response, .. } => {
                    let _ = response.send(Err(err));
                }
            }
        }
    }

    /// Returns all non [NodeState::Bad] search nodes from the routing table
    async fn find_good_search_nodes(routing_table: &RoutingTable) -> impl Iterator<Item = &Node> {
        let nodes_with_state =
            futures::future::join_all(routing_table.nodes().map(|node| async move {
                let state = node.state().await;
                (node, state)
            }))
            .await;

        nodes_with_state.into_iter().flat_map(|(node, state)| {
            if state != NodeState::Bad {
                Some(node)
            } else {
                None
            }
        })
    }

    /// Collect the IPv4 and IPv6 nodes from the compact nodes.
    fn collect_nodes(nodes: &CompactIpNodes, nodes6: &CompactIPv6Nodes) -> Vec<NodeKey> {
        let nodes = match nodes {
            CompactIpNodes::IPv4(nodes) => {
                Either::Left(nodes.as_slice().into_iter().map(|e| NodeKey {
                    id: e.id,
                    addr: SocketAddr::from(&e.addr),
                }))
            }
            CompactIpNodes::IPv6(nodes) => {
                Either::Right(nodes.as_slice().into_iter().map(|e| NodeKey {
                    id: e.id,
                    addr: SocketAddr::from(&e.addr),
                }))
            }
        };

        nodes
            .chain(nodes6.as_slice().into_iter().map(|e| NodeKey {
                id: e.id,
                addr: SocketAddr::from(&e.addr),
            }))
            .collect()
    }
}

#[derive(Debug)]
enum ReaderMessage {
    Message {
        message: Message,
        message_len: usize,
        addr: SocketAddr,
    },
    Error {
        error: Error,
        payload_len: usize,
        addr: SocketAddr,
    },
}

#[derive(Debug, Display)]
#[display("DHT node reader [{}]", addr_port)]
struct NodeReader {
    socket: Arc<UdpSocket>,
    addr_port: u16,
    sender: UnboundedSender<ReaderMessage>,
    cancellation_token: CancellationToken,
}

impl NodeReader {
    /// Start the main reader loop of a node server.
    /// This will handle incoming packets and parse them before delivering them to the node server.
    async fn run(&self) {
        loop {
            let mut buffer = [0u8; MAX_PACKET_SIZE];
            select! {
                _ = self.cancellation_token.cancelled() => break,
                Ok((len, addr)) = self.socket.recv_from(&mut buffer) => {
                    if let Err(e) = self.handle_incoming_message(&buffer[0..len], addr).await {
                        let _ = self.sender.send(ReaderMessage::Error { error: e, payload_len: len, addr });
                    }
                },
            }
        }
        debug!("{} main loop ended", self);
    }

    async fn handle_incoming_message(&self, bytes: &[u8], addr: SocketAddr) -> Result<()> {
        // check if the port of the sender is known
        if addr.port() == 0 {
            trace!(
                "{} received packet with unknown port, ignoring packet message",
                self
            );
            return Ok(());
        }

        let start_time = Instant::now();
        let message = bencode::from_bytes::<Message>(bytes).map_err(|e| {
            trace!(
                "{} failed to parse incoming message, {}\n{}",
                self,
                e,
                String::from_utf8_lossy(bytes)
            );
            e
        })?;
        let elapsed = start_time.elapsed();
        trace!(
            "{} read {} bytes from {} in {}.{:03}ms",
            self,
            bytes.len(),
            addr,
            elapsed.as_millis(),
            elapsed.as_micros(),
        );

        let message_len = bytes.len();
        let _ = self.sender.send(ReaderMessage::Message {
            message,
            message_len,
            addr,
        });
        Ok(())
    }
}

/// Represents a request that has been sent to a DHT node and is awaiting a response.
#[derive(Debug)]
struct PendingRequest {
    query_name: String,
    request_type: Option<PendingRequestType>,
    timestamp_sent: Instant,
}

/// The type of a pending request.
/// It determines which result should be sent back to the waiter.
#[derive(Debug)]
enum PendingRequestType {
    Ping(oneshot::Sender<Result<NodeKey>>),
    FindNode(oneshot::Sender<Result<Vec<NodeKey>>>),
    AnnouncePeer(oneshot::Sender<Result<()>>),
    GetPeers {
        info_hash: InfoHash,
        response: oneshot::Sender<Result<GetPeersResult>>,
    },
    ScrapeInfoHashes(oneshot::Sender<Result<Vec<InfoHash>>>),
    Put(oneshot::Sender<Result<()>>),
    Get {
        public_key: Option<PublicKey>,
        salt: Option<Vec<u8>>,
        response: oneshot::Sender<Result<GetResult>>,
    },
}

#[derive(Debug, Display, Clone, PartialEq, Eq, Hash)]
#[display("{}[{}]", addr, id)]
struct TransactionKey {
    pub id: TransactionId,
    pub addr: SocketAddr,
}

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

    mod new {
        use super::*;

        #[tokio::test]
        async fn test_new() {
            init_logger!();
            let node_id = NodeId::new();
            let verifier = ItemSignature::new().unwrap();
            let mode = Mode::Server;
            let tracker = DhtTracker::new(Config {
                id: node_id,
                mode,
                max_torrents: 1,
                info_hash_indexing_enabled: true,
                info_hash_indexing_interval: Duration::from_secs(20),
                item_signature: Some(verifier),
                routing_nodes: vec![],
            })
            .await
            .expect("expected a new DHT server");

            // verify the tracker id
            let result = tracker.id().await.unwrap();
            assert_eq!(
                node_id, result,
                "expected a new random node ID to have been generated"
            );
            assert_ne!(
                0,
                tracker.port(),
                "expected a server port to have been present"
            );
            assert_eq!(
                mode,
                tracker.mode(),
                "expected the server mode to be set to the given mode"
            );
        }

        #[tokio::test]
        async fn test_read_only() {
            init_logger!();
            let source_config = {
                let mut config = Config::default();
                config.mode = Mode::Client;
                config
            };
            let source = DhtTracker::new(source_config).await.unwrap();
            let target = DhtTracker::new(Config::default()).await.unwrap();
            let source_id = source.id().await.expect("expected a source node id");
            let source_addr = (Ipv4Addr::LOCALHOST, source.addr().port()).into();
            let target_addr = (Ipv4Addr::LOCALHOST, target.addr().port()).into();

            // ping the target node
            let _ = source
                .ping(target_addr)
                .await
                .expect("expected the ping to succeed");

            // retrieve the node info from the target
            let key = NodeKey {
                id: source_id,
                addr: source_addr,
            };
            let result = target.node(&key).await;

            assert_eq!(
                None, result,
                "expected the read-only node to not have been added to the routing table"
            );
        }
    }

    mod ping {
        use super::*;

        #[tokio::test]
        async fn test_ping_valid_address() {
            init_logger!();
            let (source, target) = create_node_server_pair!();
            let incoming_id = source.id().await.unwrap();
            let outgoing_id = target.id().await.unwrap();
            let source_addr = (Ipv4Addr::LOCALHOST, source.port()).into();

            let result = timeout!(
                Duration::from_millis(750),
                target.ping(source_addr),
                "failed to ping node"
            );
            assert!(
                result.is_ok(),
                "expected ping to succeed, got {:?} instead",
                result
            );

            // check if the incoming server has added the node that pinged it
            let result = source.node_by_id(&outgoing_id).await;
            assert!(
                result.is_some(),
                "expected the outgoing node {:?} to be added",
                outgoing_id
            );

            // check if the outgoing server has added the pinged target node
            let result = target.nodes().await;
            assert!(
                result.iter().find(|e| e.id() == &incoming_id).is_some(),
                "expected the incoming node {:?} to be added",
                incoming_id
            );
            let result = target.total_nodes().await;
            assert_eq!(1, result, "expected 1 node to be added");
        }

        #[tokio::test]
        async fn test_ping_invalid_address() {
            init_logger!();
            let addr = SocketAddr::from(([0, 0, 0, 0], 9000));
            let tracker = DhtTracker::builder()
                .max_torrents(1)
                .enable_indexing(false)
                .build()
                .await
                .unwrap();

            let result = timeout!(
                Duration::from_millis(750),
                tracker.ping(addr),
                "failed to ping node"
            );

            assert_eq!(
                Err(Error::InvalidAddr),
                result,
                "expected an invalid address error"
            );
        }
    }

    mod find_node {
        use super::*;

        #[tokio::test]
        async fn test_find_node() {
            init_logger!();
            let rand = 2;
            let search_node_id = NodeId::from_ip_with_rand(&[132, 141, 12, 40].into(), rand);
            let incoming_id = NodeId::from_ip_with_rand(&Ipv4Addr::LOCALHOST.into(), rand);
            let outgoing_id = NodeId::from_ip_with_rand(&Ipv4Addr::LOCALHOST.into(), rand);
            let outgoing = DhtTracker::builder()
                .node_id(outgoing_id)
                .max_torrents(16)
                .enable_indexing(false)
                .build()
                .await
                .unwrap();
            let mut incoming = create_tracker_context!(incoming_id);

            // register the incoming tracker with the outgoing tracker
            let (tx, rx) = oneshot::channel();
            let incoming_addr = (Ipv4Addr::LOCALHOST, incoming.socket_addr.port()).into();
            tokio::spawn(async move {
                let result = outgoing.add_node(&incoming_addr).await;
                let _ = tx.send((result, outgoing));
            });

            // process the incoming ping message
            let (sender, _receiver) = channel!(1);
            let mut observer = Observer::new(sender.clone());
            let mut traversal = TraversalAlgorithm::new(8, vec![], sender);
            let message = timeout(Duration::from_millis(500), incoming.receiver.recv())
                .await
                .unwrap()
                .expect("expected a message");
            incoming
                .on_message_received(message, &mut observer, &mut traversal)
                .await;

            // verify the result of the add_node operation
            let (result, outgoing) = timeout!(
                Duration::from_millis(750),
                rx,
                "timed out while adding the node"
            )
            .unwrap();
            assert_eq!(result, Ok(()), "expected the node to be added successfully");

            // calculate the bucket which will be retrieved by the search node
            let bucket_index = incoming_id.distance(&search_node_id);
            // create a node which matches the search bucket index
            let nearby_node = create_bucket_matching_node(bucket_index, incoming_id);
            incoming
                .update_node(
                    nearby_node,
                    ([132, 141, 45, 30], 8090).into(),
                    &mut traversal,
                )
                .await;

            // process the incoming node task
            tokio::spawn(async move {
                let (_sender, receiver) = channel!(1);
                incoming
                    .run(Duration::from_secs(60), observer, traversal, receiver)
                    .await;
            });

            // request the node info from the nearby node
            let result = outgoing
                .find_nodes(&search_node_id, Duration::from_millis(500))
                .await
                .expect("expected to retrieve relevant nodes");
            assert_eq!(1, result.len(), "expected one node to have been present");
        }
    }

    mod get_peers {
        use super::*;
        use crate::channel::channel;
        use std::str::FromStr;

        #[tokio::test]
        async fn test_get_peers() {
            init_logger!();
            let info_hash = InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7")
                .expect("expected a valid hash");
            let (incoming, outgoing) = create_node_server_pair!();

            // register the incoming tracker with the outgoing tracker
            let incoming_addr = (Ipv4Addr::LOCALHOST, incoming.addr().port()).into();
            let result = outgoing.add_node(&incoming_addr).await;
            assert_eq!(result, Ok(()), "expected the node to be added successfully");

            let result = outgoing
                .get_peers(&info_hash, 2, Duration::from_secs(2))
                .await
                .expect("expected to get peers");
            assert_eq!(
                Vec::<SocketAddr>::with_capacity(0),
                result,
                "expected an empty peers list to have been returned"
            );
        }

        #[tokio::test]
        async fn test_get_peers_from() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let (source, target) = create_node_server_pair!();
            let source_addr = (Ipv4Addr::LOCALHOST, source.port()).into();

            let source_key = target.ping(source_addr).await.unwrap();
            let result = target
                .get_peers_from(&info_hash, &source_key, 1, Duration::from_secs(1))
                .await;
            assert!(
                result.is_ok(),
                "expected the peers to have been queried, but got {:?}",
                result
            );
        }

        #[tokio::test]
        async fn test_get_peers_from_storage() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let (sender, receiver) = channel(2);
            let mut context = create_tracker_context!();
            let tracker = DhtTracker {
                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 7890)),
                mode: Mode::Server,
                metrics: Default::default(),
                sender: sender.clone(),
                callbacks: MultiThreadedCallback::new(),
                cancellation_token: Default::default(),
            };
            let peer = SocketAddr::from((Ipv4Addr::LOCALHOST, 8000)).into();

            // spawn a new task for the context with an already stored peer
            let inner_info_hash = info_hash.clone();
            tokio::spawn(async move {
                context.handler.update_peer(inner_info_hash, peer, false);

                context
                    .run(
                        Duration::from_secs(60),
                        Observer::new(sender.clone()),
                        TraversalAlgorithm::new(8, vec![], sender),
                        receiver,
                    )
                    .await;
            });

            // request the peers from the tracker which has no nodes within the network
            let result = tracker
                .get_peers(&info_hash, 1, Duration::from_secs(2))
                .await
                .unwrap();

            assert_eq!(
                1,
                result.len(),
                "expected the stored peer to have been returned"
            );
            assert_eq!(peer, result[0]);
        }
    }

    mod announce_peer {
        use super::*;
        use std::str::FromStr;

        #[tokio::test]
        async fn test_announce_peer() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let (source, target) = create_node_server_pair!();
            let target_id = target.id().await.unwrap();
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();
            let peer_port = 8080;

            // request peers from the target node
            // this will set the initial announce token in the source tracker for the target node
            let target_key = source.ping(target_addr).await.unwrap();
            let result = source
                .get_peers_from(&info_hash, &target_key, 1, Duration::from_secs(1))
                .await;
            assert!(
                result.is_ok(),
                "expected the peers to have been queried, but got {:?}",
                result
            );

            // verify that an announce token has been written to the source node for the target
            let node = source
                .node_by_id(&target_id)
                .await
                .expect("expected the source node to exist within the target");
            assert!(
                node.announce_token().await.is_some(),
                "expected the target node {} to have an announce token",
                node.id()
            );

            // announce the torrent peer to the target node
            let peer_addr = (Ipv4Addr::LOCALHOST, peer_port).into();
            let result = source.announce_peer(&info_hash, peer_port, false).await;
            verify_announce_peer(&info_hash, &target, &[peer_addr], result).await;
        }

        #[tokio::test]
        async fn test_announce_peer_to() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let (source, target) = create_node_server_pair!();
            let target_id = target.id().await.unwrap();
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // request peers from the target node
            // this will set the initial announce token in the source tracker for the target node
            let target_key = source.ping(target_addr).await.unwrap();
            let result = source
                .get_peers_from(&info_hash, &target_key, 1, Duration::from_secs(1))
                .await;
            assert!(
                result.is_ok(),
                "expected the peers to have been queried, but got {:?}",
                result
            );

            // verify that an announce token has been written to the source node for the target
            let node = source
                .node_by_id(&target_id)
                .await
                .expect("expected the source node to exist within the target");
            assert!(
                node.announce_token().await.is_some(),
                "expected the target node {} to have an announce token",
                node.id()
            );

            // announce the peers to the target node
            let peer1 = (Ipv4Addr::LOCALHOST, 8080).into();
            let peer2 = (Ipv4Addr::LOCALHOST, 17000).into();
            let _ = source
                .announce_peer_to(&info_hash, 8080, false, &target_key)
                .await
                .unwrap();
            let result = source
                .announce_peer_to(&info_hash, 17000, true, &target_key)
                .await;
            verify_announce_peer(&info_hash, &target, &[peer1, peer2], result).await;
        }

        async fn verify_announce_peer(
            info_hash: &InfoHash,
            target: &DhtTracker,
            peers: &[SocketAddr],
            result: Result<()>,
        ) {
            assert!(
                result.is_ok(),
                "expected the announce to have been successful, but got {:?}",
                result
            );

            // get the stored peers of the target to which the announcement was made
            // due to a strange race condition in Github, we try a few times
            let result = {
                let mut attempt = 0;
                let mut result = HashSet::new();
                while attempt < 3 {
                    result = target.peers_for(info_hash).await;
                    if result.len() > 0 {
                        break;
                    }
                    attempt += 1;
                    time::sleep(Duration::from_millis(2)).await;
                }
                result
            };

            // verify if all announced peers are present
            for peer in peers {
                assert!(
                    result.iter().find(|e| &e.addr == peer).is_some(),
                    "expected peer {} to be present",
                    peer
                );
            }
        }
    }

    mod scrape {
        use super::*;
        use std::str::FromStr;

        #[tokio::test]
        async fn test_scrape_peers() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let source = DhtTracker::builder()
                .node_id(NodeId::new())
                .build()
                .await
                .unwrap();
            let (announcer, target) = create_node_server_pair!();
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // announce the peer addr to the target node through the announcer
            announce_peer(&announcer, &target_addr, &info_hash, 6881, false).await;

            // add the target to the source node
            let _ = source.ping(target_addr).await.unwrap();

            // scrape the target
            let result = source
                .scrape_peers(&info_hash, Duration::from_millis(750))
                .await
                .expect("expected a scrape result");
            assert_eq!(1, result.downloaders, "expected at least one downloader");
            assert_eq!(0, result.seeders, "expected no seeders");

            // announce another peer as seed
            announce_peer(&announcer, &target_addr, &info_hash, 6882, true).await;

            // scrape the target
            let result = source
                .scrape_peers(&info_hash, Duration::from_millis(750))
                .await
                .expect("expected a scrape result");
            assert!(result.downloaders >= 1, "expected at least one downloader");
            assert_eq!(1, result.seeders, "expected at least one seeder");
        }
    }

    mod scrape_info_hashes {
        use super::*;
        use std::str::FromStr;

        #[tokio::test]
        async fn test_index_interval() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let mut source = create_tracker_context!(NodeId::new(), true);
            let (sender, receiver) = channel!(2);
            let mut traversal = TraversalAlgorithm::new(8, vec![], sender.clone());
            let observer = Observer::new(sender.clone());
            let (announcer, target) = create_node_server_pair!();
            let target_id = target.id().await.unwrap();
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // announce the peer addr to the target node through the announcer
            announce_peer(&announcer, &target_addr, &info_hash, 8080, false).await;

            // add the target to the source node
            source
                .update_node(target_id, target_addr, &mut traversal)
                .await;

            // subscribe to the events
            let mut events_receiver = source.callbacks.subscribe();
            let (tx, rx) = oneshot::channel();
            tokio::spawn(async move {
                while let Ok(event) = events_receiver.recv().await {
                    if let DhtEvent::InfoHashAdded(_) = &*event {
                        let _ = tx.send(event.clone());
                        break;
                    }
                }
            });

            // run the indexer
            source.index_info_hashes().await;

            // start the source on a separate task
            tokio::spawn(async move {
                source
                    .run(Duration::from_secs(60), observer, traversal, receiver)
                    .await;
            });

            let result = timeout!(Duration::from_millis(500), rx).expect("expected an event");
            match &*result {
                DhtEvent::InfoHashAdded(result) => {
                    assert_eq!(&info_hash, result, "expected the info hash to match");
                }
                _ => assert!(
                    false,
                    "expected DhtEvent::InfoHashAdded, but got {:?}",
                    result
                ),
            }
        }

        #[tokio::test]
        async fn test_indexing_disabled() {
            init_logger!();
            let indexing_interval = Duration::from_millis(50);
            let source = DhtTracker::builder()
                .enable_indexing(false)
                .indexing_interval(indexing_interval)
                .build()
                .await
                .unwrap();
            let target = DhtTracker::builder()
                .enable_indexing(false)
                .build()
                .await
                .unwrap();

            // add the target to the source network
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();
            let _ = source
                .ping(target_addr)
                .await
                .expect("expected the target to have been pinged");

            // await the interval
            time::sleep(indexing_interval).await;

            let result = target.metrics().sample_info_hashes_requests.total();
            assert_eq!(0, result, "expected no info hashes to be indexed");
        }

        #[tokio::test]
        async fn test_scrape_info_hashes_from() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let (source, target) = create_node_server_pair!(NodeId::new(), NodeId::new(), false);
            let source_id = source.id().await.unwrap();
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // connect the source to the target
            let target_key = source.ping(target_addr).await.unwrap();

            // announce the peer addr to the target node through the announcer
            announce_peer(&source, &target_addr, &info_hash, 7800, false).await;

            // scrape the info hashes from the target
            let result = source
                .scrape_info_hashes_from(&source_id, &target_key)
                .await
                .expect("expected the scrape to have been successful");
            assert_eq!(
                Some(&info_hash),
                result.first(),
                "expected the info hash to be present"
            );
        }
    }

    mod put {
        use super::*;
        use rand::{rng, Rng};
        use serde::Deserialize;
        use sha1::{Digest, Sha1};

        #[derive(Debug, PartialEq, Serialize, Deserialize)]
        struct TestItem {
            pub id: u64,
            pub name: String,
        }

        impl TestItem {
            fn hash(&self) -> Sha1Hash {
                let bytes = bencode::to_bytes(self).unwrap();
                Sha1Hash::try_from(Sha1::digest(bytes.as_slice())).unwrap()
            }
        }

        #[tokio::test]
        async fn test_put() {
            init_logger!();
            let item = TestItem {
                id: 123,
                name: "Foo".to_string(),
            };
            let hash = item.hash();
            let (source, target) = create_node_server_pair!(NodeId::new(), NodeId::new(), false);
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // connect the source to the target and request a write token
            let target_key = source.ping(target_addr).await.unwrap();
            let _ = source
                .get_from::<TestItem>(hash.clone(), &target_key)
                .await
                .expect("expected the get operation to succeed");

            // put the item on the target
            let result = source.put(&item, Duration::from_millis(250)).await;
            assert_eq!(Ok(()), result, "expected the put operation to succeed");

            // retrieve the item from the target
            let result = source
                .get_from(hash, &target_key)
                .await
                .expect("expected the get_from operation to succeed");
            assert_eq!(Some(item), result);
        }

        #[tokio::test]
        async fn test_put_to() {
            init_logger!();
            let item = TestItem {
                id: 666,
                name: "Bar".to_string(),
            };
            let hash = item.hash();
            let (source, target) = create_node_server_pair!(NodeId::new(), NodeId::new(), false);
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // connect the source to the target and request a write token
            let target_key = source.ping(target_addr).await.unwrap();
            let _ = source
                .get_from::<TestItem>(hash.clone(), &target_key)
                .await
                .expect("expected the get operation to succeed");

            // put the item on the target
            let result = source.put_to(&item, &target_key).await;
            assert_eq!(Ok(()), result, "expected the put_to operation to succeed");

            // retrieve the item from the target
            let result = source
                .get_from(hash, &target_key)
                .await
                .expect("expected the get_from operation to succeed");
            assert_eq!(Some(item), result);
        }

        #[tokio::test]
        async fn test_put_to_no_write_token() {
            init_logger!();
            let item = TestItem {
                id: 123456,
                name: "NoWriteToken".to_string(),
            };
            let (source, target) = create_node_server_pair!(NodeId::new(), NodeId::new(), false);
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // connect the source to the target
            let target_key = source.ping(target_addr).await.unwrap();

            // try to put the item on the target
            let result = source.put_to(&item, &target_key).await;
            assert_eq!(
                Err(Error::InvalidToken),
                result,
                "expected Error::InvalidToken, but got {:?}",
                result
            );
        }

        #[tokio::test]
        async fn test_put_mutable_no_salt() {
            init_logger!();
            let item = TestItem {
                id: 8989,
                name: "MyMutableItem".to_string(),
            };
            let hash = item.hash();
            let mut secret_key: SecretKey = SecretKey::default();
            rng().fill_bytes(&mut secret_key);
            let (source, target) = create_node_server_pair!(NodeId::new(), NodeId::new(), false);
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // connect the source to the target
            let target_key = source.ping(target_addr).await.unwrap();
            let _ = source
                .get_from::<TestItem>(hash.clone(), &target_key)
                .await
                .expect("expected the get operation to succeed");

            // put the mutable item on the target
            let public_key = source
                .put_mutable(
                    &item,
                    Duration::from_millis(250),
                    Some(1),
                    None,
                    &secret_key,
                )
                .await
                .expect("expected the put operation to succeed");
            assert_ne!(
                PublicKey::default(),
                public_key,
                "expected a public key to have been returned"
            );

            // request the mutable item from the network
            let result = source
                .get_mutable::<TestItem>(&public_key, None, None, Duration::from_millis(500), 1)
                .await
                .unwrap();
            assert_eq!(Some(item), result, "expected the item to have been found");
        }
    }

    mod get {
        use super::*;
        use serde::Deserialize;
        use sha1::{Digest, Sha1};

        #[derive(Debug, PartialEq, Serialize, Deserialize)]
        struct TestItem {
            pub description: String,
        }

        impl TestItem {
            fn hash(&self) -> Sha1Hash {
                let bytes = bencode::to_bytes(self).unwrap();
                Sha1Hash::try_from(Sha1::digest(bytes.as_slice())).unwrap()
            }
        }

        #[tokio::test]
        async fn test_get() {
            init_logger!();
            let item = TestItem {
                description: "Lorem ipsum dolor sit amet".to_string(),
            };
            let hash = item.hash();
            let (source, target) = create_node_server_pair!(NodeId::new(), NodeId::new(), false);
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // connect the source to the target and request a write token
            let target_key = source.ping(target_addr).await.unwrap();
            let _ = source
                .get_from::<TestItem>(hash.clone(), &target_key)
                .await
                .expect("expected the get operation to succeed");

            // put the item on the target
            let result = source.put_to(&item, &target_key).await;
            assert_eq!(Ok(()), result, "expected the put_to operation to succeed");

            // try to retrieve the item from the DHT network
            let result = source
                .get(hash, Duration::from_millis(500), 1)
                .await
                .expect("expected the get operation to succeed");
            assert_eq!(Some(item), result);
        }
    }

    mod bootstrap {
        use super::*;

        use tokio::time;

        #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
        async fn test_bootstrap_nodes() {
            init_logger!();
            let rand = 13;
            let node_id = NodeId::from_ip_with_rand(&[141, 130, 12, 89].into(), rand);
            let bootstrap_node_id = NodeId::from_ip_with_rand(&[180, 13, 0, 3].into(), rand);
            let bootstrap_node = DhtTracker::builder()
                .node_id(bootstrap_node_id)
                .build()
                .await
                .unwrap();

            // fill the bootstrap node with nodes which can be found through the `find_node` search
            let futures = (1..111u8)
                .into_iter()
                .map(|e| async move {
                    DhtTracker::builder()
                        .node_id(NodeId::from_ip_with_rand(
                            &IpAddr::V4(Ipv4Addr::new(127, 0, 0, e)),
                            rand,
                        ))
                        .build()
                        .await
                        .unwrap()
                })
                .collect::<Vec<_>>();
            let nodes = futures::future::join_all(futures).await;

            for node in &nodes {
                let addr = (Ipv4Addr::LOCALHOST, node.port()).into();
                let result = bootstrap_node.add_node(&addr).await;
                assert_eq!(result, Ok(()), "expected the node to be added successfully");
            }

            // create the DHT tracker which will use the bootstrap node for its bootstrap process
            let tracker = DhtTracker::builder()
                .node_id(node_id)
                .routing_nodes(vec![(Ipv4Addr::LOCALHOST, bootstrap_node.port()).into()])
                .build()
                .await
                .expect("expected a new DHT tracker to have been created");

            select! {
                _ = time::sleep(Duration::from_secs(10)) => assert!(false, "timed-out while bootstrapping nodes"),
                _ = async {
                    while tracker.nodes().await.len() <= 1 {
                        time::sleep(Duration::from_millis(50)).await;
                    }
                } => {},
            }

            let result = tracker.nodes().await;
            assert!(!result.is_empty(), "expected at least one bootstrap node");
        }
    }

    mod info_hashes {
        use super::*;
        use std::str::FromStr;

        #[tokio::test]
        async fn test_info_hashes() {
            init_logger!();
            let info_hash1 =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let info_hash2 =
                InfoHash::from_str("urn:btih:2C6B6858D61DA9543D4231A71DB4B1C9264B0685").unwrap();
            let (source, target) = create_node_server_pair!();
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();

            // create a write token within the source for the target
            let target_key = source.ping(target_addr).await.unwrap();
            let result = source
                .get_peers_from(&info_hash1, &target_key, 1, Duration::from_secs(1))
                .await;
            assert!(
                result.is_ok(),
                "expected the peers to have been queried, but got {:?}",
                result
            );

            // announce the info hashes to the target
            let peer = 6800;
            source
                .announce_peer(&info_hash1, peer, false)
                .await
                .expect("expected the announce to succeed");
            source
                .announce_peer(&info_hash2, peer, false)
                .await
                .expect("expected the announce to succeed");

            // retrieve the known info hashes from the target storage
            // due to some strange race condition in Github, we'll try a few times to retrieve the info hashes
            let result: Vec<InfoHash> = {
                let mut attempt = 0;
                let mut result = vec![];
                while attempt < 3 {
                    result = target.info_hashes().await;
                    if result.len() == 2 {
                        break;
                    }

                    attempt += 1;
                    time::sleep(Duration::from_millis(2)).await;
                }
                result
            };
            for info_hash in &[info_hash1, info_hash2] {
                assert!(
                    result.contains(info_hash),
                    "expected info hash {} to be present in the storage: {:?}",
                    info_hash,
                    result
                );
            }
        }
    }

    mod peers {
        use super::*;
        use std::str::FromStr;

        #[tokio::test]
        async fn test_peers() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let (source, target) = create_node_server_pair!();
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();
            let peer_port = 9968;

            // request peers from the target node
            // this will set the initial announce token in the source tracker for the target node
            let target_key = source.ping(target_addr).await.unwrap();
            let result = source
                .get_peers_from(&info_hash, &target_key, 1, Duration::from_secs(1))
                .await;
            assert!(
                result.is_ok(),
                "expected the peers to have been queried, but got {:?}",
                result
            );

            // announce the torrent peer to the target node
            source
                .announce_peer_to(&info_hash, peer_port, false, &target_key)
                .await
                .expect("expected the announce to succeed");

            // verify that the peers storage has been updated
            let result = target.peers().await;
            assert!(
                result.contains_key(&info_hash),
                "expected the info hash {} to have been present",
                info_hash
            );
            assert_eq!(
                1,
                result[&info_hash].len(),
                "expected the info hash {} to have 1 peer",
                info_hash
            );
        }

        #[tokio::test]
        async fn test_peers_for() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let (source, target) = create_node_server_pair!();
            let target_addr = (Ipv4Addr::LOCALHOST, target.port()).into();
            let peer_port = 9900;

            // request peers from the target node
            // this will set the initial announce token in the source tracker for the target node
            let target_key = source.ping(target_addr).await.unwrap();
            let result = source
                .get_peers_from(&info_hash, &target_key, 1, Duration::from_secs(1))
                .await;
            assert!(
                result.is_ok(),
                "expected the peers to have been queried, but got {:?}",
                result
            );

            // announce the torrent peer to the target node
            source
                .announce_peer_to(&info_hash, peer_port, false, &target_key)
                .await
                .expect("expected the announce to succeed");

            // verify that the peers storage has been updated
            let result = target.peers_for(&info_hash).await;
            assert_eq!(
                1,
                result.len(),
                "expected the info hash {} to have 1 peer",
                info_hash
            );
        }
    }

    fn create_bucket_matching_node(bucket_index: u8, routing_table_id: NodeId) -> NodeId {
        let mut node_id = NodeId::new();

        while routing_table_id.distance(&node_id) != bucket_index {
            node_id = NodeId::new();
        }

        node_id
    }

    async fn announce_peer(
        announcer: &DhtTracker,
        target_addr: &SocketAddr,
        info_hash: &InfoHash,
        peer_port: u16,
        is_seed: bool,
    ) {
        let target_key = announcer
            .ping(*target_addr)
            .await
            .expect("expected the target to have been pinged");
        let _ = announcer
            .get_peers_from(info_hash, &target_key, 1, Duration::from_secs(1))
            .await
            .expect("expected to have retrieved a token for the target");
        let _ = announcer
            .announce_peer_to(info_hash, peer_port, is_seed, &target_key)
            .await
            .expect("expected the peer to have been announced");
    }
}