emissary-core 0.4.0

Rust implementation of the I2P protocol stack
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
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use crate::{
    crypto::{base64_encode, SigningPrivateKey},
    destination::{routing_path::RoutingPathHandle, DeliveryStyle},
    error::{parser::PacketParseError, StreamingError},
    i2cp::I2cpPayload,
    primitives::{Destination, DestinationId},
    runtime::{Instant, JoinSet, Runtime},
    sam::{
        protocol::streaming::{
            config::StreamConfig,
            listener::{SocketKind, StreamListener, StreamListenerEvent},
            packet::PacketBuilder,
            stream::{
                active::{Stream, StreamContext, StreamEvent, StreamKind},
                pending::{PendingStream, PendingStreamResult},
            },
        },
        socket::SamSocket,
    },
};

use bytes::{BufMut, BytesMut};
use futures::{FutureExt, StreamExt};
use hashbrown::{HashMap, HashSet};
use rand::Rng;
use thingbuf::mpsc::{channel, Receiver, Sender};

use alloc::{boxed::Box, collections::VecDeque, format, string::String, vec, vec::Vec};
use core::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
    time::Duration,
};

mod config;
mod listener;
mod packet;
mod stream;

pub use listener::ListenerKind;

#[cfg(not(feature = "fuzz"))]
use packet::Packet;
#[cfg(feature = "fuzz")]
pub use packet::Packet;

/// Logging target for the file.
const LOG_TARGET: &str = "emissary::streaming";

/// [`StreamManager`]'s message channel size.
///
/// Size of the channel used by all virtual streams to send messages to the network.
const STREAM_MANAGER_CHANNEL_SIZE: usize = 4096;

/// [`Stream`]'s message channel size.
///
/// Size of the channel used to send messages received from the network to a virtual stream.
const STREAM_CHANNEL_SIZE: usize = 512;

/// How long are streams kept in the pending state before they are pruned and rejected.
const PENDING_STREAM_PRUNE_THRESHOLD: Duration = Duration::from_secs(30);

/// How long should a pending outbound stream wait before sending another `SYN`.
const SYN_RETRY_TIMEOUT: Duration = Duration::from_millis(2500);

/// Timeout for graceful shutdown.
const GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(60);

/// Maximum `SYN` retries before the remote destination is considered unreachable.
const MAX_SYN_RETRIES: usize = 5usize;

/// Direction of stream.
pub enum Direction {
    /// Inbound stream.
    Inbound,

    /// Outbound stream.
    Outbound,
}

/// Events emitted by [`StreamManager`].
pub enum StreamManagerEvent {
    /// Stream opened.
    StreamOpened {
        /// ID of remote destination.
        destination_id: DestinationId,

        /// Direction of the stream.
        direction: Direction,
    },

    /// Stream closed.
    StreamClosed {
        /// ID of remote destination.
        destination_id: DestinationId,
    },

    /// Outbound stream rejected.
    StreamRejected {
        /// ID of remote destination.
        destination_id: DestinationId,
    },

    /// Send packet.
    SendPacket {
        /// Delivery style.
        delivery_style: DeliveryStyle,

        /// Destination port.
        dst_port: u16,

        /// Packet.
        packet: Vec<u8>,

        /// Source port.
        src_port: u16,
    },

    /// [`StreamManager`] has been shut down.
    ShutDown,
}

/// Shutdown handler.
enum ShutdownHandler<R: Runtime> {
    /// Shutdown has not been requested.
    Idle,

    /// Shutdown has been requested and a timer for forcible shutdown has been started.
    ShutdownRequested {
        /// Shutdown timer.
        ///
        /// See [`GRACEFUL_SHUTDOWN_TIMEOUT`] for more details.
        timer: R::Timer,
    },

    /// [`StreamManager`] has been shut down.
    ShutDown,
}

impl<R: Runtime> ShutdownHandler<R> {
    /// Create new [`ShutdownHandler`].
    fn new() -> Self {
        ShutdownHandler::Idle
    }

    /// Is [`StreamManager`] shutting down.
    fn shutting_down(&self) -> bool {
        core::matches!(self, Self::ShutdownRequested { .. })
    }

    /// Shut down [`StreamManager`].
    fn start_shutdown(&mut self) {
        *self = ShutdownHandler::ShutdownRequested {
            timer: R::timer(GRACEFUL_SHUTDOWN_TIMEOUT),
        };
    }

    /// Mark [`StreamManager`] as shut down.
    ///
    /// Any further calls to [`StreamManger::poll_next()`] will return `Poll::Pending`.
    fn set_as_shutdown(&mut self) {
        *self = ShutdownHandler::ShutDown;
    }
}

/// Shutdown event.
enum ShutdownEvent {
    /// Forcibly shut down [`StreamManager`].
    ShutDown,

    /// [`StreamManager`] has already been shutdown.
    AlreadyShutDown,
}

impl<R: Runtime> Future for ShutdownHandler<R> {
    type Output = ShutdownEvent;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = Pin::into_inner(self);

        match this {
            ShutdownHandler::Idle => Poll::Pending,
            ShutdownHandler::ShutdownRequested { timer } => match timer.poll_unpin(cx) {
                Poll::Pending => Poll::Pending,
                Poll::Ready(_) => {
                    this.set_as_shutdown();
                    Poll::Ready(ShutdownEvent::ShutDown)
                }
            },
            ShutdownHandler::ShutDown => Poll::Ready(ShutdownEvent::AlreadyShutDown),
        }
    }
}

/// Pending outbound stream.
struct PendingOutboundStream<R: Runtime> {
    /// ID of the remote destination.
    destination_id: DestinationId,

    /// Destination port.
    dst_port: u16,

    /// Number of `SYN`s sent thus far.
    num_sent: usize,

    /// Serialised `SYN` packet.
    packet: Vec<u8>,

    /// Routing path handle.
    routing_path_handle: RoutingPathHandle<R>,

    /// Has the stream configured to be silent.
    silent: bool,

    /// SAMv3 client socket that was used to send `STREAM CONNECT` command.
    socket: Box<SamSocket<R>>,

    /// Source port.
    src_port: u16,
}

/// I2P virtual stream manager.
pub struct StreamManager<R: Runtime> {
    /// TX channels for sending [`Packet`]'s to active streams.
    ///
    /// Indexed with receive stream ID.
    active: HashMap<u32, (DestinationId, Sender<StreamEvent>)>,

    /// Destination of the session the stream manager is bound to.
    destination: Destination,

    /// ID of the `Destination` the stream manager is bound to.
    destination_id: DestinationId,

    /// Destination ID -> stream ID mappings.
    destination_streams: HashMap<DestinationId, HashSet<u32>>,

    /// Stream listener.
    listener: StreamListener<R>,

    /// RX channel for receiving [`Packet`]s from active streams.
    outbound_rx: Receiver<(DeliveryStyle, Vec<u8>, u16, u16)>,

    /// Timers for outbound streams.
    outbound_timers: R::JoinSet<u32>,

    /// TX channel given to active streams they use for sending messages to the network.
    outbound_tx: Sender<(DeliveryStyle, Vec<u8>, u16, u16)>,

    /// Pending events.
    pending_events: VecDeque<StreamManagerEvent>,

    /// Pending inbound streams.
    ///
    /// Indexed by the remote-selected receive stream ID.
    pending_inbound: HashMap<u32, PendingStream<R>>,

    /// Pending outbound streams.
    pending_outbound: HashMap<u32, PendingOutboundStream<R>>,

    /// Timer for pruning stale pending streams.
    prune_timer: R::Timer,

    /// Shutdown handler.
    shutdown_handler: ShutdownHandler<R>,

    /// Signing key.
    signing_key: SigningPrivateKey,

    /// Active streams.
    streams: R::JoinSet<u32>,
}

impl<R: Runtime> StreamManager<R> {
    /// Create new [`StreamManager`].
    pub fn new(destination: Destination, signing_key: SigningPrivateKey) -> Self {
        let (outbound_tx, outbound_rx) = channel(STREAM_MANAGER_CHANNEL_SIZE);
        let destination_id = destination.id();

        Self {
            active: HashMap::new(),
            destination,
            destination_id: destination_id.clone(),
            destination_streams: HashMap::new(),
            listener: StreamListener::new(destination_id),
            outbound_rx,
            outbound_timers: R::join_set(),
            outbound_tx,
            pending_events: VecDeque::new(),
            pending_inbound: HashMap::new(),
            pending_outbound: HashMap::new(),
            prune_timer: R::timer(PENDING_STREAM_PRUNE_THRESHOLD),
            shutdown_handler: ShutdownHandler::new(),
            signing_key,
            streams: R::join_set(),
        }
    }

