bsv-overlay-engine 0.1.5

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

use async_trait::async_trait;
use tracing::{debug, error, info, warn};

use crate::types::{
    GASPInitialReply, GASPInitialRequest, GASPInitialResponse, GASPNode, GASPNodeResponse,
    GASPOutput,
};

/// Current GASP protocol version.
pub const GASP_VERSION: u32 = 1;

/// Default sync limit per page.
pub const DEFAULT_GASP_SYNC_LIMIT: u64 = 10000;

/// Pull 100 outputs per request under the Worker's 30-second peer budget.
/// Reference: overlay-services@480d77a src/Engine.ts:29,895 requests 10,000
/// through src/GASP/OverlayGASPRemote.ts. Smaller requests bound each reply
/// and allow a slow peer's completed prefix to persist across ticks.
/// The responder's default stays unchanged for wire compatibility.
pub const ENGINE_GASP_SYNC_PAGE_LIMIT: u64 = 100;

// ============================================================================
// Per-peer sync budgets + dead-peer quarantine (bsv-low#302)
// ============================================================================

/// PURE (bsv-low#257/#302): race `fut` against `deadline`; `None` = the
/// deadline won and `fut` was DROPPED (its in-flight work cancelled).
/// Injectable deadline so the control flow is natively unit-tested — the
/// house idiom generalized out of `overlay-cloudflare`'s scheduled handler
/// (which passes its platform `sleep_ms`) so the ENGINE's per-peer GASP
/// budget can reuse it.
pub async fn race_or_deadline<F, D, T>(fut: F, deadline: D) -> Option<T>
where
    F: std::future::Future<Output = T>,
    D: std::future::Future<Output = ()>,
{
    let mut fut = std::pin::pin!(fut);
    let mut deadline = std::pin::pin!(deadline);
    std::future::poll_fn(move |cx| {
        if let std::task::Poll::Ready(v) = fut.as_mut().poll(cx) {
            return std::task::Poll::Ready(Some(v));
        }
        if deadline.as_mut().poll(cx).is_ready() {
            return std::task::Poll::Ready(None);
        }
        std::task::Poll::Pending
    })
    .await
}

/// `deadline`, LATCHED: once it fell due it answers `Ready` on every poll and
/// its inner future is never polled again (bsv-low #555, found by the
/// delta-2 fold). The worker's sleeps are `async fn` futures, which PANIC
/// when polled after they completed, and a per-graph deadline is polled
/// again after it fell due (the shared resume deadline, kept for the next
/// record; the half deadline of D2-L1).
pub fn latched(deadline: crate::engine::SleepFuture) -> crate::engine::SleepFuture {
    let mut inner = Some(deadline);
    Box::pin(std::future::poll_fn(move |cx| {
        let Some(deadline) = inner.as_mut() else {
            return std::task::Poll::Ready(());
        };
        if deadline.as_mut().poll(cx).is_ready() {
            inner = None;
            return std::task::Poll::Ready(());
        }
        std::task::Poll::Pending
    }))
}

/// What makes a deadline COOPERATIVE around a write (bsv-low #552, the lens
/// fold's HIGH-1). `Engine::submit` is several storage writes (mark spent,
/// delete the stale coin, insert the outputs, notify, record applied), each
/// an await on D1, and a future dropped between two of them leaves a head
/// chain with NO head: the old one deleted, the new one never inserted, and
/// no applied row to say so.
///
/// The writer opens a [`WriteSection`] around ONE transaction's submit and
/// asks [`SubmitGate::stop_if_due`] between two of them.
/// [`race_or_deadline_guarded`] does not drop its future while a section is
/// open: it notes the deadline as due and keeps polling until the section
/// closes, so the wait is bounded by the writes of one transaction. What the
/// deadline leaves is then a prefix of whole transactions, never part of one.
/// The race does not bound a write that never answers: the writer does
/// (bsv-low #559, `Engine::set_finalize_submit_budget`: the engine bounds
/// each storage call and hook inside the section, and a call that never
/// answers is that call's fault; the submit itself is never dropped).
#[derive(Debug, Default)]
pub struct SubmitGate {
    writing: std::cell::Cell<u32>,
    due: std::cell::Cell<bool>,
}

impl SubmitGate {
    /// Open a section no guarded race may drop. Closed when the returned
    /// value is dropped.
    pub fn write_section(&self) -> WriteSection<'_> {
        self.writing.set(self.writing.get() + 1);
        WriteSection(self)
    }

    /// Whether a guarded race's deadline fell due while a section was open:
    /// the race is waiting for the writer to stop.
    pub fn deadline_is_due(&self) -> bool {
        self.due.get()
    }

    /// The writer's question at a transaction boundary, with NO section open.
    /// If a deadline is due this never returns: it hands the future back to
    /// the race, which drops it on this very poll (only a guarded race sets
    /// the flag, and it clears it when it ends).
    pub async fn stop_if_due(&self) {
        if self.due.get() {
            std::future::pending::<()>().await;
        }
    }
}

/// An open write section of a [`SubmitGate`].
#[must_use = "the section closes when this is dropped"]
pub struct WriteSection<'g>(&'g SubmitGate);

impl Drop for WriteSection<'_> {
    fn drop(&mut self) {
        self.0.writing.set(self.0.writing.get().saturating_sub(1));
    }
}

/// [`race_or_deadline`] that never drops `fut` inside a [`WriteSection`] of
/// `gate`. A deadline that falls due while a section is open is remembered
/// (and shown to the writer, [`SubmitGate::deadline_is_due`]); `fut` is
/// polled on, by its own wakers, and dropped at its first pending point
/// outside a section. `None` then means what it meant: the deadline won.
pub async fn race_or_deadline_guarded<F, D, T>(fut: F, deadline: D, gate: &SubmitGate) -> Option<T>
where
    F: std::future::Future<Output = T>,
    D: std::future::Future<Output = ()>,
{
    // The flag never outlives the race that set it, however the race ends
    // (an outer drop included): a stale one would park the next writer.
    struct ClearDue<'g>(&'g SubmitGate);
    impl Drop for ClearDue<'_> {
        fn drop(&mut self) {
            self.0.due.set(false);
        }
    }
    let _clear = ClearDue(gate);
    let mut fut = std::pin::pin!(fut);
    let mut deadline = std::pin::pin!(deadline);
    let mut due = false;
    std::future::poll_fn(move |cx| {
        if let std::task::Poll::Ready(v) = fut.as_mut().poll(cx) {
            return std::task::Poll::Ready(Some(v));
        }
        if !due && deadline.as_mut().poll(cx).is_ready() {
            due = true;
        }
        if due {
            if gate.writing.get() == 0 {
                return std::task::Poll::Ready(None);
            }
            // `fut` is parked inside a write: its own waker brings us back.
            gate.due.set(true);
        }
        std::task::Poll::Pending
    })
    .await
}

/// Consecutive all-failure syncs after which a peer is QUARANTINED
/// (bsv-low#302). At the production `*/15` cron cadence 8 consecutive
/// failures ≈ 2 hours of unbroken unreachability — comfortably past any
/// transient blip (deploy, restart, brief network fault, one bad tick),
/// while still cutting a genuinely dead peer's budget burn off the same
/// day it dies.
pub const PEER_QUARANTINE_THRESHOLD: u64 = 8;

/// Re-probe interval for a quarantined peer, seconds (6 h ≈ every 24 cron
/// ticks). Quarantine is NEVER a deletion: once `secs_since_last_attempt`
/// reaches this age the peer gets exactly ONE fresh sync attempt — success
/// resets its failure count to 0 (full re-admission), failure re-arms the
/// quarantine for another window. A peer that died transiently therefore
/// re-admits itself automatically on the first re-probe after it recovers.
pub const PEER_QUARANTINE_REPROBE_SECS: u64 = 6 * 3600;

/// Consecutive YIELDLESS syncs of a (peer, topic) allowed before each further
/// one is a FAILED attempt for the quarantine (bsv-low #555, the delta fold's
/// D-M2). A sync is yieldless when the peer served it work it did not hold
/// ([`GASPSync::graphs_attempted`] > 0) and it finalized no graph and moved no
/// cursor; it then counts a success only because a walk PROGRESSED (a node
/// appended), and a node is the peer's word: a hostile peer that lists one
/// fresh fabricated UTXO a tick, serves its root and hangs on its input kept
/// its slice for ever. Past this many in a row such a sync is a failure, so
/// that peer is quarantined after this many plus
/// [`PEER_QUARANTINE_THRESHOLD`] syncs (20, 5 h at `*/15`) and gets one probe
/// per [`PEER_QUARANTINE_REPROBE_SECS`] after that. A sync that finalized a
/// graph or moved the cursor resets the count; a quiet one leaves it.
/// A quarantined peer is re-admitted only by such a yield (the delta-4
/// fold's D4-L2): its sync that did not fail and yielded nothing, an empty
/// listing at its probe included, is not recorded, so its failures stay and
/// it is attended on each tick until it yields or fails again.
///
/// The bound is in SYNCS AND in TIME (the delta-2 fold's D2-M1): a yieldless
/// sync is a failure only when the streak holds more than this many syncs
/// AND began at least [`PEER_YIELDLESS_SECS_ALLOWED`] ago
/// ([`yieldless_sync_failed`]). Counted in syncs alone, 12 was three hours at
/// `*/15` and twelve minutes at LOW's one tick a minute, under the tail of a
/// block interval: an honest peer whose only new work was #582's unproven
/// head was quarantined while it waited for its block.
///
/// Why 12 and 3 h: an honest deep graph converges well inside both. The
/// measured one (#582) is an UNPROVEN head over unproven ancestry: its root
/// is re-asked at each resume and the pass after its block lands restarts the
/// walk from a proven root and completes it (`root_proven`), one or two passes
/// after a block that comes in ~10 min on average (past 3 h about once in
/// 10^8 blocks by the exponential model, at any cadence). Walked to its end
/// instead, 12 passes are about 150 nodes on the Cloudflare worker (15 s a
/// pass at 1.2 s a request) and 600 on LOW's node (60 s). Applied only with a
/// per-graph budget (`Engine::set_graph_budget`): without one no walk is
/// deferred and the quarantine is the one of #302.
pub const PEER_YIELDLESS_SYNCS_ALLOWED: u64 = 12;

/// The AGE a yieldless streak must reach, seconds since its first yieldless
/// sync, before a yieldless sync is a failure (3 h; the delta-2 fold's
/// D2-M1, see [`PEER_YIELDLESS_SYNCS_ALLOWED`]). The storage keeps the
/// streak's start ([`crate::storage::PeerYieldStreak`]) on its own clock.
pub const PEER_YIELDLESS_SECS_ALLOWED: u64 = 3 * 3600;

/// The DECAY of a yieldless streak (the delta-2 fold's D2-M1): a yieldless
/// sync more than this long (6 h, [`PEER_QUARANTINE_REPROBE_SECS`]) after the
/// streak's LAST yieldless sync starts a new streak (count 1, its start now)
/// instead of adding to the old one. Quiet syncs in between leave the streak
/// as it is (a quiet sync is not a yield), so an honest peer whose rare
/// graphs that never land are hours apart is not counted across days. The
/// cost, stated: a peer yieldless for 3 h, quiet for 6 h, and so on, keeps
/// its slice during the yieldless hours (a third of its ticks at most), as
/// #302's own accepted residual of one success in every eight.
///
/// Only for a peer that is NOT failed (`consecutive_failures` 0; the delta-3
/// fold's D3-M1). This window equals the reprobe's, so the probe of a peer
/// quarantined by this bound always came more than 6 h after its last
/// yieldless sync: it started a fresh streak (count 1, not failed), the sync
/// "progressed", the failures went to 0 and the quarantine lifted at every
/// probe (half the ticks at `*/15`). The probe of a failed peer continues
/// its streak and fails, so it gets one probe per reprobe window.
pub const PEER_YIELDLESS_DECAY_SECS: u64 = PEER_QUARANTINE_REPROBE_SECS;

/// PURE rule of the yieldless bound (bsv-low #555, the delta-2 fold's
/// D2-M1): a yieldless sync is a FAILED attempt IFF its streak holds more
/// than [`PEER_YIELDLESS_SYNCS_ALLOWED`] syncs AND is at least
/// [`PEER_YIELDLESS_SECS_ALLOWED`] old. A streak of unknown age (a backend
/// with no clock) is never past (fail-safe, as #302's unknown attempt age).
pub fn yieldless_sync_failed(streak: &crate::storage::PeerYieldStreak) -> bool {
    streak.yieldless_syncs > PEER_YIELDLESS_SYNCS_ALLOWED
        && streak
            .secs_since_first
            .is_some_and(|secs| secs >= PEER_YIELDLESS_SECS_ALLOWED)
}

/// The NORMALIZED ORIGIN of a peer URL (bsv-low #555, the delta-2 fold's
/// D2-M2): its host, lowercased, with no scheme, user, port, path, query or
/// fragment, and no trailing dot. The key of a peer's quarantine and
/// yieldless streak (the engine passes it to the three peer-health methods
/// of [`crate::storage::Storage`]) and of its share of a storage's deferred
/// graph ceiling (the worker's `origin` column): keyed on the URL string, one
/// server was eight "hosts" for eight adverts (`?1`, `:8443`, a trailing
/// slash, `#x`), each with its own share and a fresh streak. A subdomain is
/// another host still (no public suffix list here): stated. The cursor and
/// the deferred records stay keyed by the URL the peer is synced at.
pub fn peer_origin(url: &str) -> String {
    peer_authority(url).1
}

/// `(scheme, host, port)` of a peer URL: the scheme lowercased (`https`
/// when absent), the host as [`peer_origin`] gives it, the port as written
/// (`None` when absent, empty, or the scheme's default: `443` for `https`,
/// `80` for `http`).
fn peer_authority(url: &str) -> (String, String, Option<String>) {
    let url = url.trim();
    let (scheme, rest) = url.split_once("://").unwrap_or(("https", url));
    let scheme = scheme.to_ascii_lowercase();
    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
    let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
    let (host, port) = match host_port.strip_prefix('[') {
        // `[::1]:8443`: the bracketed address, brackets kept.
        Some(v6) => match v6.split_once(']') {
            Some((addr, after)) => (format!("[{addr}]"), after.strip_prefix(':')),
            None => (host_port.to_string(), None),
        },
        None => match host_port.split_once(':') {
            Some((host, port)) => (host.to_string(), Some(port)),
            None => (host_port.to_string(), None),
        },
    };
    let default_port = match scheme.as_str() {
        "https" => "443",
        "http" => "80",
        _ => "",
    };
    let port = port.filter(|p| !p.is_empty() && *p != default_port);
    (
        scheme,
        host.trim_end_matches('.').to_ascii_lowercase(),
        port.map(str::to_string),
    )
}

/// The peers of a SHIP-discovered topic, ONE per [`peer_origin`] (bsv-low
/// #555, the delta-2 fold's D2-M2; restored by the delta-4 fold, D4-M1): each
/// advertised domain is canonicalized to `scheme://host[:port]` (the scheme
/// and host lowercased; path, query, fragment, user, a trailing dot and the
/// scheme's default port dropped), and of the spellings of one origin the
/// first by `https`, then no explicit port, then the string is kept. So
/// eight adverts of one server (`/?1`, `/?2`, `/#x`, `:8443`, ...) are one
/// peer synced once a tick, and a stranger's spelling of an honest host (a
/// query, a dead port) cannot stand beside that host's own advert under its
/// quarantine key. The delta-3 fold kept one peer per `scheme://host[:port]`
/// while the failures stayed on one row per origin (D4-M1): eight adverts of
/// dead ports of an honest host's name quarantined the honest peer, and
/// seven were never quarantined, a slice each on every tick. The LIMIT,
/// stated (the delta-3 lens's D3-L1): two overlays of one host on two ports,
/// on one SHIP topic, are one peer (the default port's), so a stranger's
/// default-port spelling displaces an honest overlay that serves only on
/// another port. Sorted, for a stable order.
pub fn ship_peers_by_origin<I: IntoIterator<Item = String>>(domains: I) -> Vec<String> {
    type Rank = (bool, bool, String);
    let mut by_origin: std::collections::BTreeMap<String, (Rank, String)> =
        std::collections::BTreeMap::new();
    for domain in domains {
        let (scheme, origin, port) = peer_authority(&domain);
        if origin.is_empty() {
            continue;
        }
        let canonical = match &port {
            Some(port) => format!("{scheme}://{origin}:{port}"),
            None => format!("{scheme}://{origin}"),
        };
        let candidate = (scheme != "https", port.is_some(), canonical.clone());
        match by_origin.get(&origin) {
            Some((kept, _)) if *kept <= candidate => {}
            _ => {
                by_origin.insert(origin, (candidate, canonical));
            }
        }
    }
    let mut peers: Vec<String> = by_origin.into_values().map(|(_, url)| url).collect();
    peers.sort();
    peers
}

/// PURE quarantine rule (bsv-low#302): a peer is skipped IFF it has hit
/// [`PEER_QUARANTINE_THRESHOLD`] consecutive failures AND its last attempt
/// is younger than [`PEER_QUARANTINE_REPROBE_SECS`]. A peer with no
/// recorded attempt (`secs_since_last_attempt == None` — pristine, or a
/// backend without peer-health tracking) is NEVER quarantined, and an old
/// enough last attempt always re-opens one probe — fail-safe in the
/// "attempt more, never strand a peer forever" direction.
///
/// ACCEPTED RESIDUAL (bsv-low#304 gate M-3, documented — not built): a
/// peer that ALTERNATES one success into every window of ≤7 failures
/// resets its streak each time and is never quarantined, burning up to one
/// per-peer budget slice (30 s) per (host, topic) per tick forever. Why
/// accepted: (a) the burn is bounded by the per-peer budget times the
/// configured peer set, all inside the 240 s outer step belt — the #257
/// unbounded-hang class cannot recur; (b) sustaining it requires the peer
/// to actually COMPLETE a real sync every few ticks, i.e. behave as a
/// (slow) live peer — indistinguishable in principle from a genuinely
/// flaky honest peer, which the rule must never strand; (c) LOW's money
/// topics do not GASP-sync at all (no `sync_configuration` peers in prod),
/// so the exposure is cron-budget noise, not a money surface. A
/// streak-decay or success-ratio rule could narrow it later if a real
/// abuser appears.
pub fn peer_sync_quarantined(health: &crate::storage::PeerSyncHealth) -> bool {
    health.consecutive_failures >= PEER_QUARANTINE_THRESHOLD
        && health
            .secs_since_last_attempt
            .is_some_and(|secs| secs < PEER_QUARANTINE_REPROBE_SECS)
}

