freenet 0.2.47

Freenet core software
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
use std::collections::VecDeque;

use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use freenet_stdlib::prelude::{
    ApplicationMessage, DelegateContainer, DelegateContext, DelegateError, DelegateInterfaceResult,
    DelegateKey, DelegateMessage, GetContractRequest, InboundDelegateMsg, MessageOrigin,
    OutboundDelegateMsg, Parameters, PutContractRequest, SecretsId, SubscribeContractRequest,
    UpdateContractRequest,
};

use super::engine::{InstanceHandle, WasmEngine};
use super::native_api::{CURRENT_DELEGATE_INSTANCE, DELEGATE_ENV, DelegateCallEnv, InstanceId};
use super::{Runtime, RuntimeResult};
use crate::wasm_runtime::delegate_api::DelegateApiVersion;

/// RAII guard that ensures cleanup of delegate environment state.
/// When dropped, it clears the thread-local instance ID and removes the
/// entry from the global DELEGATE_ENV map.
struct DelegateEnvGuard {
    instance_id: InstanceId,
}

impl DelegateEnvGuard {
    fn new(instance_id: InstanceId) -> Self {
        Self { instance_id }
    }
}

impl Drop for DelegateEnvGuard {
    fn drop(&mut self) {
        // Clear thread-local first, then remove from global map
        CURRENT_DELEGATE_INSTANCE.with(|c| c.set(-1));
        DELEGATE_ENV.remove(&self.instance_id);
    }
}

#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum DelegateExecError {
    #[error(transparent)]
    DelegateError(#[from] DelegateError),

    #[error("Permission denied: secret {secret} cannot be accesed by {delegate} at this time")]
    UnauthorizedSecretAccess {
        secret: SecretsId,
        delegate: DelegateKey,
    },

    #[error("Received an unexpected message from the client apps: {0}")]
    UnexpectedMessage(&'static str),
}

pub(crate) trait DelegateRuntimeInterface {
    fn inbound_app_message(
        &mut self,
        key: &DelegateKey,
        params: &Parameters,
        origin: Option<&MessageOrigin>,
        inbound: Vec<InboundDelegateMsg>,
    ) -> RuntimeResult<Vec<OutboundDelegateMsg>>;

    fn register_delegate(
        &mut self,
        delegate: DelegateContainer,
        cipher: XChaCha20Poly1305,
        nonce: XNonce,
    ) -> RuntimeResult<()>;

    fn unregister_delegate(&mut self, key: &DelegateKey) -> RuntimeResult<()>;
}

impl Runtime {
    /// Execute the delegate's `process` function with the DelegateCallEnv set up
    /// so that host functions for context and secret access are available.
    ///
    /// Uses RAII guard pattern to ensure cleanup happens even if WASM execution panics.
    #[allow(clippy::too_many_arguments)]
    fn exec_inbound_with_env(
        &mut self,
        delegate_key: &DelegateKey,
        params: &Parameters<'_>,
        origin: Option<&MessageOrigin>,
        msg: &InboundDelegateMsg,
        context: Vec<u8>,
        handle: &InstanceHandle,
        instance_id: i64,
        api_version: DelegateApiVersion,
    ) -> RuntimeResult<(Vec<OutboundDelegateMsg>, Vec<u8>)> {
        // Set up the delegate call environment with context, secret store, and
        // contract store access.
        // SAFETY: `self.secret_store` and `self.contract_store` are valid for the
        // duration of the WASM `process()` call below, and the `DelegateEnvGuard`
        // ensures the env is removed from `DELEGATE_ENV` before this function returns.
        // Build the origin_contracts list from the MessageOrigin. Only WebApp
        // attestations grant the receiving delegate access to a contract on
        // behalf of the caller; an inter-delegate caller (Delegate variant)
        // does not propagate contract access — its identity is conveyed only
        // via the `origin` argument forwarded into the WASM `process()` call.
        let origin_contracts = match origin {
            Some(MessageOrigin::WebApp(contract_id)) => vec![*contract_id],
            Some(MessageOrigin::Delegate(_)) | None => Vec::new(),
            // MessageOrigin is `#[non_exhaustive]`; future variants reach
            // this arm because the compiler requires it. Default to "no
            // contract access" (fail closed) AND log a warning so the gap
            // is visible during the PR that adds the new variant — the
            // catch-all should not silently default in production.
            Some(other) => {
                tracing::warn!(
                    delegate_key = %delegate_key,
                    origin = ?other,
                    "Unknown MessageOrigin variant reached fail-closed default; \
                     wasm_runtime::delegate::Runtime::inbound_app_message must \
                     decide explicitly whether this variant grants contract access"
                );
                Vec::new()
            }
        };

        // SAFETY: The `DelegateCallEnv` does not outlive `self`. The raw pointers to
        // `secret_store`, `contract_store`, and `delegate_store` remain valid for the
        // duration of the WASM `process()` call, and are cleaned up via DELEGATE_ENV
        // removal below.
        let env = unsafe {
            DelegateCallEnv::new(
                context,
                &mut self.secret_store,
                &self.contract_store,
                self.state_store_db.clone(),
                delegate_key.clone(),
                &mut self.delegate_store,
                0, // creation_depth: always 0 for top-level calls
                origin_contracts,
            )
        };

        debug_assert!(
            !DELEGATE_ENV.contains_key(&instance_id),
            "Instance ID {instance_id} already exists in DELEGATE_ENV - this indicates a bug"
        );

        DELEGATE_ENV.insert(instance_id, env);
        CURRENT_DELEGATE_INSTANCE.with(|c| c.set(instance_id));

        // Create RAII guard to ensure cleanup on all exit paths (including panic)
        let _guard = DelegateEnvGuard::new(instance_id);

        // Execute the WASM process function.
        // V2 delegates use call_async (async host functions for contract access).
        // V1 delegates use synchronous call.
        let result = self.exec_inbound(params, origin, msg, handle, api_version);

        // Read back the (possibly mutated) context before guard drops
        let updated_context = DELEGATE_ENV
            .get(&instance_id)
            .map(|env| env.context.clone())
            .unwrap_or_default();

        let outbound = result?;
        Ok((outbound, updated_context))
    }

    fn exec_inbound(
        &mut self,
        params: &Parameters<'_>,
        origin: Option<&MessageOrigin>,
        msg: &InboundDelegateMsg,
        handle: &InstanceHandle,
        api_version: DelegateApiVersion,
    ) -> RuntimeResult<Vec<OutboundDelegateMsg>> {
        let param_buf_ptr = {
            let mut param_buf = self.init_buf(handle, params)?;
            param_buf.write(params)?;
            param_buf.ptr()
        };
        let origin_buf_ptr = {
            let bytes = match origin {
                Some(o) => bincode::serialize(o)?,
                None => Vec::new(),
            };
            let mut origin_buf = self.init_buf(handle, &bytes)?;
            origin_buf.write(bytes)?;
            origin_buf.ptr()
        };
        let msg_ptr = {
            let msg = bincode::serialize(msg)?;
            let mut msg_buf = self.init_buf(handle, &msg)?;
            msg_buf.write(msg)?;
            msg_buf.ptr()
        };
        let inbound_msg_name = match msg {
            InboundDelegateMsg::ApplicationMessage(_) => "ApplicationMessage",
            InboundDelegateMsg::UserResponse(_) => "UserResponse",
            InboundDelegateMsg::GetContractResponse(_) => "GetContractResponse",
            InboundDelegateMsg::PutContractResponse(_) => "PutContractResponse",
            InboundDelegateMsg::UpdateContractResponse(_) => "UpdateContractResponse",
            InboundDelegateMsg::SubscribeContractResponse(_) => "SubscribeContractResponse",
            InboundDelegateMsg::ContractNotification(_) => "ContractNotification",
            InboundDelegateMsg::DelegateMessage(_) => "DelegateMessage",
            // `InboundDelegateMsg` is `#[non_exhaustive]` (stdlib 0.6.0+).
            // Future variants land here for tracing only — they still flow
            // through the wasm boundary as raw bincode below; classifying
            // them as "Unknown" affects logs only, not delivery.
            _ => "Unknown",
        };
        tracing::debug!(
            inbound_msg_name,
            api_version = %api_version,
            "Calling delegate with inbound message"
        );

        let res = match api_version {
            DelegateApiVersion::V1 => {
                // V1: synchronous call — no async host functions involved.
                // Must stay on calling thread for thread-local env.
                self.engine.call_3i64(
                    handle,
                    "process",
                    param_buf_ptr as i64,
                    origin_buf_ptr as i64,
                    msg_ptr as i64,
                )?
            }
            DelegateApiVersion::V2 => {
                // V2: async call — contract host functions are async.
                // Uses Store::into_async() + call_async() under the hood.
                self.engine.call_3i64_async_imports(
                    handle,
                    "process",
                    param_buf_ptr as i64,
                    origin_buf_ptr as i64,
                    msg_ptr as i64,
                )?
            }
        };

        let linear_mem = self.linear_mem(handle)?;
        // SAFETY: `res` is the return value from the WASM `process` call and
        // `linear_mem` points to the instance's live linear memory, so `from_raw`
        // reads a valid, in-bounds result descriptor.
        let outbound = unsafe {
            DelegateInterfaceResult::from_raw(res, &linear_mem)
                .unwrap(linear_mem)
                .map_err(Into::<DelegateExecError>::into)?
        };
        self.log_delegate_exec_result(inbound_msg_name, &outbound);
        Ok(outbound)
    }

    fn log_delegate_exec_result(&self, inbound_msg_name: &str, outbound: &[OutboundDelegateMsg]) {
        if tracing::enabled!(tracing::Level::DEBUG) {
            let outbound_message_names = outbound
                .iter()
                .map(|m| match m {
                    OutboundDelegateMsg::ApplicationMessage(am) => format!(
                        "ApplicationMessage(payload_len={}, processed={}, context_len={})",
                        am.payload.len(),
                        am.processed,
                        am.context.as_ref().len()
                    ),
                    OutboundDelegateMsg::RequestUserInput(_) => "RequestUserInput".to_string(),
                    OutboundDelegateMsg::ContextUpdated(_) => "ContextUpdated".to_string(),
                    OutboundDelegateMsg::GetContractRequest(req) => {
                        format!("GetContractRequest(contract={})", req.contract_id)
                    }
                    OutboundDelegateMsg::PutContractRequest(req) => {
                        format!("PutContractRequest(contract={})", req.contract.key())
                    }
                    OutboundDelegateMsg::UpdateContractRequest(req) => {
                        format!("UpdateContractRequest(contract={})", req.contract_id)
                    }
                    OutboundDelegateMsg::SubscribeContractRequest(req) => {
                        format!("SubscribeContractRequest(contract={})", req.contract_id)
                    }
                    OutboundDelegateMsg::SendDelegateMessage(msg) => {
                        format!(
                            "SendDelegateMessage(target={}, payload_len={})",
                            msg.target,
                            msg.payload.len()
                        )
                    }
                })
                .collect::<Vec<String>>()
                .join(", ");
            tracing::debug!(
                inbound_msg_name,
                outbound_message_names,
                "Delegate returned outbound messages"
            );
        } else {
            tracing::debug!(
                inbound_msg_name,
                outbound_len = outbound.len(),
                "Delegate returned outbound messages"
            );
        }
    }

    fn log_process_outbound_entry(
        &self,
        delegate_key: &DelegateKey,
        origin: Option<&MessageOrigin>,
        outbound_msgs: &VecDeque<OutboundDelegateMsg>,
    ) {
        tracing::debug!(
            delegate_key = ?delegate_key,
            ?origin,
            outbound_msgs_len = outbound_msgs.len(),
            outbound_msg_details = debug(if tracing::enabled!(tracing::Level::DEBUG) {
                outbound_msgs.iter().map(|msg| {
                    match msg {
                        OutboundDelegateMsg::ApplicationMessage(m) => format!("AppMsg(payload_len={})", m.payload.len()),
                        OutboundDelegateMsg::RequestUserInput(_) => "UserInputReq".to_string(),
                        OutboundDelegateMsg::ContextUpdated(_) => "ContextUpdate".to_string(),
                        OutboundDelegateMsg::GetContractRequest(r) => format!("GetContractReq({})", r.contract_id),
                        OutboundDelegateMsg::PutContractRequest(r) => format!("PutContractReq({})", r.contract.key()),
                        OutboundDelegateMsg::UpdateContractRequest(r) => format!("UpdateContractReq({})", r.contract_id),
                        OutboundDelegateMsg::SubscribeContractRequest(r) => format!("SubscribeContractReq({})", r.contract_id),
                        OutboundDelegateMsg::SendDelegateMessage(m) => format!("SendDelegateMsg(target={})", m.target),
                    }
                }).collect::<Vec<_>>()
            } else {
                Vec::new()
            }),
            "process_outbound called"
        );
    }

    /// Process outbound messages from a delegate.
    #[allow(clippy::too_many_arguments)]
    fn process_outbound(
        &mut self,
        delegate_key: &DelegateKey,
        _handle: &InstanceHandle,
        _instance_id: i64,
        _params: &Parameters<'_>,
        origin: Option<&MessageOrigin>,
        outbound_msgs: &mut VecDeque<OutboundDelegateMsg>,
        context: &mut Vec<u8>,
        results: &mut Vec<OutboundDelegateMsg>,
    ) -> RuntimeResult<()> {
        self.log_process_outbound_entry(delegate_key, origin, outbound_msgs);

        while let Some(outbound) = outbound_msgs.pop_front() {
            match outbound {
                OutboundDelegateMsg::ApplicationMessage(mut msg) => {
                    tracing::debug!(
                        payload_len = msg.payload.len(),
                        processed = msg.processed,
                        "Adding ApplicationMessage to results"
                    );
                    msg.context = DelegateContext::default();
                    results.push(OutboundDelegateMsg::ApplicationMessage(msg));
                    for remaining in outbound_msgs.drain(..) {
                        results.push(remaining);
                    }
                    break;
                }

                OutboundDelegateMsg::RequestUserInput(req) => {
                    tracing::debug!(
                        request_id = req.request_id,
                        "Passing RequestUserInput to executor for user prompting"
                    );
                    results.push(OutboundDelegateMsg::RequestUserInput(req));
                    for remaining in outbound_msgs.drain(..) {
                        results.push(remaining);
                    }
                    break;
                }

                OutboundDelegateMsg::ContextUpdated(new_context) => {
                    *context = new_context.as_ref().to_vec();
                }
                OutboundDelegateMsg::GetContractRequest(req) if !req.processed => {
                    tracing::debug!(
                        contract_id = %req.contract_id,
                        "Passing GetContractRequest to executor for async handling"
                    );
                    results.push(OutboundDelegateMsg::GetContractRequest(req));
                    for remaining in outbound_msgs.drain(..) {
                        results.push(remaining);
                    }
                    break;
                }
                OutboundDelegateMsg::GetContractRequest(GetContractRequest {
                    context: ctx,
                    ..
                }) => {
                    tracing::debug!("GetContractRequest processed");
                    *context = ctx.as_ref().to_vec();
                }
                OutboundDelegateMsg::PutContractRequest(req) if !req.processed => {
                    tracing::debug!(
                        contract = %req.contract.key(),
                        "Passing PutContractRequest to executor for async handling"
                    );
                    results.push(OutboundDelegateMsg::PutContractRequest(req));
                    for remaining in outbound_msgs.drain(..) {
                        results.push(remaining);
                    }
                    break;
                }
                OutboundDelegateMsg::PutContractRequest(PutContractRequest {
                    context: ctx,
                    ..
                }) => {
                    tracing::debug!("PutContractRequest processed");
                    *context = ctx.as_ref().to_vec();
                }
                OutboundDelegateMsg::UpdateContractRequest(req) if !req.processed => {
                    tracing::debug!(
                        contract_id = %req.contract_id,
                        "Passing UpdateContractRequest to executor for async handling"
                    );
                    results.push(OutboundDelegateMsg::UpdateContractRequest(req));
                    for remaining in outbound_msgs.drain(..) {
                        results.push(remaining);
                    }
                    break;
                }
                OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
                    context: ctx,
                    ..
                }) => {
                    tracing::debug!("UpdateContractRequest processed");
                    *context = ctx.as_ref().to_vec();
                }
                OutboundDelegateMsg::SubscribeContractRequest(req) if !req.processed => {
                    tracing::debug!(
                        contract_id = %req.contract_id,
                        "Passing SubscribeContractRequest to executor for async handling"
                    );
                    results.push(OutboundDelegateMsg::SubscribeContractRequest(req));
                    for remaining in outbound_msgs.drain(..) {
                        results.push(remaining);
                    }
                    break;
                }
                OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
                    context: ctx,
                    ..
                }) => {
                    tracing::debug!("SubscribeContractRequest processed");
                    *context = ctx.as_ref().to_vec();
                }
                OutboundDelegateMsg::SendDelegateMessage(mut msg) if !msg.processed => {
                    tracing::debug!(
                        target_delegate = %msg.target,
                        "Passing SendDelegateMessage to executor for delivery"
                    );
                    // Sender attestation: overwrite sender with the actual delegate key
                    msg.sender = delegate_key.clone();
                    results.push(OutboundDelegateMsg::SendDelegateMessage(msg));
                    // Attest any remaining SendDelegateMessage variants to prevent
                    // spoofing via drain bypass (see PR #3282 review).
                    for remaining in outbound_msgs.drain(..) {
                        match remaining {
                            OutboundDelegateMsg::SendDelegateMessage(mut m) if !m.processed => {
                                m.sender = delegate_key.clone();
                                results.push(OutboundDelegateMsg::SendDelegateMessage(m));
                            }
                            msg @ (OutboundDelegateMsg::ApplicationMessage(_)
                            | OutboundDelegateMsg::RequestUserInput(_)
                            | OutboundDelegateMsg::ContextUpdated(_)
                            | OutboundDelegateMsg::GetContractRequest(_)
                            | OutboundDelegateMsg::PutContractRequest(_)
                            | OutboundDelegateMsg::UpdateContractRequest(_)
                            | OutboundDelegateMsg::SubscribeContractRequest(_)
                            | OutboundDelegateMsg::SendDelegateMessage(_)) => results.push(msg),
                        }
                    }
                    break;
                }
                OutboundDelegateMsg::SendDelegateMessage(DelegateMessage {
                    context: ctx, ..
                }) => {
                    tracing::debug!("SendDelegateMessage processed");
                    *context = ctx.as_ref().to_vec();
                }
            }
        }
        Ok(())
    }
}