    /// Handle message with `SYN`.
    ///
    /// If this a response to an outbound stream sent by us, convert the pending stream to an active
    /// stream by allocating it a new channel and spawning it in a background task.
    ///
    /// If this a new inbound stream ensure that signature and destination are in the message and
    /// verify their validity. Additionally ensure that the NACK field contains local destination's
    /// ID. If validity checks pass, send the message to a listener if it exists. If there are no
    /// active listeners, mark the stream as pending and start a timer for waiting for a new
    /// listener to be registered. If no listener is registered within the time window, the stream
    /// is closed.
    fn on_synchronize(
        &mut self,
        packet: Vec<u8>,
        src_port: u16,
        dst_port: u16,
    ) -> Result<(), StreamingError> {
        let Packet {
            send_stream_id,
            recv_stream_id,
            nacks,
            flags,
            payload,
            ..
        } = Packet::parse::<R>(&packet)?;

        // verify signature
        let signature = flags.signature().ok_or_else(|| {
            tracing::warn!(
                target: LOG_TARGET,
                ?recv_stream_id,
                ?send_stream_id,
                "signature missing from syn packet",
            );

            StreamingError::SignatureMissing
        })?;
        let destination = flags.from_included().as_ref().ok_or_else(|| {
            tracing::warn!(
                target: LOG_TARGET,
                ?recv_stream_id,
                ?send_stream_id,
                "destination missing from syn packet",
            );
            StreamingError::DestinationMissing
        })?;
        let destination_id = destination.id();

        {
            // if the packet included an offline signature, use the verifying key specified in the
            // offline signature to verify the packet's signature
            //
            // otherwise use the verifying key specified in the destination
            let verifying_key = match flags.offline_signature() {
                None => destination.verifying_key(),
                Some(key) => key,
            };

            // signature field is the last field of options, meaning it starts at
            // `original.len() - payload.len() - verifying_key.signature_len()`
            //
            // in order to verify the signature, the calculated signature must be filled
            // with zeros
            let mut original = packet.to_vec();

            if original.len() < payload.len() + verifying_key.signature_len() {
                tracing::warn!(
                    target: LOG_TARGET,
                    local = %self.destination_id,
                    remote = %destination_id,
                    ?recv_stream_id,
                    ?send_stream_id,
                    "cannot verify signature, packet is too short",
                );
                return Err(StreamingError::Malformed(PacketParseError::PacketTooShort));
            }

            let signature_start = original.len() - payload.len() - verifying_key.signature_len();
            original[signature_start..signature_start + verifying_key.signature_len()]
                .copy_from_slice(&vec![0u8; verifying_key.signature_len()]);

            verifying_key.verify(&original, signature).map_err(|error| {
                tracing::warn!(
                    target: LOG_TARGET,
                    local = %self.destination_id,
                    remote = %destination_id,
                    ?recv_stream_id,
                    ?send_stream_id,
                    ?error,
                    "failed to verify packet signature"
                );

                StreamingError::InvalidSignature
            })?;
        }

        // if this is a syn-ack for an outbound stream, initialize state
        // for a new stream future and spawn it in the background
        if let Some(PendingOutboundStream {
            destination_id,
            silent,
            socket,
            dst_port,
            src_port,
            routing_path_handle,
            ..
        }) = self.pending_outbound.remove(&send_stream_id)
        {
            tracing::trace!(
                target: LOG_TARGET,
                local = %self.destination_id,
                remote = %destination_id,
                ?recv_stream_id,
                ?send_stream_id,
                "outbound stream accepted",
            );

            self.spawn_stream(
                SocketKind::Connect {
                    routing_path_handle,
                    silent,
                    socket: socket.into_inner(),
                },
                recv_stream_id,
                destination_id.clone(),
                None,
                StreamKind::Outbound {
                    dst_port,
                    send_stream_id,
                    src_port,
                    payload: payload.to_vec(),
                },
            );

            return Ok(());
        }

        // verify that the nacks field contains local destination id for replay protection
        if nacks.len() != 8 {
            tracing::debug!(
                target: LOG_TARGET,
                local = %self.destination_id,
                remote = %destination_id,
                ?recv_stream_id,
                ?send_stream_id,
                "destination id for replay protection not set",
            );
            return Err(StreamingError::ReplayProtectionCheckFailed);
        }

        let constructed_destination_id = nacks
            .into_iter()
            .fold(BytesMut::with_capacity(32), |mut acc, x| {
                acc.put_slice(&x.to_be_bytes());
                acc
            })
            .freeze()
            .to_vec();

        if constructed_destination_id != self.destination_id.to_vec() {
            return Err(StreamingError::ReplayProtectionCheckFailed);
        }

        tracing::info!(
            target: LOG_TARGET,
            local = %self.destination_id,
            remote = %destination_id,
            ?recv_stream_id,
            ?send_stream_id,
            payload_len = ?payload.len(),
            "inbound stream accepted",
        );

        // attempt to acquire a socket from `StreamListener`
        //
        // if no listener exists, the stream is marked as pending
        match self.listener.pop_socket() {
            Some(socket) => self.spawn_stream(
                socket,
                recv_stream_id,
                destination.id(),
                Some(destination.clone()),
                StreamKind::Inbound {
                    payload: payload.to_vec(),
                },
            ),
            None => {
                tracing::info!(
                    target: LOG_TARGET,
                    local = %self.destination_id,
                    remote = %destination_id,
                    ?recv_stream_id,
                    ?send_stream_id,
                    "inbound stream but no available listeners",
                );

                // create new pending stream and send syn-ack for it
                let destination_id = destination.id();

                let (pending, packet) = PendingStream::new(
                    &self.destination,
                    destination.clone(),
                    recv_stream_id,
                    payload.to_vec(),
                    &self.signing_key,
                );

                let _ = self.outbound_tx.try_send((
                    DeliveryStyle::Unspecified {
                        destination_id: destination_id.clone(),
                    },
                    packet,
                    dst_port,
                    src_port,
                ));

                self.pending_inbound.insert(recv_stream_id, pending);
                self.destination_streams
                    .entry(destination_id.clone())
                    .or_default()
                    .insert(recv_stream_id);
            }
        }

        Ok(())
    }

    /// Spawn new [`Stream`] in the background.
    ///
    /// This function can spawn streams of two different kinds:
    ///  - streams where no packet exchange has happened yet (fresh streams)
    ///  - streams where packet exchange has happened (pending streams)
    ///
    /// If the stream is fresh,
    fn spawn_stream(
        &mut self,
        socket: SocketKind<R>,
        recv_stream_id: u32,
        destination_id: DestinationId,
        destination: Option<Destination>,
        stream_kind: StreamKind,
    ) {
        // create context for the stream
        //
        // since this is an inbound stream, the stream will be indexed in `active` by the
        // remote-chosen receive stream id and the local stream will generate itself a random id
        // when it starts and uses that for sending
        let (tx, rx) = channel(STREAM_CHANNEL_SIZE);
        let context = StreamContext {
            destination: self.destination.clone(),
            cmd_rx: rx,
            event_tx: self.outbound_tx.clone(),
            local: self.destination_id.clone(),
            recv_stream_id,
            remote: destination_id.clone(),
            signing_key: self.signing_key.clone(),
        };

        // if the socket wasn't configured to be silent, send the remote's destination
        // to client before the socket is convered into a regural tcp stream
        let initial_message = match &socket {
            // `destination` must exist if this is an inbound stream
            SocketKind::Accept { silent, .. } | SocketKind::Forwarded { silent, .. } if !silent =>
                Some(
                    format!(
                        "{}\n",
                        base64_encode(destination.expect("to exist").serialized())
                    )
                    .into_bytes(),
                ),
            SocketKind::Connect { silent, .. } if !silent =>
                Some(b"STREAM STATUS RESULT=OK\n".to_vec()),
            _ => None,
        };

        // store the tx channel of the stream in `StreamManager`'s context
        //
        // `StreamManager` sends all inbound messages with `recv_stream_id` to this stream and all
        // outbound messages from the stream to remote peer are send through `event_tx`
        self.active.insert(recv_stream_id, (destination_id.clone(), tx));
        self.destination_streams
            .entry(destination_id.clone())
            .or_default()
            .insert(recv_stream_id);

        // if socket kind is `Connect` this is an outbound stream
        //
        // accept/forward indicates an inbound stream
        match &socket {
            SocketKind::Connect { .. } =>
                self.pending_events.push_back(StreamManagerEvent::StreamOpened {
                    destination_id: destination_id.clone(),
                    direction: Direction::Outbound,
                }),
            SocketKind::Accept { .. } | SocketKind::Forwarded { .. } =>
                self.pending_events.push_back(StreamManagerEvent::StreamOpened {
                    destination_id: destination_id.clone(),
                    direction: Direction::Inbound,
                }),
        }

        // start new future for the stream in the background
        //
        // if `SILENT` was set to false, the first message `Stream` sends to the connected
        // client is the destination id of the remote peer after which it transfers to send
        // anything that was received from the remote peer via `StreamManager`
        //
        // if the listener was created with `STREAM FORWARD`, a new tcp connection must be opened to
        // the forwarded listener before the stream can be started and if the listener is not
        // active, the stream is closed immediately
        match socket {
            SocketKind::Connect {
                socket,
                routing_path_handle,
                ..
            } => self.streams.push(Stream::<R>::new(
                socket,
                initial_message,
                context,
                StreamConfig::default(),
                stream_kind,
                routing_path_handle,
            )),
            SocketKind::Accept {
                pending_routing_path_handle,
                socket,
                ..
            } => {
                self.streams.push(async move {
                    let Some(routing_path_handle) =
                        pending_routing_path_handle.bind::<R>(destination_id).await
                    else {
                        tracing::warn!(
                            target: LOG_TARGET,
                            "failed to bind routing path handle, cannot accept inbound stream",
                        );
                        return context.recv_stream_id;
                    };

                    Stream::<R>::new(
                        socket,
                        initial_message,
                        context,
                        StreamConfig::default(),
                        stream_kind,
                        routing_path_handle,
                    )
                    .await
                });
            }
            SocketKind::Forwarded {
                future,
                pending_routing_path_handle,
                ..
            } => self.streams.push(async move {
                let Some(routing_path_handle) =
                    pending_routing_path_handle.bind::<R>(destination_id).await
                else {
                    tracing::warn!(
                        target: LOG_TARGET,
                        "failed to bind routing path handle, cannot accept inbound stream",
                    );
                    return context.recv_stream_id;
                };

                let Some(stream) = future.await else {
                    tracing::warn!(
                        target: LOG_TARGET,
                        "failed to open tcp stream to forwarded listener",
                    );
                    return context.recv_stream_id;
                };

                Stream::<R>::new(
                    stream,
                    initial_message,
                    context,
                    StreamConfig::default(),
                    stream_kind,
                    routing_path_handle,
                )
                .await
            }),
        }
    }

    /// Handle ready listener.
    ///
    /// An inbound stream may be received while there are no listeners or the listeners are busy
    /// sending status messages to the connected client. In those cases the inbound streams are put
    /// in a pending state where they remain waiting for a listener to be registered for a period of
    /// time before they're destroyed as session owner is apparently not interested in accepting
    /// inbound streams.
    ///
    /// When a listener is registered and it is ready to serve an inbound stream, [`StreamListener`]
    /// emits an event informing the [`StreamManager`] of it and the stream manager must check if
    /// there are any pending streams and if so, start event loops for the streams. If there are no
    /// pending streams, the event is ignored.
    fn on_listener_ready(&mut self) {
        tracing::debug!(
            target: LOG_TARGET,
            local = %self.destination_id,
            num_pending = ?self.pending_inbound.len(),
            "listener ready",
        );

        // loop through all pending streams until either:
        //  a) there are no more pending streams
        //  b) there are no more available listeners
        loop {
            let Some(stream_id) = self.pending_inbound.keys().next().copied() else {
                return;
            };

            let Some(socket) = self.listener.pop_socket() else {
                return;
            };

            // stream must exist since it was checked earlier that it's in the map
            let PendingStream {
                remote_destination,
                destination_id,
                send_stream_id,
                packets,
                seq_nro,
                ..
            } = self.pending_inbound.remove(&stream_id).expect("to exist");

            // spawn new task for the stream in the background
            self.spawn_stream(
                socket,
                stream_id,
                destination_id,
                Some(remote_destination),
                StreamKind::InboundPending {
                    send_stream_id,
                    seq_nro,
                    packets,
                },
            );
        }
    }

    /// Register listener into [`StreamManager`].
    ///
    /// This function calls [`StreamListener::register_listener()`] which either rejects `kind`
    /// because it's in conflict with an active listener kind, accepts the listener and possibly
    /// notifies the client of if it the socket wasn't configured to be silent. Client notification
    /// happens in the background, making the listener temporarily inactive. Once the client has
    /// been notified of listener acceptance, [`StreamManager`] is notified via
    /// [`StreamListener::poll_next()`] that there is an active listener.
    ///
    /// If the listener was configured to be silent and it was of type [`ListenerKind::Ephemeral`],
    /// the listener is immediately available for use. In these cases,
    /// [`StreamListener::register_listener()`] returns `Ok(true)` to indicate that
    /// [`StreamManager`] can accept a pending inbound stream using the registered listener,
    /// if a pending stream exists.
    pub fn register_listener(&mut self, kind: ListenerKind<R>) -> Result<(), StreamingError> {
        if self.listener.register_listener(kind)? {
            self.on_listener_ready();
        }

        Ok(())
    }