// ============================================================================
// Deferred graphs (bsv-low #555)
// ============================================================================

/// Default per-GRAPH call budget (bsv-low #555): requests to the peer, or
/// chain fetches, that ONE graph's walk may make in one pass before it is
/// deferred. With [`DEFAULT_GRAPH_BUDGET_MS`]: at the 1.2 s per request
/// measured on beta (2026-10-09, #582) 100 calls take about 120 s, so on a
/// slow peer the time binds first (about 50 nodes a pass) and on a fast one
/// the calls do, which also bounds how much a record grows per pass.
pub const DEFAULT_GRAPH_BUDGET_CALLS: u32 = 100;

/// Default per-GRAPH time budget, ms (bsv-low #555): half of the 120 s
/// topic slice of LOW's node (one peer), so a deep graph takes at most half
/// of its topic's slice and the UTXOs after it keep the other half. A caller
/// keeps it BELOW its per-peer budget (`Engine::set_peer_sync_budget`); a
/// graph the per-peer deadline cuts first is deferred all the same.
pub const DEFAULT_GRAPH_BUDGET_MS: u64 = 60_000;

/// Default per-GRAPH bytes budget (bsv-low #586): the bytes of the nodes ONE
/// graph's walk may be SERVED in one pass before it is deferred, counted as
/// the peer serves them and as a record keeps them (the hex of each node's
/// raw transaction and of its proof, every answer counted, a repeat too).
/// A BUDGET PER PASS, not a limit: the walk makes at least one request a
/// pass whatever its size, and what the pass leaves is resumed.
///
/// 917,504 bytes: a budget per pass and nothing else (bsv-low #585). It was
/// derived from a 1 MiB cap on a record (seven eighths of it, the lens fold's
/// E586-L1) so that the pass it cut left a record that fitted; a record has
/// no cap since #585 (the storage keeps one of any size, the worker in
/// chunks), so the figure is kept for what it measures, 18 heads of 26 KB a
/// fresh pass, and no longer sits "under" anything. A consumer may set any
/// other ([`GraphBudget::max_bytes_fetched`]).
pub const DEFAULT_GRAPH_BUDGET_BYTES: u64 = 917_504;

/// Default per-GRAPH node budget (bsv-low #586): the nodes ONE graph's walk
/// may APPEND in one pass before it is deferred (five times the 12 of
/// Zanaadu's largest legitimate graph). As [`DEFAULT_GRAPH_BUDGET_BYTES`], a
/// budget per pass that resumes; it also bounds the JSON a pass adds to a
/// record around its nodes' hex, which the bytes limb does not count.
pub const DEFAULT_GRAPH_BUDGET_NODES: u32 = 64;

/// A deferred graph whose record has been deferred this many passes is
/// dropped at its next resume (reason `max_passes`) and its UTXO fails as a
/// failed ingest does: the gap guard asks for it again and the next pass
/// walks it from its root. One hour at a one-minute cadence, fifteen at
/// `*/15`.
pub const DEFERRED_GRAPH_MAX_PASSES: u32 = 60;

/// The most records one (peer, topic) may hold. A new deferral past it is
/// not saved (reason `too_many`) and its walk goes on under the per-peer
/// budget alone, as before #555 (the lens fold's L4): a peer that serves many
/// deep graphs costs at most 16 records. A storage may refuse a record at a
/// ceiling of its own ([`DeferredGraphSave::AtCeiling`]), counted `too_many`
/// too (the worker's global ceiling, the lens fold's M3). A record has NO
/// byte bound (bsv-low #585: it had 1 MiB, `too_big`): a graph of any size
/// is deferred and resumed whole, and the storage's ceiling is a BUDGET of
/// room, under which a RESUMED walk keeps the record it holds.
pub const DEFERRED_GRAPHS_PER_PEER_TOPIC: usize = 16;

/// A RESUMED walk that faults having appended no node keeps its record (an
/// honest peer's transient 5xx), but not for free (bsv-low #555, the
/// delta-2 fold's D2-M2): at this many such passes in a row the record is
/// dropped (reason `idle_faults`) and the UTXO fails, as a fresh walk's
/// fault does. Before the fold a stranger's record was rewritten for one
/// quick 503 a tick and held its place for its 60 passes (and the sync is
/// yieldless, so it counts against the yieldless bound too).
pub const DEFERRED_GRAPH_MAX_IDLE_FAULTS: u32 = 3;

/// The per-graph budget of a [`GASPSync`] (bsv-low #555,
/// `Engine::set_graph_budget`). Setting one turns deferral ON for that sync.
pub struct GraphBudget<'a> {
    /// Calls one graph may make in one pass ([`DEFAULT_GRAPH_BUDGET_CALLS`]).
    pub max_calls: u32,
    /// Bytes one graph may be served in one pass
    /// ([`DEFAULT_GRAPH_BUDGET_BYTES`], bsv-low #586). Reached, the graph is
    /// DEFERRED as at `max_calls` (reason `bytes`): never dropped, never
    /// refused.
    pub max_bytes_fetched: u64,
    /// Nodes one graph may append in one pass
    /// ([`DEFAULT_GRAPH_BUDGET_NODES`], bsv-low #586). Reached, the graph is
    /// deferred (reason `nodes`).
    pub max_nodes: u32,
    /// A fresh deadline for ONE graph's pass ([`DEFAULT_GRAPH_BUDGET_MS`]).
    pub deadline: Box<dyn Fn() -> crate::engine::SleepFuture + 'a>,
    /// A fresh deadline for HALF of it (the delta-2 fold's D2-L1): a FRESH
    /// walk that faults once this fell due, or after half its calls, has
    /// paid for a record and keeps one. `None`: the calls alone decide.
    pub half_deadline: Option<Box<dyn Fn() -> crate::engine::SleepFuture + 'a>>,
}

impl GraphBudget<'_> {
    /// What one pass of one graph may spend.
    fn pass(&self) -> PassCap {
        PassCap {
            calls: self.max_calls,
            bytes: self.max_bytes_fetched,
            nodes: self.max_nodes,
        }
    }
}

/// What one pass of a graph's walk may still spend of the per-graph budget's
/// three counted limbs (its time is a deadline): calls made, bytes served,
/// nodes appended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PassCap {
    calls: u32,
    bytes: u64,
    nodes: u32,
}

impl PassCap {
    /// No bound: a sync with no per-graph budget, or a walk that goes on
    /// under the per-peer budget alone (L4).
    const NONE: PassCap = PassCap {
        calls: u32::MAX,
        bytes: u64::MAX,
        nodes: u32::MAX,
    };

    /// Whether a limb is spent to nothing.
    fn spent(self) -> bool {
        self.calls == 0 || self.bytes == 0 || self.nodes == 0
    }
}

/// The key of one held record (bsv-low #555): what a sync loads up front.
/// The record itself is read only when the peer serves its UTXO
/// ([`GASPStorage::get_deferred_graph`]), so at most one record is in memory
/// at a time (the lens fold's L3: the up-front load held up to 16 of them).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeferredGraphKey {
    /// The root UTXO, `txid.outputIndex`.
    pub outpoint: String,
    /// The root UTXO's score at the peer.
    pub score: u64,
}

/// What a storage did with a record it was asked to save (bsv-low #555).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeferredGraphSave {
    /// Saved (replaced).
    Saved,
    /// Refused at a ceiling of the storage's own (the worker's global count
    /// and byte bounds, the lens fold's M3): counted `too_many`, and the walk
    /// goes on under the per-peer budget alone, as before #555. A BUDGET
    /// signal, never the loss of a walk (bsv-low #585): the storage must
    /// leave the record it HELD under that key as it was, and the engine
    /// keeps it, so a resumed graph refused room resumes from that record at
    /// the next pass and never walks from its root again.
    AtCeiling,
}

/// One node a deferred walk has fetched and appended, in append order.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WalkedNode {
    /// The node as it was appended (the root's proof hydrated, if it was).
    pub node: GASPNode,
    /// `txid.outputIndex` of the node that spends it; `None` for the root.
    pub spent_by: Option<String>,
}

/// One input a deferred walk has still to ask for.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PendingInput {
    /// `txid.outputIndex` of the input (for the root, the UTXO itself).
    pub outpoint: String,
    /// The graph id the request carries (the root's outpoint).
    pub graph_id: String,
    /// Whether the input's metadata is asked for.
    pub metadata: bool,
    /// `txid.outputIndex` of the node that needs it; `None` for the root.
    pub spent_by: Option<String>,
    /// Whether that node is PROVEN: a named input the peer does not hold is
    /// then pruned (the D8 rule), else it fails the graph.
    pub parent_proven: bool,
}

/// The persisted partial walk of ONE graph (bsv-low #555): one record per
/// (peer, topic, root outpoint), REPLACED on every deferral, never appended.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeferredGraph {
    /// The peer the graph is walked from.
    pub peer: String,
    /// The topic.
    pub topic: String,
    /// The root UTXO, `txid.outputIndex`.
    pub outpoint: String,
    /// The root UTXO's score at the peer.
    pub score: u64,
    /// The nodes fetched so far, with their proofs, in append order.
    pub nodes: Vec<WalkedNode>,
    /// The inputs still to ask for, a stack (the last is asked next).
    pub pending: Vec<PendingInput>,
    /// Calls spent on this graph over every pass.
    pub calls: u64,
    /// Passes that deferred it (its age, in passes).
    pub passes: u32,
    /// Why it was last deferred: `calls`, `time`, `bytes`, `nodes`, `fault`,
    /// `anchor_unavailable`, `anchor_walk_held` (the E592 lens fold: the
    /// anchor's walk past the budget, held until the root is served proven),
    /// `not_landed` or `peer_deadline`.
    pub reason: String,
    /// Whether the peer is a CONFIGURED one (`SyncTarget::Peers`), not one
    /// `ls_ship` discovered (bsv-low #555, the delta-2 fold's D2-M2): a
    /// storage reserves part of its ceiling for these (the worker: records
    /// of discovered peers hold at most half of it). Set by the storage
    /// adapter on every save; `false` in a record saved before the fold.
    #[serde(default)]
    pub configured: bool,
    /// Consecutive RESUMED passes that faulted having appended no node
    /// (the delta-2 fold's D2-M2): the record is dropped (`idle_faults`)
    /// when it reaches [`DEFERRED_GRAPH_MAX_IDLE_FAULTS`]; a pass that
    /// appends a node resets it.
    #[serde(default)]
    pub idle_faults: u32,
}

impl DeferredGraph {
    /// The record's size as stored (its JSON): what the deferral's log line
    /// and a storage's byte budget read. Nothing refuses a record for it
    /// (bsv-low #585).
    pub fn byte_size(&self) -> usize {
        serde_json::to_vec(self).map_or(usize::MAX, |b| b.len())
    }
}

/// Why a deferred graph's record was deleted without converging.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DropReason {
    /// Deferred [`DEFERRED_GRAPH_MAX_PASSES`] times; the UTXO fails.
    MaxPasses,
    /// Past [`DEFERRED_GRAPHS_PER_PEER_TOPIC`] or the storage's ceiling: a
    /// walk the budget cut goes on under the per-peer budget alone (L4),
    /// else the UTXO fails. A RESUMED walk's held record is KEPT (bsv-low
    /// #585): the count is of the pass that found no room, not of a record.
    TooMany,
    /// The record could not be written; as [`Self::TooMany`] (D-L2).
    StoreFault,
    /// A sync that ran to its end was not served the UTXO (spent at the peer).
    NotServed,
    /// The node already holds the UTXO (it landed another way).
    Held,
    /// The peer answered it does not hold an input an UNPROVEN node needs;
    /// the UTXO fails, as in the reference.
    NotHeld,
    /// The root came back PROVEN: the walk restarts from it, shorter.
    RootProven,
    /// The anchor check refused the graph (a final verdict, the cursor moves).
    Refused,
    /// A resumed record whose pass ended still holding no node (a record
    /// saved before the lens fold's H1, which saves none such); the UTXO
    /// fails.
    NoProgress,
    /// [`DEFERRED_GRAPH_MAX_IDLE_FAULTS`] resumed passes in a row faulted
    /// having appended no node (the delta-2 fold's D2-M2); the UTXO fails.
    IdleFaults,
}

impl DropReason {
    /// Every reason, for a caller that serves a counter per reason.
    pub const ALL: [DropReason; 10] = [
        Self::MaxPasses,
        Self::TooMany,
        Self::StoreFault,
        Self::NotServed,
        Self::Held,
        Self::NotHeld,
        Self::RootProven,
        Self::Refused,
        Self::NoProgress,
        Self::IdleFaults,
    ];

    /// The reason's name, as logged and counted.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::MaxPasses => "max_passes",
            Self::TooMany => "too_many",
            Self::StoreFault => "store_fault",
            Self::NotServed => "not_served",
            Self::Held => "held",
            Self::NotHeld => "not_held",
            Self::RootProven => "root_proven",
            Self::Refused => "refused",
            Self::NoProgress => "no_progress",
            Self::IdleFaults => "idle_faults",
        }
    }
}

/// One record dropped in a sync.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DroppedGraph {
    /// The root outpoint.
    pub outpoint: String,
    /// Why.
    pub reason: DropReason,
}

/// What a sync did with deferred graphs (bsv-low #555).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DeferralStats {
    /// Graphs deferred (a new record, or a resumed one deferred again).
    pub deferred: u64,
    /// Graphs resumed from a record.
    pub resumed: u64,
    /// Resumed graphs that completed and landed (their record deleted).
    pub converged: u64,
    /// Records deleted without converging.
    pub dropped: Vec<DroppedGraph>,
    /// Walks of the sync that ended unfinished (deferred, or dropped at a
    /// bound) having appended at least one node in their pass, or that
    /// completed the graph (the lens fold's H1): the peer answered.
    pub progressed: u64,
    /// Walks of the sync that ended unfinished having appended NO node in
    /// their pass (a hung or failing peer; the lens fold's H1). A sync whose
    /// only outcome was these is a FAILED attempt for #302's quarantine.
    pub stalled: u64,
    /// Records NOT resumed this sync because the resumes of the pass had
    /// spent their shared budget (the lens fold's M1); held, untouched, for
    /// the next sync.
    pub held_back: u64,
}

impl Walk {
    /// The counted limb this pass has spent, if any: its name is the
    /// deferral's reason.
    fn over(&self) -> Option<&'static str> {
        if self.calls_this_pass >= self.cap.calls {
            Some("calls")
        } else if self.bytes_this_pass >= self.cap.bytes {
            Some("bytes")
        } else if self.nodes_this_pass >= self.cap.nodes {
            Some("nodes")
        } else {
            None
        }
    }
}

/// The walk of the graph in hand: its record (what a deferral saves) and
/// the per-pass state. Lives in the [`GASPSync`], OUTSIDE the walk's
/// future, so a deadline that drops the future leaves it whole.
struct Walk {
    record: DeferredGraph,
    seen: std::collections::HashSet<String>,
    calls_this_pass: u32,
    /// Bytes served to this pass (bsv-low #586; see
    /// [`DEFAULT_GRAPH_BUDGET_BYTES`] for what is counted).
    bytes_this_pass: u64,
    /// Nodes this pass appended (bsv-low #586).
    nodes_this_pass: u32,
    resumed: bool,
    /// What this pass may spend: the per-graph budget, or what the resumes
    /// of the pass have left of their shared one (M1); [`PassCap::NONE`]
    /// once a walk that cannot be kept goes on under the per-peer budget
    /// alone (L4).
    cap: PassCap,
    /// `record.nodes.len()` when the pass started (H1).
    nodes_at_start: usize,
    /// Whether this pass was already counted progressed or stalled.
    counted: bool,
    /// The walk could not be kept and GOES ON under the per-peer budget
    /// alone (L4): its drop is counted once, when it went on, and it is
    /// never saved again in this pass (the delta fold's D-L1: a per-peer
    /// deadline that then cut it counted the drop twice and asked the
    /// storage a second time).
    gone_on: bool,
    /// A FRESH walk's half-budget deadline, started with the walk (the
    /// delta-2 fold's D2-L1); `None` for a resumed walk or with no
    /// [`GraphBudget::half_deadline`].
    half: Option<crate::engine::SleepFuture>,
}

/// How a graph's walk ended in this pass.
enum WalkEnd {
    /// Nothing is pending: complete the graph.
    Done,
    /// Deferred, with this reason.
    Deferred(&'static str),
}

/// What one step of the walk got.
enum StepOut {
    Pruned,
    Seen,
    Appended {
        node_id: String,
        walked: Box<WalkedNode>,
        children: Vec<PendingInput>,
    },
}

/// How [`GASPSync::ingest_utxo`] ended for a UTXO.
enum Ingested {
    Completed,
    Deferred,
    /// A record not resumed: the pass's resumes spent their shared budget.
    HeldBack,
}

/// What [`GASPSync::save_walk`] did with the walk in hand.
enum Saved {
    Yes,
    /// Not kept, for this reason; the walk is handed back so the caller can
    /// go on with it (L4) or drop it.
    Unkept(DropReason, Box<Walk>),
    /// The storage faulted (counted `store_fault`, a held record deleted);
    /// the walk is handed back so the caller can go on with it (D-L2).
    Fault(GASPError, Box<Walk>),
    /// A RESUMED walk the storage had no room for (`AtCeiling`; counted
    /// `too_many`): the record it holds is KEPT as it was (bsv-low #585), and
    /// the walk is handed back so the caller can go on with it.
    Ceiling(Box<Walk>),
    /// The walk had already gone on (D-L1): nothing saved, nothing counted.
    WentOn,
}

// ============================================================================
// GASPStorage trait
// ============================================================================

/// Local storage interface for the GASP protocol.
///
/// Manages known UTXOs, temporary graph construction during sync,
/// and graph validation/finalization.
#[async_trait(?Send)]
pub trait GASPStorage {
    /// Returns UTXOs known to be unspent since the given score/timestamp.
    /// Non-confirmed UTXOs should always be returned regardless of `since`.
    async fn find_known_utxos(
        &self,
        since: u64,
        limit: Option<u64>,
    ) -> Result<Vec<GASPOutput>, GASPError>;

    /// Hydrate a GASP node with transaction data, proof, and optional metadata.
    async fn hydrate_gasp_node(
        &self,
        graph_id: &str,
        txid: &str,
        output_index: u32,
        metadata: bool,
    ) -> Result<GASPNode, GASPError>;