impl DelegateRuntimeInterface for Runtime {
    fn inbound_app_message(
        &mut self,
        delegate_key: &DelegateKey,
        params: &Parameters,
        origin: Option<&MessageOrigin>,
        inbound: Vec<InboundDelegateMsg>,
    ) -> RuntimeResult<Vec<OutboundDelegateMsg>> {
        let mut results = Vec::with_capacity(inbound.len());
        if inbound.is_empty() {
            return Ok(results);
        }
        let (mut running, api_version) = self.prepare_delegate_call(params, delegate_key, 4096)?;
        let instance_id = running.id;

        tracing::debug!(
            delegate_key = %delegate_key,
            api_version = %api_version,
            "Starting delegate execution"
        );

        // State maintained across process() calls within this conversation
        let mut context: Vec<u8> = Vec::new();

        // Process all messages, collecting the result.
        // Cleanup happens after the loop regardless of success/failure.
        let process_result: RuntimeResult<()> = (|| {
            for msg in inbound {
                // The wildcard arm at the bottom of this match exists
                // solely because `InboundDelegateMsg` is `#[non_exhaustive]`
                // (stdlib 0.6.0+); every currently-known variant is
                // enumerated above. Re-listing them in a `pat | _` shape
                // (as `wildcard_enum_match_arm` would prefer) is needless
                // duplication that defeats the safety net the wildcard
                // provides for future variants.
                #[allow(clippy::wildcard_enum_match_arm)]
                match msg {
                    InboundDelegateMsg::ApplicationMessage(ApplicationMessage {
                        payload,
                        processed,
                        ..
                    }) => {
                        let app_msg = InboundDelegateMsg::ApplicationMessage(
                            ApplicationMessage::new(payload)
                                .processed(processed)
                                .with_context(DelegateContext::new(context.clone())),
                        );

                        let (outbound, updated_context) = self.exec_inbound_with_env(
                            delegate_key,
                            params,
                            origin,
                            &app_msg,
                            context.clone(),
                            &running.handle,
                            instance_id,
                            api_version,
                        )?;
                        context = updated_context;

                        let mut outbound_queue = VecDeque::from(outbound);
                        self.process_outbound(
                            delegate_key,
                            &running.handle,
                            instance_id,
                            params,
                            origin,
                            &mut outbound_queue,
                            &mut context,
                            &mut results,
                        )?;
                    }
                    InboundDelegateMsg::UserResponse(response) => {
                        let (outbound, updated_context) = self.exec_inbound_with_env(
                            delegate_key,
                            params,
                            origin,
                            &InboundDelegateMsg::UserResponse(response),
                            context.clone(),
                            &running.handle,
                            instance_id,
                            api_version,
                        )?;
                        context = updated_context;

                        let mut outbound_queue = VecDeque::from(outbound);
                        self.process_outbound(
                            delegate_key,
                            &running.handle,
                            instance_id,
                            params,
                            origin,
                            &mut outbound_queue,
                            &mut context,
                            &mut results,
                        )?;
                    }
                    InboundDelegateMsg::GetContractResponse(response) => {
                        let (outbound, updated_context) = self.exec_inbound_with_env(
                            delegate_key,
                            params,
                            origin,
                            &InboundDelegateMsg::GetContractResponse(response),
                            context.clone(),
                            &running.handle,
                            instance_id,
                            api_version,
                        )?;
                        context = updated_context;

                        let mut outbound_queue = VecDeque::from(outbound);
                        self.process_outbound(
                            delegate_key,
                            &running.handle,
                            instance_id,
                            params,
                            origin,
                            &mut outbound_queue,
                            &mut context,
                            &mut results,
                        )?;
                    }
                    msg @ (InboundDelegateMsg::PutContractResponse(_)
                    | InboundDelegateMsg::UpdateContractResponse(_)
                    | InboundDelegateMsg::SubscribeContractResponse(_)
                    | InboundDelegateMsg::ContractNotification(_)
                    | InboundDelegateMsg::DelegateMessage(_)) => {
                        let (outbound, updated_context) = self.exec_inbound_with_env(
                            delegate_key,
                            params,
                            origin,
                            &msg,
                            context.clone(),
                            &running.handle,
                            instance_id,
                            api_version,
                        )?;
                        context = updated_context;

                        let mut outbound_queue = VecDeque::from(outbound);
                        self.process_outbound(
                            delegate_key,
                            &running.handle,
                            instance_id,
                            params,
                            origin,
                            &mut outbound_queue,
                            &mut context,
                            &mut results,
                        )?;
                    }
                    // `InboundDelegateMsg` is `#[non_exhaustive]` (stdlib
                    // 0.6.0+). Future variants are forwarded to the WASM
                    // through the same generic exec path so a delegate
                    // built against a newer stdlib can handle them; the
                    // host neither inspects nor classifies their payload.
                    other => {
                        let (outbound, updated_context) = self.exec_inbound_with_env(
                            delegate_key,
                            params,
                            origin,
                            &other,
                            context.clone(),
                            &running.handle,
                            instance_id,
                            api_version,
                        )?;
                        context = updated_context;

                        let mut outbound_queue = VecDeque::from(outbound);
                        self.process_outbound(
                            delegate_key,
                            &running.handle,
                            instance_id,
                            params,
                            origin,
                            &mut outbound_queue,
                            &mut context,
                            &mut results,
                        )?;
                    }
                }
            }
            Ok(())
        })();

        // Always clean up the WASM Instance, even on error.
        self.drop_running_instance(&mut running);

        process_result?;

        tracing::debug!(
            count = results.len(),
            "Final results returned by inbound_app_message"
        );
        Ok(results)
    }

    #[inline]
    fn register_delegate(
        &mut self,
        delegate: DelegateContainer,
        cipher: XChaCha20Poly1305,
        nonce: XNonce,
    ) -> RuntimeResult<()> {
        self.secret_store
            .register_delegate(delegate.key().clone(), cipher, nonce)?;
        self.delegate_store.store_delegate(delegate)
    }

    #[inline]
    fn unregister_delegate(&mut self, key: &DelegateKey) -> RuntimeResult<()> {
        self.delegate_modules.lock().unwrap().pop(key);
        self.delegate_store.remove_delegate(key)
    }
}

#[cfg(all(test, feature = "wasmtime-backend"))]
mod test {
    use chacha20poly1305::aead::{AeadCore, KeyInit, OsRng};
    use freenet_stdlib::prelude::*;
    use serde::{Deserialize, Serialize};
    use std::sync::Arc;

    use std::os::unix::fs::PermissionsExt;

    use crate::util::tests::get_temp_dir;

    use super::super::{ContractStore, SecretsStore, delegate_store::DelegateStore};
    use super::*;

    const TEST_DELEGATE_2: &str = "test_delegate_2";

    /// Message types for test-delegate-2 (host function API)
    mod delegate2_messages {
        use super::*;

        #[derive(Debug, Serialize, Deserialize)]
        pub enum InboundAppMessage {
            CreateInboxRequest,
            PleaseSignMessage(Vec<u8>),
            WriteContext(Vec<u8>),
            ReadContext,
            ClearContext,
            IncrementCounter,
            HasSecret(Vec<u8>),
            GetNonExistentSecret(Vec<u8>),
            StoreSecret { key: Vec<u8>, value: Vec<u8> },
            RemoveSecret(Vec<u8>),
            WriteLargeContext(usize),
            StoreLargeSecret { key: Vec<u8>, size: usize },
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub enum OutboundAppMessage {
            CreateInboxResponse(Vec<u8>),
            MessageSigned(Vec<u8>),
            ContextData(Vec<u8>),
            CounterValue(u32),
            SecretExists(bool),
            SecretResult(Option<Vec<u8>>),
            ContextWritten,
            ContextCleared,
            SecretStored,
            SecretRemoved,
            LargeContextWritten(usize),
            LargeSecretStored(usize),
            SecretStoreFailed,
        }
    }