    /// Handle `payload` received from `src_port` to `dst_port`.
    pub fn on_packet(&mut self, payload: I2cpPayload) -> Result<(), StreamingError> {
        let I2cpPayload {
            payload,
            dst_port,
            src_port,
            ..
        } = payload;

        let packet = Packet::peek(&payload).ok_or(StreamingError::Malformed(
            PacketParseError::InvalidBitstream,
        ))?;

        tracing::trace!(
            target: LOG_TARGET,
            local = %self.destination_id,
            send_stream_id = ?packet.send_stream_id(),
            recv_stream_id = ?packet.recv_stream_id(),
            seq_nro = ?packet.seq_nro(),
            "inbound message",
        );

        // forward received packet to an active handler if it exists
        if let Some((_, tx)) = self.active.get(&packet.recv_stream_id()) {
            if let Err(error) = tx.try_send(StreamEvent::Packet { packet: payload }) {
                tracing::debug!(
                    target: LOG_TARGET,
                    local = %self.destination_id,
                    send_stream_id = ?packet.send_stream_id(),
                    recv_stream_id = ?packet.recv_stream_id(),
                    seq_nro = ?packet.seq_nro(),
                    ?error,
                    "failed to send packet to stream, dropping",
                );
            }

            return Ok(());
        }

        if let Some(stream) = self.pending_inbound.get_mut(&packet.recv_stream_id()) {
            match stream.on_packet(payload) {
                PendingStreamResult::DoNothing => {}
                PendingStreamResult::Send { packet } => {
                    let _ = self.outbound_tx.try_send((
                        DeliveryStyle::Unspecified {
                            destination_id: stream.destination_id.clone(),
                        },
                        packet,
                        dst_port,
                        src_port,
                    ));
                }
                PendingStreamResult::SendAndDestroy { packet: pkt } => {
                    tracing::debug!(
                        target: LOG_TARGET,
                        local = %self.destination_id,
                        recv_stream_id = ?packet.recv_stream_id(),
                        "send packet and destroy pending stream",
                    );
                    let _ = self.outbound_tx.try_send((
                        DeliveryStyle::Unspecified {
                            destination_id: stream.destination_id.clone(),
                        },
                        pkt,
                        dst_port,
                        src_port,
                    ));

                    if let Some(PendingStream { destination_id, .. }) =
                        self.pending_inbound.remove(&packet.recv_stream_id())
                    {
                        if let Some(stream) = self.destination_streams.get_mut(&destination_id) {
                            stream.remove(&packet.recv_stream_id());
                        }
                    }
                }
                PendingStreamResult::Destroy => {
                    tracing::debug!(
                        target: LOG_TARGET,
                        local = %self.destination_id,
                        recv_stream_id = ?packet.recv_stream_id(),
                        "destroy pending stream",
                    );

                    if let Some(PendingStream { destination_id, .. }) =
                        self.pending_inbound.remove(&packet.recv_stream_id())
                    {
                        if let Some(stream) = self.destination_streams.get_mut(&destination_id) {
                            stream.remove(&packet.recv_stream_id());
                        }
                    }
                }
            }

            return Ok(());
        }

        // handle new stream
        //
        // both deserialized packet and the original payload are returned
        // so the included signature can be verified
        //
        // any new streams are ignored if stream manager is shutting down
        if packet.synchronize() && !self.shutdown_handler.shutting_down() {
            return self.on_synchronize(payload, src_port, dst_port);
        }

        let Packet {
            send_stream_id,
            recv_stream_id,
            seq_nro,
            ack_through,
            nacks,
            resend_delay,
            flags,
            payload,
        } = Packet::parse::<R>(&payload)?;

        tracing::debug!(
            target: LOG_TARGET,
            local = %self.destination_id,
            ?send_stream_id,
            ?recv_stream_id,
            ?seq_nro,
            ?ack_through,
            ?nacks,
            ?resend_delay,
            %flags,
            payload_len = ?payload.len(),
            "ignoring unrecognized packet",
        );

        Ok(())
    }

    /// Create outbound stream to remote peer identfied by `destination_id`.
    ///
    /// Construct initial `SYN` packet and create pending outbound stream.
    ///
    /// Returns the initial packet and the selected receive stream ID which the caller
    /// can use to remove the pending stream if the session is rejected at a lower layer.
    pub fn create_stream(
        &mut self,
        destination_id: DestinationId,
        mut routing_path_handle: RoutingPathHandle<R>,
        socket: Box<SamSocket<R>>,
        options: HashMap<String, String>,
    ) -> (u32, BytesMut, DeliveryStyle, u16, u16) {
        let silent = options
            .get("SILENT")
            .is_some_and(|value| value.parse::<bool>().unwrap_or(false));
        let src_port = options
            .get("FROM_PORT")
            .map_or(0u16, |value| value.parse::<u16>().unwrap_or(0u16));
        let dst_port = options
            .get("TO_PORT")
            .map_or(0u16, |value| value.parse::<u16>().unwrap_or(0u16));

        // generate free receive stream id
        let recv_stream_id = {
            let mut rng = R::rng();

            loop {
                let stream_id = rng.next_u32();

                if !self.active.contains_key(&stream_id)
                    && !self.pending_outbound.contains_key(&stream_id)
                {
                    break stream_id;
                }
            }
        };

        let packet = PacketBuilder::new(recv_stream_id)
            .with_send_stream_id(0u32)
            .with_replay_protection(&destination_id)
            .with_synchronize()
            .with_signature()
            .with_from_included(&self.destination)
            .build_and_sign(&self.signing_key);

        tracing::debug!(
            target: LOG_TARGET,
            local = %self.destination_id,
            remote = %destination_id,
            ?recv_stream_id,
            "open stream",
        );

        let delivery_style = match routing_path_handle.routing_path() {
            None => DeliveryStyle::Unspecified {
                destination_id: destination_id.clone(),
            },
            Some(routing_path) => DeliveryStyle::ViaRoute { routing_path },
        };

        // create pending stream and start timer for retrying `SYN` if the remote doesn't respond to
        // the first packet
        //
        // `SYN` is retried 3 times before the remote destination is considered unreachable
        self.pending_outbound.insert(
            recv_stream_id,
            PendingOutboundStream {
                destination_id: destination_id.clone(),
                dst_port,
                num_sent: 1usize,
                packet: packet.clone().to_vec(),
                routing_path_handle,
                silent,
                socket,
                src_port,
            },
        );
        self.destination_streams
            .entry(destination_id)
            .or_default()
            .insert(recv_stream_id);
        self.outbound_timers.push(async move {
            R::delay(SYN_RETRY_TIMEOUT).await;
            recv_stream_id
        });

        (recv_stream_id, packet, delivery_style, src_port, dst_port)
    }

    /// Remove all streaming context associated with `destination_id`.
    pub fn remove_session(&mut self, destination_id: &DestinationId) {
        let Some(streams) = self.destination_streams.remove(destination_id) else {
            return;
        };

        tracing::debug!(
            target: LOG_TARGET,
            local = %self.destination_id,
            remote = %destination_id,
            num_streams = ?streams.len(),
            "remove session"
        );

        streams.into_iter().for_each(|stream_id| {
            self.active.remove(&stream_id);
            self.pending_inbound.remove(&stream_id);
            self.pending_outbound.remove(&stream_id);
        });
    }

    /// Shut down [`StreamManager`].
    ///
    /// Send shutdown signal for each active stream which causes them to send a `CLOSE` packet to
    /// remote. After all streams have exited, the stream manager can be shut down.
    ///
    /// A timer is also started which
    ///
    /// If there are no active streams, the stream manager is shut down right away.
    pub fn shutdown(&mut self) {
        tracing::info!(
            target: LOG_TARGET,
            local = %self.destination_id,
            "shut down stream manager",
        );

        self.active.values().for_each(|(_, tx)| {
            if let Err(error) = tx.try_send(StreamEvent::ShutDown) {
                tracing::error!(
                    target: LOG_TARGET,
                    local = %self.destination_id,
                    ?error,
                    "failed to send shutdown signal to active stream",
                );
            }
        });

        self.shutdown_handler.start_shutdown();
    }
}

impl<R: Runtime> futures::Stream for StreamManager<R> {
    type Item = StreamManagerEvent;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if let Some(event) = self.pending_events.pop_front() {
            return Poll::Ready(Some(event));
        }

        // poll shutdown handler
        //
        // if shutdown hasn't been requested or the graceful shutdown timer is active,
        // `shutdown_handler` keeps returning `Poll::Pending`
        //
        // once the timer expires, a graceful shutdown is skipped and stream manager is forcibly
        // shut down, without gracefully closing all open streams
        //
        // after that (or after all streams have been gracefully shut down), the `shutdown_handler`
        // is set to a shut down state and it keeps returning [`ShutdownEvent::AlreadyShutdown`]
        // which short-circuits this stream implementation and keeps returning `Poll::Pending`
        //
        // this is done so that stream manager doesn't get polled after it has been shut down which
        // might happen because the stream manager is shut down before the sam session that owns the
        // manager is shut down
        match self.shutdown_handler.poll_unpin(cx) {
            Poll::Pending => {}
            Poll::Ready(ShutdownEvent::ShutDown) => {
                tracing::warn!(
                    target: LOG_TARGET,
                    local = %self.destination_id,
                    num_active = ?self.active.len(),
                    "forcibly shutting down stream manager",
                );
                return Poll::Ready(Some(StreamManagerEvent::ShutDown));
            }
            Poll::Ready(ShutdownEvent::AlreadyShutDown) => return Poll::Pending,
        }

        match self.outbound_rx.poll_recv(cx) {
            Poll::Pending => {}
            Poll::Ready(None) => return Poll::Ready(None),
            Poll::Ready(Some((delivery_style, packet, src_port, dst_port))) =>
                return Poll::Ready(Some(StreamManagerEvent::SendPacket {
                    delivery_style,
                    dst_port,
                    packet,
                    src_port,
                })),
        }

        loop {
            match self.streams.poll_next_unpin(cx) {
                Poll::Pending => break,
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Ready(Some(stream_id)) => {
                    tracing::debug!(
                        target: LOG_TARGET,
                        local = %self.destination_id,
                        ?stream_id,
                        "stream closed"
                    );

                    // active stream may not exist if it was removed by calling
                    // `StreamManager::remove_session()`
                    let Some((destination_id, _)) = self.active.remove(&stream_id) else {
                        tracing::debug!(
                            target: LOG_TARGET,
                            local = %self.destination_id,
                            ?stream_id,
                            "active stream doesn't exist",
                        );
                        continue;
                    };

                    if self.streams.is_empty() && self.shutdown_handler.shutting_down() {
                        tracing::info!(
                            target: LOG_TARGET,
                            local = %self.destination_id,
                            "stream manager has been shut down",
                        );

                        self.shutdown_handler.set_as_shutdown();
                        self.pending_events.push_back(StreamManagerEvent::ShutDown);
                    }

                    return Poll::Ready(Some(StreamManagerEvent::StreamClosed { destination_id }));
                }
            }
        }

        loop {
            match self.listener.poll_next_unpin(cx) {
                Poll::Pending => break,
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Ready(Some(StreamListenerEvent::ListenerReady)) => self.on_listener_ready(),
            }
        }