    /// Determine which input transactions are needed to validate this node.
    /// Returns None if no additional inputs are needed.
    async fn find_needed_inputs(
        &self,
        node: &GASPNode,
    ) -> Result<Option<GASPNodeResponse>, GASPError>;

    /// Append a node to a temporary graph being constructed during sync.
    /// `spent_by` is the "txid.outputIndex" of the node that spent this one (if not the root).
    async fn append_to_graph(
        &self,
        node: &GASPNode,
        spent_by: Option<&str>,
    ) -> Result<(), GASPError>;

    /// Validate that the graph's anchor (root) references only proven or known transactions.
    async fn validate_graph_anchor(&self, graph_id: &str) -> Result<(), GASPError>;

    /// Finalize a graph — commit the synced UTXO and its ancestors to permanent storage.
    async fn finalize_graph(&self, graph_id: &str) -> Result<(), GASPError>;

    /// Discard a temporary graph that failed validation.
    async fn discard_graph(&self, graph_id: &str) -> Result<(), GASPError>;

    /// The keys of the deferred graphs of this (peer, topic), lowest score
    /// first (bsv-low #555). REQUIRED, as the three below (the lens fold's
    /// M2): a storage that keeps no records says so here, by answering none
    /// and refusing every save, and its graphs past the budget then fail.
    async fn load_deferred_graphs(&self) -> Result<Vec<DeferredGraphKey>, GASPError>;

    /// The record of the graph rooted at `outpoint`, if one is held.
    async fn get_deferred_graph(&self, outpoint: &str) -> Result<Option<DeferredGraph>, GASPError>;

    /// Save (replace) the record of one deferred graph.
    async fn save_deferred_graph(
        &self,
        record: &DeferredGraph,
    ) -> Result<DeferredGraphSave, GASPError>;

    /// Delete the record of the graph rooted at `outpoint`.
    async fn delete_deferred_graph(&self, outpoint: &str) -> Result<(), GASPError>;
}

// ============================================================================
// GASPRemote trait
// ============================================================================

/// Communication interface with a foreign GASP peer.
#[async_trait(?Send)]
pub trait GASPRemote {
    /// Send an initial request and get the peer's initial response.
    async fn get_initial_response(
        &self,
        request: &GASPInitialRequest,
    ) -> Result<GASPInitialResponse, GASPError>;

    /// Send our initial response and get the peer's reply.
    async fn get_initial_reply(
        &self,
        response: &GASPInitialResponse,
    ) -> Result<GASPInitialReply, GASPError>;

    /// Request a specific node from the peer.
    async fn request_node(
        &self,
        graph_id: &str,
        txid: &str,
        output_index: u32,
        metadata: bool,
    ) -> Result<GASPNode, GASPError>;

    /// Submit a node to the peer and get back which inputs they need.
    async fn submit_node(&self, node: &GASPNode) -> Result<Option<GASPNodeResponse>, GASPError>;
}

// ============================================================================
// GASPRemoteFactory trait
// ============================================================================

/// Factory for creating `GASPRemote` instances for specific peers.
///
/// The Engine holds an optional factory. Platform-specific crates (like
/// overlay-cloudflare) provide an implementation that creates HTTP-based
/// remotes.
pub trait GASPRemoteFactory {
    /// Create a `GASPRemote` for the given peer URL and topic.
    fn create_remote(&self, peer_url: &str, topic: &str) -> Box<dyn GASPRemote>;
}

// ============================================================================
// AncestorFetcher trait (OPT-IN, OFF by default)
// ============================================================================

/// Optional chain-backed ancestor fetcher for GASP ingest self-healing.
///
/// **OPT-IN / OFF BY DEFAULT.** When a peer (e.g. legacy TS beta) cannot serve
/// a needed ancestor node during graph ingest (it returns HTTP 400 "Incomplete
/// SPV data!" because its stored BEEF is minimal), the orchestrator normally
/// abandons that graph. If — and ONLY if — an `AncestorFetcher` is configured,
/// `process_incoming_node` falls back to fetching the ancestor's raw tx from
/// chain (e.g. WhatsOnChain) and synthesizing a no-proof `GASPNode` that the
/// existing recursion stitches into the graph.
///
/// This is a deliberate one-time-migration escape hatch. Production must NOT
/// configure a fetcher: when the fetcher is `None` the ingest path is
/// byte-identical to today (peer errors propagate / are swallowed upstream).
///
/// The orchestrator stays platform-agnostic; the concrete WoC/`worker::Fetch`
/// implementation lives in the platform crate (e.g. zanaadu `overlay`), never
/// in this engine crate (no `reqwest`/`std::time` — must stay wasm-clean).
#[async_trait(?Send)]
pub trait AncestorFetcher {
    /// Fetch an ancestor transaction by txid from chain.
    ///
    /// Returns the raw tx hex plus, when the ancestor is mined, its BUMP merkle
    /// proof hex. A proven node ends the walk unless its topic manager names
    /// inputs needed for overlay history. Managers naming nothing still stop
    /// at the first proven layer. Managers needing history select those inputs
    /// instead of walking every funding/fee input back toward coinbase.
    ///
    /// The transaction DAG (no cycles), `seen` keyed by `txid.outputIndex`,
    /// the already-known strip, and the manager naming nothing at genesis
    /// bound the walk. There is no node cap, matching the reference's undefined
    /// `maxNodesInGraph` in `Engine.startGASPSync`. A per-peer budget drops the
    /// sync future at its deadline: the graphs finalized before it stay
    /// admitted (bsv-low #552, [`FinalizedGraphHook`]), the graph in flight
    /// is lost whole and walked again by the next sync, unless a per-graph
    /// budget is set (bsv-low #555, `Engine::set_graph_budget`): then a walk
    /// past either budget is deferred with its fetched nodes kept and resumed
    /// by the next sync, so ONE graph deeper than a pass converges over
    /// passes. Without it such a graph still never completes.
    ///
    /// The implementation MUST verify that the returned bytes hash to the
    /// requested `txid` before returning them (integrity check) so a
    /// malicious/garbled response cannot inject a forged ancestor.
    async fn fetch_ancestor(&self, txid: &str) -> Result<FetchedAncestor, GASPError>;

    /// Fetch (and chaintracks-verify) ONLY the merkle BUMP for `txid`, WITHOUT
    /// fetching the raw tx.
    ///
    /// The proof-completion passes (`complete_missing_proofs`, the LOW pot-store
    /// tick) already hold the raw in the stored BEEF, so the raw fetch that
    /// [`Self::fetch_ancestor`] performs is a redundant network round-trip there
    /// — and a free-tier WhatsOnChain raw fetch 429s (#192/#193). This method is
    /// the raw-free path.
    ///
    /// Default: delegate to `fetch_ancestor` and drop the raw, so a fetcher that
    /// only implements `fetch_ancestor` keeps working unchanged. The production
    /// `ChainProofFetcher` overrides it to skip the raw fetch entirely. Returns
    /// `None` for an unmined/unverifiable tx (fail-closed), never an error.
    async fn verified_proof_for(&self, txid: &str) -> Option<String> {
        self.fetch_ancestor(txid).await.ok().and_then(|a| a.proof)
    }

    /// Like [`Self::verified_proof_for`], but a TRANSPORT/READ FAULT stays
    /// distinguishable (bsv-low#304 gate M-5): `Err` = the proof source or
    /// header source READ failed (e.g. a chaintracks call starved at the
    /// invocation's subrequest wall) — retryable, NOT a chain verdict;
    /// `Ok(None)` = honestly no verified proof yet. Money-relevant callers
    /// (the spend-confirmation chaser) surface + count the fault so a
    /// starved tick is visible instead of masquerading as "not mined yet".
    /// Default: wrap `verified_proof_for` (which never faults) — existing
    /// fetchers keep their semantics unchanged.
    async fn verified_proof_for_detailed(&self, txid: &str) -> Result<Option<String>, String> {
        Ok(self.verified_proof_for(txid).await)
    }

    /// bsv-low #451 slice B (2026-09-17): like [`Self::verified_proof_for_detailed`], but the ladder asks EVERY
    /// rung — no per-pass short-circuit on the broadcaster's "held unmined" word. The completion passes may stop
    /// early (a fresh unmined word from Arcade means no courier holds a proof yet; the next tick asks again), but
    /// a caller that ACTS on `Ok(None)` this pass — the reorg re-anchor, which demotes a refuted row it could not
    /// re-prove; the unmined-ancestry walk, which treats an unproven ancestor as a branch to keep walking — must
    /// hear the couriers too (the delta-verify's LOW-A). Default: the detailed ask (a fetcher with no short-circuit
    /// has nothing to skip).
    async fn verified_proof_for_exhaustive(&self, txid: &str) -> Result<Option<String>, String> {
        self.verified_proof_for_detailed(txid).await
    }

    /// bsv-low M19B-G1 round 2 (review MED-2): the ladder's REMAINING
    /// per-invocation budget, when it keeps one (`None` = unbounded, or not
    /// known). A budgeted ladder answers `Ok(None)` to every ask once its
    /// budget is spent, which a caller must not read as "no courier serves a
    /// proof": it checks this first and leaves the row for a fresh budget.
    fn budget_remaining(&self) -> Option<u32> {
        None
    }

    /// Verify that `bump_hex` is a chaintracks-valid merkle proof for `txid`.
    ///
    /// Used by proof completion to re-check a STORED structural bump before
    /// trusting its `has_proof` flag: a structural bump admitted WITHOUT SPV (or
    /// forged) must never be latched-proven and trimmed on (#192/#193). Default:
    /// fail-closed `false` — a fetcher with no header source can prove nothing.
    /// The production `ChainProofFetcher` overrides it against chaintracks.
    async fn verify_proof(&self, txid: &str, bump_hex: &str) -> bool {
        let _ = (txid, bump_hex);
        false
    }

    /// Which txid spends `txid:vout`, per an EXTERNAL INDEXER — a HINT, never
    /// a verdict (bsv-low 2026-08-18, the displaced-spender reconcile). The
    /// caller must independently prove the hint before acting on it:
    /// [`Self::spender_binding_raw`] (the bytes really spend the outpoint)
    /// and [`Self::verified_proof_for_detailed`] (the spender is MINED, root
    /// verified against our PoW-anchored headers). An indexer can therefore
    /// only ever point at the REAL confirmed spender — pointing anywhere else
    /// fails one of the two proofs and changes nothing.
    ///
    /// Default `Ok(None)` — unknown — so every existing implementation keeps
    /// compiling AND keeps today's behavior (no resolution, fail-closed).
    async fn resolve_spender(&self, _txid: &str, _vout: u32) -> Result<Option<String>, String> {
        Ok(None)
    }

    /// bsv-low (2026-09-04) — the SCRIPTHASH-HISTORY rung: the txids a
    /// courier's script-history index lists for `scripthash_le_hex` OTHER
    /// than `funding_txid` (newest first, a few at most). A pot's covenant
    /// script is unique to that pot, so its history is exactly
    /// `[funding, spender]` and the answer is the spender CANDIDATE; the
    /// caller BINDS it with [`spender_binding_raw`] before believing it. This
    /// rung survives a provider retiring its per-output spend endpoint
    /// (Bitails, pruned mode, 2026-09). `Err` = every rung faulted; an empty
    /// `Ok` = the indexes answered and list no other tx. Default: no index.
    ///
    /// [`spender_binding_raw`]: AncestorFetcher::spender_binding_raw
    async fn resolve_spender_by_script(
        &self,
        _scripthash_le_hex: &str,
        _funding_txid: &str,
    ) -> Result<Vec<String>, String> {
        Ok(Vec::new())
    }

    /// bsv-low (2026-09-04): an output's LOCKING SCRIPT by outpoint from a
    /// courier's output index (BananaBlocks `/txo/{txid}/{vout}`) — the
    /// scripthash rung's script source when no BEEF is stored for the row.
    /// `Ok(None)` = the index never saw it. Default: no such index.
    async fn output_script_hint(&self, _txid: &str, _vout: u32) -> Result<Option<Vec<u8>>, String> {
        Ok(None)
    }

    /// `spender`'s raw tx hex — fetched CONTENT-ADDRESSED (the bytes must
    /// hash to `spender`) — returned iff those bytes carry an input spending
    /// exactly `txid:vout`. This is the binding that turns
    /// [`Self::resolve_spender`]'s hint into a fact, and the caller gets the
    /// PROVEN bytes back so it can derive further facts from them (bytes
    /// finality, a durable BEEF) without a second fetch. `Ok(None)` = the
    /// bytes were read and do NOT bind (a lying or garbled hint — refuse);
    /// `Err` = could not read (a fault, never a verdict). Default `Ok(None)`:
    /// fail-closed, an unbindable hint is a dead hint.
    async fn spender_binding_raw(
        &self,
        _spender: &str,
        _txid: &str,
        _vout: u32,
    ) -> Result<Option<String>, String> {
        Ok(None)
    }
}

/// An ancestor transaction fetched from chain: its raw tx hex plus an optional
/// BUMP merkle proof hex (present when the tx is mined).
#[derive(Debug, Clone)]
pub struct FetchedAncestor {
    /// Raw transaction hex.
    pub raw_tx: String,
    /// BUMP merkle proof hex, if the ancestor is mined. When `Some`, the
    /// synthesized node ends the walk unless its topic manager names inputs.
    pub proof: Option<String>,
}

// ============================================================================
// FinalizedGraphHook (bsv-low #552)
// ============================================================================

/// Called by [`GASPSync::sync`] after EVERY incoming UTXO whose graph was
/// completed (finalized, or refused by the anchor check and discarded), before
/// the next UTXO is asked for.
///
/// The reference submits inside `finalizeGraph`, so a graph is admitted the
/// moment it is finalized. Here `OverlayGASPStorage::finalize_graph` only
/// pushes to a sink (it holds a `Storage`, not the engine), and the engine
/// used to drain that sink after the WHOLE sync: a sync dropped at its
/// per-peer budget admitted nothing. With a hook the engine drains the sink
/// per graph, inside the raced future, so what was finalized before the
/// deadline stays admitted and the next sync's known-UTXO skip and known-input
/// strip resume from it.
///
/// An `Err` FAILS THAT UTXO, exactly as a failed ingest does: the gap guard
/// keeps the cursor below it and the next sync asks for it again. The engine
/// answers `Err` when a finalize submit did not land (the lens fold's
/// MEDIUM-1). It cannot fail the sync. While the hook runs,
/// [`GASPSync::completed_cursor`] still sits BELOW the UTXO just completed,
/// so a sync dropped inside the hook asks for that UTXO again.
#[async_trait(?Send)]
pub trait FinalizedGraphHook {
    /// One incoming UTXO's graph was completed; drain what it finalized.
    async fn graph_completed(&self) -> Result<(), GASPError>;
}

// ============================================================================
// GASP orchestrator
// ============================================================================

/// GASP sync orchestrator.
///
/// Coordinates between local `GASPStorage` and a `GASPRemote` peer to
/// synchronize overlay UTXOs. Supports paginated sync and unidirectional mode.
///
/// The lifetime `'a` allows the storage and remote to borrow from their
/// environment (e.g., `OverlayGASPStorage` borrows from the Engine's storage).
pub struct GASPSync<'a> {
    storage: Box<dyn GASPStorage + 'a>,
    remote: Box<dyn GASPRemote + 'a>,
    /// Score of last successful interaction with this peer.
    pub last_interaction: u64,
    /// If true, only pull from remote — don't push local UTXOs.
    pub unidirectional: bool,
    log_prefix: String,
    /// OPT-IN / OFF BY DEFAULT chain-backed ancestor fetcher. When `None`
    /// (the default), a peer's `request_node` error propagates and the graph
    /// is abandoned upstream, except for an input NAMED by a proven node's
    /// topic manager that the peer answers it does not hold
    /// (`GASPError::NodeNotFound`), whose branch is pruned (the D8 decoy
    /// rule). When `Some`, ancestors come from chain instead of the peer and
    /// nothing is pruned: every fetcher error abandons the graph.
    ancestor_fetcher: Option<std::rc::Rc<dyn AncestorFetcher + 'a>>,
    /// Manager-named inputs whose branch was PRUNED because the peer answered
    /// that it does not hold them (zanaadu-v2 #314, D8), keyed
    /// `txid.outputIndex`. One entry is one failed round trip: an outpoint in
    /// this set is never asked for again in this sync, whichever parent or
    /// graph names it. Cleared at the start of each `sync`.
    pruned: std::cell::RefCell<std::collections::HashSet<String>>,
    /// Distinct outpoints pruned in the last `sync` (the size of `pruned`).
    pruned_inputs: std::cell::Cell<u64>,
    /// Graphs REFUSED by `validate_graph_anchor` and discarded in the last
    /// `sync` (bsv-low #551). Cleared at the start of each `sync`.
    discarded_graphs: std::cell::Cell<u64>,
    /// Graphs whose anchor walk could not run within the budget and were
    /// HELD (the E592 lens fold): [`GASPSync::anchor_walk_held`].
    anchor_walk_held: std::cell::Cell<u64>,
    /// Called after every completed incoming UTXO (bsv-low #552). `None`
    /// (the default): nothing is called and `sync` runs as it always did.
    finalized_hook: Option<Box<dyn FinalizedGraphHook + 'a>>,
    /// See [`Self::completed_cursor`].
    completed_cursor: u64,
    /// See [`Self::graph_in_flight`].
    graph_in_flight: bool,
    /// The per-graph budget (bsv-low #555). `None` (the default): no graph
    /// is deferred and the walk is the one before #555.
    graph_budget: Option<GraphBudget<'a>>,
    /// The roots of this (peer, topic)'s records not yet resumed in this
    /// sync (their keys; a record is read when its UTXO is served).
    deferred: std::cell::RefCell<std::collections::HashSet<String>>,
    /// ONE deadline for every resume of the sync (the lens fold's M1), made
    /// at the first resume.
    resume_deadline: std::cell::RefCell<Option<crate::engine::SleepFuture>>,
    /// What every resume of the sync may still spend together (M1).
    resume_left: std::cell::Cell<PassCap>,
    /// Calls made by the sync's walks so far.
    calls_made: std::cell::Cell<u64>,
    /// Bytes served to the sync's walks so far (bsv-low #586).
    bytes_fetched: std::cell::Cell<u64>,
    /// Nodes appended by the sync's walks so far (bsv-low #586).
    nodes_appended: std::cell::Cell<u64>,
    /// How many records this (peer, topic) holds in storage.
    held_records: std::cell::Cell<usize>,
    /// The walk of the graph in hand (see [`Walk`]).
    walk: std::cell::RefCell<Option<Walk>>,
    /// See [`Self::deferral_stats`].
    stats: std::cell::RefCell<DeferralStats>,
    /// See [`Self::graphs_attempted`].
    graphs_attempted: std::cell::Cell<u64>,
}