    async fn setup_runtime(
        name: &str,
    ) -> Result<(DelegateContainer, Runtime, tempfile::TempDir), Box<dyn std::error::Error>> {
        use crate::contract::storages::Storage;
        let temp_dir = get_temp_dir();
        let contracts_dir = temp_dir.path().join("contracts");
        let delegates_dir = temp_dir.path().join("delegates");
        let secrets_dir = temp_dir.path().join("secrets");

        let db = Storage::new(temp_dir.path()).await?;
        let contract_store = ContractStore::new(contracts_dir, 10_000, db.clone())?;
        let delegate_store = DelegateStore::new(delegates_dir, 10_000, db.clone())?;
        let secret_store = SecretsStore::new(secrets_dir, Default::default(), db)?;

        let mut runtime =
            Runtime::build(contract_store, delegate_store, secret_store, false).unwrap();

        let delegate = {
            let bytes = super::super::tests::get_test_module(name)?;
            DelegateContainer::Wasm(DelegateWasmAPIVersion::V1(Delegate::from((
                &bytes.into(),
                &vec![].into(),
            ))))
        };
        let _stored = runtime.delegate_store.store_delegate(delegate.clone());

        let key = XChaCha20Poly1305::generate_key(&mut OsRng);
        let cipher = XChaCha20Poly1305::new(&key);
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let _registered =
            runtime
                .secret_store
                .register_delegate(delegate.key().clone(), cipher, nonce);

        Ok((delegate, runtime, temp_dir))
    }

    const TEST_DELEGATE_CAPABILITIES: &str = "test_delegate_capabilities";

    /// Message types for test-delegate-capabilities (must match the delegate's types)
    mod capabilities_messages {
        use super::*;

        #[derive(Debug, Serialize, Deserialize)]
        #[allow(clippy::enum_variant_names)]
        pub enum DelegateCommand {
            GetContractState {
                contract_id: ContractInstanceId,
            },
            GetMultipleContractStates {
                contract_ids: Vec<ContractInstanceId>,
            },
            GetContractWithEcho {
                contract_id: ContractInstanceId,
                echo_message: String,
            },
            PutContractState {
                contract: ContractContainer,
                state: Vec<u8>,
            },
            UpdateContractState {
                contract_id: ContractInstanceId,
                state: Vec<u8>,
            },
            SubscribeContract {
                contract_id: ContractInstanceId,
            },
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub enum DelegateResponse {
            ContractState {
                contract_id: ContractInstanceId,
                state: Option<Vec<u8>>,
            },
            MultipleContractStates {
                results: Vec<(ContractInstanceId, Option<Vec<u8>>)>,
            },
            Echo {
                message: String,
            },
            ContractPutResult {
                contract_id: ContractInstanceId,
                success: bool,
                error: Option<String>,
            },
            ContractUpdateResult {
                contract_id: ContractInstanceId,
                success: bool,
                error: Option<String>,
            },
            ContractSubscribeResult {
                contract_id: ContractInstanceId,
                success: bool,
                error: Option<String>,
            },
            ContractNotificationReceived {
                contract_id: ContractInstanceId,
                new_state: Vec<u8>,
            },
            Error {
                message: String,
            },
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_get_contract_request_response() -> Result<(), Box<dyn std::error::Error>> {
        use capabilities_messages::*;

        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_CAPABILITIES).await?;
        let target_contract_id = ContractInstanceId::new([42u8; 32]);
        let _app_id = ContractInstanceId::new([1u8; 32]);

        let command = DelegateCommand::GetContractState {
            contract_id: target_contract_id,
        };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 1, "Expected exactly one outbound message");
        let contract_request = match &outbound[0] {
            OutboundDelegateMsg::GetContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected GetContractRequest, got {:?}", other)
            }
        };
        assert_eq!(contract_request.contract_id, target_contract_id);
        assert!(!contract_request.processed);

        let contract_state = vec![1, 2, 3, 4, 5];
        let response = InboundDelegateMsg::GetContractResponse(GetContractResponse {
            contract_id: target_contract_id,
            state: Some(WrappedState::new(contract_state.clone())),
            context: contract_request.context.clone(),
        });

        let final_outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![response])?;

        assert_eq!(final_outbound.len(), 1);
        let final_msg = match &final_outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(final_msg.processed);

        let response: DelegateResponse = bincode::deserialize(&final_msg.payload)?;
        match response {
            DelegateResponse::ContractState { contract_id, state } => {
                assert_eq!(contract_id, target_contract_id);
                assert_eq!(state, Some(contract_state));
            }
            other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::ContractNotificationReceived { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected ContractState response, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_get_contract_not_found() -> Result<(), Box<dyn std::error::Error>> {
        use capabilities_messages::*;

        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_CAPABILITIES).await?;
        let target_contract_id = ContractInstanceId::new([99u8; 32]);
        let _app_id = ContractInstanceId::new([1u8; 32]);

        let command = DelegateCommand::GetContractState {
            contract_id: target_contract_id,
        };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        let contract_request = match &outbound[0] {
            OutboundDelegateMsg::GetContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected GetContractRequest, got {:?}", other)
            }
        };

        let response = InboundDelegateMsg::GetContractResponse(GetContractResponse {
            contract_id: target_contract_id,
            state: None,
            context: contract_request.context.clone(),
        });

        let final_outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![response])?;

        let final_msg = match &final_outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };

        let response: DelegateResponse = bincode::deserialize(&final_msg.payload)?;
        match response {
            DelegateResponse::ContractState { state, .. } => {
                assert!(state.is_none());
            }
            other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::ContractNotificationReceived { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected ContractState response, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_multiple_contract_requests() -> Result<(), Box<dyn std::error::Error>> {
        use capabilities_messages::*;

        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_CAPABILITIES).await?;

        let contract1 = ContractInstanceId::new([1u8; 32]);
        let contract2 = ContractInstanceId::new([2u8; 32]);
        let contract3 = ContractInstanceId::new([3u8; 32]);
        let _app_id = ContractInstanceId::new([10u8; 32]);

        let command = DelegateCommand::GetMultipleContractStates {
            contract_ids: vec![contract1, contract2, contract3],
        };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 1);
        let req1 = match &outbound[0] {
            OutboundDelegateMsg::GetContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected GetContractRequest, got {:?}", other)
            }
        };
        assert_eq!(req1.contract_id, contract1);

        let response1 = InboundDelegateMsg::GetContractResponse(GetContractResponse {
            contract_id: contract1,
            state: Some(WrappedState::new(vec![1, 1, 1])),
            context: req1.context,
        });

