exochain-node 0.2.0-beta

EXOCHAIN distributed node — single binary for joining and participating in the constitutional governance network
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! SQLite-backed `DagStore` implementation.
//!
//! Each node persists the DAG and committed state in a local SQLite database.
//! This implementation mirrors `MemoryStore` from `exo-dag` but uses durable
//! storage so state survives restarts.

use std::{collections::BTreeSet, future::Future, path::Path};

use exo_core::types::{Did, Hash256, Signature, Timestamp, TrustReceipt};
use exo_dag::{
    consensus::{CommitCertificate, Vote},
    dag::DagNode,
    error::{DagError, Result as DagResult},
};
use exo_economy::{EconomyObjectKind, EconomyRecordAnchor};
use serde::{Serialize, de::DeserializeOwned};
use sqlx::{PgPool, Postgres, Row, Transaction};

/// Map a SQLite / CBOR error into `DagError::StoreError`.
fn store_err(e: impl std::fmt::Display) -> DagError {
    DagError::StoreError(e.to_string())
}
use rusqlite::{Connection, params};

fn sqlite_u64_to_i64(value: u64, field: &str) -> DagResult<i64> {
    i64::try_from(value)
        .map_err(|_| store_err(format!("{field} value {value} exceeds SQLite INTEGER max")))
}

fn sqlite_i64_to_u64(value: i64, field: &str) -> DagResult<u64> {
    u64::try_from(value).map_err(|_| store_err(format!("{field} value {value} is negative")))
}

fn decode_hash_bytes(bytes: &[u8], field: &str) -> DagResult<Hash256> {
    let arr: [u8; 32] = bytes
        .try_into()
        .map_err(|_| store_err(format!("{field} must be 32 bytes, got {}", bytes.len())))?;
    Ok(Hash256::from_bytes(arr))
}

fn decode_signature_bytes(bytes: &[u8], field: &str) -> DagResult<Signature> {
    let arr: [u8; 64] = bytes
        .try_into()
        .map_err(|_| store_err(format!("{field} must be 64 bytes, got {}", bytes.len())))?;
    let signature = Signature::from_bytes(arr);
    validate_signature(&signature, field)?;
    Ok(signature)
}

fn validate_signature(signature: &Signature, field: &str) -> DagResult<()> {
    if signature.is_empty() {
        return Err(store_err(format!("{field} must not be empty or all-zero")));
    }
    Ok(())
}

fn encode_cbor<T: Serialize>(value: &T, field: &str) -> DagResult<Vec<u8>> {
    let mut buf = Vec::new();
    ciborium::into_writer(value, &mut buf)
        .map_err(|e| store_err(format!("{field} CBOR encode: {e}")))?;
    Ok(buf)
}

fn decode_cbor<T: DeserializeOwned>(bytes: &[u8], field: &str) -> DagResult<T> {
    ciborium::from_reader(bytes).map_err(|e| store_err(format!("{field} CBOR decode: {e}")))
}

fn validate_ed25519_signature<'a>(
    signature: &'a Signature,
    field: &str,
) -> DagResult<&'a [u8; 64]> {
    let Signature::Ed25519(bytes) = signature else {
        return Err(store_err(format!(
            "{field} must be an Ed25519 signature for consensus persistence"
        )));
    };
    if bytes.iter().all(|b| *b == 0) {
        return Err(store_err(format!("{field} must not be empty or all-zero")));
    }
    Ok(bytes)
}

fn decode_did(value: &str, field: &str) -> DagResult<Did> {
    Did::new(value).map_err(|e| store_err(format!("{field} is invalid: {e}")))
}

fn validate_vote(vote: &Vote, context: &str) -> DagResult<()> {
    validate_ed25519_signature(&vote.signature, &format!("{context}.signature"))?;
    Ok(())
}

fn validate_commit_certificate(cert: &CommitCertificate) -> DagResult<()> {
    if cert.votes.is_empty() {
        return Err(store_err("commit_certificates.votes must not be empty"));
    }

    for (idx, vote) in cert.votes.iter().enumerate() {
        let context = format!("commit_certificates.votes[{idx}]");
        if vote.round != cert.round {
            return Err(store_err(format!(
                "{context}.round {} does not match certificate round {}",
                vote.round, cert.round
            )));
        }
        if vote.node_hash != cert.node_hash {
            return Err(store_err(format!(
                "{context}.node_hash does not match certificate node_hash"
            )));
        }
        validate_vote(vote, &context)?;
    }

    Ok(())
}

/// Compatibility handle for node DAG persistence.
///
/// Test/dev callers may still construct the legacy SQLite backend directly via
/// [`SqliteDagStore::open`]. Production startup uses [`DagDbNodeStore::open`],
/// which returns this same handle backed by the tenant-scoped DAG DB tables.
pub struct SqliteDagStore {
    backend: NodeStoreBackend,
}

enum NodeStoreBackend {
    #[allow(dead_code)]
    LegacySqlite(Connection),
    DagDb(PostgresDagNodeStore),
}

#[derive(Clone)]
struct PostgresDagNodeStore {
    pool: PgPool,
    tenant_id: String,
    namespace: String,
}

/// Production DAG DB-backed node store constructor.
pub struct DagDbNodeStore;

impl DagDbNodeStore {
    /// Open the tenant-scoped DAG DB node store from an already-migrated pool.
    pub async fn open(
        pool: PgPool,
        tenant_id: String,
        namespace: String,
    ) -> anyhow::Result<SqliteDagStore> {
        validate_scope_component("tenant_id", &tenant_id)?;
        validate_scope_component("namespace", &namespace)?;
        let store = PostgresDagNodeStore {
            pool,
            tenant_id,
            namespace,
        };
        store.verify_schema().await?;
        Ok(SqliteDagStore {
            backend: NodeStoreBackend::DagDb(store),
        })
    }
}

fn validate_scope_component(field: &str, value: &str) -> anyhow::Result<()> {
    if value.trim().is_empty() {
        anyhow::bail!("DAG DB node store {field} must not be empty");
    }
    Ok(())
}

fn block_on_dagdb<T, F>(future: F) -> DagResult<T>
where
    T: Send + 'static,
    F: Future<Output = DagResult<T>> + Send + 'static,
{
    match tokio::runtime::Handle::try_current() {
        Ok(_) => std::thread::spawn(move || {
            let runtime = tokio::runtime::Runtime::new()
                .map_err(|error| store_err(format!("DAG DB node store runtime: {error}")))?;
            runtime.block_on(future)
        })
        .join()
        .map_err(|_| store_err("DAG DB node store worker panicked"))?,
        Err(_) => {
            let runtime = tokio::runtime::Runtime::new()
                .map_err(|error| store_err(format!("DAG DB node store runtime: {error}")))?;
            runtime.block_on(future)
        }
    }
}

impl SqliteDagStore {
    fn dagdb(&self) -> Option<&PostgresDagNodeStore> {
        match &self.backend {
            NodeStoreBackend::LegacySqlite(_) => None,
            NodeStoreBackend::DagDb(store) => Some(store),
        }
    }

    fn sqlite_conn(&self) -> DagResult<&Connection> {
        match &self.backend {
            NodeStoreBackend::LegacySqlite(conn) => Ok(conn),
            NodeStoreBackend::DagDb(_) => Err(store_err(
                "legacy SQLite connection is unavailable for DAG DB-backed node store",
            )),
        }
    }

    fn sqlite_conn_mut(&mut self) -> DagResult<&mut Connection> {
        match &mut self.backend {
            NodeStoreBackend::LegacySqlite(conn) => Ok(conn),
            NodeStoreBackend::DagDb(_) => Err(store_err(
                "legacy SQLite connection is unavailable for DAG DB-backed node store",
            )),
        }
    }
}

impl PostgresDagNodeStore {
    async fn verify_schema(&self) -> anyhow::Result<()> {
        let mut tx =
            self.pool.begin().await.map_err(|error| {
                anyhow::anyhow!("DAG DB node store schema check failed: {error}")
            })?;
        self.bind_tenant(&mut tx)
            .await
            .map_err(|error| anyhow::anyhow!("DAG DB node store tenant binding failed: {error}"))?;
        let present: bool =
            sqlx::query_scalar("SELECT to_regclass('dagdb_node_dag_nodes') IS NOT NULL")
                .fetch_one(&mut *tx)
                .await
                .map_err(|error| {
                    anyhow::anyhow!("DAG DB node store schema lookup failed: {error}")
                })?;
        tx.commit().await.map_err(|error| {
            anyhow::anyhow!("DAG DB node store schema check commit failed: {error}")
        })?;
        if !present {
            anyhow::bail!("DAG DB node store schema is missing dagdb_node_dag_nodes");
        }
        Ok(())
    }

    async fn bind_tenant(
        &self,
        tx: &mut Transaction<'_, Postgres>,
    ) -> std::result::Result<(), sqlx::Error> {
        sqlx::query("SELECT set_config('exo.tenant_id', $1, true)")
            .bind(&self.tenant_id)
            .execute(&mut **tx)
            .await?;
        Ok(())
    }