impl<'a> GASPSync<'a> {
    /// Create a new GASP sync orchestrator.
    ///
    /// The ancestor fetcher is OFF by default. Use `with_ancestor_fetcher` to
    /// opt in to chain-backed ancestry hydration (one-time-migration only).
    pub fn new(
        storage: Box<dyn GASPStorage + 'a>,
        remote: Box<dyn GASPRemote + 'a>,
        last_interaction: u64,
        log_prefix: impl Into<String>,
        unidirectional: bool,
    ) -> Self {
        Self {
            storage,
            remote,
            last_interaction,
            unidirectional,
            log_prefix: log_prefix.into(),
            ancestor_fetcher: None,
            pruned: std::cell::RefCell::new(std::collections::HashSet::new()),
            pruned_inputs: std::cell::Cell::new(0),
            discarded_graphs: std::cell::Cell::new(0),
            anchor_walk_held: std::cell::Cell::new(0),
            finalized_hook: None,
            completed_cursor: last_interaction,
            graph_in_flight: false,
            graph_budget: None,
            deferred: std::cell::RefCell::new(std::collections::HashSet::new()),
            resume_deadline: std::cell::RefCell::new(None),
            resume_left: std::cell::Cell::new(PassCap::NONE),
            calls_made: std::cell::Cell::new(0),
            bytes_fetched: std::cell::Cell::new(0),
            nodes_appended: std::cell::Cell::new(0),
            held_records: std::cell::Cell::new(0),
            walk: std::cell::RefCell::new(None),
            stats: std::cell::RefCell::new(DeferralStats::default()),
            graphs_attempted: std::cell::Cell::new(0),
        }
    }

    /// Bound each graph's walk by `budget` and DEFER a graph past it
    /// (bsv-low #555): its partial walk is saved through
    /// [`GASPStorage::save_deferred_graph`], its UTXO is held below the
    /// cursor like a failed one, the sync goes on to the next UTXO, and the
    /// next sync that is served the UTXO RESUMES the walk from the record,
    /// asking only what is still pending. Without a budget nothing is
    /// deferred and `sync` is unchanged.
    #[must_use]
    pub fn with_graph_budget(mut self, budget: GraphBudget<'a>) -> Self {
        self.graph_budget = Some(budget);
        self
    }

    /// What the last `sync` did with deferred graphs (bsv-low #555).
    pub fn deferral_stats(&self) -> DeferralStats {
        self.stats.borrow().clone()
    }

    /// How many UTXOs the sync set out to ingest (a new walk, a resume, or a
    /// record held back): the peer served it work it did not hold. A sync
    /// that attempted none was quiet (bsv-low #555, the delta fold's D-M2:
    /// a quiet sync never counts toward [`PEER_YIELDLESS_SYNCS_ALLOWED`]).
    pub fn graphs_attempted(&self) -> u64 {
        self.graphs_attempted.get()
    }

    /// Have `hook` called after every completed incoming UTXO (bsv-low #552,
    /// see [`FinalizedGraphHook`]). Without one `sync` is unchanged.
    #[must_use]
    pub fn with_finalized_graph_hook(mut self, hook: Box<dyn FinalizedGraphHook + 'a>) -> Self {
        self.finalized_hook = Some(hook);
        self
    }

    /// The cursor that is safe to persist if `sync` stopped RIGHT NOW (its
    /// future dropped at a deadline; bsv-low #552). It is the gap guard's
    /// rule applied to completed scores: never above a completed output, and
    /// strictly below the lowest score of
    /// any UTXO of the current page not yet completed (the one in flight
    /// included) and of any UTXO whose ingest failed, never below the cursor
    /// the sync entered with. The remote serves `score >= since`, so the next
    /// sync is served everything this one did not finish. After a completed
    /// `sync` it equals `last_interaction`.
    ///
    /// `last_interaction` itself is NOT safe after a drop: it is raised to
    /// each UTXO's score BEFORE that UTXO is ingested, for pagination.
    pub fn completed_cursor(&self) -> u64 {
        self.completed_cursor
    }

    /// Whether a graph was being fetched, walked or anchor-checked when `sync`
    /// last stopped: `true` only after a `sync` future dropped mid-graph
    /// (bsv-low #552). That graph's nodes died with the storage adapter;
    /// nothing of it was finalized.
    pub fn graph_in_flight(&self) -> bool {
        self.graph_in_flight
    }

    /// Highest completed score below every gap, floored at the entry cursor.
    /// Retaining scores handles unordered pages without inventing a cursor
    /// between outputs or skipping an unfinished member of a score tie.
    fn cursor_for_completed(
        completed: &std::collections::BTreeSet<u64>,
        lowest_unfinished: Option<u64>,
        floor: u64,
    ) -> u64 {
        let highest = match lowest_unfinished {
            Some(score) => completed.range(..score).next_back(),
            None => completed.iter().next_back(),
        };
        highest.copied().unwrap_or(floor).max(floor)
    }

    /// How many graphs this orchestrator's last `sync` discarded because
    /// `validate_graph_anchor` REFUSED them (a root that does not verify, or
    /// one the topic manager does not admit at the end of the replay; bsv-low
    /// #551). Nothing of a discarded graph is finalized. As in the reference
    /// a refused graph is not a failed UTXO: the cursor advances past it. A
    /// graph whose anchor could not be CHECKED
    /// (`GASPError::AnchorUnavailable`: a tracker or storage fault, a topic
    /// manager error in the replay) is not counted here: that one fails its
    /// UTXO and is asked for again.
    pub fn discarded_graphs(&self) -> u64 {
        self.discarded_graphs.get()
    }

    /// How many graphs this orchestrator's last `sync` HELD because their
    /// anchor's script walk could not run within the engine's walk budget
    /// (`GASPError::AnchorWalkHeld`; bsv-low #592, the E592 lens fold): not
    /// finalized, the UTXO failed and the cursor kept below it, until the
    /// peer serves the root proven. Not counted in `discarded_graphs`.
    pub fn anchor_walk_held(&self) -> u64 {
        self.anchor_walk_held.get()
    }

    /// How many manager-named inputs this orchestrator pruned because the
    /// peer answered that it does not hold them (the D8 decoy rule, see
    /// `process_incoming_node`). Counted per DISTINCT outpoint per `sync`
    /// call of this orchestrator, which talks to ONE peer: the same decoy
    /// seen through two peers is counted by each. A pruned branch is NOT a
    /// failed UTXO: the graph completes with what it has and the cursor
    /// advances.
    pub fn pruned_inputs(&self) -> u64 {
        self.pruned_inputs.get()
    }

    /// Opt in to chain-backed ancestor hydration (OFF by default).
    ///
    /// When set, a peer's inability to serve a needed ancestor during ingest
    /// triggers a fallback fetch of that ancestor's raw tx from chain. This is
    /// a deliberate one-time-migration escape hatch — production should NOT
    /// call this. Without it, behavior is unchanged.
    #[must_use]
    pub fn with_ancestor_fetcher(
        mut self,
        fetcher: Option<std::rc::Rc<dyn AncestorFetcher + 'a>>,
    ) -> Self {
        self.ancestor_fetcher = fetcher;
        self
    }

    /// Run the sync protocol with the remote peer.
    ///
    /// 1. Request remote's UTXOs since last interaction (paginated)
    /// 2. For each unknown UTXO, request the full graph and ingest it
    /// 3. If bidirectional, push our unknown UTXOs to the remote
    pub async fn sync(&mut self, limit: Option<u64>) -> Result<(), GASPError> {
        info!(
            "{} Starting sync. last_interaction={}",
            self.log_prefix, self.last_interaction
        );
        self.pruned.borrow_mut().clear();
        self.pruned_inputs.set(0);
        self.discarded_graphs.set(0);
        self.anchor_walk_held.set(0);
        self.completed_cursor = self.last_interaction;
        self.graph_in_flight = false;
        self.walk.borrow_mut().take();
        *self.stats.borrow_mut() = DeferralStats::default();
        self.deferred.borrow_mut().clear();
        self.held_records.set(0);
        self.resume_deadline.borrow_mut().take();
        self.resume_left.set(
            self.graph_budget
                .as_ref()
                .map_or(PassCap::NONE, GraphBudget::pass),
        );
        // bsv-low #555: the deferred graphs of this (peer, topic), resumed
        // as the peer serves their UTXOs again (the cursor was held below
        // them). Only their keys: a record is read when its UTXO is served
        // (the lens fold's L3). A read fault resumes nothing this sync: those
        // UTXOs are walked from their roots and their records replaced, and
        // the (peer, topic) is taken as FULL, so no new record is saved over
        // a count not known (the lens fold's L6).
        if self.graph_budget.is_some() {
            match self.storage.load_deferred_graphs().await {
                Ok(keys) => {
                    self.held_records.set(keys.len());
                    self.deferred
                        .borrow_mut()
                        .extend(keys.into_iter().map(|k| k.outpoint));
                }
                Err(e) => {
                    self.held_records.set(DEFERRED_GRAPHS_PER_PEER_TOPIC);
                    warn!(
                        "{} Could not read the deferred graphs (bsv-low #555): {}",
                        self.log_prefix, e
                    );
                }
            }
        }

        // Track what we already know
        let local_utxos = self.storage.find_known_utxos(0, None).await?;
        let mut known_outpoints: std::collections::HashSet<String> = local_utxos
            .iter()
            .map(|u| format!("{}.{}", u.txid, u.output_index))
            .collect();
        let mut shared_outpoints: std::collections::HashSet<String> =
            std::collections::HashSet::new();

        // The cursor we entered with. The persisted cursor must never regress
        // below it (a failed RE-ingest of an already-synced range is not a new
        // gap), and the gap-guard below is floored at it.
        let initial_interaction = self.last_interaction;
        let mut completed_scores = std::collections::BTreeSet::new();
        // Lowest score of any UTXO whose graph ingest FAILED this run. The
        // in-loop `last_interaction` advance below is by max-seen-score so
        // pagination terminates, but a transient ingest failure must NOT let the
        // PERSISTED cursor skip past that output — else the peer never re-serves
        // it (next `since` excludes scores below the cursor) and it is stranded
        // forever. After the loop we cap the cursor strictly below this score so
        // the next sync re-requests the failed graph. (Without this, a single
        // blipped graph fetch silently drops that UTXO from continuous sync.)
        let mut min_failed_score: Option<u64> = None;
        // The UTXOs whose ingest FAILED this run (bsv-low #554). The cursor
        // moves to a UTXO's score before its ingest and the responder serves
        // `score >= since`, so the row at a page boundary is served again on
        // the next page of this same sync. A completed one is in
        // `shared_outpoints` and skipped; a failed one was in no set and was
        // walked a second time, at twice the requests and twice the per-peer
        // budget. An addition to the reference: `GASP.ts sync` keeps only
        // `sharedOutpoints` (added on success), so a failed UTXO served
        // again by a later page is ingested again there. Here a UTXO is
        // ingested at most once per sync; the retry is the next sync's, which
        // the gap guard below makes sure is served it. Kept apart from
        // `shared_outpoints`, which also decides what a bidirectional sync
        // pushes.
        let mut failed_outpoints: std::collections::HashSet<String> =
            std::collections::HashSet::new();

        // Paginated pull from remote
        loop {
            let cursor_before_page = self.last_interaction;
            // Every UTXO seen so far is completed or failed: were the sync
            // dropped inside the page request below, this is what it did.
            self.completed_cursor = Self::cursor_for_completed(
                &completed_scores,
                min_failed_score,
                initial_interaction,
            );
            let request = GASPInitialRequest {
                version: GASP_VERSION,
                since: self.last_interaction,
                limit,
            };
            let response = self.remote.get_initial_response(&request).await?;
            let page_size = response.utxo_list.len();

            info!(
                "{} Processing page with {} UTXOs (since: {})",
                self.log_prefix, page_size, response.since
            );

            // lowest_ahead[i]: the lowest score among this page's UTXOs from
            // i on, for `completed_cursor` (a page is not assumed sorted).
            let mut lowest_ahead: Vec<u64> =
                response.utxo_list.iter().map(|u| u.score as u64).collect();
            for i in (0..lowest_ahead.len().saturating_sub(1)).rev() {
                lowest_ahead[i] = lowest_ahead[i].min(lowest_ahead[i + 1]);
            }

            // The request may have returned an unordered page. Hold below all
            // its unfinished outputs before any graph or storage await.
            let unfinished = match lowest_ahead.as_slice() {
                [lowest, ..] => Some(min_failed_score.map_or(*lowest, |score| score.min(*lowest))),
                [] => min_failed_score,
            };
            self.completed_cursor =
                Self::cursor_for_completed(&completed_scores, unfinished, initial_interaction);

            for (position, utxo) in response.utxo_list.iter().enumerate() {
                // Track highest score for pagination
                if utxo.score as u64 > self.last_interaction {
                    self.last_interaction = utxo.score as u64;
                }

                let outpoint = format!("{}.{}", utxo.txid, utxo.output_index);
                if known_outpoints.contains(&outpoint) {
                    // A deferred graph whose UTXO the node now holds (it
                    // landed another way): nothing to resume.
                    if self.deferred.borrow_mut().remove(&outpoint) {
                        self.drop_record(&outpoint, DropReason::Held).await;
                    }
                    shared_outpoints.insert(outpoint.clone());
                    known_outpoints.remove(&outpoint);
                } else if !shared_outpoints.contains(&outpoint)
                    && !failed_outpoints.contains(&outpoint)
                {
                    // New UTXO — request and ingest the graph
                    let lowest_unfinished = min_failed_score
                        .map_or(lowest_ahead[position], |f| f.min(lowest_ahead[position]));
                    self.completed_cursor = Self::cursor_for_completed(
                        &completed_scores,
                        Some(lowest_unfinished),
                        initial_interaction,
                    );
                    self.graph_in_flight = true;
                    let ingested = self.ingest_utxo(utxo, &outpoint).await;
                    self.graph_in_flight = false;
                    let ingested = match ingested {
                        Ok(Ingested::Completed) => {
                            let landed = match &self.finalized_hook {
                                Some(hook) => hook.graph_completed().await,
                                None => Ok(()),
                            };
                            self.settle_completed(landed.is_ok()).await;
                            landed.map(|()| true)
                        }
                        Ok(Ingested::Deferred | Ingested::HeldBack) => Ok(false),
                        Err(e) => {
                            self.walk.borrow_mut().take();
                            Err(e)
                        }
                    };
                    match ingested {
                        Ok(true) => {
                            shared_outpoints.insert(outpoint.clone());
                        }
                        // bsv-low #555: DEFERRED, its walk saved (or a
                        // record held back for the next sync, M1). Held
                        // below the cursor like a failed UTXO (the gap
                        // guard) and not walked again in this sync (#554);
                        // the next sync resumes it. The sync goes on.
                        Ok(false) => {
                            let s = utxo.score as u64;
                            min_failed_score = Some(min_failed_score.map_or(s, |cur| cur.min(s)));
                            failed_outpoints.insert(outpoint.clone());
                        }
                        Err(e) => {
                            warn!(
                                "{} Error ingesting UTXO {}: {}",
                                self.log_prefix, outpoint, e
                            );
                            // Remember the lowest failed score so the persisted
                            // cursor cannot skip past it (see cap below).
                            let s = utxo.score as u64;
                            min_failed_score = Some(min_failed_score.map_or(s, |cur| cur.min(s)));
                            // Not again in this sync (bsv-low #554).
                            failed_outpoints.insert(outpoint.clone());
                        }
                    }
                }
                // Known outputs and graphs whose finalize hook landed are
                // settled. Explicit anchor refusals retain the existing
                // terminal-discard rule; deferred, held and faulted graphs
                // remain gaps until a later pass completes them.
                if shared_outpoints.contains(&outpoint) {
                    completed_scores.insert(utxo.score as u64);
                }
                let unfinished = lowest_ahead
                    .get(position + 1)
                    .copied()
                    .into_iter()
                    .chain(min_failed_score)
                    .min();
                self.completed_cursor =
                    Self::cursor_for_completed(&completed_scores, unfinished, initial_interaction);
            }

            // Keep the settled frontier and any completed scores above a gap.
            // An advancing page needs no older score again.
            completed_scores.retain(|score| *score >= self.completed_cursor);

            // Pagination termination (bsv-low #291 gate findings M1/LOW-A):
            // keep paging on ANY page that advanced the score cursor —
            // with or without a requested limit. The old rule ("continue
            // only on a full page"; `None` never paged at all) silently
            // terminated after one page against a responder that CLAMPS
            // the page size (Engine::clamp_sync_limit clamps BOTH an
            // over-large and an ABSENT limit) — a clamped page is never
            // "full" by our limit, yet more rows remain. A non-advancing
            // page (empty, or only rows at scores we already hold — the
            // responder serves `score >= since`, so the boundary row is
            // re-served) is the true completion signal: no further request
            // can make progress.
            //
            // Known residual (gate LOW-B, documented not fixed): the
            // cursor is the bare GASP `since` score, so a tie group of
            // IDENTICAL scores at least as large as the responder's page
            // would end the run with that group's tail unreached (break on
            // non-advance — a silent gap, never a spin). A compound
            // (score, rowid) cursor would need a wire change to `since`,
            // which is out of bounds; unconstructible in practice — see
            // the responder-side note at
            // `D1Storage::find_utxos_for_topic`.
            if self.last_interaction == cursor_before_page {
                break;
            }
        }

        // Gap-guard: if any graph ingest failed transiently, cap the cursor
        // strictly below the lowest failed score so the next sync re-pulls it
        // (the remote serves `score >= since`). Floored at `initial_interaction`
        // so the cursor never regresses — a failure within the already-synced
        // range is not a new gap and must not rewind the cursor.
        self.completed_cursor =
            Self::cursor_for_completed(&completed_scores, min_failed_score, initial_interaction);
        if let Some(failed) = min_failed_score {
            if self.last_interaction > self.completed_cursor {
                warn!(
                    "{} Capping cursor {} -> {} (transient ingest failure at score {}); next sync will re-pull",
                    self.log_prefix, self.last_interaction, self.completed_cursor, failed
                );
            }
        }
        self.last_interaction = self.completed_cursor;

        // bsv-low #555: a record whose UTXO a sync that ran to its end was
        // not served (spent at the peer, or no longer listed): nothing will
        // resume it.
        let unserved: Vec<String> = self.deferred.borrow_mut().drain().collect();
        for outpoint in unserved {
            self.drop_record(&outpoint, DropReason::NotServed).await;
        }

        // Bidirectional: push our UTXOs to remote
        if !self.unidirectional {
            // Find local UTXOs the remote doesn't have
            for utxo in &local_utxos {
                let outpoint = format!("{}.{}", utxo.txid, utxo.output_index);
                if !shared_outpoints.contains(&outpoint) {
                    match self.push_utxo(utxo).await {
                        Ok(()) => {}
                        Err(e) => {
                            warn!("{} Error pushing UTXO {}: {}", self.log_prefix, outpoint, e);
                        }
                    }
                }
            }
        }

        info!("{} Sync completed!", self.log_prefix);
        Ok(())
    }