        let outbound2 =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![response1])?;

        assert_eq!(outbound2.len(), 1);
        let req2 = match &outbound2[0] {
            OutboundDelegateMsg::GetContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected GetContractRequest for contract2, got {:?}", other)
            }
        };
        assert_eq!(req2.contract_id, contract2);

        let response2 = InboundDelegateMsg::GetContractResponse(GetContractResponse {
            contract_id: contract2,
            state: Some(WrappedState::new(vec![2, 2, 2])),
            context: req2.context,
        });

        let outbound3 =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![response2])?;

        assert_eq!(outbound3.len(), 1);
        let req3 = match &outbound3[0] {
            OutboundDelegateMsg::GetContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected GetContractRequest for contract3, got {:?}", other)
            }
        };
        assert_eq!(req3.contract_id, contract3);

        let response3 = InboundDelegateMsg::GetContractResponse(GetContractResponse {
            contract_id: contract3,
            state: Some(WrappedState::new(vec![3, 3, 3])),
            context: req3.context,
        });

        let final_outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![response3])?;

        assert_eq!(final_outbound.len(), 1);
        let final_msg = match &final_outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(final_msg.processed);

        let response: DelegateResponse = bincode::deserialize(&final_msg.payload)?;
        match response {
            DelegateResponse::MultipleContractStates { results } => {
                assert_eq!(results.len(), 3);
                assert_eq!(results[0].0, contract1);
                assert_eq!(results[0].1, Some(vec![1, 1, 1]));
                assert_eq!(results[1].0, contract2);
                assert_eq!(results[1].1, Some(vec![2, 2, 2]));
                assert_eq!(results[2].0, contract3);
                assert_eq!(results[2].1, Some(vec![3, 3, 3]));
            }
            other @ DelegateResponse::ContractState { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::ContractNotificationReceived { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected MultipleContractStates, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_message_accumulation() -> Result<(), Box<dyn std::error::Error>> {
        use capabilities_messages::*;

        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_CAPABILITIES).await?;

        let contract_id = ContractInstanceId::new([42u8; 32]);
        let _app_id = ContractInstanceId::new([1u8; 32]);
        let echo_message = "Hello from test!".to_string();

        let command = DelegateCommand::GetContractWithEcho {
            contract_id,
            echo_message: echo_message.clone(),
        };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 2);

        let contract_request = outbound
            .iter()
            .find_map(|msg| match msg {
                OutboundDelegateMsg::GetContractRequest(req) => Some(req.clone()),
                OutboundDelegateMsg::ApplicationMessage(_)
                | OutboundDelegateMsg::RequestUserInput(_)
                | OutboundDelegateMsg::ContextUpdated(_)
                | OutboundDelegateMsg::PutContractRequest(_)
                | OutboundDelegateMsg::UpdateContractRequest(_)
                | OutboundDelegateMsg::SubscribeContractRequest(_)
                | OutboundDelegateMsg::SendDelegateMessage(_) => None,
            })
            .expect("Expected a GetContractRequest");
        assert_eq!(contract_request.contract_id, contract_id);

        let echo_msg = outbound
            .iter()
            .find_map(|msg| match msg {
                OutboundDelegateMsg::ApplicationMessage(m) => Some(m.clone()),
                OutboundDelegateMsg::RequestUserInput(_)
                | OutboundDelegateMsg::ContextUpdated(_)
                | OutboundDelegateMsg::GetContractRequest(_)
                | OutboundDelegateMsg::PutContractRequest(_)
                | OutboundDelegateMsg::UpdateContractRequest(_)
                | OutboundDelegateMsg::SubscribeContractRequest(_)
                | OutboundDelegateMsg::SendDelegateMessage(_) => None,
            })
            .expect("Expected an ApplicationMessage (Echo)");
        assert!(echo_msg.processed);

        let echo_response: DelegateResponse = bincode::deserialize(&echo_msg.payload)?;
        match echo_response {
            DelegateResponse::Echo { message } => {
                assert_eq!(message, echo_message);
            }
            other @ DelegateResponse::ContractState { .. }
            | other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::ContractNotificationReceived { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected Echo response, got {:?}", other)
            }
        }

        let contract_response = InboundDelegateMsg::GetContractResponse(GetContractResponse {
            contract_id,
            state: Some(WrappedState::new(vec![1, 2, 3, 4])),
            context: contract_request.context,
        });

        let final_outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![contract_response],
        )?;

        assert_eq!(final_outbound.len(), 1);
        let final_msg = match &final_outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };

        let response: DelegateResponse = bincode::deserialize(&final_msg.payload)?;
        match response {
            DelegateResponse::ContractState {
                contract_id: id,
                state,
            } => {
                assert_eq!(id, contract_id);
                assert_eq!(state, Some(vec![1, 2, 3, 4]));
            }
            other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::ContractNotificationReceived { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected ContractState response, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn validate_host_function_delegate() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let payload: Vec<u8> = bincode::serialize(&InboundAppMessage::CreateInboxRequest).unwrap();
        let create_msg = ApplicationMessage::new(payload);
        let inbound = InboundDelegateMsg::ApplicationMessage(create_msg);
        let outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![inbound])?;

        let expected_payload =
            bincode::serialize(&OutboundAppMessage::CreateInboxResponse(vec![1])).unwrap();
        assert_eq!(outbound.len(), 1);
        assert!(matches!(
            outbound.first(),
            Some(OutboundDelegateMsg::ApplicationMessage(msg)) if *msg.payload == expected_payload
        ));

        let payload: Vec<u8> =
            bincode::serialize(&InboundAppMessage::PleaseSignMessage(vec![1, 2, 3])).unwrap();
        let sign_msg = ApplicationMessage::new(payload);
        let inbound = InboundDelegateMsg::ApplicationMessage(sign_msg);
        let outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![inbound])?;

        let expected_payload =
            bincode::serialize(&OutboundAppMessage::MessageSigned(vec![4, 5, 2])).unwrap();
        assert_eq!(outbound.len(), 1);
        assert!(matches!(
            outbound.first(),
            Some(OutboundDelegateMsg::ApplicationMessage(msg)) if *msg.payload == expected_payload
        ));

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_context_persistence_within_call() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let test_data = vec![1, 2, 3, 4, 5];

        let write_payload =
            bincode::serialize(&InboundAppMessage::WriteContext(test_data.clone()))?;
        let read_payload = bincode::serialize(&InboundAppMessage::ReadContext)?;

        let messages = vec![
            InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(write_payload)),
            InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(read_payload)),
        ];

        let outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, messages)?;

        assert_eq!(outbound.len(), 2);

        let response1: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response1, OutboundAppMessage::ContextWritten));

        let response2: OutboundAppMessage = match &outbound[1] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response2 {
            OutboundAppMessage::ContextData(data) => {
                assert_eq!(data, test_data);
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeContextWritten(_)
            | other @ OutboundAppMessage::LargeSecretStored(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected ContextData, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_context_reset_between_calls() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let payload = bincode::serialize(&InboundAppMessage::IncrementCounter)?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::CounterValue(1)));

        let payload = bincode::serialize(&InboundAppMessage::IncrementCounter)?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::CounterValue(1)));

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_has_secret_host_function() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let secret_key = vec![10, 20, 30];
        let secret_value = vec![100, 200];

        let payload = bincode::serialize(&InboundAppMessage::HasSecret(secret_key.clone()))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::SecretExists(false)));

        let payload = bincode::serialize(&InboundAppMessage::StoreSecret {
            key: secret_key.clone(),
            value: secret_value.clone(),
        })?;
        let msg = ApplicationMessage::new(payload);
        let _ = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let payload = bincode::serialize(&InboundAppMessage::HasSecret(secret_key.clone()))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::SecretExists(true)));

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_get_nonexistent_secret() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let nonexistent_key = vec![99, 98, 97];
        let payload =
            bincode::serialize(&InboundAppMessage::GetNonExistentSecret(nonexistent_key))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::SecretResult(None)));

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_store_and_retrieve_secret() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let secret_key = vec![42, 43, 44];
        let secret_value = vec![1, 2, 3, 4, 5, 6, 7, 8];

        let payload = bincode::serialize(&InboundAppMessage::StoreSecret {
            key: secret_key.clone(),
            value: secret_value.clone(),
        })?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::SecretStored));

        let payload =
            bincode::serialize(&InboundAppMessage::GetNonExistentSecret(secret_key.clone()))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response {
            OutboundAppMessage::SecretResult(Some(value)) => {
                assert_eq!(value, secret_value);
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::ContextData(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeContextWritten(_)
            | other @ OutboundAppMessage::LargeSecretStored(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected SecretResult(Some(...)), got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_set_secret_failure_returns_secret_store_failed()
    -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        // Make secrets directory read-only so store_secret fails with an I/O error
        let secrets_dir = temp_dir.path().join("secrets");
        std::fs::set_permissions(&secrets_dir, std::fs::Permissions::from_mode(0o444))?;

        let payload = bincode::serialize(&InboundAppMessage::StoreSecret {
            key: vec![1, 2, 3],
            value: vec![4, 5, 6],
        })?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(
            matches!(response, OutboundAppMessage::SecretStoreFailed),
            "Expected SecretStoreFailed when secrets dir is read-only, got {:?}",
            response
        );

        // Restore permissions so temp_dir cleanup works
        std::fs::set_permissions(&secrets_dir, std::fs::Permissions::from_mode(0o755))?;
        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_read_empty_context() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let payload = bincode::serialize(&InboundAppMessage::ReadContext)?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response {
            OutboundAppMessage::ContextData(data) => {
                assert!(data.is_empty());
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeContextWritten(_)
            | other @ OutboundAppMessage::LargeSecretStored(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected ContextData, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_context_clear() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let test_data = vec![1, 2, 3, 4, 5];
        let payload = bincode::serialize(&InboundAppMessage::WriteContext(test_data.clone()))?;
        let msg = ApplicationMessage::new(payload);
        let _ = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let payload = bincode::serialize(&InboundAppMessage::ClearContext)?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::ContextCleared));

        let payload = bincode::serialize(&InboundAppMessage::ReadContext)?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response {
            OutboundAppMessage::ContextData(data) => {
                assert!(data.is_empty());
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeContextWritten(_)
            | other @ OutboundAppMessage::LargeSecretStored(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected ContextData, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_context_shared_across_batch() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let messages: Vec<InboundDelegateMsg> = (0..3)
            .map(|_| {
                let payload = bincode::serialize(&InboundAppMessage::IncrementCounter).unwrap();
                InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(payload))
            })
            .collect();

        let outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, messages)?;

        assert_eq!(outbound.len(), 3);

        for (i, msg) in outbound.iter().enumerate() {
            let response: OutboundAppMessage = match msg {
                OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
                OutboundDelegateMsg::RequestUserInput(_)
                | OutboundDelegateMsg::ContextUpdated(_)
                | OutboundDelegateMsg::GetContractRequest(_)
                | OutboundDelegateMsg::PutContractRequest(_)
                | OutboundDelegateMsg::UpdateContractRequest(_)
                | OutboundDelegateMsg::SubscribeContractRequest(_)
                | OutboundDelegateMsg::SendDelegateMessage(_) => {
                    panic!("Expected ApplicationMessage")
                }
            };
            match response {
                OutboundAppMessage::CounterValue(value) => {
                    assert_eq!(value, (i + 1) as u32);
                }
                other @ OutboundAppMessage::CreateInboxResponse(_)
                | other @ OutboundAppMessage::MessageSigned(_)
                | other @ OutboundAppMessage::ContextData(_)
                | other @ OutboundAppMessage::SecretExists(_)
                | other @ OutboundAppMessage::SecretResult(_)
                | other @ OutboundAppMessage::ContextWritten
                | other @ OutboundAppMessage::ContextCleared
                | other @ OutboundAppMessage::SecretStored
                | other @ OutboundAppMessage::SecretRemoved
                | other @ OutboundAppMessage::LargeContextWritten(_)
                | other @ OutboundAppMessage::LargeSecretStored(_)
                | other @ OutboundAppMessage::SecretStoreFailed => {
                    panic!("Expected CounterValue, got {:?}", other)
                }
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_remove_secret_host_function() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let secret_key = vec![50, 51, 52];
        let secret_value = vec![200, 201, 202];

        let payload = bincode::serialize(&InboundAppMessage::StoreSecret {
            key: secret_key.clone(),
            value: secret_value.clone(),
        })?;
        let msg = ApplicationMessage::new(payload);
        let _ = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;

        let payload = bincode::serialize(&InboundAppMessage::HasSecret(secret_key.clone()))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;
        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::SecretExists(true)));

        let payload = bincode::serialize(&InboundAppMessage::RemoveSecret(secret_key.clone()))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;
        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::SecretRemoved));

        let payload = bincode::serialize(&InboundAppMessage::HasSecret(secret_key.clone()))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;
        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        assert!(matches!(response, OutboundAppMessage::SecretExists(false)));

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_large_context_data() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let large_size = 1024 * 1024;

        let payload = bincode::serialize(&InboundAppMessage::WriteLargeContext(large_size))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;
        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response {
            OutboundAppMessage::LargeContextWritten(size) => {
                assert_eq!(size, large_size);
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::ContextData(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeSecretStored(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected LargeContextWritten, got {:?}", other)
            }
        }

        let payload = bincode::serialize(&InboundAppMessage::ReadContext)?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;
        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response {
            OutboundAppMessage::ContextData(data) => {
                assert!(data.is_empty());
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeContextWritten(_)
            | other @ OutboundAppMessage::LargeSecretStored(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected ContextData, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_large_context_within_batch() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let large_size = 256 * 1024;

        let write_payload = bincode::serialize(&InboundAppMessage::WriteLargeContext(large_size))?;
        let read_payload = bincode::serialize(&InboundAppMessage::ReadContext)?;

        let messages = vec![
            InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(write_payload)),
            InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(read_payload)),
        ];

        let outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, messages)?;

        assert_eq!(outbound.len(), 2);

        let response: OutboundAppMessage = match &outbound[1] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response {
            OutboundAppMessage::ContextData(data) => {
                assert_eq!(data.len(), large_size);
                for (i, byte) in data.iter().enumerate() {
                    assert_eq!(*byte, (i % 256) as u8, "Data pattern mismatch at index {i}");
                }
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeContextWritten(_)
            | other @ OutboundAppMessage::LargeSecretStored(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected ContextData, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    /// Indirect regression test for #3248 (stale WASM memory base pointer).
    ///
    /// Storing a 1 MB secret forces `memory.grow` which can relocate WASM linear
    /// memory. If the cached `MEM_ADDR.start_ptr` is not refreshed via
    /// `refresh_mem_addr_from_caller`, the subsequent read uses a stale pointer
    /// and returns garbage data. Under full parallel test suite runs (~1600 tests)
    /// the relocation is more likely due to memory pressure.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_large_secret_data() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_2).await?;
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let secret_key = vec![77, 88, 99];
        let large_size = 1024 * 1024;

        let payload = bincode::serialize(&InboundAppMessage::StoreLargeSecret {
            key: secret_key.clone(),
            size: large_size,
        })?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;
        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response {
            OutboundAppMessage::LargeSecretStored(size) => {
                assert_eq!(size, large_size);
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::ContextData(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeContextWritten(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected LargeSecretStored, got {:?}", other)
            }
        }

        let payload =
            bincode::serialize(&InboundAppMessage::GetNonExistentSecret(secret_key.clone()))?;
        let msg = ApplicationMessage::new(payload);
        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(msg)],
        )?;
        let response: OutboundAppMessage = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => bincode::deserialize(&m.payload)?,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage")
            }
        };
        match response {
            OutboundAppMessage::SecretResult(Some(data)) => {
                assert_eq!(data.len(), large_size);
                for (i, byte) in data.iter().enumerate() {
                    assert_eq!(*byte, (i % 256) as u8, "Data pattern mismatch at index {i}");
                }
            }
            other @ OutboundAppMessage::CreateInboxResponse(_)
            | other @ OutboundAppMessage::MessageSigned(_)
            | other @ OutboundAppMessage::ContextData(_)
            | other @ OutboundAppMessage::CounterValue(_)
            | other @ OutboundAppMessage::SecretExists(_)
            | other @ OutboundAppMessage::SecretResult(_)
            | other @ OutboundAppMessage::ContextWritten
            | other @ OutboundAppMessage::ContextCleared
            | other @ OutboundAppMessage::SecretStored
            | other @ OutboundAppMessage::SecretRemoved
            | other @ OutboundAppMessage::LargeContextWritten(_)
            | other @ OutboundAppMessage::LargeSecretStored(_)
            | other @ OutboundAppMessage::SecretStoreFailed => {
                panic!("Expected SecretResult(Some(...)), got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_concurrent_delegate_execution() -> Result<(), Box<dyn std::error::Error>> {
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};
        use std::sync::Arc;
        use tokio::sync::Barrier;

        let (delegate1, runtime1, temp_dir1) = setup_runtime(TEST_DELEGATE_2).await?;
        let (delegate2, runtime2, temp_dir2) = setup_runtime(TEST_DELEGATE_2).await?;

        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let runtime1 = Arc::new(std::sync::Mutex::new(runtime1));
        let runtime2 = Arc::new(std::sync::Mutex::new(runtime2));
        let delegate1 = Arc::new(delegate1);
        let delegate2 = Arc::new(delegate2);

        let barrier = Arc::new(Barrier::new(2));

        let barrier1 = barrier.clone();
        let runtime1_clone = runtime1.clone();
        let delegate1_clone = delegate1.clone();
        let handle1 = tokio::spawn(async move {
            barrier1.wait().await;

            let secret_key = b"thread1_key".to_vec();
            let secret_value = b"thread1_value".to_vec();

            let payload = bincode::serialize(&InboundAppMessage::StoreSecret {
                key: secret_key.clone(),
                value: secret_value.clone(),
            })
            .unwrap();
            let msg = ApplicationMessage::new(payload);
            {
                let mut runtime = runtime1_clone.lock().unwrap();
                let _ = runtime
                    .inbound_app_message(
                        delegate1_clone.key(),
                        &vec![].into(),
                        None,
                        vec![InboundDelegateMsg::ApplicationMessage(msg)],
                    )
                    .unwrap();
            }

            let payload =
                bincode::serialize(&InboundAppMessage::GetNonExistentSecret(secret_key.clone()))
                    .unwrap();
            let msg = ApplicationMessage::new(payload);
            let outbound = {
                let mut runtime = runtime1_clone.lock().unwrap();
                runtime
                    .inbound_app_message(
                        delegate1_clone.key(),
                        &vec![].into(),
                        None,
                        vec![InboundDelegateMsg::ApplicationMessage(msg)],
                    )
                    .unwrap()
            };

            let response: OutboundAppMessage = match &outbound[0] {
                OutboundDelegateMsg::ApplicationMessage(m) => {
                    bincode::deserialize(&m.payload).unwrap()
                }
                OutboundDelegateMsg::RequestUserInput(_)
                | OutboundDelegateMsg::ContextUpdated(_)
                | OutboundDelegateMsg::GetContractRequest(_)
                | OutboundDelegateMsg::PutContractRequest(_)
                | OutboundDelegateMsg::UpdateContractRequest(_)
                | OutboundDelegateMsg::SubscribeContractRequest(_)
                | OutboundDelegateMsg::SendDelegateMessage(_) => {
                    panic!("Expected ApplicationMessage")
                }
            };
            match response {
                OutboundAppMessage::SecretResult(Some(value)) => {
                    assert_eq!(value, secret_value);
                }
                other @ OutboundAppMessage::CreateInboxResponse(_)
                | other @ OutboundAppMessage::MessageSigned(_)
                | other @ OutboundAppMessage::ContextData(_)
                | other @ OutboundAppMessage::CounterValue(_)
                | other @ OutboundAppMessage::SecretExists(_)
                | other @ OutboundAppMessage::SecretResult(_)
                | other @ OutboundAppMessage::ContextWritten
                | other @ OutboundAppMessage::ContextCleared
                | other @ OutboundAppMessage::SecretStored
                | other @ OutboundAppMessage::SecretRemoved
                | other @ OutboundAppMessage::LargeContextWritten(_)
                | other @ OutboundAppMessage::LargeSecretStored(_)
                | other @ OutboundAppMessage::SecretStoreFailed => panic!(
                    "Thread 1: Expected SecretResult(Some(...)), got {:?}",
                    other
                ),
            }
        });

        let barrier2 = barrier.clone();
        let runtime2_clone = runtime2.clone();
        let delegate2_clone = delegate2.clone();
        let handle2 = tokio::spawn(async move {
            barrier2.wait().await;

            let secret_key = b"thread2_key".to_vec();
            let secret_value = b"thread2_value".to_vec();

            let payload = bincode::serialize(&InboundAppMessage::StoreSecret {
                key: secret_key.clone(),
                value: secret_value.clone(),
            })
            .unwrap();
            let msg = ApplicationMessage::new(payload);
            {
                let mut runtime = runtime2_clone.lock().unwrap();
                let _ = runtime
                    .inbound_app_message(
                        delegate2_clone.key(),
                        &vec![].into(),
                        None,
                        vec![InboundDelegateMsg::ApplicationMessage(msg)],
                    )
                    .unwrap();
            }

            let payload =
                bincode::serialize(&InboundAppMessage::GetNonExistentSecret(secret_key.clone()))
                    .unwrap();
            let msg = ApplicationMessage::new(payload);
            let outbound = {
                let mut runtime = runtime2_clone.lock().unwrap();
                runtime
                    .inbound_app_message(
                        delegate2_clone.key(),
                        &vec![].into(),
                        None,
                        vec![InboundDelegateMsg::ApplicationMessage(msg)],
                    )
                    .unwrap()
            };

            let response: OutboundAppMessage = match &outbound[0] {
                OutboundDelegateMsg::ApplicationMessage(m) => {
                    bincode::deserialize(&m.payload).unwrap()
                }
                OutboundDelegateMsg::RequestUserInput(_)
                | OutboundDelegateMsg::ContextUpdated(_)
                | OutboundDelegateMsg::GetContractRequest(_)
                | OutboundDelegateMsg::PutContractRequest(_)
                | OutboundDelegateMsg::UpdateContractRequest(_)
                | OutboundDelegateMsg::SubscribeContractRequest(_)
                | OutboundDelegateMsg::SendDelegateMessage(_) => {
                    panic!("Expected ApplicationMessage")
                }
            };
            match response {
                OutboundAppMessage::SecretResult(Some(value)) => {
                    assert_eq!(value, secret_value);
                }
                other @ OutboundAppMessage::CreateInboxResponse(_)
                | other @ OutboundAppMessage::MessageSigned(_)
                | other @ OutboundAppMessage::ContextData(_)
                | other @ OutboundAppMessage::CounterValue(_)
                | other @ OutboundAppMessage::SecretExists(_)
                | other @ OutboundAppMessage::SecretResult(_)
                | other @ OutboundAppMessage::ContextWritten
                | other @ OutboundAppMessage::ContextCleared
                | other @ OutboundAppMessage::SecretStored
                | other @ OutboundAppMessage::SecretRemoved
                | other @ OutboundAppMessage::LargeContextWritten(_)
                | other @ OutboundAppMessage::LargeSecretStored(_)
                | other @ OutboundAppMessage::SecretStoreFailed => panic!(
                    "Thread 2: Expected SecretResult(Some(...)), got {:?}",
                    other
                ),
            }
        });

        handle1.await?;
        handle2.await?;

        std::mem::drop(temp_dir1);
        std::mem::drop(temp_dir2);
        Ok(())
    }

    /// Verify that V1 delegates are correctly detected as V1 even when
    /// state_store_db is configured. This ensures backward compatibility —
    /// V2 detection is based on module imports, not runtime configuration.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_v1_delegate_detected_as_v1_with_state_store()
    -> Result<(), Box<dyn std::error::Error>> {
        use crate::contract::storages::Storage;
        use delegate2_messages::{InboundAppMessage, OutboundAppMessage};

        let temp_dir = get_temp_dir();
        let contracts_dir = temp_dir.path().join("contracts");
        let delegates_dir = temp_dir.path().join("delegates");
        let secrets_dir = temp_dir.path().join("secrets");

        let db = Storage::new(temp_dir.path()).await?;
        let contract_store = ContractStore::new(contracts_dir, 10_000, db.clone())?;
        let delegate_store = DelegateStore::new(delegates_dir, 10_000, db.clone())?;
        let secret_store = SecretsStore::new(secrets_dir, Default::default(), db.clone())?;

        let mut runtime =
            Runtime::build(contract_store, delegate_store, secret_store, false).unwrap();

        // Configure state_store_db — V1 delegates should STILL be detected as V1
        runtime.set_state_store_db(db);

        let delegate = {
            let bytes = super::super::tests::get_test_module(TEST_DELEGATE_2)?;
            DelegateContainer::Wasm(DelegateWasmAPIVersion::V1(Delegate::from((
                &bytes.into(),
                &vec![].into(),
            ))))
        };
        let _stored = runtime.delegate_store.store_delegate(delegate.clone());

        let key = XChaCha20Poly1305::generate_key(&mut OsRng);
        let cipher = XChaCha20Poly1305::new(&key);
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let _registered =
            runtime
                .secret_store
                .register_delegate(delegate.key().clone(), cipher, nonce);

        // Verify API version detection: V1 delegate should be V1
        let (mut running, api_version) =
            runtime.prepare_delegate_call(&vec![].into(), delegate.key(), 4096)?;
        assert_eq!(
            api_version,
            DelegateApiVersion::V1,
            "V1 delegate should be detected as V1 even with state_store_db configured"
        );
        runtime.drop_running_instance(&mut running);

        // Verify the delegate still works normally via the V1 path
        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![1])),
            Parameters::from(vec![]),
        );
        let _app = ContractInstanceId::try_from(contract.key.to_string()).unwrap();

        let payload: Vec<u8> = bincode::serialize(&InboundAppMessage::CreateInboxRequest).unwrap();
        let create_msg = ApplicationMessage::new(payload);
        let inbound = InboundDelegateMsg::ApplicationMessage(create_msg);
        let outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![inbound])?;

        let expected_payload =
            bincode::serialize(&OutboundAppMessage::CreateInboxResponse(vec![1])).unwrap();
        assert_eq!(outbound.len(), 1);
        assert!(matches!(
            outbound.first(),
            Some(OutboundDelegateMsg::ApplicationMessage(msg)) if *msg.payload == expected_payload
        ));

        std::mem::drop(temp_dir);
        Ok(())
    }

    const TEST_DELEGATE_V2_CONTRACTS: &str = "test_delegate_v2_contracts";

    /// Message types for test-delegate-v2-contracts (must match the delegate's types)
    mod v2_contracts_messages {
        use super::*;

        #[derive(Debug, Serialize, Deserialize)]
        pub enum InboundAppMessage {
            GetContractState {
                contract_id: [u8; 32],
            },
            PutContractState {
                contract_id: [u8; 32],
                state: Vec<u8>,
            },
            UpdateContractState {
                contract_id: [u8; 32],
                state: Vec<u8>,
            },
            SubscribeContract {
                contract_id: [u8; 32],
            },
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub enum OutboundAppMessage {
            ContractState {
                contract_id: [u8; 32],
                state: Vec<u8>,
            },
            ContractNotFound {
                contract_id: [u8; 32],
                error_code: i64,
            },
            Success {
                contract_id: [u8; 32],
            },
            Failed {
                contract_id: [u8; 32],
                error_code: i64,
            },
        }
    }

    /// V2 delegate end-to-end test: a real compiled WASM delegate that reads
    /// contract state via host functions from the `freenet_delegate_contracts`
    /// namespace. This exercises the full V2 async call path:
    ///
    /// 1. Module is detected as V2 (imports `freenet_delegate_contracts`)
    /// 2. `call_3i64_async_imports` is used instead of `call_3i64`
    /// 3. Host functions `get_contract_state_len` and `get_contract_state`
    ///    read from the ReDb state store
    #[tokio::test(flavor = "multi_thread")]
    async fn test_v2_delegate_reads_contract_state() -> Result<(), Box<dyn std::error::Error>> {
        use crate::contract::storages::Storage;
        use crate::wasm_runtime::StateStorage;
        use v2_contracts_messages::*;

        let temp_dir = get_temp_dir();
        let contracts_dir = temp_dir.path().join("contracts");
        let delegates_dir = temp_dir.path().join("delegates");
        let secrets_dir = temp_dir.path().join("secrets");

        let db = Storage::new(temp_dir.path()).await?;
        let contract_store = ContractStore::new(contracts_dir, 10_000, db.clone())?;
        let delegate_store = DelegateStore::new(delegates_dir, 10_000, db.clone())?;
        let secret_store = SecretsStore::new(secrets_dir, Default::default(), db.clone())?;

        let mut runtime =
            Runtime::build(contract_store, delegate_store, secret_store, false).unwrap();
        runtime.set_state_store_db(db.clone());

        // Store contract state in the DB so the V2 delegate can read it
        let contract_instance_id = ContractInstanceId::new([42u8; 32]);
        let contract_code = ContractCode::from(vec![1, 2, 3]);
        let contract_key =
            ContractKey::from_id_and_code(contract_instance_id, *contract_code.hash());
        let expected_state = vec![10, 20, 30, 40, 50, 60, 70, 80];
        db.store(contract_key, WrappedState::new(expected_state.clone()))
            .await?;
        // Index the contract so code_hash_from_id() works
        runtime.contract_store.ensure_key_indexed(&contract_key)?;

        // Load the V2 delegate
        let delegate = {
            let bytes = super::super::tests::get_test_module(TEST_DELEGATE_V2_CONTRACTS)?;
            DelegateContainer::Wasm(DelegateWasmAPIVersion::V1(Delegate::from((
                &bytes.into(),
                &vec![].into(),
            ))))
        };
        let _stored = runtime.delegate_store.store_delegate(delegate.clone());

        let key = XChaCha20Poly1305::generate_key(&mut OsRng);
        let cipher = XChaCha20Poly1305::new(&key);
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let _registered =
            runtime
                .secret_store
                .register_delegate(delegate.key().clone(), cipher, nonce);

        // Verify the module is detected as V2
        let (mut running, api_version) =
            runtime.prepare_delegate_call(&vec![].into(), delegate.key(), 4096)?;
        assert_eq!(
            api_version,
            DelegateApiVersion::V2,
            "V2 delegate should be detected as V2 (imports freenet_delegate_contracts)"
        );
        runtime.drop_running_instance(&mut running);

        // Send a message asking the delegate to read the contract state
        let _app_id = ContractInstanceId::new([1u8; 32]);
        let command = InboundAppMessage::GetContractState {
            contract_id: [42u8; 32],
        };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 1, "Expected exactly one outbound message");
        let response_msg = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(response_msg.processed);

        let response: OutboundAppMessage = bincode::deserialize(&response_msg.payload)?;
        match response {
            OutboundAppMessage::ContractState { contract_id, state } => {
                assert_eq!(contract_id, [42u8; 32]);
                assert_eq!(
                    state, expected_state,
                    "V2 delegate should read contract state via host functions"
                );
            }
            other @ OutboundAppMessage::ContractNotFound { .. }
            | other @ OutboundAppMessage::Success { .. }
            | other @ OutboundAppMessage::Failed { .. } => {
                panic!("V2 delegate returned {other:?} — expected ContractState");
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    /// V2 delegate: contract not found returns error code.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_v2_delegate_contract_not_found() -> Result<(), Box<dyn std::error::Error>> {
        use crate::contract::storages::Storage;
        use v2_contracts_messages::*;

        let temp_dir = get_temp_dir();
        let contracts_dir = temp_dir.path().join("contracts");
        let delegates_dir = temp_dir.path().join("delegates");
        let secrets_dir = temp_dir.path().join("secrets");

        let db = Storage::new(temp_dir.path()).await?;
        let contract_store = ContractStore::new(contracts_dir, 10_000, db.clone())?;
        let delegate_store = DelegateStore::new(delegates_dir, 10_000, db.clone())?;
        let secret_store = SecretsStore::new(secrets_dir, Default::default(), db.clone())?;

        let mut runtime =
            Runtime::build(contract_store, delegate_store, secret_store, false).unwrap();
        runtime.set_state_store_db(db);

        // Load the V2 delegate (no contract state stored — should get not-found)
        let delegate = {
            let bytes = super::super::tests::get_test_module(TEST_DELEGATE_V2_CONTRACTS)?;
            DelegateContainer::Wasm(DelegateWasmAPIVersion::V1(Delegate::from((
                &bytes.into(),
                &vec![].into(),
            ))))
        };
        let _stored = runtime.delegate_store.store_delegate(delegate.clone());

        let key = XChaCha20Poly1305::generate_key(&mut OsRng);
        let cipher = XChaCha20Poly1305::new(&key);
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let _registered =
            runtime
                .secret_store
                .register_delegate(delegate.key().clone(), cipher, nonce);

        // Ask for a contract that doesn't exist
        let _app_id = ContractInstanceId::new([1u8; 32]);
        let command = InboundAppMessage::GetContractState {
            contract_id: [99u8; 32],
        };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 1);
        let response_msg = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };

        let response: OutboundAppMessage = bincode::deserialize(&response_msg.payload)?;
        match response {
            OutboundAppMessage::ContractNotFound { error_code, .. } => {
                assert!(
                    error_code < 0,
                    "Expected negative error code for not-found, got {error_code}"
                );
            }
            other @ OutboundAppMessage::ContractState { .. }
            | other @ OutboundAppMessage::Success { .. }
            | other @ OutboundAppMessage::Failed { .. } => {
                panic!("Expected ContractNotFound for non-existent contract, got {other:?}");
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    /// Helper: set up a V2 delegate runtime with a registered contract.
    async fn setup_v2_runtime_with_contract(
        contract_id_byte: u8,
        initial_state: Option<&[u8]>,
    ) -> Result<
        (
            DelegateContainer,
            Runtime,
            ContractInstanceId,
            tempfile::TempDir,
        ),
        Box<dyn std::error::Error>,
    > {
        use crate::contract::storages::Storage;
        use crate::wasm_runtime::StateStorage;

        let temp_dir = get_temp_dir();
        let contracts_dir = temp_dir.path().join("contracts");
        let delegates_dir = temp_dir.path().join("delegates");
        let secrets_dir = temp_dir.path().join("secrets");

        let db = Storage::new(temp_dir.path()).await?;
        let contract_store = ContractStore::new(contracts_dir, 10_000, db.clone())?;
        let delegate_store = DelegateStore::new(delegates_dir, 10_000, db.clone())?;
        let secret_store = SecretsStore::new(secrets_dir, Default::default(), db.clone())?;

        let mut runtime =
            Runtime::build(contract_store, delegate_store, secret_store, false).unwrap();
        runtime.set_state_store_db(db.clone());

        // Register the contract
        let contract_instance_id = ContractInstanceId::new([contract_id_byte; 32]);
        let contract_code = ContractCode::from(vec![contract_id_byte, 2, 3]);
        let contract_key =
            ContractKey::from_id_and_code(contract_instance_id, *contract_code.hash());
        runtime.contract_store.ensure_key_indexed(&contract_key)?;

        if let Some(state) = initial_state {
            db.store(contract_key, WrappedState::new(state.to_vec()))
                .await?;
        }

        // Load the V2 delegate
        let delegate = {
            let bytes = super::super::tests::get_test_module(TEST_DELEGATE_V2_CONTRACTS)?;
            DelegateContainer::Wasm(DelegateWasmAPIVersion::V1(Delegate::from((
                &bytes.into(),
                &vec![].into(),
            ))))
        };
        let _stored = runtime.delegate_store.store_delegate(delegate.clone());

        let key = XChaCha20Poly1305::generate_key(&mut OsRng);
        let cipher = XChaCha20Poly1305::new(&key);
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let _registered =
            runtime
                .secret_store
                .register_delegate(delegate.key().clone(), cipher, nonce);

        Ok((delegate, runtime, contract_instance_id, temp_dir))
    }

    /// Helper: send a message to the V2 delegate and deserialize the response.
    fn send_v2_message(
        runtime: &mut Runtime,
        delegate: &DelegateContainer,
        message: &v2_contracts_messages::InboundAppMessage,
    ) -> Result<v2_contracts_messages::OutboundAppMessage, Box<dyn std::error::Error>> {
        let _app_id = ContractInstanceId::new([1u8; 32]);
        let payload = bincode::serialize(message)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 1, "Expected exactly one outbound message");
        let response_msg = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(response_msg.processed);

        Ok(bincode::deserialize(&response_msg.payload)?)
    }

    /// V2 E2E: PUT state via delegate, then GET it back.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_v2_delegate_put_then_get() -> Result<(), Box<dyn std::error::Error>> {
        use v2_contracts_messages::*;

        let (delegate, mut runtime, contract_instance_id, _temp_dir) =
            setup_v2_runtime_with_contract(50, None).await?;
        let cid: [u8; 32] = contract_instance_id.as_bytes().try_into().unwrap();

        // PUT state
        let put_response = send_v2_message(
            &mut runtime,
            &delegate,
            &InboundAppMessage::PutContractState {
                contract_id: cid,
                state: vec![100, 200, 150],
            },
        )?;
        match put_response {
            OutboundAppMessage::Success { contract_id } => {
                assert_eq!(contract_id, cid);
            }
            other @ OutboundAppMessage::ContractState { .. }
            | other @ OutboundAppMessage::ContractNotFound { .. }
            | other @ OutboundAppMessage::Failed { .. } => {
                panic!("Expected Success from PUT, got {:?}", other)
            }
        }

        // GET it back
        let get_response = send_v2_message(
            &mut runtime,
            &delegate,
            &InboundAppMessage::GetContractState { contract_id: cid },
        )?;
        match get_response {
            OutboundAppMessage::ContractState { contract_id, state } => {
                assert_eq!(contract_id, cid);
                assert_eq!(state, vec![100, 200, 150]);
            }
            other @ OutboundAppMessage::ContractNotFound { .. }
            | other @ OutboundAppMessage::Success { .. }
            | other @ OutboundAppMessage::Failed { .. } => {
                panic!("Expected ContractState from GET, got {:?}", other)
            }
        }

        Ok(())
    }

    /// V2 E2E: UPDATE existing state via delegate.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_v2_delegate_update_existing_state() -> Result<(), Box<dyn std::error::Error>> {
        use v2_contracts_messages::*;

        let (delegate, mut runtime, contract_instance_id, _temp_dir) =
            setup_v2_runtime_with_contract(51, Some(&[1, 2, 3])).await?;
        let cid: [u8; 32] = contract_instance_id.as_bytes().try_into().unwrap();

        // UPDATE the existing state
        let update_response = send_v2_message(
            &mut runtime,
            &delegate,
            &InboundAppMessage::UpdateContractState {
                contract_id: cid,
                state: vec![7, 8, 9],
            },
        )?;
        match update_response {
            OutboundAppMessage::Success { contract_id } => {
                assert_eq!(contract_id, cid);
            }
            other @ OutboundAppMessage::ContractState { .. }
            | other @ OutboundAppMessage::ContractNotFound { .. }
            | other @ OutboundAppMessage::Failed { .. } => {
                panic!("Expected Success from UPDATE, got {:?}", other)
            }
        }

        // Verify via GET
        let get_response = send_v2_message(
            &mut runtime,
            &delegate,
            &InboundAppMessage::GetContractState { contract_id: cid },
        )?;
        match get_response {
            OutboundAppMessage::ContractState { state, .. } => {
                assert_eq!(state, vec![7, 8, 9]);
            }
            other @ OutboundAppMessage::ContractNotFound { .. }
            | other @ OutboundAppMessage::Success { .. }
            | other @ OutboundAppMessage::Failed { .. } => {
                panic!("Expected ContractState, got {:?}", other)
            }
        }

        Ok(())
    }

    /// V2 E2E: UPDATE non-existent state returns error.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_v2_delegate_update_nonexistent_fails() -> Result<(), Box<dyn std::error::Error>> {
        use v2_contracts_messages::*;

        let (delegate, mut runtime, contract_instance_id, _temp_dir) =
            setup_v2_runtime_with_contract(52, None).await?;
        let cid: [u8; 32] = contract_instance_id.as_bytes().try_into().unwrap();

        let response = send_v2_message(
            &mut runtime,
            &delegate,
            &InboundAppMessage::UpdateContractState {
                contract_id: cid,
                state: vec![1, 2, 3],
            },
        )?;
        match response {
            OutboundAppMessage::Failed { error_code, .. } => {
                assert!(
                    error_code < 0,
                    "Expected negative error code, got {error_code}"
                );
            }
            other @ OutboundAppMessage::ContractState { .. }
            | other @ OutboundAppMessage::ContractNotFound { .. }
            | other @ OutboundAppMessage::Success { .. } => panic!(
                "Expected Failed from UPDATE on non-existent, got {:?}",
                other
            ),
        }

        Ok(())
    }

    /// V2 E2E: SUBSCRIBE to a known contract succeeds.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_v2_delegate_subscribe_known() -> Result<(), Box<dyn std::error::Error>> {
        use v2_contracts_messages::*;

        let (delegate, mut runtime, contract_instance_id, _temp_dir) =
            setup_v2_runtime_with_contract(53, Some(&[1])).await?;
        let cid: [u8; 32] = contract_instance_id.as_bytes().try_into().unwrap();

        let response = send_v2_message(
            &mut runtime,
            &delegate,
            &InboundAppMessage::SubscribeContract { contract_id: cid },
        )?;
        match response {
            OutboundAppMessage::Success { contract_id } => {
                assert_eq!(contract_id, cid);
            }
            other @ OutboundAppMessage::ContractState { .. }
            | other @ OutboundAppMessage::ContractNotFound { .. }
            | other @ OutboundAppMessage::Failed { .. } => {
                panic!("Expected Success from SUBSCRIBE, got {:?}", other)
            }
        }

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_put_contract_request_response() -> Result<(), Box<dyn std::error::Error>> {
        use capabilities_messages::*;

        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_CAPABILITIES).await?;

        let _app_id = ContractInstanceId::new([1u8; 32]);

        let code = ContractCode::from(vec![0u8; 10]);
        let params = Parameters::from(vec![]);
        let wrapped = WrappedContract::new(Arc::new(code), params);
        let contract = ContractContainer::Wasm(ContractWasmAPIVersion::V1(wrapped));
        let contract_key = contract.key();

        let command = DelegateCommand::PutContractState {
            contract,
            state: vec![10, 20, 30],
        };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 1, "Expected exactly one outbound message");
        let put_request = match &outbound[0] {
            OutboundDelegateMsg::PutContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected PutContractRequest, got {:?}", other)
            }
        };
        assert_eq!(put_request.contract.key(), contract_key);
        assert!(!put_request.processed);

        let response = InboundDelegateMsg::PutContractResponse(PutContractResponse {
            contract_id: *contract_key.id(),
            result: Ok(()),
            context: put_request.context.clone(),
        });

        let final_outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![response])?;

        assert_eq!(
            final_outbound.len(),
            1,
            "Expected exactly one final message"
        );
        let final_msg = match &final_outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(final_msg.processed);

        let response: DelegateResponse = bincode::deserialize(&final_msg.payload)?;
        match response {
            DelegateResponse::ContractPutResult { success, error, .. } => {
                assert!(success);
                assert!(error.is_none());
            }
            other @ DelegateResponse::ContractState { .. }
            | other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::ContractNotificationReceived { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected ContractPutResult, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_update_contract_request_response() -> Result<(), Box<dyn std::error::Error>> {
        use capabilities_messages::*;

        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_CAPABILITIES).await?;

        let contract_id = ContractInstanceId::new([42u8; 32]);
        let _app_id = ContractInstanceId::new([1u8; 32]);

        let command = DelegateCommand::UpdateContractState {
            contract_id,
            state: vec![10, 20, 30],
        };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 1, "Expected exactly one outbound message");
        let update_request = match &outbound[0] {
            OutboundDelegateMsg::UpdateContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected UpdateContractRequest, got {:?}", other)
            }
        };
        assert_eq!(update_request.contract_id, contract_id);
        assert!(!update_request.processed);

        let response = InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
            contract_id,
            result: Ok(()),
            context: update_request.context.clone(),
        });

        let final_outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![response])?;

        assert_eq!(
            final_outbound.len(),
            1,
            "Expected exactly one final message"
        );
        let final_msg = match &final_outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(final_msg.processed);

        let response: DelegateResponse = bincode::deserialize(&final_msg.payload)?;
        match response {
            DelegateResponse::ContractUpdateResult {
                contract_id: id,
                success,
                error,
            } => {
                assert_eq!(id, contract_id);
                assert!(success);
                assert!(error.is_none());
            }
            other @ DelegateResponse::ContractState { .. }
            | other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::ContractNotificationReceived { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected ContractUpdateResult, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_subscribe_contract_request_response() -> Result<(), Box<dyn std::error::Error>> {
        use capabilities_messages::*;

        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_CAPABILITIES).await?;

        let contract_id = ContractInstanceId::new([42u8; 32]);
        let _app_id = ContractInstanceId::new([1u8; 32]);

        let command = DelegateCommand::SubscribeContract { contract_id };
        let payload = bincode::serialize(&command)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        assert_eq!(outbound.len(), 1, "Expected exactly one outbound message");
        let subscribe_request = match &outbound[0] {
            OutboundDelegateMsg::SubscribeContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected SubscribeContractRequest, got {:?}", other)
            }
        };
        assert_eq!(subscribe_request.contract_id, contract_id);
        assert!(!subscribe_request.processed);

        let response = InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
            contract_id,
            result: Err("not yet implemented".to_string()),
            context: subscribe_request.context.clone(),
        });

        let final_outbound =
            runtime.inbound_app_message(delegate.key(), &vec![].into(), None, vec![response])?;

        assert_eq!(
            final_outbound.len(),
            1,
            "Expected exactly one final message"
        );
        let final_msg = match &final_outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(final_msg.processed);

        let response: DelegateResponse = bincode::deserialize(&final_msg.payload)?;
        match response {
            DelegateResponse::ContractSubscribeResult {
                contract_id: id,
                success,
                error,
            } => {
                assert_eq!(id, contract_id);
                assert!(!success);
                assert!(error.is_some());
            }
            other @ DelegateResponse::ContractState { .. }
            | other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractNotificationReceived { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected ContractSubscribeResult, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_contract_notification_delivered() -> Result<(), Box<dyn std::error::Error>> {
        use capabilities_messages::*;

        let (delegate, mut runtime, temp_dir) = setup_runtime(TEST_DELEGATE_CAPABILITIES).await?;

        let contract_id = ContractInstanceId::new([42u8; 32]);
        let new_state = vec![10, 20, 30, 40];

        let notification = InboundDelegateMsg::ContractNotification(ContractNotification {
            contract_id,
            new_state: WrappedState::new(new_state.clone()),
            context: DelegateContext::default(),
        });

        let outbound = runtime.inbound_app_message(
            delegate.key(),
            &vec![].into(),
            None,
            vec![notification],
        )?;

        assert_eq!(outbound.len(), 1, "Expected exactly one outbound message");
        let msg = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(msg.processed);

        let response: DelegateResponse = bincode::deserialize(&msg.payload)?;
        match response {
            DelegateResponse::ContractNotificationReceived {
                contract_id: id,
                new_state: state,
            } => {
                assert_eq!(id, contract_id);
                assert_eq!(state, new_state);
            }
            other @ DelegateResponse::ContractState { .. }
            | other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected ContractNotificationReceived, got {:?}", other)
            }
        }

        std::mem::drop(temp_dir);
        Ok(())
    }

    /// End-to-end integration test: subscribe → registry populated → notification delivered.
    ///
    /// Verifies the full pipeline:
    /// 1. Delegate subscribes to a contract via SubscribeContractRequest
    /// 2. Subscription is registered in DELEGATE_SUBSCRIPTIONS
    /// 3. ContractNotification is delivered to the delegate
    /// 4. Delegate responds with ContractNotificationReceived
    /// 5. Cleanup: unregister delegate removes subscription entries
    #[tokio::test(flavor = "multi_thread")]
    async fn test_subscribe_then_notify_roundtrip() -> Result<(), Box<dyn std::error::Error>> {
        use crate::contract::storages::Storage;
        use crate::wasm_runtime::StateStorage;
        use capabilities_messages::*;

        let temp_dir = get_temp_dir();
        let contracts_dir = temp_dir.path().join("contracts");
        let delegates_dir = temp_dir.path().join("delegates");
        let secrets_dir = temp_dir.path().join("secrets");

        let db = Storage::new(temp_dir.path()).await?;
        let contract_store = ContractStore::new(contracts_dir, 10_000, db.clone())?;
        let delegate_store = DelegateStore::new(delegates_dir, 10_000, db.clone())?;
        let secret_store = SecretsStore::new(secrets_dir, Default::default(), db.clone())?;

        let mut runtime =
            Runtime::build(contract_store, delegate_store, secret_store, false).unwrap();
        runtime.set_state_store_db(db.clone());

        // Set up a contract so subscribe validation passes
        let contract_instance_id = ContractInstanceId::new([42u8; 32]);
        let contract_code = ContractCode::from(vec![42, 2, 3]);
        let contract_key =
            ContractKey::from_id_and_code(contract_instance_id, *contract_code.hash());
        runtime.contract_store.ensure_key_indexed(&contract_key)?;
        db.store(contract_key, WrappedState::new(vec![1, 2, 3]))
            .await?;

        // Load the delegate
        let delegate = {
            let bytes = super::super::tests::get_test_module(TEST_DELEGATE_CAPABILITIES)?;
            DelegateContainer::Wasm(DelegateWasmAPIVersion::V1(Delegate::from((
                &bytes.into(),
                &vec![].into(),
            ))))
        };
        let _stored = runtime.delegate_store.store_delegate(delegate.clone());

        let key = XChaCha20Poly1305::generate_key(&mut OsRng);
        let cipher = XChaCha20Poly1305::new(&key);
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let _registered =
            runtime
                .secret_store
                .register_delegate(delegate.key().clone(), cipher, nonce);

        let delegate_key = delegate.key().clone();
        let _app_id = ContractInstanceId::new([1u8; 32]);

        // --- Step 1: Delegate subscribes to the contract ---
        let subscribe_cmd = DelegateCommand::SubscribeContract {
            contract_id: contract_instance_id,
        };
        let payload = bincode::serialize(&subscribe_cmd)?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            &delegate_key,
            &vec![].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        // Should emit SubscribeContractRequest
        assert_eq!(outbound.len(), 1);
        let subscribe_req = match &outbound[0] {
            OutboundDelegateMsg::SubscribeContractRequest(req) => req.clone(),
            other @ OutboundDelegateMsg::ApplicationMessage(_)
            | other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected SubscribeContractRequest, got {:?}", other)
            }
        };
        assert_eq!(subscribe_req.contract_id, contract_instance_id);

        // Simulate the V1 subscribe handler path (contract.rs:387-405):
        // validate contract existence via lookup, then register if found.
        let subscribe_result = if runtime
            .contract_store
            .code_hash_from_id(&subscribe_req.contract_id)
            .is_some()
        {
            crate::wasm_runtime::DELEGATE_SUBSCRIPTIONS
                .entry(subscribe_req.contract_id)
                .or_default()
                .insert(delegate_key.clone());
            Ok(())
        } else {
            Err("Contract not found".to_string())
        };
        assert!(
            subscribe_result.is_ok(),
            "Subscribe should succeed for known contract"
        );

        // Feed the SubscribeContractResponse back to the delegate
        let subscribe_response =
            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
                contract_id: subscribe_req.contract_id,
                result: subscribe_result,
                context: subscribe_req.context.clone(),
            });
        let outbound = runtime.inbound_app_message(
            &delegate_key,
            &vec![].into(),
            None,
            vec![subscribe_response],
        )?;
        // Delegate should emit a ContractSubscribeResult ApplicationMessage
        assert_eq!(outbound.len(), 1);
        match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => {
                let resp: DelegateResponse = bincode::deserialize(&msg.payload)?;
                match resp {
                    DelegateResponse::ContractSubscribeResult { success, .. } => {
                        assert!(success, "Subscribe response should indicate success");
                    }
                    other @ DelegateResponse::ContractState { .. }
                    | other @ DelegateResponse::MultipleContractStates { .. }
                    | other @ DelegateResponse::Echo { .. }
                    | other @ DelegateResponse::ContractPutResult { .. }
                    | other @ DelegateResponse::ContractUpdateResult { .. }
                    | other @ DelegateResponse::ContractNotificationReceived { .. }
                    | other @ DelegateResponse::Error { .. } => {
                        panic!("Expected ContractSubscribeResult, got {:?}", other)
                    }
                }
            }
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        }

        // --- Step 2: Verify registry is populated ---
        {
            let entry = crate::wasm_runtime::DELEGATE_SUBSCRIPTIONS.get(&contract_instance_id);
            let subscribers = entry.as_ref().unwrap();
            assert!(
                subscribers.contains(&delegate_key),
                "Delegate should be registered as subscriber"
            );
        }

        // Also verify that subscribing to an UNKNOWN contract fails validation
        let unknown_id = ContractInstanceId::new([99u8; 32]);
        let has_code = runtime
            .contract_store
            .code_hash_from_id(&unknown_id)
            .is_some();
        assert!(!has_code, "Unknown contract should not be in store");

        // --- Step 3: Deliver ContractNotification ---
        let updated_state = vec![10, 20, 30, 40, 50];
        let notification = InboundDelegateMsg::ContractNotification(ContractNotification {
            contract_id: contract_instance_id,
            new_state: WrappedState::new(updated_state.clone()),
            context: DelegateContext::default(),
        });

        let outbound =
            runtime.inbound_app_message(&delegate_key, &vec![].into(), None, vec![notification])?;

        // --- Step 4: Verify delegate responds correctly ---
        assert_eq!(outbound.len(), 1, "Expected one outbound from notification");
        let msg = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            other @ OutboundDelegateMsg::RequestUserInput(_)
            | other @ OutboundDelegateMsg::ContextUpdated(_)
            | other @ OutboundDelegateMsg::GetContractRequest(_)
            | other @ OutboundDelegateMsg::PutContractRequest(_)
            | other @ OutboundDelegateMsg::UpdateContractRequest(_)
            | other @ OutboundDelegateMsg::SubscribeContractRequest(_)
            | other @ OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", other)
            }
        };
        assert!(msg.processed);

        let response: DelegateResponse = bincode::deserialize(&msg.payload)?;
        match response {
            DelegateResponse::ContractNotificationReceived {
                contract_id: id,
                new_state: state,
            } => {
                assert_eq!(id, contract_instance_id);
                assert_eq!(state, updated_state);
            }
            other @ DelegateResponse::ContractState { .. }
            | other @ DelegateResponse::MultipleContractStates { .. }
            | other @ DelegateResponse::Echo { .. }
            | other @ DelegateResponse::ContractPutResult { .. }
            | other @ DelegateResponse::ContractUpdateResult { .. }
            | other @ DelegateResponse::ContractSubscribeResult { .. }
            | other @ DelegateResponse::Error { .. } => {
                panic!("Expected ContractNotificationReceived, got {:?}", other)
            }
        }

        // --- Step 5: Cleanup on delegate unregister ---
        crate::wasm_runtime::DELEGATE_SUBSCRIPTIONS.retain(|_, subscribers| {
            subscribers.remove(&delegate_key);
            !subscribers.is_empty()
        });

        // Verify cleanup
        let entry = crate::wasm_runtime::DELEGATE_SUBSCRIPTIONS.get(&contract_instance_id);
        assert!(
            entry.is_none() || entry.as_ref().unwrap().is_empty(),
            "Subscription should be cleaned up after delegate unregister"
        );

        std::mem::drop(temp_dir);
        Ok(())
    }

    /// Test: removing a contract cleans up DELEGATE_SUBSCRIPTIONS.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_contract_removal_cleans_subscriptions() -> Result<(), Box<dyn std::error::Error>>
    {
        use crate::contract::storages::Storage;

        let temp_dir = get_temp_dir();
        let contracts_dir = temp_dir.path().join("contracts");
        let delegates_dir = temp_dir.path().join("delegates");
        let secrets_dir = temp_dir.path().join("secrets");

        let db = Storage::new(temp_dir.path()).await?;
        let contract_store = ContractStore::new(contracts_dir, 10_000, db.clone())?;
        let delegate_store = DelegateStore::new(delegates_dir, 10_000, db.clone())?;
        let secret_store = SecretsStore::new(secrets_dir, Default::default(), db.clone())?;

        let mut runtime =
            Runtime::build(contract_store, delegate_store, secret_store, false).unwrap();
        runtime.set_state_store_db(db.clone());

        // Create and store a contract
        let contract_instance_id = ContractInstanceId::new([99u8; 32]);
        let contract_code = ContractCode::from(vec![99, 2, 3]);
        let contract_key =
            ContractKey::from_id_and_code(contract_instance_id, *contract_code.hash());
        // Store the WASM file so remove_contract can delete it
        let wasm_path = runtime.contract_store.get_contract_path(&contract_key)?;
        std::fs::create_dir_all(wasm_path.parent().unwrap())?;
        std::fs::write(&wasm_path, [0u8; 10])?;
        runtime.contract_store.ensure_key_indexed(&contract_key)?;

        // Simulate delegate subscriptions
        let delegate_key_a = DelegateKey::new([1u8; 32], CodeHash::new([10u8; 32]));
        let delegate_key_b = DelegateKey::new([2u8; 32], CodeHash::new([20u8; 32]));
        {
            let mut entry = crate::wasm_runtime::DELEGATE_SUBSCRIPTIONS
                .entry(contract_instance_id)
                .or_default();
            entry.insert(delegate_key_a);
            entry.insert(delegate_key_b);
        }

        // Verify subscriptions exist
        assert!(
            crate::wasm_runtime::DELEGATE_SUBSCRIPTIONS
                .get(&contract_instance_id)
                .is_some()
        );

        // Remove the contract — should clean up subscriptions
        runtime.contract_store.remove_contract(&contract_key)?;

        // Verify subscriptions are cleaned up
        assert!(
            crate::wasm_runtime::DELEGATE_SUBSCRIPTIONS
                .get(&contract_instance_id)
                .is_none(),
            "DELEGATE_SUBSCRIPTIONS should be cleaned up when contract is removed"
        );

        std::mem::drop(temp_dir);
        Ok(())
    }

    // --- Delegate-to-delegate messaging tests ---

    const TEST_DELEGATE_MESSAGING: &str = "test_delegate_messaging";

    mod messaging_messages {
        use super::*;

        #[derive(Debug, Serialize, Deserialize)]
        pub enum InboundAppMessage {
            SendToDelegate {
                target_key_bytes: Vec<u8>,
                target_code_hash: Vec<u8>,
                payload: Vec<u8>,
            },
            Ping {
                data: Vec<u8>,
            },
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub enum OutboundAppMessage {
            MessageSent,
            DelegateMessageReceived {
                sender_key_bytes: Vec<u8>,
                payload: Vec<u8>,
                /// Mirror of the same field in the WASM-side
                /// `OutboundAppMessage`; populated when the runtime delivered
                /// this message with `MessageOrigin::Delegate(k)` (#3860).
                origin_delegate_key_bytes: Option<Vec<u8>>,
            },
            PingResponse {
                data: Vec<u8>,
            },
        }
    }

    async fn setup_runtime_with_params(
        name: &str,
        params: Vec<u8>,
    ) -> Result<(DelegateContainer, Runtime, tempfile::TempDir), Box<dyn std::error::Error>> {
        use crate::contract::storages::Storage;
        let temp_dir = get_temp_dir();
        let contracts_dir = temp_dir.path().join("contracts");
        let delegates_dir = temp_dir.path().join("delegates");
        let secrets_dir = temp_dir.path().join("secrets");

        let db = Storage::new(temp_dir.path()).await?;
        let contract_store = ContractStore::new(contracts_dir, 10_000, db.clone())?;
        let delegate_store = DelegateStore::new(delegates_dir, 10_000, db.clone())?;
        let secret_store = SecretsStore::new(secrets_dir, Default::default(), db)?;

        let mut runtime =
            Runtime::build(contract_store, delegate_store, secret_store, false).unwrap();

        let delegate = {
            let bytes = super::super::tests::get_test_module(name)?;
            DelegateContainer::Wasm(DelegateWasmAPIVersion::V1(Delegate::from((
                &bytes.into(),
                &params.into(),
            ))))
        };
        let _stored = runtime.delegate_store.store_delegate(delegate.clone());

        let key = XChaCha20Poly1305::generate_key(&mut OsRng);
        let cipher = XChaCha20Poly1305::new(&key);
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let _registered =
            runtime
                .secret_store
                .register_delegate(delegate.key().clone(), cipher, nonce);

        Ok((delegate, runtime, temp_dir))
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_delegate_emits_send_delegate_message() -> Result<(), Box<dyn std::error::Error>> {
        use messaging_messages::*;

        let (delegate_a, mut runtime, _temp_dir) =
            setup_runtime_with_params(TEST_DELEGATE_MESSAGING, vec![1]).await?;
        let key_a = delegate_a.key().clone();

        // Create a fake target delegate key B
        let target_key_bytes = vec![42u8; 32];
        let target_code_hash = vec![99u8; 32];

        let _app_id = ContractInstanceId::new([1u8; 32]);
        let payload = bincode::serialize(&InboundAppMessage::SendToDelegate {
            target_key_bytes: target_key_bytes.clone(),
            target_code_hash: target_code_hash.clone(),
            payload: b"hello".to_vec(),
        })?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound = runtime.inbound_app_message(
            &key_a,
            &vec![1u8].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        // Should have SendDelegateMessage and ApplicationMessage(MessageSent)
        assert!(
            !outbound.is_empty(),
            "Expected at least 1 outbound message, got {}",
            outbound.len()
        );

        let send_msg = outbound
            .iter()
            .find_map(|m| match m {
                OutboundDelegateMsg::SendDelegateMessage(msg) => Some(msg),
                OutboundDelegateMsg::ApplicationMessage(_)
                | OutboundDelegateMsg::RequestUserInput(_)
                | OutboundDelegateMsg::ContextUpdated(_)
                | OutboundDelegateMsg::GetContractRequest(_)
                | OutboundDelegateMsg::PutContractRequest(_)
                | OutboundDelegateMsg::UpdateContractRequest(_)
                | OutboundDelegateMsg::SubscribeContractRequest(_) => None,
            })
            .expect("Expected SendDelegateMessage in outbound");

        // Verify target matches what we sent
        let mut expected_key = [0u8; 32];
        expected_key.copy_from_slice(&target_key_bytes);
        let mut expected_hash = [0u8; 32];
        expected_hash.copy_from_slice(&target_code_hash);
        assert_eq!(*send_msg.target, expected_key);
        assert_eq!(send_msg.target.code_hash(), &CodeHash::new(expected_hash));

        // Verify sender attestation: runtime overwrites sender with actual delegate key
        assert_eq!(
            send_msg.sender, key_a,
            "Sender should be attested as delegate A"
        );

        // Verify payload
        assert_eq!(send_msg.payload, b"hello");

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_delegate_receives_delegate_message() -> Result<(), Box<dyn std::error::Error>> {
        use messaging_messages::*;

        let (delegate_b, mut runtime, _temp_dir) =
            setup_runtime_with_params(TEST_DELEGATE_MESSAGING, vec![2]).await?;
        let key_b = delegate_b.key().clone();

        // Create a fake sender key A
        let sender_key = DelegateKey::new([11u8; 32], CodeHash::new([22u8; 32]));

        // Deliver a DelegateMessage to B
        let delegate_msg =
            DelegateMessage::new(key_b.clone(), sender_key.clone(), b"hello".to_vec());

        let outbound = runtime.inbound_app_message(
            &key_b,
            &vec![2u8].into(),
            None,
            vec![InboundDelegateMsg::DelegateMessage(delegate_msg)],
        )?;

        assert_eq!(outbound.len(), 1, "Expected 1 outbound message");

        let app_msg = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!("Expected ApplicationMessage, got {:?}", &outbound[0])
            }
        };

        let response: OutboundAppMessage = bincode::deserialize(&app_msg.payload)?;
        match response {
            OutboundAppMessage::DelegateMessageReceived {
                sender_key_bytes,
                payload,
                origin_delegate_key_bytes,
            } => {
                assert_eq!(sender_key_bytes, sender_key.bytes());
                assert_eq!(payload, b"hello");
                assert!(
                    origin_delegate_key_bytes.is_none(),
                    "origin was None, so receiver should see no Delegate origin"
                );
            }
            OutboundAppMessage::MessageSent | OutboundAppMessage::PingResponse { .. } => {
                panic!("Expected DelegateMessageReceived, got {:?}", response)
            }
        }

        Ok(())
    }

    /// Regression test for issue #3860: when the runtime delivers an inbound
    /// `DelegateMessage` with `Some(MessageOrigin::Delegate(caller_key))`, the
    /// receiving delegate's `process()` MUST see exactly that origin in its
    /// `origin` parameter. Previously the inter-delegate dispatch path passed
    /// `None`, leaving the receiver unable to authorize on caller identity.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_inbound_app_message_propagates_delegate_origin()
    -> Result<(), Box<dyn std::error::Error>> {
        use messaging_messages::*;

        let (delegate_b, mut runtime, _temp_dir) =
            setup_runtime_with_params(TEST_DELEGATE_MESSAGING, vec![2]).await?;
        let key_b = delegate_b.key().clone();

        // Synthetic caller delegate A — its key is what we expect the
        // receiver to observe via MessageOrigin::Delegate.
        let caller_a = DelegateKey::new([0xA1u8; 32], CodeHash::new([0xA2u8; 32]));

        // Build an inbound DelegateMessage for B, with `sender` distinct from
        // `caller_a` so the test cannot pass by accident if the receiver
        // confuses `msg.sender` with the runtime-attested origin.
        let inband_sender = DelegateKey::new([0xBBu8; 32], CodeHash::new([0xCCu8; 32]));
        let delegate_msg =
            DelegateMessage::new(key_b.clone(), inband_sender, b"attest-me".to_vec());

        let origin = MessageOrigin::Delegate(caller_a.clone());
        let outbound = runtime.inbound_app_message(
            &key_b,
            &vec![2u8].into(),
            Some(&origin),
            vec![InboundDelegateMsg::DelegateMessage(delegate_msg)],
        )?;

        assert_eq!(outbound.len(), 1, "Expected exactly one outbound message");

        // Wildcard satisfies #[non_exhaustive] on OutboundDelegateMsg so
        // future stdlib variants don't break this test at compile time.
        #[allow(clippy::wildcard_enum_match_arm)]
        let app_msg = match &outbound[0] {
            OutboundDelegateMsg::ApplicationMessage(m) => m,
            other => panic!("Expected ApplicationMessage, got {other:?}"),
        };
        let response: OutboundAppMessage = bincode::deserialize(&app_msg.payload)?;
        // Wildcard satisfies #[non_exhaustive] on OutboundAppMessage so
        // future stdlib variants don't break this test at compile time.
        #[allow(clippy::wildcard_enum_match_arm)]
        match response {
            OutboundAppMessage::DelegateMessageReceived {
                origin_delegate_key_bytes,
                ..
            } => {
                let observed = origin_delegate_key_bytes
                    .expect("Receiver should see Some(MessageOrigin::Delegate(..))");
                assert_eq!(
                    observed,
                    caller_a.bytes(),
                    "Receiver must see the runtime-attested caller key, not msg.sender"
                );
            }
            other => panic!("Expected DelegateMessageReceived, got {other:?}"),
        }

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_delegate_to_delegate_roundtrip() -> Result<(), Box<dyn std::error::Error>> {
        use messaging_messages::*;

        // Load same code with different params → different keys
        let (delegate_a, mut runtime_a, _temp_dir_a) =
            setup_runtime_with_params(TEST_DELEGATE_MESSAGING, vec![1]).await?;
        let key_a = delegate_a.key().clone();

        let (delegate_b, mut runtime_b, _temp_dir_b) =
            setup_runtime_with_params(TEST_DELEGATE_MESSAGING, vec![2]).await?;
        let key_b = delegate_b.key().clone();

        // Step 1: Send command to A: "send a message to B"
        let _app_id = ContractInstanceId::new([1u8; 32]);
        let payload = bincode::serialize(&InboundAppMessage::SendToDelegate {
            target_key_bytes: key_b.bytes().to_vec(),
            target_code_hash: key_b.code_hash().as_ref().to_vec(),
            payload: b"inter-delegate".to_vec(),
        })?;
        let app_msg = ApplicationMessage::new(payload);

        let outbound_a = runtime_a.inbound_app_message(
            &key_a,
            &vec![1u8].into(),
            None,
            vec![InboundDelegateMsg::ApplicationMessage(app_msg)],
        )?;

        // Step 2: Extract the SendDelegateMessage from A's output
        let send_msg = outbound_a
            .iter()
            .find_map(|m| match m {
                OutboundDelegateMsg::SendDelegateMessage(msg) => Some(msg.clone()),
                OutboundDelegateMsg::ApplicationMessage(_)
                | OutboundDelegateMsg::RequestUserInput(_)
                | OutboundDelegateMsg::ContextUpdated(_)
                | OutboundDelegateMsg::GetContractRequest(_)
                | OutboundDelegateMsg::PutContractRequest(_)
                | OutboundDelegateMsg::UpdateContractRequest(_)
                | OutboundDelegateMsg::SubscribeContractRequest(_) => None,
            })
            .expect("Expected SendDelegateMessage from delegate A");

        assert_eq!(send_msg.sender, key_a, "Sender should be attested as A");
        assert_eq!(send_msg.payload, b"inter-delegate");

        // Step 3: Deliver to B as InboundDelegateMsg::DelegateMessage
        let outbound_b = runtime_b.inbound_app_message(
            &key_b,
            &vec![2u8].into(),
            None,
            vec![InboundDelegateMsg::DelegateMessage(send_msg)],
        )?;

        assert_eq!(outbound_b.len(), 1);

        let app_msg_b = match &outbound_b[0] {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg,
            OutboundDelegateMsg::RequestUserInput(_)
            | OutboundDelegateMsg::ContextUpdated(_)
            | OutboundDelegateMsg::GetContractRequest(_)
            | OutboundDelegateMsg::PutContractRequest(_)
            | OutboundDelegateMsg::UpdateContractRequest(_)
            | OutboundDelegateMsg::SubscribeContractRequest(_)
            | OutboundDelegateMsg::SendDelegateMessage(_) => {
                panic!(
                    "Expected ApplicationMessage from B, got {:?}",
                    &outbound_b[0]
                )
            }
        };

        let response: OutboundAppMessage = bincode::deserialize(&app_msg_b.payload)?;
        match response {
            OutboundAppMessage::DelegateMessageReceived {
                sender_key_bytes,
                payload,
                origin_delegate_key_bytes,
            } => {
                assert_eq!(
                    sender_key_bytes,
                    key_a.bytes(),
                    "B should see A as the sender"
                );
                assert_eq!(payload, b"inter-delegate");
                // Origin not asserted here: this roundtrip test calls
                // inbound_app_message with origin=None (it bypasses the
                // executor that injects MessageOrigin::Delegate). End-to-end
                // propagation of MessageOrigin::Delegate through the WASM
                // boundary is covered by
                // `test_inbound_app_message_propagates_delegate_origin`.
                let _ = origin_delegate_key_bytes;
            }
            OutboundAppMessage::MessageSent | OutboundAppMessage::PingResponse { .. } => {
                panic!("Expected DelegateMessageReceived, got {:?}", response)
            }
        }

        Ok(())
    }

    /// Verify that when a delegate emits multiple SendDelegateMessage outbound,
    /// all of them get sender attestation (not just the first one).
    /// Regression test for PR #3282 review: drain(..) bypass.
    #[tokio::test(flavor = "multi_thread")]
    async fn test_multiple_send_delegate_messages_all_attested()
    -> Result<(), Box<dyn std::error::Error>> {
        let (delegate_a, mut runtime, _temp_dir) =
            setup_runtime_with_params(TEST_DELEGATE_MESSAGING, vec![1]).await?;
        let key_a = delegate_a.key().clone();

        // Create two different target keys
        let target_b = DelegateKey::new([42u8; 32], CodeHash::new([99u8; 32]));
        let target_c = DelegateKey::new([43u8; 32], CodeHash::new([98u8; 32]));

        // Send two messages via two separate inbound ApplicationMessages.
        // The first triggers SendDelegateMessage → break + drain, so
        // the second SendDelegateMessage goes through drain(..).
        let _app_id = ContractInstanceId::new([1u8; 32]);
        let payload1 =
            bincode::serialize(&messaging_messages::InboundAppMessage::SendToDelegate {
                target_key_bytes: target_b.bytes().to_vec(),
                target_code_hash: target_b.code_hash().as_ref().to_vec(),
                payload: b"msg1".to_vec(),
            })?;
        let payload2 =
            bincode::serialize(&messaging_messages::InboundAppMessage::SendToDelegate {
                target_key_bytes: target_c.bytes().to_vec(),
                target_code_hash: target_c.code_hash().as_ref().to_vec(),
                payload: b"msg2".to_vec(),
            })?;

        let outbound = runtime.inbound_app_message(
            &key_a,
            &vec![1u8].into(),
            None,
            vec![
                InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(payload1)),
                InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(payload2)),
            ],
        )?;

        // Collect all SendDelegateMessage from outbound
        let send_msgs: Vec<&DelegateMessage> = outbound
            .iter()
            .filter_map(|m| match m {
                OutboundDelegateMsg::SendDelegateMessage(msg) => Some(msg),
                OutboundDelegateMsg::ApplicationMessage(_)
                | OutboundDelegateMsg::RequestUserInput(_)
                | OutboundDelegateMsg::ContextUpdated(_)
                | OutboundDelegateMsg::GetContractRequest(_)
                | OutboundDelegateMsg::PutContractRequest(_)
                | OutboundDelegateMsg::UpdateContractRequest(_)
                | OutboundDelegateMsg::SubscribeContractRequest(_) => None,
            })
            .collect();

        // Should have at least 1 (the first triggers break+drain,
        // second may come through drain)
        assert!(
            !send_msgs.is_empty(),
            "Expected at least one SendDelegateMessage"
        );

        // ALL SendDelegateMessage must have sender attested as key_a
        for (i, msg) in send_msgs.iter().enumerate() {
            assert_eq!(
                msg.sender, key_a,
                "SendDelegateMessage[{i}] sender should be attested as delegate A, \
                 but got {:?}",
                msg.sender
            );
        }

        Ok(())
    }
}