    async fn begin(&self) -> DagResult<Transaction<'_, Postgres>> {
        let mut tx = self.pool.begin().await.map_err(store_err)?;
        self.bind_tenant(&mut tx).await.map_err(store_err)?;
        Ok(tx)
    }

    async fn insert_node_tx(
        &self,
        tx: &mut Transaction<'_, Postgres>,
        node: &DagNode,
    ) -> DagResult<()> {
        let cbor = SqliteDagStore::encode_node(node)?;
        sqlx::query(
            "INSERT INTO dagdb_node_dag_nodes (tenant_id, namespace, hash, cbor_payload) \
             VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(node.hash.as_bytes().to_vec())
        .bind(cbor)
        .execute(&mut **tx)
        .await
        .map_err(store_err)?;

        for parent in &node.parents {
            sqlx::query(
                "INSERT INTO dagdb_node_dag_parents \
                 (tenant_id, namespace, child_hash, parent_hash) \
                 VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
            )
            .bind(&self.tenant_id)
            .bind(&self.namespace)
            .bind(node.hash.as_bytes().to_vec())
            .bind(parent.as_bytes().to_vec())
            .execute(&mut **tx)
            .await
            .map_err(store_err)?;
        }
        Ok(())
    }

    async fn ensure_node_exists_tx(
        &self,
        tx: &mut Transaction<'_, Postgres>,
        hash: &Hash256,
    ) -> DagResult<()> {
        let present: bool = sqlx::query_scalar(
            "SELECT EXISTS (
                 SELECT 1 FROM dagdb_node_dag_nodes
                 WHERE tenant_id = $1 AND namespace = $2 AND hash = $3
             )",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(hash.as_bytes().to_vec())
        .fetch_one(&mut **tx)
        .await
        .map_err(store_err)?;
        if present {
            Ok(())
        } else {
            Err(DagError::NodeNotFound(*hash))
        }
    }

    async fn insert_committed_tx(
        &self,
        tx: &mut Transaction<'_, Postgres>,
        hash: &Hash256,
        height: u64,
    ) -> DagResult<()> {
        let height = sqlite_u64_to_i64(height, "dagdb_node_committed.height")?;
        sqlx::query(
            "INSERT INTO dagdb_node_committed (tenant_id, namespace, hash, height) \
             VALUES ($1, $2, $3, $4) \
             ON CONFLICT (tenant_id, namespace, hash) DO UPDATE SET height = EXCLUDED.height",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(hash.as_bytes().to_vec())
        .bind(height)
        .execute(&mut **tx)
        .await
        .map_err(store_err)?;
        Ok(())
    }

    async fn insert_certificate_tx(
        &self,
        tx: &mut Transaction<'_, Postgres>,
        cert: &CommitCertificate,
    ) -> DagResult<()> {
        let round = sqlite_u64_to_i64(cert.round, "dagdb_node_commit_certificates.round")?;
        validate_commit_certificate(cert)?;
        let cbor_buf = encode_cbor(cert, "dagdb_node_commit_certificates.cbor_data")?;
        sqlx::query(
            "INSERT INTO dagdb_node_commit_certificates \
             (tenant_id, namespace, node_hash, round, cbor_data) \
             VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(cert.node_hash.as_bytes().to_vec())
        .bind(round)
        .bind(cbor_buf)
        .execute(&mut **tx)
        .await
        .map_err(store_err)?;
        Ok(())
    }

    async fn insert_receipt_tx(
        &self,
        tx: &mut Transaction<'_, Postgres>,
        receipt: &TrustReceipt,
    ) -> DagResult<()> {
        validate_signature(&receipt.signature, "dagdb_node_trust_receipts.signature")?;
        let timestamp_ms = sqlite_u64_to_i64(
            receipt.timestamp.physical_ms,
            "dagdb_node_trust_receipts.timestamp_ms",
        )?;
        let buf = encode_cbor(receipt, "dagdb_node_trust_receipts.cbor_data")?;
        sqlx::query(
            "INSERT INTO dagdb_node_trust_receipts \
             (tenant_id, namespace, receipt_hash, actor_did, action_type, outcome, timestamp_ms, cbor_data) \
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT DO NOTHING",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(receipt.receipt_hash.as_bytes().to_vec())
        .bind(receipt.actor_did.to_string())
        .bind(receipt.action_type.as_str())
        .bind(receipt.outcome.to_string())
        .bind(timestamp_ms)
        .bind(buf)
        .execute(&mut **tx)
        .await
        .map_err(store_err)?;
        Ok(())
    }

    async fn get_sync_async(&self, hash: &Hash256) -> DagResult<Option<DagNode>> {
        let mut tx = self.begin().await?;
        let result: Option<Vec<u8>> = sqlx::query_scalar(
            "SELECT cbor_payload FROM dagdb_node_dag_nodes \
             WHERE tenant_id = $1 AND namespace = $2 AND hash = $3",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(hash.as_bytes().to_vec())
        .fetch_optional(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        result
            .map(|bytes| SqliteDagStore::decode_node(&bytes))
            .transpose()
    }

    async fn put_many_sync_async(&self, nodes: Vec<DagNode>) -> DagResult<()> {
        let mut tx = self.begin().await?;
        for node in &nodes {
            self.insert_node_tx(&mut tx, node).await?;
        }
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn put_committed_node_with_receipt_sync_async(
        &self,
        node: DagNode,
        height: u64,
        receipt: TrustReceipt,
    ) -> DagResult<()> {
        if receipt.action_hash != node.hash {
            return Err(store_err(
                "dagdb_node_trust_receipts.action_hash must match committed node hash",
            ));
        }
        let mut tx = self.begin().await?;
        self.insert_node_tx(&mut tx, &node).await?;
        self.insert_committed_tx(&mut tx, &node.hash, height)
            .await?;
        self.insert_receipt_tx(&mut tx, &receipt).await?;
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn contains_sync_async(&self, hash: &Hash256) -> DagResult<bool> {
        let mut tx = self.begin().await?;
        let present: bool = sqlx::query_scalar(
            "SELECT EXISTS (
                 SELECT 1 FROM dagdb_node_dag_nodes
                 WHERE tenant_id = $1 AND namespace = $2 AND hash = $3
             )",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(hash.as_bytes().to_vec())
        .fetch_one(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        Ok(present)
    }

    async fn tips_sync_async(&self) -> DagResult<Vec<Hash256>> {
        let mut tx = self.begin().await?;
        let rows: Vec<Vec<u8>> = sqlx::query_scalar(
            "SELECT node.hash FROM dagdb_node_dag_nodes node
             WHERE node.tenant_id = $1
               AND node.namespace = $2
               AND NOT EXISTS (
                   SELECT 1 FROM dagdb_node_dag_parents parent
                   WHERE parent.tenant_id = node.tenant_id
                     AND parent.namespace = node.namespace
                     AND parent.parent_hash = node.hash
               )
             ORDER BY node.hash ASC",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .fetch_all(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        rows.into_iter()
            .map(|bytes| decode_hash_bytes(&bytes, "dagdb_node_dag_nodes.hash"))
            .collect()
    }

    async fn committed_height_sync_async(&self) -> DagResult<u64> {
        let mut tx = self.begin().await?;
        let height: i64 = sqlx::query_scalar(
            "SELECT COALESCE(MAX(height), 0) FROM dagdb_node_committed \
             WHERE tenant_id = $1 AND namespace = $2",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .fetch_one(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        sqlite_i64_to_u64(height, "dagdb_node_committed.height")
    }

    async fn mark_committed_sync_async(&self, hash: Hash256, height: u64) -> DagResult<()> {
        let mut tx = self.begin().await?;
        self.ensure_node_exists_tx(&mut tx, &hash).await?;
        self.insert_committed_tx(&mut tx, &hash, height).await?;
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn committed_nodes_in_range_async(
        &self,
        from_height: u64,
        to_height: u64,
    ) -> DagResult<Vec<(Hash256, u64)>> {
        let from_height = sqlite_u64_to_i64(from_height, "dagdb_node_committed.from_height")?;
        let to_height = sqlite_u64_to_i64(to_height, "dagdb_node_committed.to_height")?;
        let mut tx = self.begin().await?;
        let rows = sqlx::query(
            "SELECT hash, height FROM dagdb_node_committed
             WHERE tenant_id = $1 AND namespace = $2 AND height >= $3 AND height <= $4
             ORDER BY height ASC",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(from_height)
        .bind(to_height)
        .fetch_all(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        rows.into_iter()
            .map(|row| {
                let hash: Vec<u8> = row.get("hash");
                let height: i64 = row.get("height");
                Ok((
                    decode_hash_bytes(&hash, "dagdb_node_committed.hash")?,
                    sqlite_i64_to_u64(height, "dagdb_node_committed.height")?,
                ))
            })
            .collect()
    }

    async fn save_consensus_round_async(&self, round: u64) -> DagResult<()> {
        let mut tx = self.begin().await?;
        sqlx::query(
            "INSERT INTO dagdb_node_consensus_meta (tenant_id, namespace, key, value) \
             VALUES ($1, $2, 'round', $3) \
             ON CONFLICT (tenant_id, namespace, key) DO UPDATE SET value = EXCLUDED.value",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(round.to_string())
        .execute(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn load_consensus_round_async(&self) -> DagResult<u64> {
        let mut tx = self.begin().await?;
        let value: Option<String> = sqlx::query_scalar(
            "SELECT value FROM dagdb_node_consensus_meta \
             WHERE tenant_id = $1 AND namespace = $2 AND key = 'round'",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .fetch_optional(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        value.map_or(Ok(0), |text| text.parse::<u64>().map_err(store_err))
    }

    async fn save_vote_async(&self, vote: Vote) -> DagResult<()> {
        let round = sqlite_u64_to_i64(vote.round, "dagdb_node_consensus_votes.round")?;
        validate_vote(&vote, "dagdb_node_consensus_votes")?;
        let signature =
            validate_ed25519_signature(&vote.signature, "dagdb_node_consensus_votes.signature")?;
        let mut tx = self.begin().await?;
        sqlx::query(
            "INSERT INTO dagdb_node_consensus_votes \
             (tenant_id, namespace, round, node_hash, voter_did, signature) \
             VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(round)
        .bind(vote.node_hash.as_bytes().to_vec())
        .bind(vote.voter.to_string())
        .bind(signature.to_vec())
        .execute(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn load_votes_for_round_async(&self, round: u64) -> DagResult<Vec<Vote>> {
        let round_i64 = sqlite_u64_to_i64(round, "dagdb_node_consensus_votes.round")?;
        let mut tx = self.begin().await?;
        let rows = sqlx::query(
            "SELECT node_hash, voter_did, signature FROM dagdb_node_consensus_votes \
             WHERE tenant_id = $1 AND namespace = $2 AND round = $3 \
             ORDER BY node_hash ASC, voter_did ASC",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(round_i64)
        .fetch_all(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        rows.into_iter()
            .map(|row| {
                let hash_bytes: Vec<u8> = row.get("node_hash");
                let voter_str: String = row.get("voter_did");
                let sig_bytes: Vec<u8> = row.get("signature");
                Ok(Vote {
                    voter: decode_did(&voter_str, "dagdb_node_consensus_votes.voter_did")?,
                    round,
                    node_hash: decode_hash_bytes(
                        &hash_bytes,
                        "dagdb_node_consensus_votes.node_hash",
                    )?,
                    signature: decode_signature_bytes(
                        &sig_bytes,
                        "dagdb_node_consensus_votes.signature",
                    )?,
                })
            })
            .collect()
    }

    async fn save_certificate_async(&self, cert: CommitCertificate) -> DagResult<()> {
        let mut tx = self.begin().await?;
        self.insert_certificate_tx(&mut tx, &cert).await?;
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn load_certificates_async(&self) -> DagResult<Vec<CommitCertificate>> {
        let mut tx = self.begin().await?;
        let rows: Vec<Vec<u8>> = sqlx::query_scalar(
            "SELECT cbor_data FROM dagdb_node_commit_certificates \
             WHERE tenant_id = $1 AND namespace = $2 ORDER BY round ASC, node_hash ASC",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .fetch_all(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        rows.into_iter()
            .map(|bytes| {
                let cert: CommitCertificate = ciborium::from_reader(bytes.as_slice())
                    .map_err(|e| store_err(format!("CBOR decode certificate: {e}")))?;
                validate_commit_certificate(&cert)?;
                Ok(cert)
            })
            .collect()
    }

    async fn load_certificate_for_hash_async(
        &self,
        hash: Hash256,
    ) -> DagResult<Option<CommitCertificate>> {
        let mut tx = self.begin().await?;
        let result: Option<Vec<u8>> = sqlx::query_scalar(
            "SELECT cbor_data FROM dagdb_node_commit_certificates \
             WHERE tenant_id = $1 AND namespace = $2 AND node_hash = $3",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(hash.as_bytes().to_vec())
        .fetch_optional(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        result
            .map(|bytes| {
                let certificate: CommitCertificate = ciborium::from_reader(bytes.as_slice())
                    .map_err(|e| store_err(format!("CBOR decode certificate: {e}")))?;
                if certificate.node_hash != hash {
                    return Err(store_err(
                        "dagdb_node_commit_certificates.node_hash does not match CBOR certificate node_hash",
                    ));
                }
                validate_commit_certificate(&certificate)?;
                Ok(certificate)
            })
            .transpose()
    }

    async fn save_validator_set_async(&self, validators: BTreeSet<Did>) -> DagResult<()> {
        let mut tx = self.begin().await?;
        sqlx::query("DELETE FROM dagdb_node_validators WHERE tenant_id = $1 AND namespace = $2")
            .bind(&self.tenant_id)
            .bind(&self.namespace)
            .execute(&mut *tx)
            .await
            .map_err(store_err)?;
        for did in validators {
            sqlx::query(
                "INSERT INTO dagdb_node_validators (tenant_id, namespace, did) VALUES ($1, $2, $3)",
            )
            .bind(&self.tenant_id)
            .bind(&self.namespace)
            .bind(did.to_string())
            .execute(&mut *tx)
            .await
            .map_err(store_err)?;
        }
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn load_validator_set_async(&self) -> DagResult<BTreeSet<Did>> {
        let mut tx = self.begin().await?;
        let rows: Vec<String> = sqlx::query_scalar(
            "SELECT did FROM dagdb_node_validators \
             WHERE tenant_id = $1 AND namespace = $2 ORDER BY did ASC",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .fetch_all(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        rows.into_iter()
            .map(|did| decode_did(&did, "dagdb_node_validators.did"))
            .collect()
    }

    async fn mark_committed_with_receipt_sync_async(
        &self,
        hash: Hash256,
        height: u64,
        receipt: TrustReceipt,
    ) -> DagResult<()> {
        if receipt.action_hash != hash {
            return Err(store_err(
                "dagdb_node_trust_receipts.action_hash must match committed node hash",
            ));
        }
        let mut tx = self.begin().await?;
        self.ensure_node_exists_tx(&mut tx, &hash).await?;
        self.insert_committed_tx(&mut tx, &hash, height).await?;
        self.insert_receipt_tx(&mut tx, &receipt).await?;
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn persist_commit_certificate_with_receipt_sync_async(
        &self,
        hash: Hash256,
        height: u64,
        cert: CommitCertificate,
        receipt: TrustReceipt,
    ) -> DagResult<()> {
        if cert.node_hash != hash {
            return Err(store_err(
                "dagdb_node_commit_certificates.node_hash must match committed node hash",
            ));
        }
        if receipt.action_hash != hash {
            return Err(store_err(
                "dagdb_node_trust_receipts.action_hash must match committed node hash",
            ));
        }
        let mut tx = self.begin().await?;
        self.ensure_node_exists_tx(&mut tx, &hash).await?;
        self.insert_committed_tx(&mut tx, &hash, height).await?;
        self.insert_certificate_tx(&mut tx, &cert).await?;
        self.insert_receipt_tx(&mut tx, &receipt).await?;
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn load_receipt_async(&self, receipt_hash: Hash256) -> DagResult<Option<TrustReceipt>> {
        let mut tx = self.begin().await?;
        let result: Option<Vec<u8>> = sqlx::query_scalar(
            "SELECT cbor_data FROM dagdb_node_trust_receipts \
             WHERE tenant_id = $1 AND namespace = $2 AND receipt_hash = $3",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(receipt_hash.as_bytes().to_vec())
        .fetch_optional(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        result
            .map(|data| {
                ciborium::from_reader(&data[..])
                    .map_err(|e| store_err(format!("CBOR decode receipt: {e}")))
            })
            .transpose()
    }

    async fn load_receipts_by_actor_async(
        &self,
        actor_did: String,
        limit: u32,
    ) -> DagResult<Vec<TrustReceipt>> {
        let mut tx = self.begin().await?;
        let rows: Vec<Vec<u8>> = sqlx::query_scalar(
            "SELECT cbor_data FROM dagdb_node_trust_receipts \
             WHERE tenant_id = $1 AND namespace = $2 AND actor_did = $3 \
             ORDER BY timestamp_ms DESC, receipt_hash ASC LIMIT $4",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(actor_did)
        .bind(i64::from(limit))
        .fetch_all(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        rows.into_iter()
            .map(|data| {
                ciborium::from_reader(&data[..])
                    .map_err(|e| store_err(format!("CBOR decode receipt: {e}")))
            })
            .collect()
    }

    async fn load_recent_receipts_async(&self, limit: u32) -> DagResult<Vec<TrustReceipt>> {
        let mut tx = self.begin().await?;
        let rows: Vec<Vec<u8>> = sqlx::query_scalar(
            "SELECT cbor_data FROM dagdb_node_trust_receipts \
             WHERE tenant_id = $1 AND namespace = $2 \
             ORDER BY timestamp_ms DESC, receipt_hash ASC LIMIT $3",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(i64::from(limit))
        .fetch_all(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        rows.into_iter()
            .map(|data| {
                ciborium::from_reader(&data[..])
                    .map_err(|e| store_err(format!("CBOR decode receipt: {e}")))
            })
            .collect()
    }

    async fn children_async(&self, parent_hash: Hash256) -> DagResult<Vec<Hash256>> {
        let mut tx = self.begin().await?;
        let rows: Vec<Vec<u8>> = sqlx::query_scalar(
            "SELECT child_hash FROM dagdb_node_dag_parents \
             WHERE tenant_id = $1 AND namespace = $2 AND parent_hash = $3 \
             ORDER BY child_hash ASC",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(parent_hash.as_bytes().to_vec())
        .fetch_all(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        rows.into_iter()
            .map(|bytes| decode_hash_bytes(&bytes, "dagdb_node_dag_parents.child_hash"))
            .collect()
    }

    async fn committed_height_for_async(&self, hash: Hash256) -> DagResult<Option<u64>> {
        let mut tx = self.begin().await?;
        let height: Option<i64> = sqlx::query_scalar(
            "SELECT height FROM dagdb_node_committed \
             WHERE tenant_id = $1 AND namespace = $2 AND hash = $3",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(hash.as_bytes().to_vec())
        .fetch_optional(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        height
            .map(|value| sqlite_i64_to_u64(value, "dagdb_node_committed.height"))
            .transpose()
    }

    async fn put_committed_many_with_certificates_sync_async(
        &self,
        nodes: Vec<(DagNode, u64)>,
        certificates: Vec<CommitCertificate>,
    ) -> DagResult<()> {
        if nodes.len() != certificates.len() {
            return Err(store_err(format!(
                "committed batch must include one certificate per node: got {} certificates for {} nodes",
                certificates.len(),
                nodes.len()
            )));
        }
        let mut tx = self.begin().await?;
        for ((node, height), certificate) in nodes.iter().zip(certificates.iter()) {
            if certificate.node_hash != node.hash {
                return Err(store_err(format!(
                    "commit certificate node_hash {} does not match DAG node hash {}",
                    certificate.node_hash, node.hash
                )));
            }
            self.insert_node_tx(&mut tx, node).await?;
            self.insert_committed_tx(&mut tx, &node.hash, *height)
                .await?;
            self.insert_certificate_tx(&mut tx, certificate).await?;
        }
        tx.commit().await.map_err(store_err)?;
        Ok(())
    }

    async fn latest_economy_anchor_hash_sync_async(&self) -> DagResult<Hash256> {
        let mut tx = self.begin().await?;
        let value: Option<Vec<u8>> = sqlx::query_scalar(
            "SELECT value FROM dagdb_node_economy_meta \
             WHERE tenant_id = $1 AND namespace = $2 AND key = 'latest_anchor_hash'",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .fetch_optional(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        match value {
            Some(bytes) => decode_hash_bytes(&bytes, "dagdb_node_economy_meta.latest_anchor_hash"),
            None => Ok(Hash256::ZERO),
        }
    }

    async fn latest_economy_anchor_hash_tx(
        &self,
        tx: &mut Transaction<'_, Postgres>,
    ) -> DagResult<Hash256> {
        let value: Option<Vec<u8>> = sqlx::query_scalar(
            "SELECT value FROM dagdb_node_economy_meta \
             WHERE tenant_id = $1 AND namespace = $2 AND key = 'latest_anchor_hash'",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .fetch_optional(&mut **tx)
        .await
        .map_err(store_err)?;
        match value {
            Some(bytes) => decode_hash_bytes(&bytes, "dagdb_node_economy_meta.latest_anchor_hash"),
            None => Ok(Hash256::ZERO),
        }
    }

    async fn put_economy_object_sync_async(
        &self,
        object_kind: EconomyObjectKind,
        object_id: Hash256,
        content_hash: Hash256,
        created_at: Timestamp,
        object_cbor: Vec<u8>,
    ) -> DagResult<EconomyRecordAnchor> {
        if object_id == Hash256::ZERO {
            return Err(store_err("economy object_id must not be Hash256::ZERO"));
        }
        if content_hash == Hash256::ZERO {
            return Err(store_err("economy content_hash must not be Hash256::ZERO"));
        }
        if created_at == Timestamp::ZERO {
            return Err(store_err("economy created_at must not be Timestamp::ZERO"));
        }

        let mut tx = self.begin().await?;
        let previous_anchor_hash = self.latest_economy_anchor_hash_tx(&mut tx).await?;
        let anchor = EconomyRecordAnchor {
            anchor_hash: Hash256::ZERO,
            previous_anchor_hash,
            object_kind,
            object_id,
            object_hash: content_hash,
            created_at,
        }
        .anchor()
        .map_err(store_err)?;
        let anchor_cbor = encode_cbor(&anchor, "dagdb_node_economy_anchors.cbor_data")?;
        let created_physical_ms = sqlite_u64_to_i64(
            created_at.physical_ms,
            "dagdb_node_economy.created_physical_ms",
        )?;
        let created_logical = sqlite_u64_to_i64(
            u64::from(created_at.logical),
            "dagdb_node_economy.created_logical",
        )?;

        sqlx::query(
            "INSERT INTO dagdb_node_economy_objects (
                tenant_id, namespace, object_kind, object_id, content_hash,
                created_physical_ms, created_logical, cbor_data
             ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(object_kind.label())
        .bind(object_id.as_bytes().to_vec())
        .bind(content_hash.as_bytes().to_vec())
        .bind(created_physical_ms)
        .bind(created_logical)
        .bind(object_cbor)
        .execute(&mut *tx)
        .await
        .map_err(|e| store_err(format!("insert DAG DB economy object: {e}")))?;

        sqlx::query(
            "INSERT INTO dagdb_node_economy_anchors (
                tenant_id, namespace, anchor_hash, previous_anchor_hash, object_kind,
                object_id, object_hash, created_physical_ms, created_logical, cbor_data
             ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(anchor.anchor_hash.as_bytes().to_vec())
        .bind(anchor.previous_anchor_hash.as_bytes().to_vec())
        .bind(object_kind.label())
        .bind(object_id.as_bytes().to_vec())
        .bind(content_hash.as_bytes().to_vec())
        .bind(created_physical_ms)
        .bind(created_logical)
        .bind(anchor_cbor)
        .execute(&mut *tx)
        .await
        .map_err(|e| store_err(format!("insert DAG DB economy anchor: {e}")))?;

        sqlx::query(
            "INSERT INTO dagdb_node_economy_meta (tenant_id, namespace, key, value) \
             VALUES ($1, $2, 'latest_anchor_hash', $3) \
             ON CONFLICT (tenant_id, namespace, key) DO UPDATE SET value = EXCLUDED.value",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(anchor.anchor_hash.as_bytes().to_vec())
        .execute(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        Ok(anchor)
    }

    async fn get_economy_object_sync_async<T>(
        &self,
        object_kind: EconomyObjectKind,
        object_id: Hash256,
    ) -> DagResult<Option<T>>
    where
        T: DeserializeOwned,
    {
        let mut tx = self.begin().await?;
        let result: Option<Vec<u8>> = sqlx::query_scalar(
            "SELECT cbor_data FROM dagdb_node_economy_objects \
             WHERE tenant_id = $1 AND namespace = $2 AND object_kind = $3 AND object_id = $4",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(object_kind.label())
        .bind(object_id.as_bytes().to_vec())
        .fetch_optional(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        result
            .map(|bytes| decode_cbor(&bytes, "dagdb_node_economy_objects.cbor_data"))
            .transpose()
    }

    async fn get_economy_anchor_sync_async(
        &self,
        anchor_hash: Hash256,
    ) -> DagResult<Option<EconomyRecordAnchor>> {
        let mut tx = self.begin().await?;
        let result: Option<Vec<u8>> = sqlx::query_scalar(
            "SELECT cbor_data FROM dagdb_node_economy_anchors \
             WHERE tenant_id = $1 AND namespace = $2 AND anchor_hash = $3",
        )
        .bind(&self.tenant_id)
        .bind(&self.namespace)
        .bind(anchor_hash.as_bytes().to_vec())
        .fetch_optional(&mut *tx)
        .await
        .map_err(store_err)?;
        tx.commit().await.map_err(store_err)?;
        result
            .map(|bytes| decode_cbor(&bytes, "dagdb_node_economy_anchors.cbor_data"))
            .transpose()
    }
}

impl SqliteDagStore {
    /// Open (or create) the SQLite database in the given data directory.
    #[allow(dead_code)]
    pub fn open(data_dir: &Path) -> anyhow::Result<Self> {
        let db_path = data_dir.join("dag.db");
        let conn = Connection::open(&db_path)?;

        // WAL mode for concurrent reads.
        conn.execute_batch("PRAGMA journal_mode=WAL;")?;
        conn.execute_batch("PRAGMA synchronous=NORMAL;")?;

        // Create tables if they don't exist.
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS dag_nodes (
                hash         BLOB PRIMARY KEY NOT NULL,
                cbor_payload BLOB NOT NULL
            );

            CREATE TABLE IF NOT EXISTS dag_parents (
                child_hash   BLOB NOT NULL,
                parent_hash  BLOB NOT NULL,
                PRIMARY KEY (child_hash, parent_hash)
            );

            CREATE TABLE IF NOT EXISTS committed (
                hash   BLOB PRIMARY KEY NOT NULL,
                height INTEGER NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_parents_parent ON dag_parents(parent_hash);
            CREATE INDEX IF NOT EXISTS idx_committed_height ON committed(height);

            -- Persistent consensus state: survives restarts.
            CREATE TABLE IF NOT EXISTS consensus_meta (
                key   TEXT PRIMARY KEY NOT NULL,
                value TEXT NOT NULL
            );

            CREATE TABLE IF NOT EXISTS consensus_votes (
                round     INTEGER NOT NULL,
                node_hash BLOB    NOT NULL,
                voter_did TEXT    NOT NULL,
                signature BLOB   NOT NULL,
                PRIMARY KEY (round, node_hash, voter_did)
            );

            CREATE TABLE IF NOT EXISTS commit_certificates (
                node_hash BLOB PRIMARY KEY NOT NULL,
                round     INTEGER NOT NULL,
                cbor_data BLOB    NOT NULL
            );

            CREATE TABLE IF NOT EXISTS validators (
                did TEXT PRIMARY KEY NOT NULL
            );

            CREATE TABLE IF NOT EXISTS trust_receipts (
                receipt_hash BLOB PRIMARY KEY NOT NULL,
                actor_did    TEXT    NOT NULL,
                action_type  TEXT    NOT NULL,
                outcome      TEXT    NOT NULL,
                timestamp_ms INTEGER NOT NULL,
                cbor_data    BLOB    NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_receipts_actor
                ON trust_receipts(actor_did);
            CREATE INDEX IF NOT EXISTS idx_receipts_ts
                ON trust_receipts(timestamp_ms);

            CREATE TABLE IF NOT EXISTS economy_objects (
                object_kind          TEXT    NOT NULL,
                object_id            BLOB    NOT NULL,
                content_hash         BLOB    NOT NULL,
                created_physical_ms  INTEGER NOT NULL,
                created_logical      INTEGER NOT NULL,
                cbor_data            BLOB    NOT NULL,
                PRIMARY KEY (object_kind, object_id)
            );

            CREATE INDEX IF NOT EXISTS idx_economy_objects_hash
                ON economy_objects(content_hash);

            CREATE TABLE IF NOT EXISTS economy_anchors (
                anchor_hash          BLOB PRIMARY KEY NOT NULL,
                previous_anchor_hash BLOB NOT NULL,
                object_kind          TEXT NOT NULL,
                object_id            BLOB NOT NULL,
                object_hash          BLOB NOT NULL,
                created_physical_ms  INTEGER NOT NULL,
                created_logical      INTEGER NOT NULL,
                cbor_data            BLOB NOT NULL
            );

            CREATE TABLE IF NOT EXISTS economy_meta (
                key   TEXT PRIMARY KEY NOT NULL,
                value BLOB NOT NULL
            );",
        )?;

        Ok(Self {
            backend: NodeStoreBackend::LegacySqlite(conn),
        })
    }

    /// Convenience accessor for the current committed height.
    pub fn committed_height_value(&self) -> DagResult<u64> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.committed_height_sync_async().await });
        }
        self.committed_height_sync()
    }

    /// Serialize a `DagNode` to CBOR bytes.
    fn encode_node(node: &DagNode) -> DagResult<Vec<u8>> {
        let mut buf = Vec::new();
        ciborium::into_writer(node, &mut buf)
            .map_err(|e| store_err(format!("CBOR encode: {e}")))?;
        Ok(buf)
    }

    /// Deserialize a `DagNode` from CBOR bytes.
    fn decode_node(bytes: &[u8]) -> DagResult<DagNode> {
        ciborium::from_reader(bytes).map_err(|e| store_err(format!("CBOR decode: {e}")))
    }

    /// Query committed nodes in a height range (inclusive), ordered by height.
    ///
    /// Returns `(hash, height)` pairs. Used by state sync to serve snapshot chunks.
    pub fn committed_nodes_in_range(
        &self,
        from_height: u64,
        to_height: u64,
    ) -> DagResult<Vec<(Hash256, u64)>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move {
                store
                    .committed_nodes_in_range_async(from_height, to_height)
                    .await
            });
        }
        let from_height = sqlite_u64_to_i64(from_height, "committed.from_height")?;
        let to_height = sqlite_u64_to_i64(to_height, "committed.to_height")?;
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached(
                "SELECT hash, height FROM committed
                 WHERE height >= ?1 AND height <= ?2
                 ORDER BY height ASC",
            )
            .map_err(store_err)?;

        let rows = stmt
            .query_map(params![from_height, to_height], |row| {
                let bytes: Vec<u8> = row.get(0)?;
                let height: i64 = row.get(1)?;
                Ok((bytes, height))
            })
            .map_err(store_err)?;

        let mut result = Vec::new();
        for row in rows {
            let (bytes, height) = row.map_err(store_err)?;
            result.push((
                decode_hash_bytes(&bytes, "committed.hash")?,
                sqlite_i64_to_u64(height, "committed.height")?,
            ));
        }
        Ok(result)
    }

    // -----------------------------------------------------------------
    // Consensus state persistence
    // -----------------------------------------------------------------

    /// Save the current consensus round number.
    pub fn save_consensus_round(&mut self, round: u64) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.save_consensus_round_async(round).await });
        }
        self.sqlite_conn_mut()?
            .execute(
                "INSERT OR REPLACE INTO consensus_meta (key, value) VALUES ('round', ?1)",
                params![round.to_string()],
            )
            .map_err(store_err)?;
        Ok(())
    }

    /// Load the persisted consensus round number (0 if none).
    pub fn load_consensus_round(&self) -> DagResult<u64> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.load_consensus_round_async().await });
        }
        let result: Result<String, _> = self.sqlite_conn()?.query_row(
            "SELECT value FROM consensus_meta WHERE key = 'round'",
            [],
            |row| row.get(0),
        );
        match result {
            Ok(s) => s.parse::<u64>().map_err(store_err),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(0),
            Err(e) => Err(store_err(e)),
        }
    }

    /// Persist a consensus vote.
    pub fn save_vote(&mut self, vote: &Vote) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let vote = vote.clone();
            return block_on_dagdb(async move { store.save_vote_async(vote).await });
        }
        let round = sqlite_u64_to_i64(vote.round, "consensus_votes.round")?;
        validate_vote(vote, "consensus_votes")?;
        let signature = validate_ed25519_signature(&vote.signature, "consensus_votes.signature")?;

        self.sqlite_conn_mut()?
            .execute(
                "INSERT OR IGNORE INTO consensus_votes (round, node_hash, voter_did, signature) VALUES (?1, ?2, ?3, ?4)",
                params![
                    round,
                    vote.node_hash.0.as_slice(),
                    vote.voter.to_string(),
                    signature,
                ],
            )
            .map_err(store_err)?;
        Ok(())
    }

    /// Load all votes for a given round.
    pub fn load_votes_for_round(&self, round: u64) -> DagResult<Vec<Vote>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.load_votes_for_round_async(round).await });
        }
        let round_i64 = sqlite_u64_to_i64(round, "consensus_votes.round")?;
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached(
                "SELECT node_hash, voter_did, signature FROM consensus_votes WHERE round = ?1",
            )
            .map_err(store_err)?;

        let rows = stmt
            .query_map(params![round_i64], |row| {
                let hash_bytes: Vec<u8> = row.get(0)?;
                let voter_str: String = row.get(1)?;
                let sig_bytes: Vec<u8> = row.get(2)?;
                Ok((hash_bytes, voter_str, sig_bytes))
            })
            .map_err(store_err)?;

        let mut votes = Vec::new();
        for row in rows {
            let (hash_bytes, voter_str, sig_bytes) = row.map_err(store_err)?;
            votes.push(Vote {
                voter: decode_did(&voter_str, "consensus_votes.voter_did")?,
                round,
                node_hash: decode_hash_bytes(&hash_bytes, "consensus_votes.node_hash")?,
                signature: decode_signature_bytes(&sig_bytes, "consensus_votes.signature")?,
            });
        }
        Ok(votes)
    }

    /// Persist a commit certificate.
    #[allow(dead_code)]
    pub fn save_certificate(&mut self, cert: &CommitCertificate) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let cert = cert.clone();
            return block_on_dagdb(async move { store.save_certificate_async(cert).await });
        }
        let round = sqlite_u64_to_i64(cert.round, "commit_certificates.round")?;
        validate_commit_certificate(cert)?;

        let mut cbor_buf = Vec::new();
        ciborium::into_writer(cert, &mut cbor_buf)
            .map_err(|e| store_err(format!("CBOR encode certificate: {e}")))?;

        self.sqlite_conn_mut()?
            .execute(
                "INSERT OR IGNORE INTO commit_certificates (node_hash, round, cbor_data) VALUES (?1, ?2, ?3)",
                params![
                    cert.node_hash.0.as_slice(),
                    round,
                    cbor_buf,
                ],
            )
            .map_err(store_err)?;
        Ok(())
    }

    fn ensure_node_exists_tx(tx: &rusqlite::Transaction<'_>, hash: &Hash256) -> DagResult<()> {
        match tx.query_row(
            "SELECT 1 FROM dag_nodes WHERE hash = ?1",
            params![hash.0.as_slice()],
            |_| Ok(()),
        ) {
            Ok(()) => Ok(()),
            Err(rusqlite::Error::QueryReturnedNoRows) => Err(DagError::NodeNotFound(*hash)),
            Err(e) => Err(store_err(format!("dag_nodes.hash presence query: {e}"))),
        }
    }

    fn insert_committed_tx(
        tx: &rusqlite::Transaction<'_>,
        hash: &Hash256,
        height: u64,
    ) -> DagResult<()> {
        let height = sqlite_u64_to_i64(height, "committed.height")?;
        tx.execute(
            "INSERT OR REPLACE INTO committed (hash, height) VALUES (?1, ?2)",
            params![hash.0.as_slice(), height],
        )
        .map_err(store_err)?;
        Ok(())
    }

    fn insert_certificate_tx(
        tx: &rusqlite::Transaction<'_>,
        cert: &CommitCertificate,
    ) -> DagResult<()> {
        let round = sqlite_u64_to_i64(cert.round, "commit_certificates.round")?;
        validate_commit_certificate(cert)?;
        let cbor_buf = encode_cbor(cert, "commit_certificates.cbor_data")?;
        tx.execute(
            "INSERT OR IGNORE INTO commit_certificates (node_hash, round, cbor_data) VALUES (?1, ?2, ?3)",
            params![cert.node_hash.0.as_slice(), round, cbor_buf],
        )
        .map_err(store_err)?;
        Ok(())
    }

    fn insert_receipt_tx(tx: &rusqlite::Transaction<'_>, receipt: &TrustReceipt) -> DagResult<()> {
        validate_signature(&receipt.signature, "trust_receipts.signature")?;
        let timestamp_ms =
            sqlite_u64_to_i64(receipt.timestamp.physical_ms, "trust_receipts.timestamp_ms")?;
        let buf = encode_cbor(receipt, "trust_receipts.cbor_data")?;
        tx.execute(
            "INSERT OR IGNORE INTO trust_receipts (receipt_hash, actor_did, action_type, outcome, timestamp_ms, cbor_data) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            params![
                receipt.receipt_hash.0.as_slice(),
                receipt.actor_did.to_string(),
                receipt.action_type.as_str(),
                receipt.outcome.to_string(),
                timestamp_ms,
                buf,
            ],
        )
        .map_err(store_err)?;
        Ok(())
    }

    /// Load all persisted commit certificates.
    pub fn load_certificates(&self) -> DagResult<Vec<CommitCertificate>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.load_certificates_async().await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT cbor_data FROM commit_certificates ORDER BY round ASC")
            .map_err(store_err)?;

        let rows = stmt
            .query_map([], |row| {
                let bytes: Vec<u8> = row.get(0)?;
                Ok(bytes)
            })
            .map_err(store_err)?;

        let mut certs = Vec::new();
        for row in rows {
            let bytes = row.map_err(store_err)?;
            let cert: CommitCertificate = ciborium::from_reader(bytes.as_slice())
                .map_err(|e| store_err(format!("CBOR decode certificate: {e}")))?;
            validate_commit_certificate(&cert)?;
            certs.push(cert);
        }
        Ok(certs)
    }

    /// Load the persisted commit certificate for a committed node hash.
    pub fn load_certificate_for_hash(
        &self,
        hash: &Hash256,
    ) -> DagResult<Option<CommitCertificate>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let hash = *hash;
            return block_on_dagdb(
                async move { store.load_certificate_for_hash_async(hash).await },
            );
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT cbor_data FROM commit_certificates WHERE node_hash = ?1")
            .map_err(store_err)?;

        let result: Result<Vec<u8>, rusqlite::Error> =
            stmt.query_row(params![hash.0.as_slice()], |row| row.get(0));

        match result {
            Ok(bytes) => {
                let certificate: CommitCertificate = ciborium::from_reader(bytes.as_slice())
                    .map_err(|e| store_err(format!("CBOR decode certificate: {e}")))?;
                if certificate.node_hash != *hash {
                    return Err(store_err(
                        "commit_certificates.node_hash does not match CBOR certificate node_hash",
                    ));
                }
                validate_commit_certificate(&certificate)?;
                Ok(Some(certificate))
            }
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(store_err(format!("commit_certificates.cbor_data: {e}"))),
        }
    }

    // -----------------------------------------------------------------
    // Validator set persistence
    // -----------------------------------------------------------------

    /// Save the current validator set to the database.
    ///
    /// Reserved for the committed governance path that applies validator-set
    /// updates after consensus. The HTTP validator endpoint must not call this
    /// directly.
    #[allow(dead_code)]
    pub fn save_validator_set(&mut self, validators: &BTreeSet<Did>) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let validators = validators.clone();
            return block_on_dagdb(async move { store.save_validator_set_async(validators).await });
        }
        let tx = self.sqlite_conn_mut()?.transaction().map_err(store_err)?;
        tx.execute("DELETE FROM validators", [])
            .map_err(store_err)?;
        for did in validators {
            tx.execute(
                "INSERT INTO validators (did) VALUES (?1)",
                params![did.to_string()],
            )
            .map_err(store_err)?;
        }
        tx.commit().map_err(store_err)?;
        Ok(())
    }

    /// Load the persisted validator set (empty if none saved).
    pub fn load_validator_set(&self) -> DagResult<BTreeSet<Did>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.load_validator_set_async().await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT did FROM validators ORDER BY did ASC")
            .map_err(store_err)?;

        let rows = stmt
            .query_map([], |row| {
                let did_str: String = row.get(0)?;
                Ok(did_str)
            })
            .map_err(store_err)?;

        let mut set = BTreeSet::new();
        for row in rows {
            let did_str = row.map_err(store_err)?;
            let did = decode_did(&did_str, "validators.did")?;
            set.insert(did);
        }
        Ok(set)
    }

    /// Save a trust receipt to the database.
    #[cfg(test)]
    pub fn save_receipt(&mut self, receipt: &TrustReceipt) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let receipt = receipt.clone();
            return block_on_dagdb(async move {
                let mut tx = store.begin().await?;
                store.insert_receipt_tx(&mut tx, &receipt).await?;
                tx.commit().await.map_err(store_err)?;
                Ok(())
            });
        }
        validate_signature(&receipt.signature, "trust_receipts.signature")?;
        let timestamp_ms =
            sqlite_u64_to_i64(receipt.timestamp.physical_ms, "trust_receipts.timestamp_ms")?;

        let mut buf = Vec::new();
        ciborium::into_writer(receipt, &mut buf)
            .map_err(|e| store_err(format!("CBOR encode receipt: {e}")))?;

        self.sqlite_conn_mut()?
            .execute(
                "INSERT OR IGNORE INTO trust_receipts (receipt_hash, actor_did, action_type, outcome, timestamp_ms, cbor_data) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                params![
                    receipt.receipt_hash.0.as_slice(),
                    receipt.actor_did.to_string(),
                    receipt.action_type,
                    receipt.outcome.to_string(),
                    timestamp_ms,
                    buf,
                ],
            )
            .map_err(store_err)?;
        Ok(())
    }

    /// Atomically persist a committed marker with the trust receipt that proves it.
    pub fn mark_committed_with_receipt_sync(
        &mut self,
        hash: &Hash256,
        height: u64,
        receipt: &TrustReceipt,
    ) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let hash = *hash;
            let receipt = receipt.clone();
            return block_on_dagdb(async move {
                store
                    .mark_committed_with_receipt_sync_async(hash, height, receipt)
                    .await
            });
        }
        if receipt.action_hash != *hash {
            return Err(store_err(
                "trust_receipts.action_hash must match committed node hash",
            ));
        }

        let tx = self.sqlite_conn_mut()?.transaction().map_err(store_err)?;
        Self::ensure_node_exists_tx(&tx, hash)?;
        Self::insert_committed_tx(&tx, hash, height)?;
        Self::insert_receipt_tx(&tx, receipt)?;
        tx.commit().map_err(store_err)?;
        Ok(())
    }

    /// Atomically persist a committed marker, its certificate, and its trust receipt.
    pub fn persist_commit_certificate_with_receipt_sync(
        &mut self,
        hash: &Hash256,
        height: u64,
        cert: &CommitCertificate,
        receipt: &TrustReceipt,
    ) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let hash = *hash;
            let cert = cert.clone();
            let receipt = receipt.clone();
            return block_on_dagdb(async move {
                store
                    .persist_commit_certificate_with_receipt_sync_async(hash, height, cert, receipt)
                    .await
            });
        }
        if cert.node_hash != *hash {
            return Err(store_err(
                "commit_certificates.node_hash must match committed node hash",
            ));
        }
        if receipt.action_hash != *hash {
            return Err(store_err(
                "trust_receipts.action_hash must match committed node hash",
            ));
        }

        let tx = self.sqlite_conn_mut()?.transaction().map_err(store_err)?;
        Self::ensure_node_exists_tx(&tx, hash)?;
        Self::insert_committed_tx(&tx, hash, height)?;
        Self::insert_certificate_tx(&tx, cert)?;
        Self::insert_receipt_tx(&tx, receipt)?;
        tx.commit().map_err(store_err)?;
        Ok(())
    }

    /// Load a trust receipt by its hash.
    pub fn load_receipt(
        &self,
        receipt_hash: &Hash256,
    ) -> DagResult<Option<exo_core::types::TrustReceipt>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let receipt_hash = *receipt_hash;
            return block_on_dagdb(async move { store.load_receipt_async(receipt_hash).await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT cbor_data FROM trust_receipts WHERE receipt_hash = ?1")
            .map_err(store_err)?;

        let mut rows = stmt
            .query_map(params![receipt_hash.0.as_slice()], |row| {
                let data: Vec<u8> = row.get(0)?;
                Ok(data)
            })
            .map_err(store_err)?;

        match rows.next() {
            Some(row) => {
                let data = row.map_err(store_err)?;
                let receipt: exo_core::types::TrustReceipt = ciborium::from_reader(&data[..])
                    .map_err(|e| store_err(format!("CBOR decode receipt: {e}")))?;
                Ok(Some(receipt))
            }
            None => Ok(None),
        }
    }

    /// Load receipts by actor DID, ordered by timestamp descending.
    pub fn load_receipts_by_actor(
        &self,
        actor_did: &str,
        limit: u32,
    ) -> DagResult<Vec<exo_core::types::TrustReceipt>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let actor_did = actor_did.to_owned();
            return block_on_dagdb(async move {
                store.load_receipts_by_actor_async(actor_did, limit).await
            });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached(
                "SELECT cbor_data FROM trust_receipts WHERE actor_did = ?1 ORDER BY timestamp_ms DESC LIMIT ?2",
            )
            .map_err(store_err)?;

        let rows = stmt
            .query_map(params![actor_did, limit], |row| {
                let data: Vec<u8> = row.get(0)?;
                Ok(data)
            })
            .map_err(store_err)?;

        let mut receipts = Vec::new();
        for row in rows {
            let data = row.map_err(store_err)?;
            let receipt: exo_core::types::TrustReceipt = ciborium::from_reader(&data[..])
                .map_err(|e| store_err(format!("CBOR decode receipt: {e}")))?;
            receipts.push(receipt);
        }
        Ok(receipts)
    }

    /// Load recent trust receipts across all actors, ordered deterministically.
    pub fn load_recent_receipts(
        &self,
        limit: u32,
    ) -> DagResult<Vec<exo_core::types::TrustReceipt>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.load_recent_receipts_async(limit).await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached(
                "SELECT cbor_data FROM trust_receipts
                 ORDER BY timestamp_ms DESC, receipt_hash ASC
                 LIMIT ?1",
            )
            .map_err(store_err)?;

        let rows = stmt
            .query_map(params![limit], |row| {
                let data: Vec<u8> = row.get(0)?;
                Ok(data)
            })
            .map_err(store_err)?;

        let mut receipts = Vec::new();
        for row in rows {
            let data = row.map_err(store_err)?;
            let receipt: exo_core::types::TrustReceipt = ciborium::from_reader(&data[..])
                .map_err(|e| store_err(format!("CBOR decode receipt: {e}")))?;
            receipts.push(receipt);
        }
        Ok(receipts)
    }

    /// Find all child nodes of a given parent hash.
    pub fn children(&self, parent_hash: &Hash256) -> DagResult<Vec<Hash256>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let parent_hash = *parent_hash;
            return block_on_dagdb(async move { store.children_async(parent_hash).await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT child_hash FROM dag_parents WHERE parent_hash = ?1")
            .map_err(store_err)?;

        let rows = stmt
            .query_map(params![parent_hash.0.as_slice()], |row| {
                let bytes: Vec<u8> = row.get(0)?;
                Ok(bytes)
            })
            .map_err(store_err)?;

        let mut result = Vec::new();
        for row in rows {
            let bytes = row.map_err(store_err)?;
            result.push(decode_hash_bytes(&bytes, "dag_parents.child_hash")?);
        }
        Ok(result)
    }

    /// Check whether a node hash is committed.
    #[allow(dead_code)]
    pub fn is_committed(&self, hash: &Hash256) -> DagResult<bool> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let hash = *hash;
            return block_on_dagdb(async move {
                Ok(store.committed_height_for_async(hash).await?.is_some())
            });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT 1 FROM committed WHERE hash = ?1")
            .map_err(store_err)?;
        match stmt.query_row(params![hash.0.as_slice()], |_| Ok(())) {
            Ok(()) => Ok(true),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(false),
            Err(e) => Err(store_err(format!("committed.hash presence query: {e}"))),
        }
    }

    /// Get the committed height for a specific hash (if committed).
    pub fn committed_height_for(&self, hash: &Hash256) -> DagResult<Option<u64>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let hash = *hash;
            return block_on_dagdb(async move { store.committed_height_for_async(hash).await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT height FROM committed WHERE hash = ?1")
            .map_err(store_err)?;

        match stmt.query_row(params![hash.0.as_slice()], |row| {
            let h: i64 = row.get(0)?;
            Ok(h)
        }) {
            Ok(h) => Ok(Some(sqlite_i64_to_u64(h, "committed.height")?)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(store_err(e)),
        }
    }

    /// Get all committed nodes with their full DagNode data, ordered by height.
    ///
    /// Used by state sync to serve snapshot chunks with actual node payloads.
    pub fn committed_dag_nodes_in_range(
        &self,
        from_height: u64,
        to_height: u64,
    ) -> DagResult<Vec<DagNode>> {
        let committed = self.committed_nodes_in_range(from_height, to_height)?;
        let mut nodes = Vec::with_capacity(committed.len());
        for (hash, _height) in committed {
            if let Some(node) = self.get_sync(&hash)? {
                nodes.push(node);
            }
        }
        Ok(nodes)
    }
}

// ---------------------------------------------------------------------------
// Sync helper methods — used by callers holding std::sync::Mutex locks.
// The async DagStore trait impl delegates to these.
// ---------------------------------------------------------------------------

impl SqliteDagStore {
    fn insert_node_tx(tx: &rusqlite::Transaction<'_>, node: &DagNode) -> DagResult<()> {
        let cbor = Self::encode_node(node)?;

        tx.execute(
            "INSERT OR IGNORE INTO dag_nodes (hash, cbor_payload) VALUES (?1, ?2)",
            params![node.hash.0.as_slice(), cbor],
        )
        .map_err(store_err)?;

        for parent in &node.parents {
            tx.execute(
                "INSERT OR IGNORE INTO dag_parents (child_hash, parent_hash) VALUES (?1, ?2)",
                params![node.hash.0.as_slice(), parent.0.as_slice()],
            )
            .map_err(store_err)?;
        }

        Ok(())
    }

    /// Sync version of `DagStore::get`.
    pub fn get_sync(&self, hash: &Hash256) -> DagResult<Option<DagNode>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let hash = *hash;
            return block_on_dagdb(async move { store.get_sync_async(&hash).await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT cbor_payload FROM dag_nodes WHERE hash = ?1")
            .map_err(store_err)?;

        let result: Result<Vec<u8>, rusqlite::Error> =
            stmt.query_row(params![hash.0.as_slice()], |row| row.get(0));

        match result {
            Ok(bytes) => Ok(Some(Self::decode_node(&bytes)?)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(store_err(format!("dag_nodes.cbor_payload: {e}"))),
        }
    }

    /// Sync version of `DagStore::put`.
    pub fn put_sync(&mut self, node: DagNode) -> DagResult<()> {
        self.put_many_sync(&[node])
    }

    /// Persist a batch of DAG nodes atomically.
    pub fn put_many_sync(&mut self, nodes: &[DagNode]) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let nodes = nodes.to_vec();
            return block_on_dagdb(async move { store.put_many_sync_async(nodes).await });
        }
        let tx = self.sqlite_conn_mut()?.transaction().map_err(store_err)?;
        for node in nodes {
            Self::insert_node_tx(&tx, node)?;
        }
        tx.commit().map_err(store_err)?;
        Ok(())
    }

    /// Atomically persist a DAG node, committed marker, and proving trust receipt.
    pub fn put_committed_node_with_receipt_sync(
        &mut self,
        node: &DagNode,
        height: u64,
        receipt: &TrustReceipt,
    ) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let node = node.clone();
            let receipt = receipt.clone();
            return block_on_dagdb(async move {
                store
                    .put_committed_node_with_receipt_sync_async(node, height, receipt)
                    .await
            });
        }
        if receipt.action_hash != node.hash {
            return Err(store_err(
                "trust_receipts.action_hash must match committed node hash",
            ));
        }

        let tx = self.sqlite_conn_mut()?.transaction().map_err(store_err)?;
        Self::insert_node_tx(&tx, node)?;
        Self::insert_committed_tx(&tx, &node.hash, height)?;
        Self::insert_receipt_tx(&tx, receipt)?;
        tx.commit().map_err(store_err)?;
        Ok(())
    }

    /// Persist nodes, commit markers, and finality certificates atomically.
    pub fn put_committed_many_with_certificates_sync(
        &mut self,
        nodes: &[(DagNode, u64)],
        certificates: &[CommitCertificate],
    ) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let nodes = nodes.to_vec();
            let certificates = certificates.to_vec();
            return block_on_dagdb(async move {
                store
                    .put_committed_many_with_certificates_sync_async(nodes, certificates)
                    .await
            });
        }
        if nodes.len() != certificates.len() {
            return Err(store_err(format!(
                "committed batch must include one certificate per node: got {} certificates for {} nodes",
                certificates.len(),
                nodes.len()
            )));
        }

        let tx = self.sqlite_conn_mut()?.transaction().map_err(store_err)?;
        for ((node, height), certificate) in nodes.iter().zip(certificates) {
            if certificate.node_hash != node.hash {
                return Err(store_err(format!(
                    "commit certificate node_hash {} does not match DAG node hash {}",
                    certificate.node_hash, node.hash
                )));
            }
            Self::insert_node_tx(&tx, node)?;
            Self::insert_committed_tx(&tx, &node.hash, *height)?;
            Self::insert_certificate_tx(&tx, certificate)?;
        }
        tx.commit().map_err(store_err)?;
        Ok(())
    }

    /// Sync version of `DagStore::contains`.
    #[allow(dead_code)]
    pub fn contains_sync(&self, hash: &Hash256) -> DagResult<bool> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let hash = *hash;
            return block_on_dagdb(async move { store.contains_sync_async(&hash).await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT 1 FROM dag_nodes WHERE hash = ?1")
            .map_err(store_err)?;

        match stmt.query_row(params![hash.0.as_slice()], |_| Ok(())) {
            Ok(()) => Ok(true),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(false),
            Err(e) => Err(store_err(format!("dag_nodes.hash presence query: {e}"))),
        }
    }

    /// Sync version of `DagStore::tips`.
    pub fn tips_sync(&self) -> DagResult<Vec<Hash256>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.tips_sync_async().await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached(
                "SELECT hash FROM dag_nodes
                 WHERE hash NOT IN (SELECT parent_hash FROM dag_parents)
                 ORDER BY hash",
            )
            .map_err(store_err)?;

        let rows = stmt
            .query_map([], |row| {
                let bytes: Vec<u8> = row.get(0)?;
                Ok(bytes)
            })
            .map_err(store_err)?;

        let mut tips = Vec::new();
        for row in rows {
            let bytes = row.map_err(store_err)?;
            tips.push(decode_hash_bytes(&bytes, "dag_nodes.hash")?);
        }
        Ok(tips)
    }

    /// Sync version of `DagStore::committed_height`.
    pub fn committed_height_sync(&self) -> DagResult<u64> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(async move { store.committed_height_sync_async().await });
        }
        let mut stmt = self
            .sqlite_conn()?
            .prepare_cached("SELECT COALESCE(MAX(height), 0) FROM committed")
            .map_err(store_err)?;

        let height: i64 = stmt.query_row([], |row| row.get(0)).map_err(store_err)?;

        sqlite_i64_to_u64(height, "committed.height")
    }

    /// Sync version of `DagStore::mark_committed`.
    #[allow(dead_code)]
    pub fn mark_committed_sync(&mut self, hash: &Hash256, height: u64) -> DagResult<()> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let hash = *hash;
            return block_on_dagdb(
                async move { store.mark_committed_sync_async(hash, height).await },
            );
        }
        if !self.contains_sync(hash)? {
            return Err(DagError::NodeNotFound(*hash));
        }

        let height = sqlite_u64_to_i64(height, "committed.height")?;
        self.sqlite_conn_mut()?
            .execute(
                "INSERT OR REPLACE INTO committed (hash, height) VALUES (?1, ?2)",
                params![hash.0.as_slice(), height],
            )
            .map_err(store_err)?;

        Ok(())
    }

    fn latest_economy_anchor_hash_tx(tx: &rusqlite::Transaction<'_>) -> DagResult<Hash256> {
        let result: Result<Vec<u8>, rusqlite::Error> = tx.query_row(
            "SELECT value FROM economy_meta WHERE key = 'latest_anchor_hash'",
            [],
            |row| row.get(0),
        );
        match result {
            Ok(bytes) => decode_hash_bytes(&bytes, "economy_meta.latest_anchor_hash"),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(Hash256::ZERO),
            Err(e) => Err(store_err(format!("economy_meta.latest_anchor_hash: {e}"))),
        }
    }

    /// Return the latest deterministic HonorGood/economy object anchor hash.
    pub fn latest_economy_anchor_hash_sync(&self) -> DagResult<Hash256> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            return block_on_dagdb(
                async move { store.latest_economy_anchor_hash_sync_async().await },
            );
        }
        let result: Result<Vec<u8>, rusqlite::Error> = self.sqlite_conn()?.query_row(
            "SELECT value FROM economy_meta WHERE key = 'latest_anchor_hash'",
            [],
            |row| row.get(0),
        );
        match result {
            Ok(bytes) => decode_hash_bytes(&bytes, "economy_meta.latest_anchor_hash"),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(Hash256::ZERO),
            Err(e) => Err(store_err(format!("economy_meta.latest_anchor_hash: {e}"))),
        }
    }

    /// Persist one canonical economy object and append its hash-linked anchor.
    pub fn put_economy_object_sync<T: Serialize>(
        &mut self,
        object_kind: EconomyObjectKind,
        object_id: &Hash256,
        content_hash: &Hash256,
        created_at: Timestamp,
        object: &T,
    ) -> DagResult<EconomyRecordAnchor> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let object_id = *object_id;
            let content_hash = *content_hash;
            let object_cbor = encode_cbor(object, "dagdb_node_economy_objects.cbor_data")?;
            return block_on_dagdb(async move {
                store
                    .put_economy_object_sync_async(
                        object_kind,
                        object_id,
                        content_hash,
                        created_at,
                        object_cbor,
                    )
                    .await
            });
        }
        if *object_id == Hash256::ZERO {
            return Err(store_err("economy object_id must not be Hash256::ZERO"));
        }
        if *content_hash == Hash256::ZERO {
            return Err(store_err("economy content_hash must not be Hash256::ZERO"));
        }
        if created_at == Timestamp::ZERO {
            return Err(store_err("economy created_at must not be Timestamp::ZERO"));
        }

        let object_cbor = encode_cbor(object, "economy_objects.cbor_data")?;
        let tx = self.sqlite_conn_mut()?.transaction().map_err(store_err)?;
        let previous_anchor_hash = Self::latest_economy_anchor_hash_tx(&tx)?;
        let anchor = EconomyRecordAnchor {
            anchor_hash: Hash256::ZERO,
            previous_anchor_hash,
            object_kind,
            object_id: *object_id,
            object_hash: *content_hash,
            created_at,
        }
        .anchor()
        .map_err(store_err)?;
        let anchor_cbor = encode_cbor(&anchor, "economy_anchors.cbor_data")?;
        let created_physical_ms =
            sqlite_u64_to_i64(created_at.physical_ms, "economy.created_physical_ms")?;
        let created_logical =
            sqlite_u64_to_i64(u64::from(created_at.logical), "economy.created_logical")?;

        tx.execute(
            "INSERT INTO economy_objects (
                object_kind, object_id, content_hash, created_physical_ms,
                created_logical, cbor_data
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            params![
                object_kind.label(),
                object_id.0.as_slice(),
                content_hash.0.as_slice(),
                created_physical_ms,
                created_logical,
                object_cbor
            ],
        )
        .map_err(|e| store_err(format!("insert economy object: {e}")))?;

        tx.execute(
            "INSERT INTO economy_anchors (
                anchor_hash, previous_anchor_hash, object_kind, object_id,
                object_hash, created_physical_ms, created_logical, cbor_data
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            params![
                anchor.anchor_hash.0.as_slice(),
                anchor.previous_anchor_hash.0.as_slice(),
                object_kind.label(),
                object_id.0.as_slice(),
                content_hash.0.as_slice(),
                created_physical_ms,
                created_logical,
                anchor_cbor
            ],
        )
        .map_err(|e| store_err(format!("insert economy anchor: {e}")))?;

        tx.execute(
            "INSERT OR REPLACE INTO economy_meta (key, value)
             VALUES ('latest_anchor_hash', ?1)",
            params![anchor.anchor_hash.0.as_slice()],
        )
        .map_err(store_err)?;
        tx.commit().map_err(store_err)?;
        Ok(anchor)
    }

    /// Load one persisted economy object by kind and canonical object id.
    pub fn get_economy_object_sync<T: DeserializeOwned + Send + 'static>(
        &self,
        object_kind: EconomyObjectKind,
        object_id: &Hash256,
    ) -> DagResult<Option<T>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let object_id = *object_id;
            return block_on_dagdb(async move {
                store
                    .get_economy_object_sync_async(object_kind, object_id)
                    .await
            });
        }
        let result: Result<Vec<u8>, rusqlite::Error> = self.sqlite_conn()?.query_row(
            "SELECT cbor_data FROM economy_objects
             WHERE object_kind = ?1 AND object_id = ?2",
            params![object_kind.label(), object_id.0.as_slice()],
            |row| row.get(0),
        );
        match result {
            Ok(bytes) => Ok(Some(decode_cbor(&bytes, "economy_objects.cbor_data")?)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(store_err(format!("economy_objects.cbor_data: {e}"))),
        }
    }

    /// Load a persisted economy anchor by its hash.
    pub fn get_economy_anchor_sync(
        &self,
        anchor_hash: &Hash256,
    ) -> DagResult<Option<EconomyRecordAnchor>> {
        if let Some(store) = self.dagdb() {
            let store = store.clone();
            let anchor_hash = *anchor_hash;
            return block_on_dagdb(async move {
                store.get_economy_anchor_sync_async(anchor_hash).await
            });
        }
        let result: Result<Vec<u8>, rusqlite::Error> = self.sqlite_conn()?.query_row(
            "SELECT cbor_data FROM economy_anchors WHERE anchor_hash = ?1",
            params![anchor_hash.0.as_slice()],
            |row| row.get(0),
        );
        match result {
            Ok(bytes) => Ok(Some(decode_cbor(&bytes, "economy_anchors.cbor_data")?)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(store_err(format!("economy_anchors.cbor_data: {e}"))),
        }
    }
}

// NOTE: SqliteDagStore does NOT implement the async DagStore trait because
// rusqlite::Connection is !Sync. Callers use the _sync methods directly
// (via Arc<Mutex<SqliteDagStore>>). The async DagStore trait is implemented
// by MemoryStore (exo-dag) and PostgresStore (exo-dag, postgres feature).

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use std::collections::BTreeSet;

    use exo_core::types::{Did, Signature};
    use exo_dag::dag::{Dag, DeterministicDagClock, append};
    use exo_economy::{
        EconomyObjectKind, LegacyReceipt, Mission, apex_velocity_catalyst_client_services_mission,
        archon_exoforge_legacy_receipt,
    };

    use super::*;

    type SignFn = Box<dyn Fn(&[u8]) -> Signature>;

    fn make_sign_fn() -> SignFn {
        Box::new(|data: &[u8]| {
            let h = blake3::hash(data);
            let mut sig = [0u8; 64];
            sig[..32].copy_from_slice(h.as_bytes());
            Signature::from_bytes(sig)
        })
    }

    fn make_test_node() -> DagNode {
        let mut dag = Dag::new();
        let mut clock = DeterministicDagClock::new();
        let creator = Did::new("did:exo:test").expect("valid");
        let sign_fn = make_sign_fn();
        append(&mut dag, &[], b"genesis", &creator, &*sign_fn, &mut clock).unwrap()
    }

    fn commit_certificate_for(hash: Hash256, round: u64) -> CommitCertificate {
        CommitCertificate {
            node_hash: hash,
            round,
            votes: vec![Vote {
                voter: Did::new("did:exo:v0").unwrap(),
                round,
                node_hash: hash,
                signature: Signature::from_bytes([7u8; 64]),
            }],
        }
    }

    fn temp_store() -> SqliteDagStore {
        let dir = tempfile::tempdir().unwrap();
        SqliteDagStore::open(dir.path()).unwrap()
    }

    #[test]
    fn production_store_source_does_not_suppress_or_use_truncating_sqlite_integer_casts() {
        let source = include_str!("store.rs");
        let production = source
            .split("\n#[cfg(test)]")
            .next()
            .expect("production section");

        assert!(
            !production.contains("clippy::as_conversions"),
            "production store source must not suppress integer conversion lints"
        );
        assert!(
            !production.contains("value as u64"),
            "SQLite INTEGER conversion must use checked conversion, not an as cast"
        );
    }

    #[test]
    fn production_store_presence_checks_do_not_squash_sqlite_errors() {
        let source = include_str!("store.rs");
        let production = source
            .split("\n#[cfg(test)]")
            .next()
            .expect("production section");

        assert!(
            !production.contains(
                ".query_row(params![hash.0.as_slice()], |_| Ok(()))\n            .is_ok()"
            ),
            "presence checks must distinguish missing rows from SQLite read errors"
        );
        assert!(
            production.contains("Err(rusqlite::Error::QueryReturnedNoRows) => Ok(false)"),
            "missing rows may map to false, but other SQLite errors must propagate"
        );
    }

    #[test]
    fn new_store_is_empty() {
        let store = temp_store();
        assert_eq!(store.committed_height_sync().unwrap(), 0);
        assert!(store.tips_sync().unwrap().is_empty());
    }

    #[test]
    fn put_and_get() {
        let mut store = temp_store();
        let node = make_test_node();

        store.put_sync(node.clone()).unwrap();
        let retrieved = store.get_sync(&node.hash).unwrap();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().hash, node.hash);
    }

    #[test]
    fn economy_object_persistence_round_trips_and_hash_links_anchors() {
        let mut store = temp_store();
        let mission = apex_velocity_catalyst_client_services_mission(Some(1_000_000)).unwrap();
        let mission_anchor = store
            .put_economy_object_sync(
                EconomyObjectKind::Mission,
                &mission.mission_id,
                &mission.content_hash,
                mission.created_at,
                &mission,
            )
            .unwrap();

        let legacy = archon_exoforge_legacy_receipt().unwrap();
        let legacy_anchor = store
            .put_economy_object_sync(
                EconomyObjectKind::LegacyReceipt,
                &legacy.legacy_receipt_id,
                &legacy.content_hash,
                legacy.created_at,
                &legacy,
            )
            .unwrap();

        let loaded_mission: Mission = store
            .get_economy_object_sync(EconomyObjectKind::Mission, &mission.mission_id)
            .unwrap()
            .unwrap();
        let loaded_legacy: LegacyReceipt = store
            .get_economy_object_sync(EconomyObjectKind::LegacyReceipt, &legacy.legacy_receipt_id)
            .unwrap()
            .unwrap();

        assert_eq!(loaded_mission, mission);
        assert_eq!(loaded_legacy, legacy);
        assert_eq!(mission_anchor.previous_anchor_hash, Hash256::ZERO);
        assert_eq!(
            legacy_anchor.previous_anchor_hash,
            mission_anchor.anchor_hash
        );
        assert_eq!(
            store.latest_economy_anchor_hash_sync().unwrap(),
            legacy_anchor.anchor_hash
        );
        assert_eq!(
            store
                .get_economy_anchor_sync(&legacy_anchor.anchor_hash)
                .unwrap(),
            Some(legacy_anchor)
        );
    }

    #[test]
    fn economy_object_persistence_rejects_duplicate_or_zero_ids() {
        let mut store = temp_store();
        let mission = apex_velocity_catalyst_client_services_mission(None).unwrap();
        store
            .put_economy_object_sync(
                EconomyObjectKind::Mission,
                &mission.mission_id,
                &mission.content_hash,
                mission.created_at,
                &mission,
            )
            .unwrap();

        assert!(
            store
                .put_economy_object_sync(
                    EconomyObjectKind::Mission,
                    &mission.mission_id,
                    &mission.content_hash,
                    mission.created_at,
                    &mission,
                )
                .is_err()
        );
        assert!(
            store
                .put_economy_object_sync(
                    EconomyObjectKind::Mission,
                    &Hash256::ZERO,
                    &mission.content_hash,
                    mission.created_at,
                    &mission,
                )
                .is_err()
        );
    }

    #[test]
    fn get_nonexistent() {
        let store = temp_store();
        let result = store.get_sync(&Hash256::ZERO).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn get_sync_propagates_payload_read_errors() {
        let store = temp_store();
        let mut hash = [0u8; 32];
        hash[0] = 0xD0;
        let hash = Hash256::from_bytes(hash);
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO dag_nodes (hash, cbor_payload) VALUES (?1, ?2)",
                rusqlite::params![hash.0.as_slice(), 7_i64],
            )
            .unwrap();

        let err = store.get_sync(&hash).unwrap_err();

        assert!(
            err.to_string().contains("dag_nodes.cbor_payload"),
            "malformed persisted payload must surface as a store error"
        );
    }

    #[test]
    fn contains() {
        let mut store = temp_store();
        let node = make_test_node();

        assert!(!store.contains_sync(&node.hash).unwrap());
        store.put_sync(node.clone()).unwrap();
        assert!(store.contains_sync(&node.hash).unwrap());
    }

    #[test]
    fn tips_single_node() {
        let mut store = temp_store();
        let node = make_test_node();
        store.put_sync(node.clone()).unwrap();
        let t = store.tips_sync().unwrap();
        assert_eq!(t, vec![node.hash]);
    }

    #[test]
    fn tips_with_children() {
        let mut dag = Dag::new();
        let mut clock = DeterministicDagClock::new();
        let creator = Did::new("did:exo:test").expect("valid");
        let sign_fn = make_sign_fn();

        let genesis = append(&mut dag, &[], b"genesis", &creator, &*sign_fn, &mut clock).unwrap();
        let child = append(
            &mut dag,
            &[genesis.hash],
            b"child",
            &creator,
            &*sign_fn,
            &mut clock,
        )
        .unwrap();

        let mut store = temp_store();
        store.put_sync(genesis).unwrap();
        store.put_sync(child.clone()).unwrap();

        let t = store.tips_sync().unwrap();
        assert_eq!(t, vec![child.hash]);
    }

    #[test]
    fn committed_height_tracking() {
        let mut store = temp_store();
        let node = make_test_node();
        store.put_sync(node.clone()).unwrap();

        assert_eq!(store.committed_height_sync().unwrap(), 0);

        store.mark_committed_sync(&node.hash, 1).unwrap();
        assert_eq!(store.committed_height_sync().unwrap(), 1);
    }

    #[test]
    fn mark_committed_nonexistent_fails() {
        let mut store = temp_store();
        let err = store.mark_committed_sync(&Hash256::ZERO, 1).unwrap_err();
        assert!(matches!(err, DagError::NodeNotFound(_)));
    }

    #[test]
    fn consensus_round_persistence() {
        let mut store = temp_store();
        assert_eq!(store.load_consensus_round().unwrap(), 0);
        store.save_consensus_round(42).unwrap();
        assert_eq!(store.load_consensus_round().unwrap(), 42);
        store.save_consensus_round(100).unwrap();
        assert_eq!(store.load_consensus_round().unwrap(), 100);
    }

    #[test]
    fn load_consensus_round_propagates_store_errors() {
        let store = temp_store();
        store
            .sqlite_conn()
            .unwrap()
            .execute("DROP TABLE consensus_meta", [])
            .unwrap();

        let err = store.load_consensus_round().unwrap_err();

        assert!(err.to_string().contains("consensus_meta"));
    }

    #[test]
    fn vote_persistence_roundtrip() {
        use exo_core::types::Signature;
        let mut store = temp_store();
        let did = Did::new("did:exo:voter1").unwrap();
        let mut hash = [0u8; 32];
        hash[0] = 0xAB;
        let vote = Vote {
            voter: did.clone(),
            round: 5,
            node_hash: Hash256::from_bytes(hash),
            signature: Signature::from_bytes([7u8; 64]),
        };
        store.save_vote(&vote).unwrap();

        let loaded = store.load_votes_for_round(5).unwrap();
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded[0].voter, did);
        assert_eq!(loaded[0].round, 5);
        assert_eq!(loaded[0].node_hash, Hash256::from_bytes(hash));

        // Different round returns empty.
        let empty = store.load_votes_for_round(6).unwrap();
        assert!(empty.is_empty());
    }

    #[test]
    fn load_votes_for_round_rejects_short_hash() {
        let store = temp_store();
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO consensus_votes (round, node_hash, voter_did, signature)
                 VALUES (?1, ?2, ?3, ?4)",
                rusqlite::params![7_i64, vec![0xABu8; 31], "did:exo:voter1", vec![7u8; 64]],
            )
            .unwrap();

        let err = store.load_votes_for_round(7).unwrap_err();

        assert!(err.to_string().contains("consensus_votes.node_hash"));
    }

    #[test]
    fn load_votes_for_round_rejects_short_signature() {
        let store = temp_store();
        let mut hash = [0u8; 32];
        hash[0] = 0xAB;
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO consensus_votes (round, node_hash, voter_did, signature)
                 VALUES (?1, ?2, ?3, ?4)",
                rusqlite::params![7_i64, hash.as_slice(), "did:exo:voter1", vec![7u8; 63]],
            )
            .unwrap();

        let err = store.load_votes_for_round(7).unwrap_err();

        assert!(err.to_string().contains("consensus_votes.signature"));
    }

    #[test]
    fn load_votes_for_round_rejects_zero_signature() {
        let store = temp_store();
        let mut hash = [0u8; 32];
        hash[0] = 0xAB;
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO consensus_votes (round, node_hash, voter_did, signature)
                 VALUES (?1, ?2, ?3, ?4)",
                rusqlite::params![7_i64, hash.as_slice(), "did:exo:voter1", vec![0u8; 64]],
            )
            .unwrap();

        let err = store.load_votes_for_round(7).unwrap_err();

        assert!(err.to_string().contains("consensus_votes.signature"));
    }

    #[test]
    fn load_votes_for_round_rejects_invalid_voter_did() {
        let store = temp_store();
        let mut hash = [0u8; 32];
        hash[0] = 0xAB;
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO consensus_votes (round, node_hash, voter_did, signature)
                 VALUES (?1, ?2, ?3, ?4)",
                rusqlite::params![7_i64, hash.as_slice(), "not-a-did", vec![7u8; 64]],
            )
            .unwrap();

        let err = store.load_votes_for_round(7).unwrap_err();

        assert!(err.to_string().contains("consensus_votes.voter_did"));
    }

    #[test]
    fn save_vote_rejects_empty_signature() {
        let mut store = temp_store();
        let vote = Vote {
            voter: Did::new("did:exo:voter1").unwrap(),
            round: 5,
            node_hash: Hash256::digest(b"vote-target"),
            signature: Signature::from_bytes([0u8; 64]),
        };

        let err = store.save_vote(&vote).unwrap_err();

        assert!(err.to_string().contains("consensus_votes.signature"));
    }

    #[test]
    fn save_vote_rejects_signature_variants_that_cannot_roundtrip() {
        let mut store = temp_store();
        let vote = Vote {
            voter: Did::new("did:exo:voter1").unwrap(),
            round: 5,
            node_hash: Hash256::digest(b"vote-target"),
            signature: Signature::PostQuantum(vec![7u8; 64]),
        };

        let err = store.save_vote(&vote).unwrap_err();

        assert!(err.to_string().contains("consensus_votes.signature"));
    }

    #[test]
    fn save_vote_rejects_rounds_that_do_not_fit_sqlite_integer() {
        let mut store = temp_store();
        let vote = Vote {
            voter: Did::new("did:exo:voter1").unwrap(),
            round: u64::MAX,
            node_hash: Hash256::digest(b"vote-target"),
            signature: Signature::from_bytes([7u8; 64]),
        };

        let err = store.save_vote(&vote).unwrap_err();

        assert!(err.to_string().contains("consensus_votes.round"));
    }

    #[test]
    fn certificate_persistence_roundtrip() {
        let mut store = temp_store();
        let mut hash = [0u8; 32];
        hash[0] = 0xCD;
        let cert = commit_certificate_for(Hash256::from_bytes(hash), 3);
        store.save_certificate(&cert).unwrap();

        let loaded = store.load_certificates().unwrap();
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded[0].round, 3);
        assert_eq!(loaded[0].node_hash, Hash256::from_bytes(hash));
        assert_eq!(loaded[0].votes.len(), 1);
    }

    #[test]
    fn load_certificate_for_hash_returns_matching_certificate_only() {
        let mut store = temp_store();
        let hash = Hash256::digest(b"cert-target");
        let cert = commit_certificate_for(hash, 3);
        store.save_certificate(&cert).unwrap();

        let loaded = store
            .load_certificate_for_hash(&hash)
            .unwrap()
            .expect("certificate should exist");
        assert_eq!(loaded, cert);
        assert!(
            store
                .load_certificate_for_hash(&Hash256::digest(b"missing-cert"))
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn load_certificate_for_hash_rejects_cbor_node_hash_mismatch() {
        let store = temp_store();
        let row_hash = Hash256::digest(b"row-node");
        let cert = commit_certificate_for(Hash256::digest(b"cbor-node"), 3);
        let mut cbor = Vec::new();
        ciborium::into_writer(&cert, &mut cbor).unwrap();
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO commit_certificates (node_hash, round, cbor_data)
                 VALUES (?1, ?2, ?3)",
                rusqlite::params![row_hash.0.as_slice(), 3_i64, cbor],
            )
            .unwrap();

        let err = store.load_certificate_for_hash(&row_hash).unwrap_err();

        assert!(err.to_string().contains("CBOR certificate node_hash"));
    }

    #[test]
    fn put_committed_many_with_certificates_persists_finality_rows() {
        let mut store = temp_store();
        let node = make_test_node();
        let certificate = commit_certificate_for(node.hash, 1);

        store
            .put_committed_many_with_certificates_sync(
                &[(node.clone(), 1)],
                std::slice::from_ref(&certificate),
            )
            .unwrap();

        assert!(store.contains_sync(&node.hash).unwrap());
        assert!(store.is_committed(&node.hash).unwrap());
        assert_eq!(
            store.load_certificate_for_hash(&node.hash).unwrap(),
            Some(certificate)
        );
    }

    #[test]
    fn put_committed_many_with_certificates_rejects_mismatched_certificate_without_partial_rows() {
        let mut store = temp_store();
        let node = make_test_node();
        let certificate = commit_certificate_for(Hash256::digest(b"wrong-node"), 1);

        let err = store
            .put_committed_many_with_certificates_sync(&[(node.clone(), 1)], &[certificate])
            .unwrap_err();

        assert!(err.to_string().contains("does not match DAG node hash"));
        assert!(!store.contains_sync(&node.hash).unwrap());
        assert!(!store.is_committed(&node.hash).unwrap());
        assert!(store.load_certificates().unwrap().is_empty());
    }

    #[test]
    fn put_committed_many_with_certificates_rolls_back_when_certificate_is_rejected() {
        let mut store = temp_store();
        let node = make_test_node();
        let mut certificate = commit_certificate_for(node.hash, 1);
        certificate.votes[0].signature = Signature::Empty;

        let err = store
            .put_committed_many_with_certificates_sync(&[(node.clone(), 1)], &[certificate])
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("commit_certificates.votes[0].signature")
        );
        assert!(!store.contains_sync(&node.hash).unwrap());
        assert!(!store.is_committed(&node.hash).unwrap());
        assert!(store.load_certificates().unwrap().is_empty());
    }

    #[test]
    fn save_certificate_rejects_empty_vote_signature() {
        let mut store = temp_store();
        let hash = Hash256::digest(b"cert-target");
        let cert = CommitCertificate {
            node_hash: hash,
            round: 3,
            votes: vec![Vote {
                voter: Did::new("did:exo:v0").unwrap(),
                round: 3,
                node_hash: hash,
                signature: Signature::Empty,
            }],
        };

        let err = store.save_certificate(&cert).unwrap_err();

        assert!(
            err.to_string()
                .contains("commit_certificates.votes[0].signature")
        );
    }

    #[test]
    fn save_certificate_rejects_signature_variants_that_cannot_verify() {
        let mut store = temp_store();
        let hash = Hash256::digest(b"cert-target");
        let cert = CommitCertificate {
            node_hash: hash,
            round: 3,
            votes: vec![Vote {
                voter: Did::new("did:exo:v0").unwrap(),
                round: 3,
                node_hash: hash,
                signature: Signature::PostQuantum(vec![7u8; 64]),
            }],
        };

        let err = store.save_certificate(&cert).unwrap_err();

        assert!(
            err.to_string()
                .contains("commit_certificates.votes[0].signature")
        );
    }

    #[test]
    fn load_certificates_rejects_empty_vote_signature() {
        let store = temp_store();
        let hash = Hash256::digest(b"cert-target");
        let cert = CommitCertificate {
            node_hash: hash,
            round: 3,
            votes: vec![Vote {
                voter: Did::new("did:exo:v0").unwrap(),
                round: 3,
                node_hash: hash,
                signature: Signature::Empty,
            }],
        };
        let mut cbor = Vec::new();
        ciborium::into_writer(&cert, &mut cbor).unwrap();
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO commit_certificates (node_hash, round, cbor_data)
                 VALUES (?1, ?2, ?3)",
                rusqlite::params![hash.0.as_slice(), 3_i64, cbor],
            )
            .unwrap();

        let err = store.load_certificates().unwrap_err();

        assert!(
            err.to_string()
                .contains("commit_certificates.votes[0].signature")
        );
    }

    #[test]
    fn save_certificate_rejects_rounds_that_do_not_fit_sqlite_integer() {
        let mut store = temp_store();
        let hash = Hash256::digest(b"cert-target");
        let cert = CommitCertificate {
            node_hash: hash,
            round: u64::MAX,
            votes: vec![Vote {
                voter: Did::new("did:exo:v0").unwrap(),
                round: u64::MAX,
                node_hash: hash,
                signature: Signature::from_bytes([1u8; 64]),
            }],
        };

        let err = store.save_certificate(&cert).unwrap_err();

        assert!(err.to_string().contains("commit_certificates.round"));
    }

    #[test]
    fn validator_set_persistence() {
        let mut store = temp_store();
        let empty = store.load_validator_set().unwrap();
        assert!(empty.is_empty());

        let mut set = BTreeSet::new();
        set.insert(Did::new("did:exo:v0").unwrap());
        set.insert(Did::new("did:exo:v1").unwrap());
        set.insert(Did::new("did:exo:v2").unwrap());
        store.save_validator_set(&set).unwrap();

        let loaded = store.load_validator_set().unwrap();
        assert_eq!(loaded.len(), 3);
        assert!(loaded.contains(&Did::new("did:exo:v0").unwrap()));
        assert!(loaded.contains(&Did::new("did:exo:v2").unwrap()));

        // Overwrite with smaller set.
        let mut smaller = BTreeSet::new();
        smaller.insert(Did::new("did:exo:v0").unwrap());
        store.save_validator_set(&smaller).unwrap();
        let loaded2 = store.load_validator_set().unwrap();
        assert_eq!(loaded2.len(), 1);
    }

    #[test]
    fn save_validator_set_preserves_existing_set_if_replacement_insert_fails() {
        let mut store = temp_store();
        let mut original = BTreeSet::new();
        original.insert(Did::new("did:exo:v0").unwrap());
        original.insert(Did::new("did:exo:v1").unwrap());
        store.save_validator_set(&original).unwrap();

        store
            .sqlite_conn()
            .unwrap()
            .execute_batch(
                "CREATE TEMP TRIGGER fail_validator_insert
                 BEFORE INSERT ON validators
                 WHEN NEW.did = 'did:exo:blocked'
                 BEGIN
                     SELECT RAISE(ABORT, 'injected validator insert failure');
                 END;",
            )
            .unwrap();

        let mut replacement = BTreeSet::new();
        replacement.insert(Did::new("did:exo:blocked").unwrap());
        replacement.insert(Did::new("did:exo:z").unwrap());

        let err = store.save_validator_set(&replacement).unwrap_err();

        assert!(
            err.to_string()
                .contains("injected validator insert failure")
        );
        let loaded = store.load_validator_set().unwrap();
        assert_eq!(loaded, original);
    }

    #[test]
    fn load_validator_set_rejects_invalid_did() {
        let store = temp_store();
        store
            .sqlite_conn()
            .unwrap()
            .execute("INSERT INTO validators (did) VALUES (?1)", ["not-a-did"])
            .unwrap();

        let err = store.load_validator_set().unwrap_err();

        assert!(err.to_string().contains("validators.did"));
    }

    #[test]
    fn receipt_save_and_load_by_hash() {
        use exo_core::types::{ReceiptOutcome, Timestamp, TrustReceipt};
        let mut store = temp_store();
        let sign_fn = make_sign_fn();

        let receipt = TrustReceipt::new(
            Did::new("did:exo:agent-a").unwrap(),
            Hash256::ZERO,
            None,
            "dag.commit".to_string(),
            Hash256::digest(b"action-payload"),
            ReceiptOutcome::Executed,
            Timestamp {
                physical_ms: 1_700_000_000_000,
                logical: 0,
            },
            &*sign_fn,
        )
        .expect("test trust receipt should encode");

        let hash = receipt.receipt_hash;
        store.save_receipt(&receipt).unwrap();

        let loaded = store.load_receipt(&hash).unwrap();
        assert!(loaded.is_some());
        let loaded = loaded.unwrap();
        assert_eq!(loaded.receipt_hash, hash);
        assert_eq!(loaded.actor_did.to_string(), "did:exo:agent-a");
        assert_eq!(loaded.action_type, "dag.commit");
        assert_eq!(loaded.outcome, ReceiptOutcome::Executed);
    }

    #[test]
    fn save_receipt_rejects_empty_signature() {
        use exo_core::types::{ReceiptOutcome, Timestamp, TrustReceipt};
        let mut store = temp_store();

        let receipt = TrustReceipt::new(
            Did::new("did:exo:agent-a").unwrap(),
            Hash256::digest(b"authority"),
            None,
            "dag.commit".to_string(),
            Hash256::digest(b"action-payload"),
            ReceiptOutcome::Executed,
            Timestamp {
                physical_ms: 1_700_000_000_000,
                logical: 0,
            },
            &|_| Signature::Empty,
        )
        .expect("test trust receipt should encode");

        let err = store.save_receipt(&receipt).unwrap_err();

        assert!(err.to_string().contains("trust_receipts.signature"));
    }

    #[test]
    fn save_receipt_rejects_timestamps_that_do_not_fit_sqlite_integer() {
        use exo_core::types::{ReceiptOutcome, Timestamp, TrustReceipt};
        let mut store = temp_store();
        let sign_fn = make_sign_fn();

        let receipt = TrustReceipt::new(
            Did::new("did:exo:agent-a").unwrap(),
            Hash256::digest(b"authority"),
            None,
            "dag.commit".to_string(),
            Hash256::digest(b"action-payload"),
            ReceiptOutcome::Executed,
            Timestamp {
                physical_ms: u64::MAX,
                logical: 0,
            },
            &*sign_fn,
        )
        .expect("test trust receipt should encode");

        let err = store.save_receipt(&receipt).unwrap_err();

        assert!(err.to_string().contains("trust_receipts.timestamp_ms"));
    }

    #[test]
    fn receipt_load_nonexistent() {
        let store = temp_store();
        let result = store.load_receipt(&Hash256::ZERO).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn receipt_load_by_actor_filters_and_limits() {
        use exo_core::types::{ReceiptOutcome, Timestamp, TrustReceipt};
        let mut store = temp_store();
        let sign_fn = make_sign_fn();

        // Save 3 receipts for actor-a at different timestamps.
        for i in 0u64..3 {
            let receipt = TrustReceipt::new(
                Did::new("did:exo:actor-a").unwrap(),
                Hash256::ZERO,
                None,
                format!("action.{i}"),
                Hash256::digest(format!("payload-{i}").as_bytes()),
                ReceiptOutcome::Executed,
                Timestamp {
                    physical_ms: 1_000_000 + i * 1000,
                    logical: 0,
                },
                &*sign_fn,
            )
            .expect("test trust receipt should encode");
            store.save_receipt(&receipt).unwrap();
        }

        // Save 1 receipt for actor-b.
        let other = TrustReceipt::new(
            Did::new("did:exo:actor-b").unwrap(),
            Hash256::ZERO,
            None,
            "other.action".to_string(),
            Hash256::digest(b"other"),
            ReceiptOutcome::Denied,
            Timestamp {
                physical_ms: 2_000_000,
                logical: 0,
            },
            &*sign_fn,
        )
        .expect("test trust receipt should encode");
        store.save_receipt(&other).unwrap();

        // Query actor-a — should get 3 receipts.
        let results = store.load_receipts_by_actor("did:exo:actor-a", 10).unwrap();
        assert_eq!(results.len(), 3);

        // Query with limit 2 — should get 2 (most recent first).
        let limited = store.load_receipts_by_actor("did:exo:actor-a", 2).unwrap();
        assert_eq!(limited.len(), 2);
        // Ordered by timestamp descending.
        assert!(limited[0].timestamp.physical_ms >= limited[1].timestamp.physical_ms);

        // Query actor-b — should get 1 receipt.
        let b_results = store.load_receipts_by_actor("did:exo:actor-b", 10).unwrap();
        assert_eq!(b_results.len(), 1);
        assert_eq!(b_results[0].outcome, ReceiptOutcome::Denied);

        // Query unknown actor — should get 0.
        let none = store.load_receipts_by_actor("did:exo:unknown", 10).unwrap();
        assert!(none.is_empty());
    }

    #[test]
    fn receipt_load_recent_across_actors_orders_and_limits() {
        use exo_core::types::{ReceiptOutcome, Timestamp, TrustReceipt};
        let mut store = temp_store();
        let sign_fn = make_sign_fn();

        let actors = [
            "did:exo:actor-a",
            "did:exo:actor-b",
            "did:exo:actor-c",
            "did:exo:actor-d",
        ];
        for (idx, actor) in actors.iter().enumerate() {
            let timestamp = Timestamp {
                physical_ms: 1_000_000 + u64::try_from(idx).unwrap() * 1000,
                logical: 0,
            };
            let receipt = TrustReceipt::new(
                Did::new(actor).unwrap(),
                Hash256::digest(format!("authority-{idx}").as_bytes()),
                None,
                format!("action.{idx}"),
                Hash256::digest(format!("payload-{idx}").as_bytes()),
                ReceiptOutcome::Executed,
                timestamp,
                &*sign_fn,
            )
            .expect("test trust receipt should encode");
            store.save_receipt(&receipt).unwrap();
        }

        let recent = store.load_recent_receipts(3).unwrap();

        assert_eq!(recent.len(), 3);
        assert_eq!(recent[0].actor_did.to_string(), "did:exo:actor-d");
        assert_eq!(recent[1].actor_did.to_string(), "did:exo:actor-c");
        assert_eq!(recent[2].actor_did.to_string(), "did:exo:actor-b");
        assert!(recent.iter().all(|receipt| receipt.verify_hash().unwrap()));
    }

    #[test]
    fn multiple_tips() {
        let mut dag = Dag::new();
        let mut clock = DeterministicDagClock::new();
        let creator = Did::new("did:exo:test").expect("valid");
        let sign_fn = make_sign_fn();

        let genesis = append(&mut dag, &[], b"genesis", &creator, &*sign_fn, &mut clock).unwrap();
        let c1 = append(
            &mut dag,
            &[genesis.hash],
            b"c1",
            &creator,
            &*sign_fn,
            &mut clock,
        )
        .unwrap();
        let c2 = append(
            &mut dag,
            &[genesis.hash],
            b"c2",
            &creator,
            &*sign_fn,
            &mut clock,
        )
        .unwrap();

        let mut store = temp_store();
        store.put_sync(genesis).unwrap();
        store.put_sync(c1.clone()).unwrap();
        store.put_sync(c2.clone()).unwrap();

        let t = store.tips_sync().unwrap();
        assert_eq!(t.len(), 2);
        assert!(t.contains(&c1.hash));
        assert!(t.contains(&c2.hash));
    }

    #[test]
    fn committed_nodes_in_range_rejects_short_hash() {
        let store = temp_store();
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO committed (hash, height) VALUES (?1, ?2)",
                rusqlite::params![vec![0xCDu8; 31], 1_i64],
            )
            .unwrap();

        let err = store.committed_nodes_in_range(0, 10).unwrap_err();

        assert!(err.to_string().contains("committed.hash"));
    }

    #[test]
    fn committed_height_for_rejects_negative_height() {
        let store = temp_store();
        let hash = Hash256::digest(b"committed-node");
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO committed (hash, height) VALUES (?1, ?2)",
                rusqlite::params![hash.0.as_slice(), -1_i64],
            )
            .unwrap();

        let err = store.committed_height_for(&hash).unwrap_err();

        assert!(err.to_string().contains("committed.height"));
    }

    #[test]
    fn committed_height_value_rejects_negative_height() {
        let store = temp_store();
        let hash = Hash256::digest(b"committed-node");
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO committed (hash, height) VALUES (?1, ?2)",
                rusqlite::params![hash.0.as_slice(), -1_i64],
            )
            .unwrap();

        let err = store.committed_height_value().unwrap_err();

        assert!(err.to_string().contains("committed.height"));
    }

    #[test]
    fn committed_height_sync_rejects_negative_height() {
        let store = temp_store();
        let hash = Hash256::digest(b"committed-node");
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO committed (hash, height) VALUES (?1, ?2)",
                rusqlite::params![hash.0.as_slice(), -1_i64],
            )
            .unwrap();

        let err = store.committed_height_sync().unwrap_err();

        assert!(err.to_string().contains("committed.height"));
    }

    #[test]
    fn mark_committed_rejects_heights_that_do_not_fit_sqlite_integer() {
        let mut store = temp_store();
        let node = make_test_node();
        store.put_sync(node.clone()).unwrap();

        let err = store.mark_committed_sync(&node.hash, u64::MAX).unwrap_err();

        assert!(err.to_string().contains("committed.height"));
    }

    #[test]
    fn mark_committed_with_receipt_rolls_back_when_receipt_is_rejected() {
        use exo_core::types::{ReceiptOutcome, Timestamp, TrustReceipt};
        let mut store = temp_store();
        let node = make_test_node();
        store.put_sync(node.clone()).unwrap();
        let receipt = TrustReceipt::new(
            Did::new("did:exo:test").unwrap(),
            Hash256::digest(b"authority"),
            None,
            "dag.commit".to_string(),
            node.hash,
            ReceiptOutcome::Executed,
            Timestamp {
                physical_ms: 1_700_000_000_000,
                logical: 0,
            },
            &|_| Signature::empty(),
        )
        .expect("test receipt should encode");

        let err = store
            .mark_committed_with_receipt_sync(&node.hash, 1, &receipt)
            .unwrap_err();

        assert!(err.to_string().contains("trust_receipts.signature"));
        assert!(
            !store.is_committed(&node.hash).unwrap(),
            "commit marker must not persist when receipt insert fails"
        );
        assert!(
            store.load_receipt(&receipt.receipt_hash).unwrap().is_none(),
            "rejected receipt must not persist partial receipt data"
        );
    }

    #[test]
    fn certificate_commit_with_receipt_rolls_back_every_row_when_receipt_is_rejected() {
        use exo_core::types::{ReceiptOutcome, Timestamp, TrustReceipt};
        let mut store = temp_store();
        let node = make_test_node();
        store.put_sync(node.clone()).unwrap();
        let cert = CommitCertificate {
            node_hash: node.hash,
            round: 0,
            votes: vec![Vote {
                voter: Did::new("did:exo:v0").unwrap(),
                round: 0,
                node_hash: node.hash,
                signature: Signature::from_bytes([7u8; 64]),
            }],
        };
        let receipt = TrustReceipt::new(
            Did::new("did:exo:test").unwrap(),
            Hash256::digest(b"authority"),
            None,
            "dag.commit".to_string(),
            node.hash,
            ReceiptOutcome::Executed,
            Timestamp {
                physical_ms: 1_700_000_000_000,
                logical: 0,
            },
            &|_| Signature::empty(),
        )
        .expect("test receipt should encode");

        let err = store
            .persist_commit_certificate_with_receipt_sync(&node.hash, 1, &cert, &receipt)
            .unwrap_err();

        assert!(err.to_string().contains("trust_receipts.signature"));
        assert!(
            !store.is_committed(&node.hash).unwrap(),
            "commit marker must not persist when receipt insert fails"
        );
        assert!(
            store.load_certificates().unwrap().is_empty(),
            "certificate must not persist without its matching receipt"
        );
        assert!(
            store.load_receipt(&receipt.receipt_hash).unwrap().is_none(),
            "rejected receipt must not persist partial receipt data"
        );
    }

    #[test]
    fn children_rejects_short_child_hash() {
        let store = temp_store();
        let parent = Hash256::digest(b"parent");
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO dag_parents (child_hash, parent_hash) VALUES (?1, ?2)",
                rusqlite::params![vec![0xABu8; 31], parent.0.as_slice()],
            )
            .unwrap();

        let err = store.children(&parent).unwrap_err();

        assert!(err.to_string().contains("dag_parents.child_hash"));
    }

    #[test]
    fn tips_rejects_short_hash() {
        let store = temp_store();
        store
            .sqlite_conn()
            .unwrap()
            .execute(
                "INSERT INTO dag_nodes (hash, cbor_payload) VALUES (?1, ?2)",
                rusqlite::params![vec![0xABu8; 31], vec![0x00u8]],
            )
            .unwrap();

        let err = store.tips_sync().unwrap_err();

        assert!(err.to_string().contains("dag_nodes.hash"));
    }
}