    /// Request a UTXO's graph from remote and ingest it locally.
    ///
    /// With a per-graph budget (bsv-low #555, [`Self::with_graph_budget`]) a
    /// walk past it is DEFERRED (`Ok(Ingested::Deferred)`): its record is
    /// saved and the caller holds the UTXO below the cursor like a failed
    /// one. A record of this UTXO saved by an earlier sync is RESUMED: its
    /// nodes are appended again (no request) and only its pending inputs are
    /// asked. A RESUMED walk's error defers it again (the progress is kept),
    /// except the peer's definite "not held" for an input an UNPROVEN node
    /// needs (an SPV necessity, as in the reference): that one fails the UTXO
    /// and drops the record. A FRESH walk's error keeps no record and fails
    /// the UTXO, as before #555 (the delta fold's D-M1). On `Completed` the walk stays in hand until
    /// [`Self::settle_completed`] knows whether it landed.
    ///
    /// Every RESUME of one sync shares ONE per-graph budget (the lens fold's
    /// M1): one deadline, made at the first resume, and one call count. The
    /// cursor is held below the deferred UTXOs, so the peer serves them
    /// first; with a budget each, two of them took the whole per-peer budget
    /// and no UTXO above them was reached. Now the resumes of a pass take at
    /// most one graph's budget and the first new UTXO keeps its own. A record
    /// served once that budget is spent is HELD BACK untouched (no read, no
    /// pass counted) for the next sync.
    async fn ingest_utxo(&self, utxo: &GASPOutput, outpoint: &str) -> Result<Ingested, GASPError> {
        debug!("{} Requesting node for {}", self.log_prefix, outpoint);
        self.graphs_attempted.set(self.graphs_attempted.get() + 1);
        let Some(budget) = &self.graph_budget else {
            *self.walk.borrow_mut() =
                Some(Self::fresh_walk(utxo.score as u64, outpoint, PassCap::NONE));
            let walked = self.walk_graph(None).await;
            let walk = self.walk.borrow_mut().take();
            walked?;
            self.complete_graph(&Self::graph_id_of(walk.as_ref(), outpoint))
                .await?;
            return Ok(Ingested::Completed);
        };

        if !self.deferred.borrow_mut().remove(outpoint) {
            let mut deadline = latched((budget.deadline)());
            return self
                .ingest_budgeted(utxo, outpoint, &mut deadline, budget.pass(), false)
                .await;
        }
        let mut deadline = self
            .resume_deadline
            .borrow_mut()
            .take()
            .unwrap_or_else(|| latched((budget.deadline)()));
        let cap = self.resume_left.get();
        if cap.spent() || Self::due(&mut deadline).await {
            *self.resume_deadline.borrow_mut() = Some(deadline);
            self.stats.borrow_mut().held_back += 1;
            info!(
                "{} Deferred graph {} held back: the resumes of this pass spent their budget (bsv-low #555)",
                self.log_prefix, outpoint
            );
            return Ok(Ingested::HeldBack);
        }
        let before = (
            self.calls_made.get(),
            self.bytes_fetched.get(),
            self.nodes_appended.get(),
        );
        let ingested = self
            .ingest_budgeted(utxo, outpoint, &mut deadline, cap, true)
            .await;
        let narrowed = |spent: u64| u32::try_from(spent).unwrap_or(u32::MAX);
        self.resume_left.set(PassCap {
            calls: cap
                .calls
                .saturating_sub(narrowed(self.calls_made.get() - before.0)),
            bytes: cap
                .bytes
                .saturating_sub(self.bytes_fetched.get() - before.1),
            nodes: cap
                .nodes
                .saturating_sub(narrowed(self.nodes_appended.get() - before.2)),
        });
        *self.resume_deadline.borrow_mut() = Some(deadline);
        ingested
    }

    /// Whether `deadline` has fallen due (polled once, with the task's own
    /// waker).
    async fn due(deadline: &mut crate::engine::SleepFuture) -> bool {
        std::future::poll_fn(|cx| std::task::Poll::Ready(deadline.as_mut().poll(cx).is_ready()))
            .await
    }

    /// A walk from the root `outpoint`, nothing fetched yet.
    fn fresh_walk(score: u64, outpoint: &str, cap: PassCap) -> Walk {
        Walk {
            record: DeferredGraph {
                peer: String::new(),
                topic: String::new(),
                outpoint: outpoint.to_string(),
                score,
                nodes: Vec::new(),
                pending: vec![PendingInput {
                    outpoint: outpoint.to_string(),
                    graph_id: outpoint.to_string(),
                    metadata: true,
                    spent_by: None,
                    parent_proven: false,
                }],
                calls: 0,
                passes: 0,
                reason: String::new(),
                configured: false,
                idle_faults: 0,
            },
            seen: std::collections::HashSet::new(),
            calls_this_pass: 0,
            bytes_this_pass: 0,
            nodes_this_pass: 0,
            resumed: false,
            cap,
            nodes_at_start: 0,
            counted: false,
            gone_on: false,
            half: None,
        }
    }

    /// One pass of a graph's walk under the per-graph budget: `deadline`,
    /// and `cap` (calls, bytes, nodes). `from_record`: a record of it is held (its key was
    /// loaded); it is read now.
    async fn ingest_budgeted(
        &self,
        utxo: &GASPOutput,
        outpoint: &str,
        deadline: &mut crate::engine::SleepFuture,
        cap: PassCap,
        from_record: bool,
    ) -> Result<Ingested, GASPError> {
        let score = utxo.score as u64;
        // A read fault fails the UTXO and keeps the record for the next sync.
        let record = if from_record {
            let record = self.storage.get_deferred_graph(outpoint).await?;
            if record.is_none() {
                // Deleted since the keys were read (the worker's sweep).
                self.held_records
                    .set(self.held_records.get().saturating_sub(1));
            }
            record
        } else {
            None
        };
        let walk = match record {
            None => {
                let mut walk = Self::fresh_walk(score, outpoint, cap);
                // D2-L1: the half-budget clock starts with the walk (polled
                // once now, so a timer that starts on its first poll runs).
                if let Some(half) = self
                    .graph_budget
                    .as_ref()
                    .and_then(|b| b.half_deadline.as_ref())
                {
                    let mut half = latched(half());
                    let _ = Self::due(&mut half).await;
                    walk.half = Some(half);
                }
                walk
            }
            Some(record) if record.passes >= DEFERRED_GRAPH_MAX_PASSES => {
                let passes = record.passes;
                self.drop_record(outpoint, DropReason::MaxPasses).await;
                return Err(GASPError::Other(format!(
                    "deferred graph {outpoint} dropped after {passes} passes (bsv-low #555)"
                )));
            }
            Some(record) => {
                self.stats.borrow_mut().resumed += 1;
                info!(
                    "{} Resuming deferred graph {} (bsv-low #555): {} nodes, {} pending, {} calls over {} passes",
                    self.log_prefix,
                    outpoint,
                    record.nodes.len(),
                    record.pending.len(),
                    record.calls,
                    record.passes
                );
                Walk {
                    seen: record
                        .nodes
                        .iter()
                        .filter_map(|w| Self::node_id(&w.node))
                        .collect(),
                    nodes_at_start: record.nodes.len(),
                    record,
                    calls_this_pass: 0,
                    bytes_this_pass: 0,
                    nodes_this_pass: 0,
                    resumed: true,
                    cap,
                    counted: false,
                    gone_on: false,
                    half: None,
                }
            }
        };
        let resumed = walk.resumed;
        let root_unproven = walk
            .record
            .nodes
            .first()
            .is_some_and(|w| w.node.proof.is_none());
        *self.walk.borrow_mut() = Some(walk);

        let ended = async {
            if resumed && root_unproven {
                // The root is asked again (one call): once its block lands
                // the peer serves it PROVEN, and the walk from it is shorter
                // than the unproven ancestry the record is still walking.
                let root = PendingInput {
                    outpoint: outpoint.to_string(),
                    graph_id: outpoint.to_string(),
                    metadata: true,
                    spent_by: None,
                    parent_proven: false,
                };
                match race_or_deadline(self.fetch_root(&root), deadline.as_mut()).await {
                    None => return Ok(WalkEnd::Deferred("time")),
                    Some(Ok(node)) if node.proof.is_some() => {
                        // The walk is fresh, the PASS is not: what it spent
                        // of every counted limb goes with it (the re-ask
                        // appends nothing, so the nodes are 0 today; carried
                        // all the same, so a limb is never forgotten here).
                        let (carried, carried_bytes, carried_nodes) =
                            self.walk.borrow().as_ref().map_or((0, 0, 0), |w| {
                                (w.calls_this_pass, w.bytes_this_pass, w.nodes_this_pass)
                            });
                        self.drop_record(outpoint, DropReason::RootProven).await;
                        let mut restarted = Self::fresh_walk(score, outpoint, cap);
                        restarted.calls_this_pass = carried;
                        restarted.bytes_this_pass = carried_bytes;
                        restarted.nodes_this_pass = carried_nodes;
                        restarted.record.calls = u64::from(carried);
                        *self.walk.borrow_mut() = Some(restarted);
                    }
                    // Unchanged, or not answered: the record goes on.
                    Some(_) => {}
                }
            }
            self.append_walked().await?;
            self.walk_graph(Some(&mut *deadline)).await
        }
        .await;
        self.finish_pass(outpoint, ended).await
    }

    /// Append the walk's fetched nodes to the graph (a resume, or a walk
    /// that goes on after its graph was discarded).
    async fn append_walked(&self) -> Result<(), GASPError> {
        let nodes: Vec<WalkedNode> = self
            .walk
            .borrow()
            .as_ref()
            .map(|w| w.record.nodes.clone())
            .unwrap_or_default();
        for walked in &nodes {
            self.storage
                .append_to_graph(&walked.node, walked.spent_by.as_deref())
                .await?;
        }
        Ok(())
    }

    /// The end of a budgeted pass: complete the graph, defer it, or fail
    /// its UTXO. A walk past its per-graph budget that cannot be KEPT (past
    /// [`DEFERRED_GRAPHS_PER_PEER_TOPIC`] or the storage's ceiling) goes on under the per-peer budget alone, as
    /// every walk did before #555 (the lens fold's L4: such a graph completed
    /// in one pass before #555, and was then failed on every pass).
    async fn finish_pass(
        &self,
        outpoint: &str,
        mut ended: Result<WalkEnd, GASPError>,
    ) -> Result<Ingested, GASPError> {
        loop {
            let graph_id = Self::graph_id_of(self.walk.borrow().as_ref(), outpoint);
            // Whether a record of this graph is still held: not after a
            // `root_proven` restart, whose walk is fresh.
            let resumed = self.walk.borrow().as_ref().is_some_and(|w| w.resumed);
            let (reason, completed) = match ended {
                Ok(WalkEnd::Done) => match self.complete_graph(&graph_id).await {
                    Ok(true) => return Ok(Ingested::Completed),
                    Ok(false) => {
                        // Refused by the anchor check: a verdict, the cursor
                        // moves, nothing to resume.
                        self.walk.borrow_mut().take();
                        if resumed {
                            self.drop_record(outpoint, DropReason::Refused).await;
                        }
                        return Ok(Ingested::Completed);
                    }
                    // `complete_graph` discarded the graph already.
                    Err(GASPError::AnchorUnavailable(_)) => ("anchor_unavailable", true),
                    // The same hold, for a walk past the budget (E592 fold).
                    Err(GASPError::AnchorWalkHeld(_)) => ("anchor_walk_held", true),
                    // A finalize fault: the graph is still in hand.
                    Err(_) => {
                        let _ = self.storage.discard_graph(&graph_id).await;
                        ("fault", true)
                    }
                },
                Ok(WalkEnd::Deferred(reason)) => (reason, false),
                Err(e @ GASPError::NodeNotFound(_)) => {
                    let _ = self.storage.discard_graph(&graph_id).await;
                    self.walk.borrow_mut().take();
                    if resumed {
                        self.drop_record(outpoint, DropReason::NotHeld).await;
                    }
                    return Err(e);
                }
                // A walk ERROR on a FRESH walk keeps no record (the delta
                // fold's D-M1): a fault is not a budget cut, and before #555
                // it failed the UTXO. A record then costs a peer a budget
                // cut (`calls`, `time`, `peer_deadline`), never a quick 5xx:
                // a stranger who answered each input with a 503 kept a
                // one-node record per UTXO, 16 per (peer, topic) in one tick
                // with no time spent, and filled the worker's ceiling. A
                // RESUMED walk keeps its record (its progress was paid for).
                //
                // Unless it PAID (the delta-2 fold's D2-L1): a fresh walk
                // that faults after half its per-graph calls or half its
                // time keeps its record as a budget cut would, so an honest
                // flaky peer's deep graph is not walked from its root on
                // every tick ((1-p)^100 a clean pass at a fault rate p).
                Err(e) if !resumed && !self.walk_paid().await => {
                    warn!(
                        "{} Walk of {} faulted: no record, the UTXO fails as before #555: {}",
                        self.log_prefix, outpoint, e
                    );
                    let _ = self.storage.discard_graph(&graph_id).await;
                    self.walk.borrow_mut().take();
                    return Err(e);
                }
                Err(e) => {
                    // D2-M2: a RESUMED pass that faulted having appended
                    // nothing is idle; at DEFERRED_GRAPH_MAX_IDLE_FAULTS in a
                    // row the record goes and the UTXO fails.
                    let idle = {
                        let mut guard = self.walk.borrow_mut();
                        guard.as_mut().map_or(0, |w| {
                            if w.resumed && w.record.nodes.len() <= w.nodes_at_start {
                                w.record.idle_faults += 1;
                            }
                            w.record.idle_faults
                        })
                    };
                    if idle >= DEFERRED_GRAPH_MAX_IDLE_FAULTS {
                        warn!(
                            "{} Walk of {} faulted with nothing appended {} passes in a row: dropped: {}",
                            self.log_prefix, outpoint, idle, e
                        );
                        let _ = self.storage.discard_graph(&graph_id).await;
                        self.walk.borrow_mut().take();
                        self.drop_record(outpoint, DropReason::IdleFaults).await;
                        return Err(e);
                    }
                    warn!(
                        "{} Walk of {} faulted, deferred with its progress: {}",
                        self.log_prefix, outpoint, e
                    );
                    let _ = self.storage.discard_graph(&graph_id).await;
                    ("fault", false)
                }
            };
            // Only a walk the per-graph budget cut may go on (L4).
            let budget_cut = matches!(reason, "calls" | "time" | "bytes" | "nodes");
            let (why, mut walk) = match self.save_walk(reason, completed).await {
                Saved::Yes => {
                    let _ = self.storage.discard_graph(&graph_id).await;
                    return Ok(Ingested::Deferred);
                }
                Saved::WentOn => {
                    let _ = self.storage.discard_graph(&graph_id).await;
                    return Err(GASPError::Other(format!(
                        "graph {outpoint} went on and did not complete (bsv-low #555)"
                    )));
                }
                // A store FAULT at a deferral goes on as the other bounds do
                // (the delta fold's D-L2; counted `store_fault` by
                // `save_walk`): it failed the UTXO, a transient D1 fault
                // failing a graph the per-peer budget would have completed.
                Saved::Fault(e, walk) => {
                    if !budget_cut {
                        let _ = self.storage.discard_graph(&graph_id).await;
                        return Err(e);
                    }
                    (DropReason::StoreFault, walk)
                }
                // No room for a RESUMED walk (bsv-low #585): its held record
                // stays, so what this pass adds is lost and nothing else. A
                // budget cut goes on as the other bounds do; any other end
                // fails the UTXO and the next pass resumes from the record.
                Saved::Ceiling(walk) => {
                    if !budget_cut {
                        let _ = self.storage.discard_graph(&graph_id).await;
                        return Err(GASPError::Other(format!(
                            "deferred graph {outpoint} found no room, its record kept (bsv-low #585)"
                        )));
                    }
                    (DropReason::TooMany, walk)
                }
                Saved::Unkept(why, mut walk) => {
                    self.unkept(why, &mut walk).await;
                    if !(budget_cut && why == DropReason::TooMany) {
                        let _ = self.storage.discard_graph(&graph_id).await;
                        return Err(GASPError::Other(format!(
                            "deferred graph {outpoint} not kept: {} (bsv-low #555)",
                            why.as_str()
                        )));
                    }
                    (why, walk)
                }
            };
            info!(
                "{} Graph {} cannot be kept ({}): its walk goes on under the per-peer budget alone (bsv-low #555)",
                self.log_prefix,
                outpoint,
                why.as_str()
            );
            walk.cap = PassCap::NONE;
            walk.gone_on = true;
            *self.walk.borrow_mut() = Some(*walk);
            // The graph in hand was never discarded: walk on.
            ended = self.walk_graph(None).await;
        }
    }

    /// After a COMPLETED graph's hook (bsv-low #555): a graph that landed
    /// deletes its record (a resumed one converged); one whose finalize did
    /// not land keeps its walk as a record with nothing pending, so the next
    /// pass completes it again without walking it again. No-op without a
    /// per-graph budget.
    async fn settle_completed(&self, landed: bool) {
        if self.graph_budget.is_none() {
            self.walk.borrow_mut().take();
            return;
        }
        if landed {
            let Some(walk) = self.walk.borrow_mut().take() else {
                return;
            };
            if walk.resumed {
                if let Err(e) = self
                    .storage
                    .delete_deferred_graph(&walk.record.outpoint)
                    .await
                {
                    warn!(
                        "{} Could not delete the record of converged graph {}: {}",
                        self.log_prefix, walk.record.outpoint, e
                    );
                }
                self.held_records
                    .set(self.held_records.get().saturating_sub(1));
                self.stats.borrow_mut().converged += 1;
                info!(
                    "{} Deferred graph {} CONVERGED after {} passes, {} calls, {} nodes (bsv-low #555)",
                    self.log_prefix,
                    walk.record.outpoint,
                    walk.record.passes + 1,
                    walk.record.calls,
                    walk.record.nodes.len()
                );
            }
        } else if let Saved::Unkept(why, mut walk) = self.save_walk("not_landed", true).await {
            self.unkept(why, &mut walk).await;
        }
    }