        loop {
            match self.outbound_timers.poll_next_unpin(cx) {
                Poll::Pending => break,
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Ready(Some(stream_id)) => {
                    let Some(PendingOutboundStream {
                        destination_id,
                        packet,
                        ref mut num_sent,
                        dst_port,
                        src_port,
                        routing_path_handle,
                        ..
                    }) = self.pending_outbound.get_mut(&stream_id)
                    else {
                        continue;
                    };

                    // pending stream still exists, check if the packet should be resent
                    // or if the stream should be destroyed
                    if *num_sent < MAX_SYN_RETRIES {
                        let dst_port = *dst_port;
                        let src_port = *src_port;
                        let packet = packet.clone();
                        *num_sent += 1;

                        // poll routing path to get any tunnel updates
                        let _ = routing_path_handle.poll_unpin(cx);

                        let Some(routing_path) = routing_path_handle.recreate_routing_path() else {
                            tracing::debug!(
                                target: LOG_TARGET,
                                %destination_id,
                                %num_sent,
                                "unable to resend `SYN`, no routing path available",
                            );

                            self.outbound_timers.push(async move {
                                R::delay(SYN_RETRY_TIMEOUT).await;
                                stream_id
                            });

                            continue;
                        };

                        tracing::debug!(
                            target: LOG_TARGET,
                            local = %self.destination_id,
                            ?stream_id,
                            "resend `SYN`",
                        );

                        // create new timer for the new syn packet
                        //
                        // the future is guaranteed to be polled as we return from this branch
                        self.outbound_timers.push(async move {
                            R::delay(SYN_RETRY_TIMEOUT).await;
                            stream_id
                        });

                        return Poll::Ready(Some(StreamManagerEvent::SendPacket {
                            delivery_style: DeliveryStyle::ViaRoute { routing_path },
                            dst_port,
                            packet,
                            src_port,
                        }));
                    } else {
                        // stream must exist since it was just fetched from `pending_outbound`
                        let PendingOutboundStream {
                            destination_id,
                            mut socket,
                            ..
                        } = self.pending_outbound.remove(&stream_id).expect("to exist");

                        tracing::debug!(
                            target: LOG_TARGET,
                            local = %self.destination_id,
                            ?stream_id,
                            "remote didn't reply after 3 tries, closing stream",
                        );

                        // send rejection to client and return event to `SamSession`
                        // indicating that the connection failed
                        R::spawn(async move {
                            let _ = socket
                                .send_message_blocking(
                                    b"STREAM STATUS RESULT=CANT_REACH_PEER\n".to_vec(),
                                )
                                .await;
                        });

                        return Poll::Ready(Some(StreamManagerEvent::StreamRejected {
                            destination_id,
                        }));
                    }
                }
            }
        }