    /// Save the walk in hand as its graph's record (bsv-low #555), counting
    /// a deferral; or hand it back UNKEPT with the reason (past a bound, or
    /// holding no node), or answer the storage's fault with the walk (a walk
    /// the per-graph budget cut then goes on, D-L2; any other fails its
    /// UTXO). A walk that already went on is neither saved nor counted again
    /// (D-L1). Counts the pass progressed or stalled (the lens fold's H1),
    /// once per pass.
    async fn save_walk(&self, reason: &'static str, completed: bool) -> Saved {
        let Some(mut walk) = self.walk.borrow_mut().take() else {
            // Nothing in hand: nothing to save.
            return Saved::Yes;
        };
        if walk.gone_on {
            // Its drop was counted when it went on (D-L1).
            return Saved::WentOn;
        }
        if !walk.counted {
            walk.counted = true;
            let mut stats = self.stats.borrow_mut();
            if completed || walk.record.nodes.len() > walk.nodes_at_start {
                stats.progressed += 1;
            } else {
                stats.stalled += 1;
            }
        }
        walk.record.passes += 1;
        walk.record.reason = reason.to_string();
        if walk.record.nodes.len() > walk.nodes_at_start {
            walk.record.idle_faults = 0;
        }
        // H1: a walk that holds no node is never kept (nothing would be lost
        // by not keeping it, and an empty record took one of the 16 places
        // for up to 60 passes, L2): its UTXO fails as before #555.
        if walk.record.nodes.is_empty() {
            return Saved::Unkept(DropReason::NoProgress, Box::new(walk));
        }
        if !walk.resumed && self.held_records.get() >= DEFERRED_GRAPHS_PER_PEER_TOPIC {
            return Saved::Unkept(DropReason::TooMany, Box::new(walk));
        }
        // No bound on a record's size (bsv-low #585): the figure is logged
        // and is the storage's to budget.
        let bytes = walk.record.byte_size();
        let outpoint = walk.record.outpoint.clone();
        match self.storage.save_deferred_graph(&walk.record).await {
            Ok(DeferredGraphSave::Saved) => {
                if !walk.resumed {
                    self.held_records.set(self.held_records.get() + 1);
                }
                self.stats.borrow_mut().deferred += 1;
                info!(
                    "{} DEFERRED graph {} ({}): {} nodes, {} pending, {} calls ({} this pass), pass {}, {} bytes (bsv-low #555)",
                    self.log_prefix,
                    outpoint,
                    reason,
                    walk.record.nodes.len(),
                    walk.record.pending.len(),
                    walk.record.calls,
                    walk.calls_this_pass,
                    walk.record.passes,
                    bytes
                );
                Saved::Yes
            }
            // The storage's ceiling is a budget of room, not a verdict on
            // the graph (bsv-low #585): a RESUMED walk keeps the record it
            // holds (it was deleted, and the graph walked from its root at
            // the next pass); a fresh walk has none to keep.
            Ok(DeferredGraphSave::AtCeiling) if walk.resumed => {
                self.note_dropped(&outpoint, DropReason::TooMany);
                Saved::Ceiling(Box::new(walk))
            }
            Ok(DeferredGraphSave::AtCeiling) => Saved::Unkept(DropReason::TooMany, Box::new(walk)),
            // The save is lost and counted `store_fault`. A RESUMED walk's
            // held record is KEPT (the delta-2 lens's D2-N2: it was deleted,
            // and one transient D1 fault threw away every earlier pass of a
            // walk the per-peer budget did not then finish): the next pass
            // resumes from it, losing this pass only; a walk that goes on
            // and lands deletes it as a converged one.
            Err(e) => {
                self.note_dropped(&outpoint, DropReason::StoreFault);
                Saved::Fault(e, Box::new(walk))
            }
        }
    }

    /// A walk [`Self::save_walk`] did not keep: its held record (if any) is
    /// deleted with the reason, else the reason is counted; a fresh walk
    /// that fetched nothing was never a record and is only logged.
    async fn unkept(&self, why: DropReason, walk: &mut Walk) {
        let outpoint = walk.record.outpoint.clone();
        if walk.resumed {
            self.drop_record(&outpoint, why).await;
            walk.resumed = false;
        } else if why == DropReason::NoProgress {
            warn!(
                "{} Walk of {} fetched nothing: not kept, the UTXO fails (bsv-low #555)",
                self.log_prefix, outpoint
            );
        } else {
            self.note_dropped(&outpoint, why);
        }
    }

    /// Whether the walk in hand has PAID for a record (the delta-2 fold's
    /// D2-L1): half its per-graph calls made in this pass, or its half
    /// deadline fallen due. A walk that holds no node never has.
    async fn walk_paid(&self) -> bool {
        let Some(budget) = &self.graph_budget else {
            return false;
        };
        let mut half = {
            let mut guard = self.walk.borrow_mut();
            let Some(walk) = guard.as_mut() else {
                return false;
            };
            if walk.record.nodes.is_empty() {
                return false;
            }
            if u64::from(walk.calls_this_pass) * 2 >= u64::from(budget.max_calls) {
                return true;
            }
            match walk.half.take() {
                Some(half) => half,
                None => return false,
            }
        };
        let paid = Self::due(&mut half).await;
        if let Some(walk) = self.walk.borrow_mut().as_mut() {
            walk.half = Some(half);
        }
        paid
    }

    /// Delete a held record and count it dropped.
    async fn drop_record(&self, outpoint: &str, reason: DropReason) {
        if let Err(e) = self.storage.delete_deferred_graph(outpoint).await {
            warn!(
                "{} Could not delete the record of deferred graph {}: {}",
                self.log_prefix, outpoint, e
            );
        }
        self.held_records
            .set(self.held_records.get().saturating_sub(1));
        self.note_dropped(outpoint, reason);
    }

    fn note_dropped(&self, outpoint: &str, reason: DropReason) {
        warn!(
            "{} Deferred graph {} DROPPED ({}) (bsv-low #555)",
            self.log_prefix,
            outpoint,
            reason.as_str()
        );
        self.stats.borrow_mut().dropped.push(DroppedGraph {
            outpoint: outpoint.to_string(),
            reason,
        });
    }

    /// Save the walk of the graph that was in hand when a deadline dropped
    /// `sync` (bsv-low #555): the per-peer deadline (D16) defers it like the
    /// per-graph one, so the next pass resumes it instead of walking it
    /// again. No-op without a per-graph budget or with no walk in hand.
    pub async fn defer_in_flight(&self) {
        if self.graph_budget.is_some() {
            if let Saved::Unkept(why, mut walk) = self.save_walk("peer_deadline", false).await {
                self.unkept(why, &mut walk).await;
            }
        }
    }

    /// The graph id of the walk in hand: its root's, else the outpoint.
    fn graph_id_of(walk: Option<&Walk>, outpoint: &str) -> String {
        walk.and_then(|w| w.record.nodes.first())
            .map_or_else(|| outpoint.to_string(), |w| w.node.graph_id.clone())
    }

    /// `txid.outputIndex` of a node, its txid computed from its raw bytes.
    fn node_id(node: &GASPNode) -> Option<String> {
        bsv_rs::transaction::Transaction::from_hex(&node.raw_tx)
            .ok()
            .map(|tx| format!("{}.{}", tx.id(), node.output_index))
    }

    /// Count a node the graph in hand was SERVED (bsv-low #586): the bytes
    /// the peer sent for it, which are the bytes a record keeps of it.
    fn count_fetched(&self, node: &GASPNode) {
        let bytes = (node.raw_tx.len() + node.proof.as_ref().map_or(0, String::len)) as u64;
        self.bytes_fetched.set(self.bytes_fetched.get() + bytes);
        if let Some(w) = self.walk.borrow_mut().as_mut() {
            w.bytes_this_pass += bytes;
        }
    }

    /// Count one call of the graph in hand.
    fn count_call(&self) {
        self.calls_made.set(self.calls_made.get() + 1);
        if let Some(w) = self.walk.borrow_mut().as_mut() {
            w.calls_this_pass += 1;
            w.record.calls += 1;
        }
    }

    /// Push a local UTXO's graph to the remote.
    async fn push_utxo(&self, utxo: &GASPOutput) -> Result<(), GASPError> {
        let outpoint = format!("{}.{}", utxo.txid, utxo.output_index);
        debug!("{} Hydrating node for {}", self.log_prefix, outpoint);

        let node = self
            .storage
            .hydrate_gasp_node(&outpoint, &utxo.txid, utxo.output_index, true)
            .await?;

        self.process_outgoing_node(&node, &mut std::collections::HashSet::new())
            .await?;

        Ok(())
    }

    /// Walk the graph in hand until nothing is pending (an explicit stack,
    /// bsv-low #555; before it a recursion, in the same order: an input's
    /// whole branch before its next sibling). Each step's result is
    /// committed to the walk only once the step has finished, so a deadline
    /// that drops this future leaves the walk as it was before that step.
    /// With a per-graph budget the walk stops at a counted limb of it (its
    /// calls; the bytes it was served or the nodes it appended, bsv-low #586)
    /// or at its `deadline`, and answers `Deferred` with the limb's name;
    /// without one it runs to its end. A limb is read BEFORE a step, so a
    /// pass always makes one: no node is too big to walk.
    async fn walk_graph(
        &self,
        mut deadline: Option<&mut crate::engine::SleepFuture>,
    ) -> Result<WalkEnd, GASPError> {
        loop {
            let (item, over) = {
                let walk = self.walk.borrow();
                let Some(walk) = walk.as_ref() else {
                    return Ok(WalkEnd::Done);
                };
                (
                    walk.record.pending.last().cloned(),
                    self.graph_budget.as_ref().and_then(|_| walk.over()),
                )
            };
            let Some(item) = item else {
                return Ok(WalkEnd::Done);
            };
            // One failed round trip per decoy: an outpoint pruned earlier in
            // this sync is not asked for again, even when a later graph of
            // the sync names it (two UTXOs of one decoy-bearing transaction).
            if item.parent_proven && self.pruned.borrow().contains(&item.outpoint) {
                debug!(
                    "{} Input {} of {:?} was already pruned in this sync; not re-requested",
                    self.log_prefix, item.outpoint, item.spent_by
                );
                if let Some(w) = self.walk.borrow_mut().as_mut() {
                    w.record.pending.pop();
                }
                continue;
            }
            if let Some(limb) = over {
                return Ok(WalkEnd::Deferred(limb));
            }
            let step = self.step(&item);
            let out = match deadline.as_mut() {
                Some(deadline) => match race_or_deadline(step, deadline.as_mut()).await {
                    Some(out) => out,
                    None => return Ok(WalkEnd::Deferred("time")),
                },
                None => step.await,
            }?;
            self.commit(out);
        }
    }

    /// Commit one finished step to the walk in hand: its item is no longer
    /// pending, and an appended node's needed inputs are, the first of them
    /// on top.
    fn commit(&self, out: StepOut) {
        let mut walk = self.walk.borrow_mut();
        let Some(walk) = walk.as_mut() else {
            return;
        };
        walk.record.pending.pop();
        if let StepOut::Appended {
            node_id,
            walked,
            children,
        } = out
        {
            walk.seen.insert(node_id);
            walk.nodes_this_pass += 1;
            self.nodes_appended.set(self.nodes_appended.get() + 1);
            walk.record.nodes.push(*walked);
            walk.record.pending.extend(children.into_iter().rev());
        }
    }

    /// The walk from a root already in hand (the lib tests' entry, from
    /// before the walk was a stack): its proof hydrated, then every needed
    /// input to the end.
    #[cfg(test)]
    async fn process_incoming_node(
        &self,
        node: &GASPNode,
        _spent_by: Option<&str>,
        _seen: &mut std::collections::HashSet<String>,
    ) -> Result<(), GASPError> {
        let root = PendingInput {
            outpoint: node.graph_id.clone(),
            graph_id: node.graph_id.clone(),
            metadata: true,
            spent_by: None,
            parent_proven: false,
        };
        *self.walk.borrow_mut() = Some(Walk {
            record: DeferredGraph {
                peer: String::new(),
                topic: String::new(),
                outpoint: node.graph_id.clone(),
                score: 0,
                nodes: Vec::new(),
                pending: vec![root.clone()],
                calls: 0,
                passes: 0,
                reason: String::new(),
                configured: false,
                idle_faults: 0,
            },
            seen: std::collections::HashSet::new(),
            calls_this_pass: 0,
            bytes_this_pass: 0,
            nodes_this_pass: 0,
            resumed: false,
            cap: PassCap::NONE,
            nodes_at_start: 0,
            counted: false,
            gone_on: false,
            half: None,
        });
        let node = self.hydrate_root(node.clone()).await;
        let out = self.absorb(&root, node).await?;
        self.commit(out);
        self.walk_graph(None).await.map(|_| ())
    }

    /// The ROOT of a graph: the peer's node for the UTXO, its own proof
    /// hydrated by the ancestor fetcher when it has none.
    async fn fetch_root(&self, item: &PendingInput) -> Result<GASPNode, GASPError> {
        let (txid, oi) = parse_outpoint(&item.outpoint)
            .ok_or_else(|| GASPError::Other(format!("bad outpoint {}", item.outpoint)))?;
        self.count_call();
        let node = self
            .remote
            .request_node(&item.graph_id, &txid, oi, item.metadata)
            .await?;
        self.count_fetched(&node);
        Ok(self.hydrate_root(node).await)
    }

    /// The root's own proof, hydrated by the ancestor fetcher when the peer
    /// served it with none.
    async fn hydrate_root(&self, mut node: GASPNode) -> GASPNode {
        // The peer already supplied the raw. Ask our proof source for only
        // its verified BUMP, inside the graph and peer deadlines. Production
        // re-verifies courier proofs against CHAINTRACKS; the graph's anchor
        // check still runs before any admission. A resumed proofless root
        // takes this path too, so a kept graph can land once its proof exists.
        if node.proof.is_none() {
            if let Some(fetcher) = &self.ancestor_fetcher {
                if let Some(node_txid) =
                    Self::node_id(&node).and_then(|id| parse_outpoint(&id).map(|(txid, _)| txid))
                {
                    self.count_call();
                    node.proof = fetcher.verified_proof_for(&node_txid).await;
                }
            }
        }
        node
    }

    /// One step of the walk: fetch `item`, append it to the graph, name its
    /// needed inputs. Nothing of the walk is changed here (see
    /// [`Self::walk_graph`]).
    async fn step(&self, item: &PendingInput) -> Result<StepOut, GASPError> {
        // THE D8 DECOY RULE (zanaadu-v2 #314, the owner's ruling of
        // 2026-10-06). A DELIBERATE DIVERGENCE from the reference.
        //
        // The reference requests every needed input with no catch
        // (`GASP.ts:602`, `await this.remote.requestNode(...)` inside
        // `processIncomingNode`), so one input the peer cannot serve
        // throws out of the walk and the per-UTXO catch in `sync`
        // drops that whole UTXO: the graph is never completed.
        //
        // We keep that for an UNPROVEN parent and diverge for a PROVEN
        // one. A proven parent needs no input for SPV; the only
        // inputs `find_needed_inputs` returns for it are the ones its
        // topic manager NAMED as history. A manager cannot always
        // tell which input is the real one: a head covenant that
        // signs under ANYONECANPAY lets a spender place a decoy
        // witness-shaped input ahead of the real head input, and once
        // mined it is permanent. The pairing is that such a manager
        // names EVERY witness-shaped input, and the engine PRUNES the
        // branch of a named input the PEER DEFINITELY DOES NOT HOLD
        // instead of discarding the graph: warn, count, carry on with
        // the parent's other named inputs, complete the graph with
        // what it has. Under the reference's rule one decoy would
        // strand the chain behind it on every sync, forever.
        //
        // An unproven parent's inputs are SPV necessities, not named
        // history: a missing one still fails the UTXO (the `?` below),
        // exactly as the reference does.
        //
        // THE CLASSIFICATION RULE. A named input is pruned only on a
        // DEFINITE answer: the peer said it does not hold the
        // outpoint, the typed class `GASPError::NodeNotFound`. Every
        // other error (the request could not be sent, a timeout, a
        // 5xx, a 429, a body that does not parse) is a fault of the
        // moment and says nothing about what the peer holds: it
        // fails the UTXO as the reference does, the per-UTXO arm of
        // `sync` records it in the cursor gap guard, and the next
        // sync asks again. Pruning on such a fault would cut the
        // REAL head input, finalize a truncated graph, advance the
        // cursor and never ask for that history again. The remote
        // decides the class: the worker's maps HTTP 400 from
        // `/requestForeignGASPNode` to `NodeNotFound` and nothing
        // else (`gasp_remote.rs`), because 400 is what the reference
        // peer answers for an outpoint it does not hold. Accepted
        // residual: the reference answers the same masked 400 when
        // its own storage faults inside `provideForeignGASPNode`, so
        // that fault at a reference peer reads as "not held".
        //
        // THE FETCHER ARM NEVER PRUNES. A chain fetcher has no
        // definite "cannot serve": every input of a mined transaction
        // exists on chain, so each of its errors is a fault of the
        // moment (its per-tick budget, a provider outage, a rate
        // limit), whatever class it carries. With a real chain
        // fetcher a decoy is SERVED from chain (one fetch, no failed
        // round trip, no prune), so the prune lives on the peer arm,
        // which is what runs when no fetcher is installed.
        //
        // NOTHING HERE BOUNDS THE DECOYS OF ONE PARENT. The manager's
        // list has no cap, and each definite decoy is one sequential
        // failed round trip inside the per-peer sync budget. A parent
        // with enough of them exceeds that budget and the sync is
        // dropped whole; what a dropped sync keeps is bsv-low #552's
        // ground, and a cap on the list is the manager's choice.
        let node = if item.spent_by.is_none() {
            self.fetch_root(item).await?
        } else {
            let Some((txid, oi)) = parse_outpoint(&item.outpoint) else {
                return Ok(StepOut::Pruned);
            };
            self.count_call();
            match &self.ancestor_fetcher {
                // OPT-IN ancestry hydration (off by default). When a
                // fetcher is configured we KNOW the peer cannot serve
                // ancestry — e.g. legacy beta stores minimal BEEFs and
                // returns HTTP 400 "Incomplete SPV data!" for every
                // ancestor — so we SKIP the doomed peer round-trip
                // entirely and fetch the ancestor's raw tx from chain
                // directly. Asking the peer first would cost one
                // sequential request per ancestor (the ~90-deep
                // user_registry chain → ~90 round-trips), enough to
                // exhaust a worker invocation before the graph finalizes.
                //
                // The fetcher returns the ancestor's rawtx and, when it
                // is mined, its BUMP proof. A proven node ends the walk
                // UNLESS its topic manager names inputs. Empty managers
                // still stop at the first proven layer; managers needing
                // history select their ancestors through this same
                // fetcher. Without a proof, every input is requested
                // as before.
                // The transaction DAG (no cycles), `seen` keyed by
                // `txid.outputIndex`, the already-known strip, and the
                // manager naming nothing at genesis bound the walk.
                // There is no node cap, matching the reference's
                // undefined `maxNodesInGraph` in `Engine.startGASPSync`.
                // A per-peer budget drops the sync future at its
                // deadline: graphs finalized before it stay admitted
                // (bsv-low #552), the graph in flight is lost whole,
                // and ONE graph whose own walk outlasts the budget
                // never completes unless a per-graph budget defers and
                // resumes it (bsv-low #555).
                //
                // Every fetcher error fails the UTXO (the `?`):
                // the fetcher arm never prunes, see the rule above.
                Some(fetcher) => {
                    let ancestor = fetcher.fetch_ancestor(&txid).await?;
                    let node = GASPNode {
                        graph_id: item.graph_id.clone(),
                        raw_tx: ancestor.raw_tx,
                        output_index: oi,
                        proof: ancestor.proof,
                        tx_metadata: None,
                        output_metadata: None,
                        inputs: None,
                    };
                    self.count_fetched(&node);
                    node
                }
                // Default / production: no fetcher → ask the peer.
                None => match self
                    .remote
                    .request_node(&item.graph_id, &txid, oi, item.metadata)
                    .await
                {
                    Ok(child_node) => {
                        self.count_fetched(&child_node);
                        child_node
                    }
                    // Proven parent and a DEFINITE "not held": the D8 prune
                    // (see the rule above).
                    Err(e @ GASPError::NodeNotFound(_)) if item.parent_proven => {
                        warn!(
                            "{} Pruned input {} named by proven node {}: the peer does not hold it: {}",
                            self.log_prefix,
                            item.outpoint,
                            item.spent_by.as_deref().unwrap_or_default(),
                            e
                        );
                        if self.pruned.borrow_mut().insert(item.outpoint.clone()) {
                            self.pruned_inputs.set(self.pruned_inputs.get() + 1);
                        }
                        return Ok(StepOut::Pruned);
                    }
                    // Any other error, and every error under an unproven
                    // parent: propagate, as the reference does.
                    Err(e) => return Err(e),
                },
            }
        };
        self.absorb(item, node).await
    }

    /// The node of `item`, fetched: append it to the graph and name its
    /// needed inputs.
    async fn absorb(&self, item: &PendingInput, node: GASPNode) -> Result<StepOut, GASPError> {
        // Key by the node's own TXID (computed from raw_tx), NOT graph_id (which
        // is constant across a whole graph) and NOT the raw_tx hex. Mirrors TS
        // @bsv/gasp processIncomingNode: nodeId = `${computeTXID(rawTx)}.${oi}`
        // (GASP.js:319) and spentBy = compute36ByteStructure(computeTXID(rawTx), oi)
        // (GASP.js:335). Matches the append-side key in gasp_overlay.rs
        // (Transaction::from_hex(raw_tx).id()). Using graph_id/raw_tx here orphaned
        // every child node → multi-node graphs never assembled → stranded sync.
        let node_txid = match bsv_rs::transaction::Transaction::from_hex(&node.raw_tx) {
            Ok(tx) => tx.id(),
            Err(_) => node.raw_tx[..node.raw_tx.len().min(64)].to_string(),
        };
        let node_id = format!("{}.{}", node_txid, node.output_index);
        if self
            .walk
            .borrow()
            .as_ref()
            .is_some_and(|w| w.seen.contains(&node_id))
        {
            return Ok(StepOut::Seen);
        }

        self.storage
            .append_to_graph(&node, item.spent_by.as_deref())
            .await?;

        let mut children = Vec::new();
        if let Some(needed) = self.storage.find_needed_inputs(&node).await? {
            let parent_proven = node.proof.is_some();
            for (outpoint, input_req) in &needed.requested_inputs {
                if parse_outpoint(outpoint).is_some() {
                    children.push(PendingInput {
                        outpoint: outpoint.clone(),
                        graph_id: node.graph_id.clone(),
                        metadata: input_req.metadata,
                        spent_by: Some(node_id.clone()),
                        parent_proven,
                    });
                }
            }
        }
        Ok(StepOut::Appended {
            node_id,
            walked: Box::new(WalkedNode {
                node,
                spent_by: item.spent_by.clone(),
            }),
            children,
        })
    }

    /// Process an outgoing node: submit to remote, then recursively send requested inputs.
    fn process_outgoing_node<'b>(
        &'b self,
        node: &'b GASPNode,
        seen: &'b mut std::collections::HashSet<String>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), GASPError>> + 'b>> {
        Box::pin(async move {
            if self.unidirectional {
                return Ok(());
            }

            let node_id = format!("{}.{}", node.graph_id, node.output_index);
            if seen.contains(&node_id) {
                return Ok(());
            }
            seen.insert(node_id);

            if let Some(response) = self.remote.submit_node(node).await? {
                for (outpoint, input_req) in &response.requested_inputs {
                    if let Some((txid, oi)) = parse_outpoint(outpoint) {
                        match self
                            .storage
                            .hydrate_gasp_node(&node.graph_id, &txid, oi, input_req.metadata)
                            .await
                        {
                            Ok(hydrated) => {
                                self.process_outgoing_node(&hydrated, seen).await?;
                            }
                            Err(e) => {
                                error!("{} Error hydrating outgoing node: {}", self.log_prefix, e);
                                return Ok(()); // Stop this branch, remote will discard
                            }
                        }
                    }
                }
            }

            Ok(())
        })
    }

    /// Validate and finalize a completed graph, or discard on failure.
    /// `Ok(true)`: finalized; `Ok(false)`: refused by the anchor check and
    /// discarded (a verdict: the cursor moves past it).
    async fn complete_graph(&self, graph_id: &str) -> Result<bool, GASPError> {
        info!("{} Completing graph: {}", self.log_prefix, graph_id);
        match self.storage.validate_graph_anchor(graph_id).await {
            Ok(()) => {
                self.storage.finalize_graph(graph_id).await?;
                info!("{} Graph finalized: {}", self.log_prefix, graph_id);
                Ok(true)
            }
            Err(e) => {
                warn!(
                    "{} Graph validation failed for {}: {}. Discarding.",
                    self.log_prefix, graph_id, e
                );
                self.storage.discard_graph(graph_id).await?;
                // The anchor could not be checked (a tracker outage, a
                // storage fault, a topic manager that answered the replay
                // with an error): no verdict. Fail the UTXO so the gap guard
                // re-requests it, instead of advancing the cursor past a
                // graph nobody judged (a divergence by addition, bsv-low
                // #551: the reference discards and moves on either way).
                if matches!(e, GASPError::AnchorUnavailable(_)) {
                    return Err(e);
                }
                // A walk past the budget: held the same way, counted apart
                // (the E592 lens fold, H1 and L3).
                if matches!(e, GASPError::AnchorWalkHeld(_)) {
                    self.anchor_walk_held.set(self.anchor_walk_held.get() + 1);
                    return Err(e);
                }
                self.discarded_graphs.set(self.discarded_graphs.get() + 1);
                Ok(false)
            }
        }
    }
}

/// Parse "txid.outputIndex" into components.
pub fn parse_outpoint(s: &str) -> Option<(String, u32)> {
    let parts: Vec<&str> = s.splitn(2, '.').collect();
    if parts.len() != 2 {
        return None;
    }
    let oi = parts[1].parse::<u32>().ok()?;
    Some((parts[0].to_string(), oi))
}

// ============================================================================
// Error type
// ============================================================================

/// GASP protocol errors.
#[derive(Debug, thiserror::Error)]
pub enum GASPError {
    /// Version mismatch between peers.
    #[error("version mismatch: local={local}, remote={remote}")]
    VersionMismatch { local: u32, remote: u32 },

    /// Invalid timestamp format.
    #[error("invalid timestamp: {0}")]
    InvalidTimestamp(String),

    /// Node not found.
    #[error("node not found: {0}")]
    NodeNotFound(String),

    /// Graph validation failed.
    #[error("graph validation failed: {0}")]
    ValidationFailed(String),

    /// Network/communication error.
    #[error("remote error: {0}")]
    RemoteError(String),

    /// Storage error.
    #[error("storage error: {0}")]
    StorageError(String),

    /// A graph's anchor could not be CHECKED right now (the chain tracker or
    /// a storage read faulted, or the topic manager answered the replay with
    /// an error): a fault of the moment, not a verdict on the graph. `GASPSync::complete_graph` discards the graph and fails the
    /// UTXO, so the cursor gap guard asks for it again (bsv-low #551).
    #[error("anchor unavailable: {0}")]
    AnchorUnavailable(String),

    /// The anchor's script walk could not run within the engine's walk
    /// budget (bsv-low #592; the E592 lens fold, H1): no verdict, and
    /// nothing stands in for one (no network accepted these bytes). Held
    /// exactly as [`GASPError::AnchorUnavailable`] holds: the graph is not
    /// finalized, the UTXO fails and the cursor stays below it, until the
    /// peer serves its root PROVEN (#555's `root_proven` restart, whose walk
    /// trusts the proof and runs no script). Counted apart
    /// (`GASPSync::anchor_walk_held`).
    #[error("anchor walk held: {0}")]
    AnchorWalkHeld(String),

    /// Generic error.
    #[error("{0}")]
    Other(String),
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::Mutex;

    // ── race_or_deadline (bsv-low#257/#302, generalized here) ──────────

    #[tokio::test]
    async fn race_or_deadline_future_wins() {
        let out = race_or_deadline(async { 42u32 }, std::future::pending::<()>()).await;
        assert_eq!(out, Some(42));
    }

    #[tokio::test]
    async fn race_or_deadline_deadline_wins() {
        let out = race_or_deadline(std::future::pending::<u32>(), async {}).await;
        assert_eq!(out, None);
    }

    // The lens fold's HIGH-1: a deadline that falls due inside a write
    // section waits for the section to close, then drops the future at its
    // next pending point; the writer that asks at the boundary stops there.
    #[tokio::test]
    async fn guarded_race_never_drops_inside_a_write_section() {
        let gate = SubmitGate::default();
        let written = std::cell::Cell::new(0u32);
        let out = race_or_deadline_guarded(
            async {
                for _ in 0..3 {
                    gate.stop_if_due().await;
                    let _section = gate.write_section();
                    // Two writes of one transaction, each a round trip.
                    tokio::task::yield_now().await;
                    written.set(written.get() + 1);
                    tokio::task::yield_now().await;
                    written.set(written.get() + 1);
                }
            },
            async {},
            &gate,
        )
        .await;
        assert_eq!(out, None, "the deadline still wins");
        assert_eq!(written.get(), 2, "one transaction, whole, and no second");
        assert!(
            !gate.deadline_is_due(),
            "the flag does not outlive the race"
        );

        // With no section open it is `race_or_deadline`.
        let out = race_or_deadline_guarded(std::future::pending::<u8>(), async {}, &gate).await;
        assert_eq!(out, None);
        let out = race_or_deadline_guarded(async { 7u8 }, std::future::pending(), &gate).await;
        assert_eq!(out, Some(7));
        // A future that finishes inside its section after the deadline wins.
        let out = race_or_deadline_guarded(
            async {
                let _section = gate.write_section();
                tokio::task::yield_now().await;
                7u8
            },
            async {},
            &gate,
        )
        .await;
        assert_eq!(out, Some(7));
        assert!(!gate.deadline_is_due());
    }

    #[tokio::test]
    async fn race_or_deadline_ready_future_beats_ready_deadline() {
        // The sync future is polled FIRST — an instantly-ready result wins
        // even against an already-expired deadline (a completed sync is
        // never discarded).
        let out = race_or_deadline(async { 7u32 }, async {}).await;
        assert_eq!(out, Some(7));
    }

    // ── peer_sync_quarantined (bsv-low#302 pure rule) ──────────────────

    fn health(fails: u64, age: Option<u64>) -> crate::storage::PeerSyncHealth {
        crate::storage::PeerSyncHealth {
            consecutive_failures: fails,
            secs_since_last_attempt: age,
        }
    }

    #[test]
    fn quarantine_needs_the_full_threshold() {
        assert!(!peer_sync_quarantined(&health(0, Some(0))));
        assert!(!peer_sync_quarantined(&health(
            PEER_QUARANTINE_THRESHOLD - 1,
            Some(0)
        )));
        assert!(peer_sync_quarantined(&health(
            PEER_QUARANTINE_THRESHOLD,
            Some(0)
        )));
        assert!(peer_sync_quarantined(&health(
            PEER_QUARANTINE_THRESHOLD + 100,
            Some(0)
        )));
    }

    #[test]
    fn quarantine_reopens_one_probe_after_the_reprobe_window() {
        let fails = PEER_QUARANTINE_THRESHOLD;
        assert!(peer_sync_quarantined(&health(
            fails,
            Some(PEER_QUARANTINE_REPROBE_SECS - 1)
        )));
        // AT the window boundary the probe re-opens — a quarantined peer is
        // never stranded forever.
        assert!(!peer_sync_quarantined(&health(
            fails,
            Some(PEER_QUARANTINE_REPROBE_SECS)
        )));
    }

    #[test]
    fn never_attempted_peer_is_never_quarantined() {
        // `None` age = pristine peer OR a backend without health tracking —
        // fail-safe: always attempted.
        assert!(!peer_sync_quarantined(&health(u64::MAX, None)));
    }

    // ── Mock GASPStorage ───────────────────────────────────────────────

    struct MockGASPStorage {
        utxos: Vec<GASPOutput>,
        graphs: Mutex<HashMap<String, Vec<GASPNode>>>,
        finalized: Mutex<Vec<String>>,
        discarded: Mutex<Vec<String>>,
    }