        if let Poll::Ready(()) = self.prune_timer.poll_unpin(cx) {
            self.pending_inbound
                .iter()
                .filter_map(|(stream_id, pending_stream)| {
                    (pending_stream.established.elapsed() > PENDING_STREAM_PRUNE_THRESHOLD)
                        .then_some(*stream_id)
                })
                .collect::<HashSet<_>>()
                .into_iter()
                .for_each(|stream_id| {
                    tracing::debug!(
                        local = %self.destination_id,
                        ?stream_id,
                        "pruning stale pending stream",
                    );
                    self.pending_inbound.remove(&stream_id);
                });

            // create new timer and register it into the executor
            {
                self.prune_timer = R::timer(PENDING_STREAM_PRUNE_THRESHOLD);
                let _ = self.prune_timer.poll_unpin(cx);
            }
        }

        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        destination::routing_path::{PendingRoutingPathHandle, RoutingPathManager},
        error::QueryError,
        primitives::{Destination, Lease, RouterId, TunnelId},
        protocol::Protocol,
        runtime::{
            mock::{MockRuntime, MockTcpStream},
            TcpStream,
        },
        sam::{protocol::streaming::packet::PacketBuilder, socket::SamSocket},
    };
    use tokio::{
        io::{AsyncBufReadExt, AsyncReadExt, BufReader},
        net::TcpListener,
    };

    use alloc::boxed::Box;

    struct SocketFactory {
        listener: TcpListener,
    }

    impl SocketFactory {
        pub async fn new() -> Self {
            Self {
                listener: TcpListener::bind("127.0.0.1:0").await.unwrap(),
            }
        }

        pub async fn socket(&self) -> (Box<SamSocket<MockRuntime>>, tokio::net::TcpStream) {
            let address = self.listener.local_addr().unwrap();
            let (stream1, stream2) =
                tokio::join!(self.listener.accept(), MockTcpStream::connect(address));
            let (stream, _) = stream1.unwrap();

            (Box::new(SamSocket::new(stream2.unwrap())), stream)
        }
    }

    #[tokio::test]
    async fn register_ephemeral_listener() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(listener.accept(), MockTcpStream::connect(address));

        let (_stream, _) = stream1.unwrap();
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream2.unwrap()));

        let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let mut manager = StreamManager::<MockRuntime>::new(destination, signing_key);

        assert!(manager
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: false,
                pending_routing_path_handle: PendingRoutingPathHandle::create(),
            })
            .is_ok());
    }

    #[tokio::test]
    async fn stale_pending_streams_are_pruned() {
        let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let destination_id = destination.id();
        let mut manager = StreamManager::<MockRuntime>::new(destination, signing_key);

        let mut packets = (0..3)
            .into_iter()
            .map(|stream_id| {
                let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
                let destination = Destination::new::<MockRuntime>(signing_key.public());
                let packet = PacketBuilder::new(stream_id as u32)
                    .with_synchronize()
                    .with_send_stream_id(0u32)
                    .with_replay_protection(&destination_id)
                    .with_from_included(&destination)
                    .with_signature()
                    .build_and_sign(&signing_key);

                packet.to_vec()
            })
            .collect::<VecDeque<_>>();

        // register syn packet and verify the stream is pending
        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 13u16,
                dst_port: 37u16,
                protocol: Protocol::Streaming,
                payload: packets.pop_front().unwrap(),
            })
            .is_ok());
        assert_eq!(manager.pending_inbound.len(), 1);

        // reset timer
        manager.prune_timer = MockRuntime::timer(PENDING_STREAM_PRUNE_THRESHOLD);

        // wait for a little while so all streams won't get pruned at the same time
        tokio::time::sleep(Duration::from_secs(20)).await;

        // register two other pending streams
        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 13u16,
                dst_port: 37u16,
                protocol: Protocol::Streaming,
                payload: packets.pop_front().unwrap(),
            })
            .is_ok());
        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 13u16,
                dst_port: 37u16,
                protocol: Protocol::Streaming,
                payload: packets.pop_front().unwrap(),
            })
            .is_ok());
        assert_eq!(manager.pending_inbound.len(), 3);

        // poll manager until the first stream is pruned
        //
        // verify that the other two are still left
        loop {
            futures::future::poll_fn(|cx| match manager.poll_next_unpin(cx) {
                Poll::Pending => Poll::Ready(()),
                Poll::Ready(_) => Poll::Ready(()),
            })
            .await;

            if manager.pending_inbound.len() != 3 {
                break;
            }

            tokio::time::sleep(Duration::from_secs(1)).await;
        }

        // verify that first pending stream is pruned and that the other two are still left
        assert!(!manager.pending_inbound.contains_key(&0));
        assert!(manager.pending_inbound.contains_key(&1));
        assert!(manager.pending_inbound.contains_key(&2));

        // reset timer
        manager.prune_timer = MockRuntime::timer(Duration::from_secs(20));

        // poll until the last two streams are also pruned
        loop {
            futures::future::poll_fn(|cx| match manager.poll_next_unpin(cx) {
                Poll::Pending => Poll::Ready(()),
                Poll::Ready(_) => panic!("invalid event"),
            })
            .await;

            if manager.pending_inbound.is_empty() {
                break;
            }

            tokio::time::sleep(Duration::from_secs(1)).await;
        }
    }

    #[tokio::test]
    async fn pending_stream_initialized_with_silent_listener() {
        let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let destination_id = destination.id();
        let mut manager = StreamManager::<MockRuntime>::new(destination, signing_key);

        // register new inbound stream and since there are no listener, the stream will be pending
        let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let remote_destination_id = destination.id();
        let packet = PacketBuilder::new(1337u32)
            .with_synchronize()
            .with_send_stream_id(0u32)
            .with_replay_protection(&destination_id)
            .with_from_included(&destination)
            .with_signature()
            .build_and_sign(&signing_key)
            .to_vec();

        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 13u16,
                dst_port: 37u16,
                protocol: Protocol::Streaming,
                payload: packet,
            })
            .is_ok());
        assert_eq!(manager.pending_inbound.len(), 1);

        // register new silent listener which is ready immediately
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(listener.accept(), MockTcpStream::connect(address));
        let (_stream, _) = stream1.unwrap();
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream2.unwrap()));

        assert!(manager
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: PendingRoutingPathHandle::create(),
            })
            .is_ok());
        assert!(manager.pending_inbound.is_empty());

        assert!(std::matches!(
            manager.next().await,
            Some(StreamManagerEvent::StreamOpened { .. })
        ));

        // poll manager until ack packet is received
        match tokio::time::timeout(Duration::from_secs(5), manager.next())
            .await
            .unwrap()
            .unwrap()
        {
            StreamManagerEvent::SendPacket {
                delivery_style,
                packet,
                ..
            } => {
                let Packet {
                    send_stream_id,
                    recv_stream_id,
                    flags,
                    ..
                } = Packet::parse::<MockRuntime>(&packet).unwrap();

                assert_eq!(delivery_style.destination_id(), &remote_destination_id);
                assert_eq!(send_stream_id, 1337u32);
                assert_ne!(recv_stream_id, 0u32);
                assert!(flags.synchronize());
            }
            _ => panic!("invalid event"),
        }
    }

    #[tokio::test]
    async fn pending_stream_initialized_with_non_silent_listener() {
        let local_signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
        let local_destination = Destination::new::<MockRuntime>(local_signing_key.public());
        let destination_id = local_destination.id();
        let mut manager =
            StreamManager::<MockRuntime>::new(local_destination.clone(), local_signing_key);

        // register new inbound stream and since there are no listener, the stream will be pending
        let remote_signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
        let remote_destination = Destination::new::<MockRuntime>(remote_signing_key.public());
        let serialized = base64_encode(remote_destination.serialize().to_vec());

        let remote_destination_id = remote_destination.id();
        let packet = PacketBuilder::new(1337u32)
            .with_synchronize()
            .with_send_stream_id(0u32)
            .with_replay_protection(&destination_id)
            .with_from_included(&remote_destination)
            .with_signature()
            .build_and_sign(&remote_signing_key)
            .to_vec();

        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 13u16,
                dst_port: 37u16,
                protocol: Protocol::Streaming,
                payload: packet,
            })
            .is_ok());
        assert_eq!(manager.pending_inbound.len(), 1);

        // register new silent listener which is ready immediately
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(listener.accept(), MockTcpStream::connect(address));
        let (stream, _) = stream1.unwrap();
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream2.unwrap()));
        let mut routing_path_manager =
            RoutingPathManager::<MockRuntime>::new(destination_id, vec![]);
        let pending_routing_path_handle = routing_path_manager.pending_handle();

        // spawn routing path in the background
        //
        // it't not used in the test but must be polled in order for the listener to
        // acquire a routing path to remote destination
        tokio::spawn(async move { while routing_path_manager.next().await.is_some() {} });

        assert!(manager
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: false,
                pending_routing_path_handle,
            })
            .is_ok());
        assert!(!manager.pending_inbound.is_empty());

        // poll manager until ack packet is received
        match tokio::time::timeout(Duration::from_secs(5), manager.next())
            .await
            .unwrap()
            .unwrap()
        {
            StreamManagerEvent::SendPacket {
                delivery_style,
                packet,
                ..
            } => {
                let Packet {
                    send_stream_id,
                    recv_stream_id,
                    flags,
                    ..
                } = Packet::parse::<MockRuntime>(&packet).unwrap();

                assert_eq!(delivery_style.destination_id(), &remote_destination_id);
                assert_eq!(send_stream_id, 1337u32);
                assert_ne!(recv_stream_id, 0u32);
                assert!(flags.synchronize());
            }
            _ => panic!("invalid event"),
        }

        // spawn stream manager in the background so it makes progress
        tokio::spawn(async move { while manager.next().await.is_some() {} });

        let mut reader = BufReader::new(stream);
        let mut response = String::new();

        // read stream status
        {
            reader.read_line(&mut response).await.unwrap();
            assert_eq!(response, String::from("STREAM STATUS RESULT=OK\n"));
        }

        // read destination
        {
            response.clear();
            reader.read_line(&mut response).await.unwrap();
            assert_eq!(response.trim_end(), serialized);
        }
    }

    #[tokio::test]
    async fn pending_stream_initialized_with_persistent_listener() {
        let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let destination_id = destination.id();
        let mut manager = StreamManager::<MockRuntime>::new(destination, signing_key);

        // register new inbound stream and since there are no listener, the stream will be pending
        let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let serialized = base64_encode(destination.serialized());
        let remote_destination_id = destination.id();
        let packet = PacketBuilder::new(1337u32)
            .with_synchronize()
            .with_send_stream_id(0u32)
            .with_replay_protection(&destination_id)
            .with_from_included(&destination)
            .with_signature()
            .build_and_sign(&signing_key)
            .to_vec();

        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());
        assert_eq!(manager.pending_inbound.len(), 1);

        // register new silent listener which is ready immediately
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let port = address.port();
        let (stream1, stream2) = tokio::join!(listener.accept(), MockTcpStream::connect(address));
        let (stream, _) = stream1.unwrap();
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream2.unwrap()));
        let mut routing_path_manager =
            RoutingPathManager::<MockRuntime>::new(destination_id, vec![]);
        let pending_routing_path_handle = routing_path_manager.pending_handle();

        // spawn routing path in the background
        //
        // it't not used in the test but must be polled in order for the listener to
        // acquire a routing path to remote destination
        tokio::spawn(async move { while routing_path_manager.next().await.is_some() {} });

        assert!(manager
            .register_listener(ListenerKind::Persistent {
                socket,
                port,
                silent: false,
                pending_routing_path_handle,
            })
            .is_ok());
        assert!(!manager.pending_inbound.is_empty());

        // poll manager until ack packet is received
        match tokio::time::timeout(Duration::from_secs(5), manager.next())
            .await
            .unwrap()
            .unwrap()
        {
            StreamManagerEvent::SendPacket {
                delivery_style,
                packet,
                ..
            } => {
                let Packet {
                    send_stream_id,
                    recv_stream_id,
                    flags,
                    ..
                } = Packet::parse::<MockRuntime>(&packet).unwrap();

                assert_eq!(delivery_style.destination_id(), &remote_destination_id);
                assert_eq!(send_stream_id, 1337u32);
                assert_ne!(recv_stream_id, 0u32);
                assert!(flags.synchronize());
            }
            _ => panic!("invalid event"),
        }

        // spawn stream manager in the background so it makes progress
        tokio::spawn(async move { while manager.next().await.is_some() {} });

        // read stream status
        {
            let mut reader = BufReader::new(stream);
            let mut response = String::new();

            reader.read_line(&mut response).await.unwrap();
            assert_eq!(response, String::from("STREAM STATUS RESULT=OK\n"));
        }

        // read destination
        {
            let (inbound_stream, _) = listener.accept().await.unwrap();
            let mut reader = BufReader::new(inbound_stream);
            let mut response = String::new();

            reader.read_line(&mut response).await.unwrap();
            assert_eq!(response.trim_end(), serialized);
        }
    }

    #[tokio::test]
    async fn pending_stream_with_buffered_data_initialized() {
        let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let destination_id = destination.id();
        let mut manager = StreamManager::<MockRuntime>::new(destination, signing_key);

        // register new inbound stream and since there are no listener, the stream will be pending
        let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let remote_destination_id = destination.id();
        let packet = PacketBuilder::new(1337u32)
            .with_synchronize()
            .with_send_stream_id(0u32)
            .with_replay_protection(&destination_id)
            .with_from_included(&destination)
            .with_signature()
            .build_and_sign(&signing_key)
            .to_vec();

        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());
        assert_eq!(manager.pending_inbound.len(), 1);

        // poll manager until ack packet is received
        let recv_stream_id = match tokio::time::timeout(Duration::from_secs(5), manager.next())
            .await
            .unwrap()
            .unwrap()
        {
            StreamManagerEvent::SendPacket {
                delivery_style,
                packet,
                ..
            } => {
                let Packet {
                    send_stream_id,
                    recv_stream_id,
                    flags,
                    ..
                } = Packet::parse::<MockRuntime>(&packet).unwrap();

                assert_eq!(delivery_style.destination_id(), &remote_destination_id);
                assert_eq!(send_stream_id, 1337u32);
                assert_ne!(recv_stream_id, 0u32);
                assert!(flags.synchronize());

                recv_stream_id
            }
            _ => panic!("invalid event"),
        };

        // send three data packets and verify that they're all ack'ed
        {
            let messages = vec![
                b"hello, world".to_vec(),
                b"testing 123".to_vec(),
                b"goodbye world".to_vec(),
            ];

            for (i, message) in messages.into_iter().enumerate() {
                let packet = PacketBuilder::new(1337u32)
                    .with_synchronize()
                    .with_send_stream_id(recv_stream_id)
                    .with_seq_nro(i as u32 + 1u32)
                    .with_payload(&message)
                    .build()
                    .to_vec();

                assert!(manager
                    .on_packet(I2cpPayload {
                        src_port: 0u16,
                        dst_port: 0u16,
                        protocol: Protocol::Streaming,
                        payload: packet
                    })
                    .is_ok());

                // poll manager until ack packet is received
                match tokio::time::timeout(Duration::from_secs(5), manager.next())
                    .await
                    .unwrap()
                    .unwrap()
                {
                    StreamManagerEvent::SendPacket {
                        delivery_style,
                        packet,
                        ..
                    } => {
                        let Packet {
                            send_stream_id,
                            recv_stream_id,
                            ack_through,
                            ..
                        } = Packet::parse::<MockRuntime>(&packet).unwrap();

                        assert_eq!(delivery_style.destination_id(), &remote_destination_id);
                        assert_eq!(send_stream_id, 1337u32);
                        assert_ne!(recv_stream_id, 0u32);
                        assert_eq!(ack_through, i as u32 + 1u32);
                    }
                    _ => panic!("invalid event"),
                }
            }
        }

        // verify that the stream is still pending
        assert_eq!(manager.pending_inbound.len(), 1);

        // register new silent listener which is ready immediately
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(listener.accept(), MockTcpStream::connect(address));
        let (mut stream, _) = stream1.unwrap();
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream2.unwrap()));

        let outbound = TunnelId::random();
        let inbound = Lease::random();
        let mut path_manager =
            RoutingPathManager::<MockRuntime>::new(destination_id.clone(), vec![outbound]);
        path_manager.register_leases(&destination_id, Ok(vec![inbound]));
        let pending_handle = path_manager.pending_handle();

        tokio::spawn(async move { while let Some(_) = path_manager.next().await {} });

        assert!(manager
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());
        assert!(manager.pending_inbound.is_empty());

        // poll manager in the background in order to drive the stream future forward
        tokio::spawn(async move { while let Some(_) = manager.next().await {} });

        // verify that the buffered data is returned to client
        let mut buffer = vec![0u8; 36];
        stream.read_exact(&mut buffer).await.unwrap();

        assert_eq!(buffer, b"hello, worldtesting 123goodbye world");
    }

    #[tokio::test]
    async fn outbound_stream_accepted() {
        let socket_factory = SocketFactory::new().await;

        let mut manager1 = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let mut manager2 = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let outbound1 = TunnelId::random();
        let inbound1 = Lease::random();
        let mut path_manager1 = RoutingPathManager::<MockRuntime>::new(
            manager1.destination_id.clone(),
            vec![outbound1],
        );
        let pending_handle = path_manager1.pending_handle();
        path_manager1.register_leases(&manager2.destination_id, Ok(vec![inbound1]));

        let outbound2 = TunnelId::random();
        let inbound2 = Lease::random();
        let mut path_manager2 = RoutingPathManager::<MockRuntime>::new(
            manager2.destination_id.clone(),
            vec![outbound2],
        );
        path_manager2.register_leases(&manager1.destination_id, Ok(vec![inbound2]));
        let handle = path_manager2.handle(manager1.destination_id.clone());

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = &mut path_manager1.next() => {}
                    _ = &mut path_manager2.next() => {}
                }
            }
        });

        // register listener for `manager1`
        let (socket, _) = socket_factory.socket().await;
        assert!(manager1
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());

        // create new oubound stream to `manager1`
        let (socket, client_stream) = socket_factory.socket().await;
        let (_stream_id, packet, _, _, _) = manager2.create_stream(
            manager1.destination_id.clone(),
            handle,
            socket,
            HashMap::new(),
        );

        assert!(manager1
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet.to_vec()
            })
            .is_ok());

        assert!(std::matches!(
            manager1.next().await,
            Some(StreamManagerEvent::StreamOpened { .. })
        ));

        let (destination_id, packet) =
            match tokio::time::timeout(Duration::from_secs(5), manager1.next())
                .await
                .unwrap()
                .unwrap()
            {
                StreamManagerEvent::SendPacket {
                    delivery_style,
                    packet,
                    ..
                } => (delivery_style.destination_id().clone(), packet),
                _ => panic!("invalid event"),
            };

        assert_eq!(destination_id, manager2.destination_id);
        assert!(manager2
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = manager1.next() => {}
                    _ = manager2.next() => {}
                }
            }
        });

        let mut reader = tokio::io::BufReader::new(client_stream);
        let mut response = String::new();
        reader.read_line(&mut response).await.unwrap();

        assert_eq!(response.as_str(), "STREAM STATUS RESULT=OK\n");
    }

    #[tokio::test(start_paused = true)]
    async fn outbound_stream_rejected() {
        let socket_factory = SocketFactory::new().await;
        let remote = DestinationId::random();

        let mut manager2 = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let mut path_manager = RoutingPathManager::<MockRuntime>::new(
            manager2.destination_id.clone(),
            vec![TunnelId::random()],
        );
        path_manager.register_leases(&remote, Ok(vec![Lease::random()]));

        // create new oubound stream to `manager1`
        let (socket, client_stream) = socket_factory.socket().await;
        let _ = manager2.create_stream(
            remote.clone(),
            path_manager.handle(remote.clone()),
            socket,
            HashMap::new(),
        );

        // verify the syn packet is sent 4 more times
        for _ in 0..4 {
            match tokio::time::timeout(Duration::from_secs(15), manager2.next())
                .await
                .expect("no timeout")
                .expect("to succeed")
            {
                StreamManagerEvent::SendPacket {
                    delivery_style,
                    packet,
                    ..
                } if delivery_style.destination_id() == &remote => {
                    assert!(Packet::parse::<MockRuntime>(&packet).unwrap().flags.synchronize());
                }
                _ => panic!("invalid event"),
            }
        }

        // verify that stream rejection is emitted
        match tokio::time::timeout(Duration::from_secs(15), manager2.next())
            .await
            .expect("no timeout")
            .expect("to succeed")
        {
            StreamManagerEvent::StreamRejected { destination_id } if destination_id == remote => {}
            _ => panic!("invalid event"),
        }

        let mut reader = BufReader::new(client_stream);
        let mut response = String::new();
        tokio::time::timeout(Duration::from_secs(15), reader.read_line(&mut response))
            .await
            .expect("no timeout")
            .expect("to succeed");

        assert_eq!(response, "STREAM STATUS RESULT=CANT_REACH_PEER\n");
    }

    #[tokio::test]
    async fn data_in_syn_packet_silent_ephemeral() {
        let socket_factory = SocketFactory::new().await;

        let mut manager = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let packet = PacketBuilder::new(1337u32)
            .with_synchronize()
            .with_send_stream_id(0u32)
            .with_replay_protection(&manager.destination.id())
            .with_from_included(&destination)
            .with_signature()
            .with_payload(b"hello, world")
            .build_and_sign(&signing_key)
            .to_vec();

        let outbound1 = TunnelId::random();
        let inbound1 = Lease::random();
        let mut path_manager1 =
            RoutingPathManager::<MockRuntime>::new(manager.destination_id.clone(), vec![outbound1]);
        let pending_handle = path_manager1.pending_handle();
        path_manager1.register_leases(&destination.id(), Ok(vec![inbound1]));

        tokio::spawn(async move { while let Some(_) = path_manager1.next().await {} });

        // register listener for `manager1`
        let (socket, mut client_socket) = socket_factory.socket().await;
        assert!(manager
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());

        // handle syn packet and spawn manager in the background
        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());

        tokio::spawn(async move { while let Some(_) = manager.next().await {} });

        // read the payload that was contained within the syn packet
        let mut buffer = [0u8; 12];
        tokio::time::timeout(
            Duration::from_secs(5),
            client_socket.read_exact(&mut buffer),
        )
        .await
        .expect("no timeout")
        .expect("to succeed");
        assert_eq!(&buffer, b"hello, world");
    }

    #[tokio::test]
    async fn data_in_syn_packet_non_silent_ephemeral() {
        let socket_factory = SocketFactory::new().await;

        let mut manager = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let serialized = base64_encode(destination.serialized());
        let packet = PacketBuilder::new(1337u32)
            .with_synchronize()
            .with_send_stream_id(0u32)
            .with_replay_protection(&manager.destination.id())
            .with_from_included(&destination)
            .with_signature()
            .with_payload(b"hello, world\n")
            .build_and_sign(&signing_key)
            .to_vec();

        let outbound1 = TunnelId::random();
        let inbound1 = Lease::random();
        let mut path_manager1 =
            RoutingPathManager::<MockRuntime>::new(manager.destination_id.clone(), vec![outbound1]);
        let pending_handle = path_manager1.pending_handle();
        path_manager1.register_leases(&destination.id(), Ok(vec![inbound1]));

        tokio::spawn(async move { while let Some(_) = path_manager1.next().await {} });

        // register listener for `manager1`
        let (socket, client_socket) = socket_factory.socket().await;
        assert!(manager
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: false,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());

        // handle syn packet and spawn manager in the background
        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());

        tokio::spawn(async move { while let Some(_) = manager.next().await {} });

        let mut reader = BufReader::new(client_socket);
        let mut response = String::new();

        // read stream status
        reader.read_line(&mut response).await.unwrap();
        assert_eq!(response, "STREAM STATUS RESULT=OK\n");

        // read remote's destination id
        response.clear();
        reader.read_line(&mut response).await.unwrap();
        assert_eq!(response, format!("{serialized}\n"));

        // read payload from syn packet
        response.clear();
        reader.read_line(&mut response).await.unwrap();
        assert_eq!(response, "hello, world\n");
    }

    #[tokio::test]
    async fn data_in_syn_packet_non_silent_pending_ephemeral() {
        let socket_factory = SocketFactory::new().await;

        let mut manager = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let serialized = base64_encode(destination.serialized());
        let packet = PacketBuilder::new(1337u32)
            .with_synchronize()
            .with_send_stream_id(0u32)
            .with_replay_protection(&manager.destination.id())
            .with_from_included(&destination)
            .with_signature()
            .with_payload(b"hello, world\n")
            .build_and_sign(&signing_key)
            .to_vec();

        // handle syn packet and spawn manager in the background
        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());
        assert!(!manager.pending_inbound.is_empty());

        let outbound = TunnelId::random();
        let inbound = Lease::random();
        let mut path_manager =
            RoutingPathManager::<MockRuntime>::new(manager.destination_id.clone(), vec![outbound]);
        path_manager.register_leases(&destination.id(), Ok(vec![inbound]));
        let pending_handle = path_manager.pending_handle();

        tokio::spawn(async move { while let Some(_) = path_manager.next().await {} });

        // register listener for `manager1`
        let (socket, client_socket) = socket_factory.socket().await;
        assert!(manager
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: false,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());

        tokio::spawn(async move { while let Some(_) = manager.next().await {} });

        let mut reader = BufReader::new(client_socket);
        let mut response = String::new();

        // read stream status
        reader.read_line(&mut response).await.unwrap();
        assert_eq!(response, "STREAM STATUS RESULT=OK\n");

        // read remote's destination id
        response.clear();
        reader.read_line(&mut response).await.unwrap();
        assert_eq!(response, format!("{serialized}\n"));

        // read payload from syn packet
        response.clear();
        reader.read_line(&mut response).await.unwrap();
        assert_eq!(response, "hello, world\n");
    }

    #[tokio::test]
    async fn data_in_syn_packet_silent_pending_ephemeral() {
        let socket_factory = SocketFactory::new().await;

        let mut manager = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let packet = PacketBuilder::new(1337u32)
            .with_synchronize()
            .with_send_stream_id(0u32)
            .with_replay_protection(&manager.destination.id())
            .with_from_included(&destination)
            .with_signature()
            .with_payload(b"hello, world\n")
            .build_and_sign(&signing_key)
            .to_vec();

        // handle syn packet and spawn manager in the background
        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());
        assert!(!manager.pending_inbound.is_empty());

        let outbound = TunnelId::random();
        let inbound = Lease::random();
        let mut path_manager =
            RoutingPathManager::<MockRuntime>::new(manager.destination_id.clone(), vec![outbound]);
        path_manager.register_leases(&destination.id(), Ok(vec![inbound]));
        let pending_handle = path_manager.pending_handle();

        tokio::spawn(async move { while let Some(_) = path_manager.next().await {} });

        // register listener for `manager1`
        let (socket, client_socket) = socket_factory.socket().await;
        assert!(manager
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());

        tokio::spawn(async move { while let Some(_) = manager.next().await {} });

        let mut reader = BufReader::new(client_socket);
        let mut response = String::new();

        // read payload from syn packet
        response.clear();
        reader.read_line(&mut response).await.unwrap();
        assert_eq!(response, "hello, world\n");
    }

    #[tokio::test]
    async fn active_session_destroyed() {
        let socket_factory = SocketFactory::new().await;

        let mut manager1 = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let mut manager2 = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let outbound1 = TunnelId::random();
        let inbound1 = Lease::random();
        let mut path_manager1 = RoutingPathManager::<MockRuntime>::new(
            manager1.destination_id.clone(),
            vec![outbound1],
        );
        let pending_handle = path_manager1.pending_handle();
        path_manager1.register_leases(&manager2.destination_id, Ok(vec![inbound1]));

        let outbound2 = TunnelId::random();
        let inbound2 = Lease::random();
        let mut path_manager2 = RoutingPathManager::<MockRuntime>::new(
            manager2.destination_id.clone(),
            vec![outbound2],
        );
        path_manager2.register_leases(&manager1.destination_id, Ok(vec![inbound2]));
        let handle = path_manager2.handle(manager1.destination_id.clone());

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = &mut path_manager1.next() => {}
                    _ = &mut path_manager2.next() => {}
                }
            }
        });

        // register listener for `manager1`
        let (socket, mut listener_stream) = socket_factory.socket().await;
        assert!(manager1
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());

        // create new oubound stream to `manager1`
        let (socket, client_stream) = socket_factory.socket().await;
        let (_stream_id, packet, _, _, _) = manager2.create_stream(
            manager1.destination_id.clone(),
            handle,
            socket,
            HashMap::new(),
        );

        assert!(manager1
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet.to_vec(),
            })
            .is_ok());

        assert!(std::matches!(
            manager1.next().await,
            Some(StreamManagerEvent::StreamOpened { .. })
        ));

        let (destination_id, packet) =
            match tokio::time::timeout(Duration::from_secs(5), manager1.next())
                .await
                .unwrap()
                .unwrap()
            {
                StreamManagerEvent::SendPacket {
                    delivery_style,
                    packet,
                    ..
                } => (delivery_style.destination_id().clone(), packet),
                _ => panic!("invalid event"),
            };

        assert_eq!(destination_id, manager2.destination_id);
        assert!(manager2
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet,
            })
            .is_ok());

        // remove session to manager2 due to error
        manager1.remove_session(&manager2.destination_id);

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = manager1.next() => {}
                    _ = manager2.next() => {}
                }
            }
        });

        let mut reader = tokio::io::BufReader::new(client_stream);
        let mut response = String::new();
        reader.read_line(&mut response).await.unwrap();

        assert_eq!(response.as_str(), "STREAM STATUS RESULT=OK\n");

        // verify that the stream has been closed
        let mut buffer = vec![0u8; 12];
        assert_eq!(listener_stream.read(&mut buffer).await.unwrap(), 0);
    }

    #[tokio::test]
    async fn signature_missing_inbound_stream() {
        let mut manager = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        // build syn packet without signature
        let payload = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());

            PacketBuilder::new(1337u32)
                .with_synchronize()
                .with_send_stream_id(0u32)
                .with_replay_protection(&manager.destination.id())
                .with_from_included(&destination)
                .with_payload(b"hello, world\n")
                .build()
                .to_vec()
        };

        assert_eq!(
            manager.on_packet(I2cpPayload {
                dst_port: 0,
                payload,
                protocol: Protocol::Streaming,
                src_port: 0
            }),
            Err(StreamingError::SignatureMissing),
        );
    }

    #[tokio::test]
    async fn destination_missing() {
        let mut manager = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        // build syn packet without replay protection
        let packet = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());

            PacketBuilder::new(1337u32)
                .with_send_stream_id(0u32)
                .with_synchronize()
                .with_signature()
                .with_from_included(&destination)
                .build_and_sign(&signing_key)
        };

        assert_eq!(
            manager.on_packet(I2cpPayload {
                dst_port: 0,
                payload: packet.to_vec(),
                protocol: Protocol::Streaming,
                src_port: 0
            }),
            Err(StreamingError::ReplayProtectionCheckFailed),
        );
    }

    #[tokio::test]
    async fn inbound_stream() {
        let signing_key = SigningPrivateKey::from_bytes(&[
            116, 15, 103, 156, 205, 43, 224, 113, 103, 249, 182, 195, 149, 25, 171, 177, 151, 135,
            221, 125, 79, 161, 205, 146, 188, 100, 15, 177, 189, 91, 167, 60,
        ])
        .unwrap();
        let destination = {
            let serialized_len = (320usize + 32usize)
                .saturating_add(32usize)
                .saturating_add(1usize)
                .saturating_add(2usize)
                .saturating_add(4usize);

            let mut out = BytesMut::with_capacity(serialized_len);

            out.put_slice(&[0u8; 320usize + 32usize]);
            out.put_slice(signing_key.public().as_ref());
            out.put_u8(0x05);
            out.put_u16(0x04);
            out.put_u16(0x0007);
            out.put_u16(0u16);

            Destination::parse(&out).unwrap()
        };
        let mut manager = StreamManager::<MockRuntime>::new(destination, signing_key);

        let payload = vec![
            0, 0, 0, 0, 7, 170, 162, 225, 0, 0, 0, 0, 0, 0, 0, 0, 8, 92, 237, 166, 51, 230, 31, 2,
            219, 176, 105, 43, 109, 206, 122, 239, 241, 221, 135, 206, 60, 147, 145, 41, 155, 120,
            133, 180, 145, 4, 26, 107, 40, 9, 4, 169, 1, 201, 127, 213, 228, 57, 98, 56, 202, 186,
            4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107,
            167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46,
            112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93,
            127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224,
            232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56,
            202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97,
            227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192,
            50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101,
            93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46,
            224, 232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57,
            98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217,
            232, 97, 227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78,
            254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107, 167,
            187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112,
            10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93, 127,
            213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232,
            108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202,
            186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227,
            107, 167, 187, 30, 101, 93, 25, 140, 66, 230, 135, 216, 58, 4, 196, 109, 50, 64, 50,
            20, 213, 102, 99, 242, 187, 7, 216, 187, 137, 158, 228, 199, 195, 182, 38, 53, 40, 227,
            5, 0, 4, 0, 7, 0, 0, 7, 20, 182, 215, 224, 75, 178, 60, 111, 31, 179, 197, 227, 223,
            204, 20, 139, 51, 220, 96, 129, 16, 67, 235, 112, 185, 5, 108, 37, 55, 24, 251, 233,
            175, 88, 10, 18, 128, 227, 33, 34, 87, 15, 141, 210, 183, 58, 42, 184, 148, 221, 156,
            78, 128, 175, 18, 79, 142, 32, 0, 13, 28, 247, 4, 222, 7,
        ];

        assert!(manager
            .on_packet(I2cpPayload {
                src_port: 13u16,
                dst_port: 37u16,
                protocol: Protocol::Streaming,
                payload,
            })
            .is_ok());
    }

    #[tokio::test]
    async fn invalid_signature() {
        let signing_key = SigningPrivateKey::from_bytes(&[
            116, 15, 103, 156, 205, 43, 224, 113, 103, 249, 182, 195, 149, 25, 171, 177, 151, 135,
            221, 125, 79, 161, 205, 146, 188, 100, 15, 177, 189, 91, 167, 60,
        ])
        .unwrap();
        let destination = {
            let serialized_len = (320usize + 32usize)
                .saturating_add(32usize)
                .saturating_add(1usize)
                .saturating_add(2usize)
                .saturating_add(4usize);

            let mut out = BytesMut::with_capacity(serialized_len);

            out.put_slice(&[0u8; 320usize + 32usize]);
            out.put_slice(signing_key.public().as_ref());
            out.put_u8(0x05);
            out.put_u16(0x04);
            out.put_u16(0x0007);
            out.put_u16(0u16);

            Destination::parse(&out).unwrap()
        };
        let mut manager = StreamManager::<MockRuntime>::new(destination, signing_key);

        let payload = vec![
            0, 0, 0, 0, 7, 170, 162, 225, 0, 0, 0, 0, 0, 0, 0, 0, 8, 92, 237, 166, 51, 230, 31, 2,
            219, 176, 105, 43, 109, 206, 122, 239, 241, 221, 135, 206, 60, 147, 145, 41, 155, 120,
            133, 180, 145, 4, 26, 107, 40, 9, 4, 169, 1, 201, 127, 213, 228, 57, 98, 56, 202, 186,
            4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107,
            167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46,
            112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93,
            127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224,
            232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56,
            202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97,
            227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192,
            50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101,
            93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46,
            224, 232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57,
            98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217,
            232, 97, 227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78,
            254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107, 167,
            187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112,
            10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93, 127,
            213, 228, 57, 98, 56, 202, 186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232,
            108, 24, 217, 232, 97, 227, 107, 167, 187, 30, 101, 93, 127, 213, 228, 57, 98, 56, 202,
            186, 4, 78, 254, 192, 50, 46, 112, 10, 223, 46, 224, 232, 108, 24, 217, 232, 97, 227,
            107, 167, 187, 30, 101, 93, 25, 140, 66, 230, 135, 216, 58, 4, 196, 109, 50, 64, 50,
            20, 213, 102, 99, 242, 187, 7, 216, 187, 137, 158, 228, 199, 195, 182, 38, 53, 40, 227,
            5, 0, 4, 0, 7, 0, 0, 7, 20, 182, 215, 224, 75, 178, 60, 111, 31, 179, 197, 227, 223,
            204, 20, 139, 51, 220, 96, 129, 16, 67, 235, 112, 185, 5, 108, 37, 55, 24, 251, 233,
            175, 88, 10, 18, 128, 227, 33, 34, 87, 15, 141, 210, 183, 58, 42, 184, 148, 221, 156,
            78, 128, 175, 18, 79, 142, 32, 0, 13, 28, 247, 4, 223, 7,
        ];

        assert_eq!(
            manager.on_packet(I2cpPayload {
                src_port: 13u16,
                dst_port: 37u16,
                protocol: Protocol::Streaming,
                payload,
            }),
            Err(StreamingError::InvalidSignature)
        );
    }

    #[tokio::test]
    async fn invalid_destination_id() {
        let mut manager = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let packet = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());

            PacketBuilder::new(1337u32)
                .with_send_stream_id(0u32)
                .with_replay_protection(&DestinationId::random())
                .with_synchronize()
                .with_signature()
                .with_from_included(&destination)
                .build_and_sign(&signing_key)
                .to_vec()
        };

        assert_eq!(
            manager.on_packet(I2cpPayload {
                src_port: 13u16,
                dst_port: 37u16,
                protocol: Protocol::Streaming,
                payload: packet,
            }),
            Err(StreamingError::ReplayProtectionCheckFailed)
        );
    }

    // TODO: add better test
    #[tokio::test]
    async fn offline() {
        // set runtime unix time clock to 0 to pass the offline signature expiration check
        MockRuntime::set_time(Some(Duration::from_nanos(0)));

        let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
        let destination = Destination::new::<MockRuntime>(signing_key.public());
        let mut manager = StreamManager::<MockRuntime>::new(destination, signing_key);

        let input = vec![
            226, 27, 26, 214, 19, 0, 72, 226, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 233, 2, 49, 0, 0,
            24, 166, 169, 39, 201, 40, 81, 192, 99, 254, 57, 144, 204, 123, 19, 99, 16, 224, 218,
            218, 95, 90, 61, 49, 141, 4, 243, 119, 192, 97, 124, 47, 92, 220, 228, 185, 127, 3,
            193, 53, 168, 224, 23, 231, 142, 15, 167, 130, 140, 84, 234, 78, 90, 43, 150, 30, 199,
            157, 223, 36, 94, 61, 106, 110, 85, 6, 93, 63, 173, 14, 132, 125, 253, 133, 124, 118,
            101, 229, 231, 87, 9, 159, 211, 21, 77, 26, 196, 169, 21, 146, 37, 85, 219, 81, 76,
            253, 183, 147, 232, 233, 118, 182, 227, 181, 107, 210, 194, 103, 219, 180, 120, 42,
            130, 143, 241, 5, 99, 212, 107, 135, 233, 208, 119, 111, 172, 19, 61, 179, 154, 152,
            45, 221, 144, 237, 124, 190, 68, 36, 125, 149, 148, 117, 19, 3, 94, 77, 29, 240, 7, 99,
            7, 65, 52, 243, 174, 39, 57, 63, 201, 244, 90, 103, 119, 106, 80, 19, 155, 168, 21, 62,
            143, 208, 58, 173, 65, 29, 163, 176, 91, 223, 244, 193, 58, 213, 170, 139, 188, 163,
            207, 90, 153, 32, 118, 126, 51, 233, 153, 38, 248, 210, 78, 112, 60, 246, 54, 255, 18,
            139, 184, 101, 139, 222, 4, 245, 40, 33, 49, 132, 108, 118, 53, 62, 146, 115, 155, 42,
            252, 98, 106, 9, 252, 224, 82, 48, 112, 234, 94, 167, 27, 134, 254, 65, 87, 116, 62,
            77, 126, 193, 244, 191, 165, 43, 139, 123, 172, 19, 117, 214, 15, 179, 240, 232, 255,
            42, 85, 129, 119, 246, 53, 8, 171, 131, 162, 52, 204, 15, 156, 214, 51, 203, 99, 120,
            152, 51, 16, 118, 199, 71, 59, 114, 212, 86, 31, 195, 18, 154, 78, 203, 208, 0, 152,
            74, 7, 14, 56, 201, 198, 221, 129, 20, 22, 198, 197, 247, 105, 100, 42, 68, 54, 76, 47,
            153, 151, 152, 83, 35, 66, 11, 48, 18, 169, 51, 142, 148, 220, 221, 166, 119, 188, 114,
            231, 172, 159, 115, 67, 92, 138, 77, 158, 161, 4, 232, 231, 185, 66, 110, 88, 56, 156,
            164, 173, 127, 213, 199, 247, 5, 21, 61, 208, 204, 49, 164, 34, 56, 241, 148, 80, 108,
            141, 66, 114, 98, 65, 99, 5, 0, 4, 0, 7, 0, 0, 6, 194, 103, 211, 114, 177, 0, 7, 114,
            245, 169, 33, 134, 26, 252, 238, 198, 139, 178, 162, 137, 244, 248, 219, 134, 158, 177,
            169, 36, 111, 194, 146, 62, 64, 132, 131, 205, 60, 141, 119, 75, 98, 229, 232, 91, 194,
            2, 167, 112, 200, 140, 187, 82, 159, 142, 104, 231, 51, 65, 186, 199, 13, 110, 250,
            125, 184, 96, 36, 20, 106, 127, 70, 84, 46, 253, 209, 8, 190, 88, 186, 122, 152, 13,
            39, 3, 238, 211, 221, 88, 159, 203, 116, 189, 186, 222, 120, 237, 193, 252, 251, 122,
            55, 198, 6, 234, 139, 212, 76, 100, 124, 36, 16, 82, 83, 191, 31, 246, 245, 9, 104,
            190, 118, 155, 58, 176, 214, 151, 106, 55, 80, 236, 75, 135, 68, 29, 86, 241, 79, 8,
            146, 151, 44, 48, 83, 253, 24, 26, 1, 172, 10, 174, 49, 29, 197, 101, 180, 213, 153, 6,
            43, 41, 125, 79, 60, 122, 216, 254, 14,
        ];

        match manager.on_packet(I2cpPayload {
            src_port: 13u16,
            dst_port: 37u16,
            protocol: Protocol::Streaming,
            payload: input,
        }) {
            Err(StreamingError::ReplayProtectionCheckFailed) => {}
            _ => panic!("invalid error"),
        }
    }

    #[tokio::test(start_paused = true)]
    async fn stream_destroyed_while_opening() {
        let socket_factory = SocketFactory::new().await;

        let mut manager1 = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let mut manager2 = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        // register listener for `manager1`
        let (socket, _) = socket_factory.socket().await;
        assert!(manager1
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: PendingRoutingPathHandle::create(),
            })
            .is_ok());

        let mut path_manager = RoutingPathManager::<MockRuntime>::new(
            manager2.destination_id.clone(),
            vec![TunnelId::random()],
        );
        path_manager.register_leases(&manager1.destination_id.clone(), Ok(vec![Lease::random()]));

        // create new oubound stream to `manager1`
        let (socket, _client_stream) = socket_factory.socket().await;
        let (stream_id, _packet, _, _, _) = manager2.create_stream(
            manager1.destination_id.clone(),
            path_manager.handle(manager1.destination_id.clone()),
            socket,
            HashMap::new(),
        );

        // verify there's one outbound timer active
        assert_eq!(manager2.outbound_timers.len(), 1);
        assert!(manager2.pending_outbound.get(&stream_id).is_some());
        assert!(manager2.destination_streams.get(&manager1.destination_id).is_some());

        // remove session and verify the timer's still active
        manager2.remove_session(&manager1.destination_id.clone());

        // verify there's one outbound timer active and that the session is gone
        assert_eq!(manager2.outbound_timers.len(), 1);
        assert!(manager2.pending_outbound.get(&stream_id).is_none());
        assert!(manager2.destination_streams.get(&manager1.destination_id).is_none());

        // wait for 15 seconds and verify that no event is emitted
        assert!(tokio::time::timeout(Duration::from_secs(15), manager2.next()).await.is_err());

        // verify that there are no timers anymore
        assert!(manager2.outbound_timers.is_empty());
        assert!(manager2.pending_outbound.get(&stream_id).is_none());
        assert!(manager2.destination_streams.get(&manager1.destination_id).is_none());
    }

    #[tokio::test]
    async fn dst_and_src_ports_specified() {
        let socket_factory = SocketFactory::new().await;

        let mut manager1 = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let mut manager2 = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let outbound1 = TunnelId::random();
        let inbound1 = Lease::random();
        let mut path_manager1 = RoutingPathManager::<MockRuntime>::new(
            manager1.destination_id.clone(),
            vec![outbound1],
        );
        let pending_handle = path_manager1.pending_handle();
        path_manager1.register_leases(&manager2.destination_id, Ok(vec![inbound1]));

        let outbound2 = TunnelId::random();
        let inbound2 = Lease::random();
        let mut path_manager2 = RoutingPathManager::<MockRuntime>::new(
            manager2.destination_id.clone(),
            vec![outbound2],
        );
        path_manager2.register_leases(&manager1.destination_id, Ok(vec![inbound2]));
        let handle = path_manager2.handle(manager1.destination_id.clone());

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = &mut path_manager1.next() => {}
                    _ = &mut path_manager2.next() => {}
                }
            }
        });

        // register listener for `manager1`
        let (socket, _) = socket_factory.socket().await;
        assert!(manager1
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());

        // create new oubound stream to `manager1`
        let (socket, client_stream) = socket_factory.socket().await;
        let (_stream_id, packet, _, src_port, dst_port) = manager2.create_stream(
            manager1.destination_id.clone(),
            handle,
            socket,
            HashMap::from_iter([
                (String::from("FROM_PORT"), String::from("1337")),
                (String::from("TO_PORT"), String::from("1338")),
            ]),
        );
        assert_eq!(src_port, 1337);
        assert_eq!(dst_port, 1338);

        assert!(manager1
            .on_packet(I2cpPayload {
                src_port,
                dst_port,
                protocol: Protocol::Streaming,
                payload: packet.to_vec()
            })
            .is_ok());

        assert!(std::matches!(
            manager1.next().await,
            Some(StreamManagerEvent::StreamOpened { .. })
        ));

        let (destination_id, packet) =
            match tokio::time::timeout(Duration::from_secs(5), manager1.next())
                .await
                .unwrap()
                .unwrap()
            {
                StreamManagerEvent::SendPacket {
                    delivery_style,
                    packet,
                    ..
                } => (delivery_style.destination_id().clone(), packet),
                _ => panic!("invalid event"),
            };

        assert_eq!(destination_id, manager2.destination_id);
        assert!(manager2
            .on_packet(I2cpPayload {
                src_port: 1337u16,
                dst_port: 1338u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = manager1.next() => {}
                    _ = manager2.next() => {}
                }
            }
        });

        let mut reader = tokio::io::BufReader::new(client_stream);
        let mut response = String::new();
        reader.read_line(&mut response).await.unwrap();

        assert_eq!(response.as_str(), "STREAM STATUS RESULT=OK\n");
    }

    #[tokio::test(start_paused = true)]
    async fn syn_resend_with_different_routing_path() {
        let socket_factory = SocketFactory::new().await;
        let remote = DestinationId::random();

        let mut manager2 = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let mut outbound = (0..3).map(|_| TunnelId::random()).collect::<HashSet<_>>();
        let mut inbound = (0..3)
            .map(|_| {
                let lease = Lease::random();

                (lease.tunnel_id, lease)
            })
            .collect::<HashMap<_, _>>();

        let mut path_manager = RoutingPathManager::<MockRuntime>::new(
            manager2.destination_id.clone(),
            outbound.iter().cloned().collect(),
        );
        path_manager.register_leases(&remote, Ok(inbound.values().cloned().collect()));

        // create new oubound stream to `manager1`
        let (socket, _client_stream) = socket_factory.socket().await;
        let (_, _, delivery_style, _, _) = manager2.create_stream(
            remote.clone(),
            path_manager.handle(remote.clone()),
            socket,
            HashMap::new(),
        );

        match delivery_style {
            DeliveryStyle::ViaRoute { routing_path } => {
                assert!(outbound.remove(&routing_path.outbound));
                assert!(inbound.remove(&routing_path.inbound).is_some());
            }
            _ => panic!("invalid delivery style"),
        }

        // verify the syn packet is sent twice more
        match tokio::time::timeout(Duration::from_secs(15), manager2.next())
            .await
            .expect("no timeout")
            .expect("to succeed")
        {
            StreamManagerEvent::SendPacket {
                delivery_style,
                packet,
                ..
            } if delivery_style.destination_id() == &remote => {
                assert!(Packet::parse::<MockRuntime>(&packet).unwrap().flags.synchronize());

                match delivery_style {
                    DeliveryStyle::ViaRoute { routing_path } => {
                        assert!(outbound.remove(&routing_path.outbound));
                        assert!(inbound.remove(&routing_path.inbound).is_some());
                    }
                    _ => panic!("invalid delivery style"),
                }
            }
            _ => panic!("invalid event"),
        }

        match tokio::time::timeout(Duration::from_secs(15), manager2.next())
            .await
            .expect("no timeout")
            .expect("to succeed")
        {
            StreamManagerEvent::SendPacket {
                delivery_style,
                packet,
                ..
            } if delivery_style.destination_id() == &remote => {
                assert!(Packet::parse::<MockRuntime>(&packet).unwrap().flags.synchronize());

                match delivery_style {
                    DeliveryStyle::ViaRoute { routing_path } => {
                        assert!(outbound.remove(&routing_path.outbound));
                        assert!(inbound.remove(&routing_path.inbound).is_some());
                    }
                    _ => panic!("invalid delivery style"),
                }
            }
            _ => panic!("invalid event"),
        }
    }

    #[tokio::test]
    async fn stream_exits_after_multiple_lease_set_query_failures() {
        let socket_factory = SocketFactory::new().await;

        let mut manager1 = {
            let signing_key = SigningPrivateKey::from_bytes(&[0u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let mut manager2 = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let outbound1 = TunnelId::random();
        let inbound1 = Lease {
            router_id: RouterId::random(),
            tunnel_id: TunnelId::random(),
            expires: MockRuntime::time_since_epoch() + Duration::from_secs(35),
        };
        let mut path_manager1 = RoutingPathManager::<MockRuntime>::new(
            manager1.destination_id.clone(),
            vec![outbound1],
        );
        let pending_handle = path_manager1.pending_handle();
        path_manager1.register_leases(&manager2.destination_id, Ok(vec![inbound1]));

        let outbound2 = TunnelId::random();
        let inbound2 = Lease {
            router_id: RouterId::random(),
            tunnel_id: TunnelId::random(),
            expires: MockRuntime::time_since_epoch() + Duration::from_secs(35),
        };
        let mut path_manager2 = RoutingPathManager::<MockRuntime>::new(
            manager2.destination_id.clone(),
            vec![outbound2],
        );
        path_manager2.register_leases(&manager1.destination_id, Ok(vec![inbound2]));
        let handle = path_manager2.handle(manager1.destination_id.clone());

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    event = &mut path_manager1.next() => {
                        let remote = event.unwrap();
                        path_manager1.register_leases(&remote, Err(QueryError::Timeout));
                    }
                    event = &mut path_manager2.next() => {
                        let remote = event.unwrap();
                        path_manager1.register_leases(&remote, Err(QueryError::Timeout));
                    }
                }
            }
        });

        // register listener for `manager1`
        let (socket, _) = socket_factory.socket().await;
        assert!(manager1
            .register_listener(ListenerKind::Ephemeral {
                socket,
                silent: true,
                pending_routing_path_handle: pending_handle,
            })
            .is_ok());

        // create new oubound stream to `manager1`
        let (socket, _client_stream) = socket_factory.socket().await;
        let manager2_dest = manager2.destination_id.clone();
        let (_stream_id, packet, _, _, _) = manager2.create_stream(
            manager1.destination_id.clone(),
            handle,
            socket,
            HashMap::new(),
        );

        assert!(manager1
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet.to_vec()
            })
            .is_ok());

        assert!(std::matches!(
            manager1.next().await,
            Some(StreamManagerEvent::StreamOpened { .. })
        ));

        let (destination_id, packet) =
            match tokio::time::timeout(Duration::from_secs(5), manager1.next())
                .await
                .unwrap()
                .unwrap()
            {
                StreamManagerEvent::SendPacket {
                    delivery_style,
                    packet,
                    ..
                } => (delivery_style.destination_id().clone(), packet),
                _ => panic!("invalid event"),
            };

        assert_eq!(destination_id, manager2.destination_id);
        assert!(manager2
            .on_packet(I2cpPayload {
                src_port: 0u16,
                dst_port: 0u16,
                protocol: Protocol::Streaming,
                payload: packet
            })
            .is_ok());

        tokio::spawn(async move {
            loop {
                let _ = manager2.next().await;
            }
        });

        match tokio::time::timeout(Duration::from_secs(50), manager1.next())
            .await
            .expect("no timeout")
            .expect("to succeed")
        {
            StreamManagerEvent::StreamClosed { destination_id } => {
                assert_eq!(destination_id, manager2_dest)
            }
            _ => panic!("invalid event"),
        }
    }

    #[tokio::test(start_paused = true)]
    async fn outbound_stream_no_routing_path() {
        let socket_factory = SocketFactory::new().await;
        let remote = DestinationId::random();

        let mut manager2 = {
            let signing_key = SigningPrivateKey::from_bytes(&[1u8; 32]).unwrap();
            let destination = Destination::new::<MockRuntime>(signing_key.public());
            StreamManager::<MockRuntime>::new(destination, signing_key)
        };

        let mut path_manager = RoutingPathManager::<MockRuntime>::new(
            manager2.destination_id.clone(),
            vec![TunnelId::random()],
        );

        // create new outbound stream to random destination for which we don't have a lease set
        let (socket, client_stream) = socket_factory.socket().await;
        let _ = manager2.create_stream(
            remote.clone(),
            path_manager.handle(remote.clone()),
            socket,
            HashMap::new(),
        );

        // verify that stream rejection is emitted
        match tokio::time::timeout(Duration::from_secs(60), manager2.next())
            .await
            .expect("no timeout")
            .expect("to succeed")
        {
            StreamManagerEvent::StreamRejected { destination_id } if destination_id == remote => {}
            _ => panic!("invalid event"),
        }

        let mut reader = BufReader::new(client_stream);
        let mut response = String::new();
        tokio::time::timeout(Duration::from_secs(15), reader.read_line(&mut response))
            .await
            .expect("no timeout")
            .expect("to succeed");

        assert_eq!(response, "STREAM STATUS RESULT=CANT_REACH_PEER\n");
    }
}