    impl MockGASPStorage {
        fn new(utxos: Vec<GASPOutput>) -> Self {
            Self {
                utxos,
                graphs: Mutex::new(HashMap::new()),
                finalized: Mutex::new(Vec::new()),
                discarded: Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait(?Send)]
    impl GASPStorage for MockGASPStorage {
        // Keeps no deferred graphs (bsv-low #555): never given a per-graph budget.
        async fn load_deferred_graphs(
            &self,
        ) -> Result<Vec<crate::gasp::DeferredGraphKey>, GASPError> {
            Ok(Vec::new())
        }
        async fn get_deferred_graph(
            &self,
            _: &str,
        ) -> Result<Option<crate::gasp::DeferredGraph>, GASPError> {
            Ok(None)
        }
        async fn save_deferred_graph(
            &self,
            _: &crate::gasp::DeferredGraph,
        ) -> Result<crate::gasp::DeferredGraphSave, GASPError> {
            Err(GASPError::StorageError("keeps no deferred graphs".into()))
        }
        async fn delete_deferred_graph(&self, _: &str) -> Result<(), GASPError> {
            Ok(())
        }
        async fn find_known_utxos(
            &self,
            since: u64,
            _limit: Option<u64>,
        ) -> Result<Vec<GASPOutput>, GASPError> {
            Ok(self
                .utxos
                .iter()
                .filter(|u| u.score as u64 >= since)
                .cloned()
                .collect())
        }

        async fn hydrate_gasp_node(
            &self,
            graph_id: &str,
            txid: &str,
            output_index: u32,
            _metadata: bool,
        ) -> Result<GASPNode, GASPError> {
            Ok(GASPNode {
                graph_id: graph_id.to_string(),
                raw_tx: format!("rawtx_{txid}"),
                output_index,
                proof: None,
                tx_metadata: None,
                output_metadata: None,
                inputs: None,
            })
        }

        async fn find_needed_inputs(
            &self,
            _node: &GASPNode,
        ) -> Result<Option<GASPNodeResponse>, GASPError> {
            Ok(None) // No inputs needed for simple tests
        }

        async fn append_to_graph(
            &self,
            node: &GASPNode,
            _spent_by: Option<&str>,
        ) -> Result<(), GASPError> {
            self.graphs
                .lock()
                .unwrap()
                .entry(node.graph_id.clone())
                .or_default()
                .push(node.clone());
            Ok(())
        }

        async fn validate_graph_anchor(&self, _graph_id: &str) -> Result<(), GASPError> {
            Ok(())
        }

        async fn finalize_graph(&self, graph_id: &str) -> Result<(), GASPError> {
            self.finalized.lock().unwrap().push(graph_id.to_string());
            Ok(())
        }

        async fn discard_graph(&self, graph_id: &str) -> Result<(), GASPError> {
            self.discarded.lock().unwrap().push(graph_id.to_string());
            Ok(())
        }
    }

    // ── Mock GASPRemote ────────────────────────────────────────────────

    struct MockGASPRemote {
        remote_utxos: Vec<GASPOutput>,
        submitted: Mutex<Vec<GASPNode>>,
    }

    impl MockGASPRemote {
        fn new(utxos: Vec<GASPOutput>) -> Self {
            Self {
                remote_utxos: utxos,
                submitted: Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait(?Send)]
    impl GASPRemote for MockGASPRemote {
        async fn get_initial_response(
            &self,
            request: &GASPInitialRequest,
        ) -> Result<GASPInitialResponse, GASPError> {
            if request.version != GASP_VERSION {
                return Err(GASPError::VersionMismatch {
                    local: GASP_VERSION,
                    remote: request.version,
                });
            }
            let utxos: Vec<GASPOutput> = self
                .remote_utxos
                .iter()
                .filter(|u| u.score as u64 >= request.since)
                .cloned()
                .collect();
            Ok(GASPInitialResponse {
                utxo_list: utxos,
                since: request.since,
            })
        }

        async fn get_initial_reply(
            &self,
            _response: &GASPInitialResponse,
        ) -> Result<GASPInitialReply, GASPError> {
            Ok(GASPInitialReply {
                utxo_list: Vec::new(),
            })
        }

        async fn request_node(
            &self,
            graph_id: &str,
            txid: &str,
            output_index: u32,
            _metadata: bool,
        ) -> Result<GASPNode, GASPError> {
            Ok(GASPNode {
                graph_id: graph_id.to_string(),
                raw_tx: format!("remote_rawtx_{txid}"),
                output_index,
                proof: Some("proof_hex".to_string()),
                tx_metadata: None,
                output_metadata: None,
                inputs: None,
            })
        }

        async fn submit_node(
            &self,
            node: &GASPNode,
        ) -> Result<Option<GASPNodeResponse>, GASPError> {
            self.submitted.lock().unwrap().push(node.clone());
            Ok(None) // No further inputs needed
        }
    }

    // ── Tests ──────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_sync_pulls_remote_utxos() {
        let local_storage = MockGASPStorage::new(vec![]);
        let remote = MockGASPRemote::new(vec![
            GASPOutput {
                txid: "tx1".to_string(),
                output_index: 0,
                score: 100.0,
            },
            GASPOutput {
                txid: "tx2".to_string(),
                output_index: 0,
                score: 200.0,
            },
        ]);

        let mut gasp = GASPSync::new(
            Box::new(local_storage),
            Box::new(remote),
            0,
            "[TEST]",
            false,
        );

        gasp.sync(None).await.unwrap();

        assert_eq!(gasp.last_interaction, 200);
    }

    #[tokio::test]
    async fn test_sync_skips_known_utxos() {
        let local_storage = MockGASPStorage::new(vec![GASPOutput {
            txid: "tx1".to_string(),
            output_index: 0,
            score: 100.0,
        }]);
        let remote = MockGASPRemote::new(vec![
            GASPOutput {
                txid: "tx1".to_string(),
                output_index: 0,
                score: 100.0,
            },
            GASPOutput {
                txid: "tx2".to_string(),
                output_index: 0,
                score: 200.0,
            },
        ]);

        let mut gasp = GASPSync::new(
            Box::new(local_storage),
            Box::new(remote),
            0,
            "[TEST]",
            true, // unidirectional — skip push
        );

        gasp.sync(None).await.unwrap();

        // Only tx2 should have been ingested (tx1 was already known)
        // last_interaction should be 200
        assert_eq!(gasp.last_interaction, 200);
    }

    #[tokio::test]
    async fn test_sync_unidirectional_skips_push() {
        let local_storage = MockGASPStorage::new(vec![GASPOutput {
            txid: "local_only".to_string(),
            output_index: 0,
            score: 50.0,
        }]);
        let remote = MockGASPRemote::new(vec![]);

        let mut gasp = GASPSync::new(Box::new(local_storage), Box::new(remote), 0, "[TEST]", true);

        gasp.sync(None).await.unwrap();
        // In unidirectional mode, local_only should NOT be pushed to remote
        // (no way to check directly with current mock, but no error = success)
    }

    #[tokio::test]
    async fn test_complete_graph_finalizes_on_valid() {
        let storage = MockGASPStorage::new(vec![]);
        let remote = MockGASPRemote::new(vec![]);

        let gasp = GASPSync::new(Box::new(storage), Box::new(remote), 0, "[TEST]", false);

        gasp.complete_graph("test_graph.0").await.unwrap();
        // Storage mock always validates OK, so graph should be finalized
    }

    #[tokio::test]
    async fn test_complete_graph_discards_on_invalid() {
        struct FailValidationStorage;

        #[async_trait(?Send)]
        impl GASPStorage for FailValidationStorage {
            // Keeps no deferred graphs (bsv-low #555): never given a per-graph budget.
            async fn load_deferred_graphs(
                &self,
            ) -> Result<Vec<crate::gasp::DeferredGraphKey>, GASPError> {
                Ok(Vec::new())
            }
            async fn get_deferred_graph(
                &self,
                _: &str,
            ) -> Result<Option<crate::gasp::DeferredGraph>, GASPError> {
                Ok(None)
            }
            async fn save_deferred_graph(
                &self,
                _: &crate::gasp::DeferredGraph,
            ) -> Result<crate::gasp::DeferredGraphSave, GASPError> {
                Err(GASPError::StorageError("keeps no deferred graphs".into()))
            }
            async fn delete_deferred_graph(&self, _: &str) -> Result<(), GASPError> {
                Ok(())
            }
            async fn find_known_utxos(
                &self,
                _: u64,
                _: Option<u64>,
            ) -> Result<Vec<GASPOutput>, GASPError> {
                Ok(vec![])
            }
            async fn hydrate_gasp_node(
                &self,
                _: &str,
                _: &str,
                _: u32,
                _: bool,
            ) -> Result<GASPNode, GASPError> {
                unreachable!()
            }
            async fn find_needed_inputs(
                &self,
                _: &GASPNode,
            ) -> Result<Option<GASPNodeResponse>, GASPError> {
                Ok(None)
            }
            async fn append_to_graph(
                &self,
                _: &GASPNode,
                _: Option<&str>,
            ) -> Result<(), GASPError> {
                Ok(())
            }
            async fn validate_graph_anchor(&self, _: &str) -> Result<(), GASPError> {
                Err(GASPError::ValidationFailed("bad anchor".into()))
            }
            async fn finalize_graph(&self, _: &str) -> Result<(), GASPError> {
                panic!("should not finalize")
            }
            async fn discard_graph(&self, _: &str) -> Result<(), GASPError> {
                Ok(())
            }
        }

        let gasp = GASPSync::new(
            Box::new(FailValidationStorage),
            Box::new(MockGASPRemote::new(vec![])),
            0,
            "[TEST]",
            false,
        );

        // Should not error — discards instead of finalizing
        gasp.complete_graph("bad_graph.0").await.unwrap();
    }

    // ── AncestorFetcher fallback tests ─────────────────────────────────

    /// Build a minimal valid tx hex with one input referencing `source_txid`.
    fn make_tx_hex(source_txid: &str, source_oi: u32) -> String {
        let mut tx = bsv_rs::transaction::Transaction::new();
        tx.inputs.push(bsv_rs::transaction::TransactionInput::new(
            source_txid.to_string(),
            source_oi,
        ));
        tx.outputs.push(bsv_rs::transaction::TransactionOutput::new(
            100,
            bsv_rs::script::LockingScript::from_hex(
                "76a914000000000000000000000000000000000000000088ac",
            )
            .unwrap(),
        ));
        tx.to_hex()
    }

    /// Storage that records appended nodes and requests exactly one ancestor
    /// (the first input) on the FIRST node it sees, then nothing further.
    struct RecordingStorage {
        appended: Mutex<Vec<GASPNode>>,
        request_once: Mutex<bool>,
        ancestor_outpoint: String,
    }

    #[async_trait(?Send)]
    impl GASPStorage for RecordingStorage {
        // Keeps no deferred graphs (bsv-low #555): never given a per-graph budget.
        async fn load_deferred_graphs(
            &self,
        ) -> Result<Vec<crate::gasp::DeferredGraphKey>, GASPError> {
            Ok(Vec::new())
        }
        async fn get_deferred_graph(
            &self,
            _: &str,
        ) -> Result<Option<crate::gasp::DeferredGraph>, GASPError> {
            Ok(None)
        }
        async fn save_deferred_graph(
            &self,
            _: &crate::gasp::DeferredGraph,
        ) -> Result<crate::gasp::DeferredGraphSave, GASPError> {
            Err(GASPError::StorageError("keeps no deferred graphs".into()))
        }
        async fn delete_deferred_graph(&self, _: &str) -> Result<(), GASPError> {
            Ok(())
        }
        async fn find_known_utxos(
            &self,
            _: u64,
            _: Option<u64>,
        ) -> Result<Vec<GASPOutput>, GASPError> {
            Ok(vec![])
        }
        async fn hydrate_gasp_node(
            &self,
            _: &str,
            _: &str,
            _: u32,
            _: bool,
        ) -> Result<GASPNode, GASPError> {
            unreachable!()
        }
        async fn find_needed_inputs(
            &self,
            _: &GASPNode,
        ) -> Result<Option<GASPNodeResponse>, GASPError> {
            let mut once = self.request_once.lock().unwrap();
            if *once {
                *once = false;
                let mut requested_inputs = HashMap::new();
                requested_inputs.insert(
                    self.ancestor_outpoint.clone(),
                    crate::types::GASPInputRequest { metadata: false },
                );
                Ok(Some(GASPNodeResponse { requested_inputs }))
            } else {
                Ok(None)
            }
        }
        async fn append_to_graph(&self, node: &GASPNode, _: Option<&str>) -> Result<(), GASPError> {
            self.appended.lock().unwrap().push(node.clone());
            Ok(())
        }
        async fn validate_graph_anchor(&self, _: &str) -> Result<(), GASPError> {
            Ok(())
        }
        async fn finalize_graph(&self, _: &str) -> Result<(), GASPError> {
            Ok(())
        }
        async fn discard_graph(&self, _: &str) -> Result<(), GASPError> {
            Ok(())
        }
    }

    /// Remote that always errors on `request_node` (mimics beta's HTTP 400
    /// "Incomplete SPV data!").
    struct FailingNodeRemote;

    #[async_trait(?Send)]
    impl GASPRemote for FailingNodeRemote {
        async fn get_initial_response(
            &self,
            _: &GASPInitialRequest,
        ) -> Result<GASPInitialResponse, GASPError> {
            Ok(GASPInitialResponse {
                utxo_list: vec![],
                since: 0,
            })
        }
        async fn get_initial_reply(
            &self,
            _: &GASPInitialResponse,
        ) -> Result<GASPInitialReply, GASPError> {
            Ok(GASPInitialReply { utxo_list: vec![] })
        }
        async fn request_node(
            &self,
            _: &str,
            _: &str,
            _: u32,
            _: bool,
        ) -> Result<GASPNode, GASPError> {
            Err(GASPError::RemoteError(
                "Peer returned HTTP 400: Incomplete SPV data!".to_string(),
            ))
        }
        async fn submit_node(&self, _: &GASPNode) -> Result<Option<GASPNodeResponse>, GASPError> {
            Ok(None)
        }
    }

    /// Mock fetcher that returns a pre-built ancestor rawtx (+ optional proof).
    struct MockFetcher {
        ancestor_hex: String,
        proof: Option<String>,
        called: Mutex<u32>,
    }

    #[async_trait(?Send)]
    impl AncestorFetcher for MockFetcher {
        async fn fetch_ancestor(&self, _txid: &str) -> Result<FetchedAncestor, GASPError> {
            *self.called.lock().unwrap() += 1;
            Ok(FetchedAncestor {
                raw_tx: self.ancestor_hex.clone(),
                proof: self.proof.clone(),
            })
        }
    }

    /// Remote that records how many times `request_node` is invoked (it would
    /// be a doomed peer call on the migration path) so a test can assert the
    /// fetcher path SKIPS the peer entirely.
    struct CountingNodeRemote {
        request_node_calls: std::rc::Rc<Mutex<u32>>,
    }

    #[async_trait(?Send)]
    impl GASPRemote for CountingNodeRemote {
        async fn get_initial_response(
            &self,
            _: &GASPInitialRequest,
        ) -> Result<GASPInitialResponse, GASPError> {
            Ok(GASPInitialResponse {
                utxo_list: vec![],
                since: 0,
            })
        }
        async fn get_initial_reply(
            &self,
            _: &GASPInitialResponse,
        ) -> Result<GASPInitialReply, GASPError> {
            Ok(GASPInitialReply { utxo_list: vec![] })
        }
        async fn request_node(
            &self,
            _: &str,
            _: &str,
            _: u32,
            _: bool,
        ) -> Result<GASPNode, GASPError> {
            *self.request_node_calls.lock().unwrap() += 1;
            Err(GASPError::RemoteError(
                "Peer returned HTTP 400: Incomplete SPV data!".to_string(),
            ))
        }
        async fn submit_node(&self, _: &GASPNode) -> Result<Option<GASPNodeResponse>, GASPError> {
            Ok(None)
        }
    }

    #[tokio::test]
    async fn ancestor_fetcher_none_preserves_peer_error() {
        // Build a tip tx whose input references some ancestor.
        let ancestor_hex = make_tx_hex(
            "1111111111111111111111111111111111111111111111111111111111111111",
            0,
        );
        let ancestor_txid = bsv_rs::transaction::Transaction::from_hex(&ancestor_hex)
            .unwrap()
            .id();
        let tip_hex = make_tx_hex(&ancestor_txid, 0);

        let storage = RecordingStorage {
            appended: Mutex::new(vec![]),
            request_once: Mutex::new(true),
            ancestor_outpoint: format!("{ancestor_txid}.0"),
        };

        // No fetcher configured → default path → peer error must propagate.
        let gasp = GASPSync::new(
            Box::new(storage),
            Box::new(FailingNodeRemote),
            0,
            "[TEST]",
            true,
        );

        let tip_node = GASPNode {
            graph_id: format!("{}.0", "deadbeef"),
            raw_tx: tip_hex,
            output_index: 0,
            proof: None,
            tx_metadata: None,
            output_metadata: None,
            inputs: None,
        };

        let mut seen = std::collections::HashSet::new();
        let result = gasp.process_incoming_node(&tip_node, None, &mut seen).await;
        assert!(
            result.is_err(),
            "with no fetcher, the peer error must propagate (default path unchanged)"
        );
    }

    #[tokio::test]
    async fn ancestor_fetcher_some_self_heals_missing_ancestor() {
        let ancestor_hex = make_tx_hex(
            "2222222222222222222222222222222222222222222222222222222222222222",
            0,
        );
        let ancestor_txid = bsv_rs::transaction::Transaction::from_hex(&ancestor_hex)
            .unwrap()
            .id();
        let tip_hex = make_tx_hex(&ancestor_txid, 0);

        let storage = RecordingStorage {
            appended: Mutex::new(vec![]),
            request_once: Mutex::new(true),
            ancestor_outpoint: format!("{ancestor_txid}.0"),
        };

        let fetcher = std::rc::Rc::new(MockFetcher {
            ancestor_hex: ancestor_hex.clone(),
            proof: None,
            called: Mutex::new(0),
        });

        let gasp = GASPSync::new(
            Box::new(storage),
            Box::new(FailingNodeRemote),
            0,
            "[TEST]",
            true,
        )
        .with_ancestor_fetcher(Some(fetcher.clone()));

        let tip_node = GASPNode {
            graph_id: "deadbeef.0".to_string(),
            raw_tx: tip_hex.clone(),
            output_index: 0,
            proof: None,
            tx_metadata: None,
            output_metadata: None,
            inputs: None,
        };

        let mut seen = std::collections::HashSet::new();
        gasp.process_incoming_node(&tip_node, None, &mut seen)
            .await
            .expect("with fetcher, missing ancestor self-heals from chain");

        assert_eq!(
            *fetcher.called.lock().unwrap(),
            2,
            "fetcher fires twice: once to hydrate the root's OWN proof (mock returns \
             proof:None here, so the root stays proofless + the walk continues), then \
             once to self-heal the missing ancestor (#126 root proof-anchoring)"
        );

        // The synthesized ancestor node must have been appended to the graph,
        // with proof: None so the existing recursion would continue upward.
        // (We can't reach into the boxed storage here, but the Ok(()) above
        // proves the synthesized node flowed through process_incoming_node and
        // append_to_graph without error.)
    }

    #[tokio::test]
    async fn ancestor_fetcher_some_skips_peer_request_node() {
        // Proof of the peer-skip optimization: with a fetcher present, the
        // doomed peer `request_node` call must NOT fire for ancestors — the
        // fetcher is consulted directly. (Otherwise a deep chain pays one
        // sequential peer round-trip per ancestor before falling back.)
        let ancestor_hex = make_tx_hex(
            "3333333333333333333333333333333333333333333333333333333333333333",
            0,
        );
        let ancestor_txid = bsv_rs::transaction::Transaction::from_hex(&ancestor_hex)
            .unwrap()
            .id();
        let tip_hex = make_tx_hex(&ancestor_txid, 0);

        let storage = RecordingStorage {
            appended: Mutex::new(vec![]),
            request_once: Mutex::new(true),
            ancestor_outpoint: format!("{ancestor_txid}.0"),
        };

        let counter = std::rc::Rc::new(Mutex::new(0u32));
        let remote = CountingNodeRemote {
            request_node_calls: counter.clone(),
        };
        let fetcher = std::rc::Rc::new(MockFetcher {
            ancestor_hex: ancestor_hex.clone(),
            proof: None,
            called: Mutex::new(0),
        });

        let gasp = GASPSync::new(Box::new(storage), Box::new(remote), 0, "[TEST]", true)
            .with_ancestor_fetcher(Some(fetcher.clone()));

        let tip_node = GASPNode {
            graph_id: "deadbeef.0".to_string(),
            raw_tx: tip_hex,
            output_index: 0,
            proof: None,
            tx_metadata: None,
            output_metadata: None,
            inputs: None,
        };

        let mut seen = std::collections::HashSet::new();
        gasp.process_incoming_node(&tip_node, None, &mut seen)
            .await
            .expect("self-heal via fetcher should succeed");

        assert_eq!(
            *counter.lock().unwrap(),
            0,
            "peer request_node must be SKIPPED for ancestors when a fetcher is present"
        );
        assert_eq!(
            *fetcher.called.lock().unwrap(),
            2,
            "fetcher fires twice: root's OWN proof hydration (#126) + serving the \
             ancestor directly (peer request_node still skipped)"
        );
    }

    #[test]
    fn test_parse_outpoint() {
        let (txid, oi) = parse_outpoint("abc123.5").unwrap();
        assert_eq!(txid, "abc123");
        assert_eq!(oi, 5);

        assert!(parse_outpoint("no_dot").is_none());
        assert!(parse_outpoint("abc.notanum").is_none());
    }

    #[tokio::test]
    async fn test_gasp_storage_is_object_safe() {
        let storage: Box<dyn GASPStorage> = Box::new(MockGASPStorage::new(vec![]));
        let utxos = storage.find_known_utxos(0, None).await.unwrap();
        assert!(utxos.is_empty());
    }

    #[tokio::test]
    async fn test_gasp_remote_is_object_safe() {
        let remote: Box<dyn GASPRemote> = Box::new(MockGASPRemote::new(vec![]));
        let response = remote
            .get_initial_response(&GASPInitialRequest {
                version: 1,
                since: 0,
                limit: None,
            })
            .await
            .unwrap();
        assert!(response.utxo_list.is_empty());
    }

    #[tokio::test]
    async fn test_version_mismatch_error() {
        let remote = MockGASPRemote::new(vec![]);
        let result = remote
            .get_initial_response(&GASPInitialRequest {
                version: 99,
                since: 0,
                limit: None,
            })
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            GASPError::VersionMismatch { .. }
        ));
    }
}