zingolib 7.0.0

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

use pepper_sync::sync::SHARDTREE_CHECKPOINT_ROLLING_WINDOW_SIZE;
use pepper_sync::wallet::IronwoodNote;
use shardtree::store::ShardStore;
use zcash_address::ZcashAddress;
use zcash_protocol::PoolType;
use zcash_protocol::ShieldedPool;
use zcash_protocol::consensus::BlockHeight;
use zcash_protocol::value::Zatoshis;

use crate::check_client_balances;
use crate::testutils::lightclient::{from_inputs, get_base_address};
use crate::testutils::mock_indexer::{MockNet, faucet_funding_transaction};
use crate::testutils::synthetic_wallet::SyntheticWalletBuilder;
use crate::wallet::error::ProposeSendError;
use crate::wallet::keys::unified::ReceiverSelection;

/// An address belonging to no wallet on the mock net, so sends to it
/// are external.
fn external_address(pool: PoolType) -> String {
    let mut external_wallet =
        SyntheticWalletBuilder::new(zingo_test_vectors::seeds::ABANDON_ART_SEED).build();
    let selection = match pool {
        PoolType::ORCHARD | PoolType::IRONWOOD => ReceiverSelection::orchard_only(),
        PoolType::SAPLING => ReceiverSelection::sapling_only(),
        _ => unimplemented!("only shielded external destinations are needed here"),
    };
    let (_, unified_address) = external_wallet
        .generate_unified_address(selection, zip32::AccountId::ZERO)
        .unwrap();
    unified_address.encode(&external_wallet.chain_type())
}

/// Returns a TEX-encoded taddr from an external wallet.
fn external_tex_address() -> String {
    use pepper_sync::keys::decode_address;
    use zcash_client_backend::address::Address;
    use zcash_transparent::address::TransparentAddress;

    let external_wallet =
        SyntheticWalletBuilder::new(zingo_test_vectors::seeds::ABANDON_ART_SEED).build();
    let taddr = external_wallet
        .transparent_addresses()
        .values()
        .next()
        .unwrap()
        .clone();
    let Address::Transparent(TransparentAddress::PublicKeyHash(taddr_bytes)) =
        decode_address(&external_wallet.chain_type(), &taddr).unwrap()
    else {
        panic!("a wallet-generated first taddr is p2pkh")
    };
    crate::testutils::interpret_taddr_as_tex_addr(taddr_bytes, &external_wallet.chain_type())
}

/// Mines one empty block, one funding block, and `extra_blocks` into every
/// chain in `nets`.
async fn fund_mirrored(
    nets: &[&MockNet],
    receivers: Vec<(&str, u64, Option<&str>)>,
    extra_blocks: u32,
) {
    let funding = faucet_funding_transaction(receivers).await;
    for net in nets {
        let mut chain = net.chain.write().await;
        chain.mine_empty_blocks(1);
        chain.mine_block(vec![funding.clone()]);
        chain.mine_empty_blocks(extra_blocks);
    }
}

/// Funds `client` with one faucet-built transaction mined into the next
/// mock block, followed by `extra_blocks` empty blocks.
async fn fund(net: &MockNet, receivers: Vec<(&str, u64, Option<&str>)>, extra_blocks: u32) {
    let funding = faucet_funding_transaction(receivers).await;
    let mut chain = net.chain.write().await;
    chain.mine_block(vec![funding]);
    chain.mine_empty_blocks(extra_blocks);
}

/// The mock-net proof: a funding block scans to a confirmed balance,
/// a real quick_send round-trips through the mock's mempool into the
/// next block, and the post-confirmation balance carries the exact
/// ZIP-317 arithmetic.
#[tokio::test]
async fn funded_send_confirms_on_the_mock_chain() {
    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let recipient_ua =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;

    recipient.sync_and_await().await.unwrap();
    check_client_balances!(recipient, i: 100_000 o: 0 s: 0 t: 0);

    from_inputs::quick_send(
        &mut recipient,
        vec![(&external_address(PoolType::ORCHARD), 20_000, None)],
    )
    .await
    .unwrap();
    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();

    // 100_000 funding minus the 20_000 payment and its 10_000 one-orchard-
    // spend, two-logical-action ZIP-317 fee.
    check_client_balances!(recipient, i: 70_000 o: 0 s: 0 t: 0);
}

/// Tests that max_send_value() returns a non-zero value for a wallet
/// with funds.
#[tokio::test]
async fn max_send_value_to_tex_empties_the_wallet() {
    let funding = 100_000;
    let mut net = MockNet::launch().await;
    let mut sender = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let sender_ua = get_base_address(&sender, PoolType::Shielded(ShieldedPool::Orchard)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(&net, vec![(&sender_ua, funding, None)], 1).await;
    sender.sync_and_await().await.unwrap();
    check_client_balances!(sender, i: funding o: 0 s: 0 t: 0);

    let tex_address = external_tex_address();
    let max_send_value = sender
        .max_send_value(
            ZcashAddress::try_from_encoded(&tex_address).unwrap(),
            zip32::AccountId::ZERO,
        )
        .await
        .unwrap();
    assert!(
        max_send_value > Zatoshis::ZERO,
        "a funded wallet can send to a TEX address"
    );

    from_inputs::quick_send(
        &mut sender,
        vec![(&tex_address, max_send_value.into_u64(), None)],
    )
    .await
    .unwrap();
    net.chain.write().await.mine_mempool();
    sender.sync_and_await().await.unwrap();

    check_client_balances!(sender, i: 0 o: 0 s: 0 t: 0);
}

#[tokio::test]
async fn max_send_value_to_shielded_empties_the_wallet() {
    let ironwood_funding = 100_000;
    let sapling_funding = 50_000;
    let mut net = MockNet::launch().await;
    let mut sender = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let sender_ua = get_base_address(&sender, PoolType::Shielded(ShieldedPool::Orchard)).await;
    let sender_sapling = get_base_address(&sender, PoolType::Shielded(ShieldedPool::Sapling)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(
        &net,
        vec![
            (&sender_ua, ironwood_funding, None),
            (&sender_sapling, sapling_funding, None),
        ],
        1,
    )
    .await;
    sender.sync_and_await().await.unwrap();
    check_client_balances!(sender, i: ironwood_funding o: 0 s: sapling_funding t: 0);

    let recipient = external_address(PoolType::ORCHARD);
    let max_send_value = sender
        .max_send_value(
            ZcashAddress::try_from_encoded(&recipient).unwrap(),
            zip32::AccountId::ZERO,
        )
        .await
        .unwrap();
    assert!(
        max_send_value > Zatoshis::ZERO,
        "a funded wallet can send to a shielded address"
    );

    let one_zat = Zatoshis::const_from_u64(1);
    let past_max = (max_send_value + one_zat).unwrap();
    assert!(matches!(
        from_inputs::propose(&mut sender, vec![(&recipient, past_max.into_u64(), None)]).await,
        Err(ProposeSendError::Proposal(
            zcash_client_backend::data_api::error::Error::InsufficientFunds { .. }
        ))
    ));

    from_inputs::quick_send(
        &mut sender,
        vec![(&recipient, max_send_value.into_u64(), None)],
    )
    .await
    .unwrap();
    net.chain.write().await.mine_mempool();
    sender.sync_and_await().await.unwrap();

    check_client_balances!(sender, i: 0 o: 0 s: 0 t: 0);
}

/// Mock-chain twin of libtonode `slow::list_value_transfers_check_fees`
/// (live original kept as the control): a two-output cross-pool send to
/// the wallet's own transparent and sapling addresses costs the exact
/// composite ZIP-317 fee: 5_000 for the transparent output, 10_000 for
/// the orchard bundle view carrying the ironwood spend, 10_000 for the
/// sapling output pair, 10_000 for the ironwood change pair (ADR
/// 0007). Every pool balance lands where the arithmetic says. The
/// self-receipts arrive through real scanning of the mock blocks.
#[tokio::test]
async fn list_value_transfers_check_fees() {
    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let recipient_ua =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
    let recipient_taddr = get_base_address(&recipient, PoolType::Transparent).await;
    let recipient_sapling =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Sapling)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;
    recipient.sync_and_await().await.unwrap();
    check_client_balances!(recipient, i: 100_000 o: 0 s: 0 t: 0);

    from_inputs::quick_send(
        &mut recipient,
        vec![
            (recipient_taddr.as_str(), 30_000, None),
            (recipient_sapling.as_str(), 30_000, None),
        ],
    )
    .await
    .unwrap();
    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();

    // 100_000 − 30_000 − 30_000 − 25_000 fee = 15_000 orchard change.
    check_client_balances!(recipient, i: 15_000 o: 0 s: 30_000 t: 30_000);
}

/// Mock-chain twin of libtonode
/// `slow::self_send_to_t_displays_as_one_transaction` (live original
/// kept as the control): mixed self-sends to the wallet's own
/// transparent, sapling, and orchard addresses (plus an incoming
/// mixed send mined in the same block) must each surface as ONE
/// transaction, so every transaction-summary txid is unique.
#[tokio::test]
async fn self_send_to_t_displays_as_one_transaction() {
    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let recipient_ua =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
    let recipient_taddr = get_base_address(&recipient, PoolType::Transparent).await;
    let recipient_zaddr =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Sapling)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(&net, vec![(&recipient_ua, 80_000, None)], 0).await;
    recipient.sync_and_await().await.unwrap();

    let sent_to_taddr_value = 5_000;
    let sent_to_zaddr_value = 11_000;
    let sent_to_self_orchard_value = 1_000;
    from_inputs::quick_send(
        &mut recipient,
        vec![(recipient_taddr.as_str(), sent_to_taddr_value, None)],
    )
    .await
    .unwrap();
    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();

    // The recipient's own mixed self-send and an incoming mixed send,
    // mined into the same block as on the live chain.
    from_inputs::quick_send(
        &mut recipient,
        vec![
            (recipient_taddr.as_str(), sent_to_taddr_value, None),
            (recipient_zaddr.as_str(), sent_to_zaddr_value, Some("foo")),
            (
                recipient_ua.as_str(),
                sent_to_self_orchard_value,
                Some("bar"),
            ),
        ],
    )
    .await
    .unwrap();
    let incoming = faucet_funding_transaction(vec![
        (recipient_taddr.as_str(), sent_to_taddr_value, None),
        (recipient_zaddr.as_str(), sent_to_zaddr_value, Some("foo2")),
        (
            recipient_ua.as_str(),
            sent_to_self_orchard_value,
            Some("bar2"),
        ),
    ])
    .await;
    {
        let mut chain = net.chain.write().await;
        chain.enter_mempool(incoming);
        chain.mine_mempool();
    }
    recipient.sync_and_await().await.unwrap();

    let txids: Vec<_> = recipient
        .transaction_summaries(false)
        .await
        .unwrap()
        .iter()
        .map(|summary| summary.txid)
        .collect();
    let unique: std::collections::HashSet<_> = txids.iter().collect();
    assert_eq!(
        unique.len(),
        txids.len(),
        "every self-send surfaces as exactly one transaction"
    );
}

/// Mock-chain twin of libtonode
/// `slow::send_to_transparent_and_sapling_maintain_balance` (live
/// original kept as the control): full transaction-summary pinning
/// across funding waves, cross-pool sends, and the
/// Transmitted-to-Confirmed transition of an unmined send.
///
/// One deliberate divergence from the live literals: the second
/// funding wave's fee is Some(10_000) here, not the live Some(20_000).
/// That fee belongs to the FAUCET's economics (its live note pool is
/// fragmented by earlier waves. The mock faucet is fresh each wave) and
/// says nothing about the recipient behavior this test protects.
#[tokio::test]
async fn send_to_transparent_and_sapling_maintain_balance() {
    use zcash_protocol::consensus::BlockHeight;
    use zingo_status::confirmation_status::ConfirmationStatus;
    use zingo_test_vectors::TEST_TXID;

    use crate::testutils::{
        assert_transaction_summary_equality, assert_transaction_summary_exists,
    };
    use crate::utils::conversion::txid_from_hex_encoded_str;
    use crate::wallet::output::SpendStatus;
    use crate::wallet::summary::data::Scope as SummaryScope;
    use crate::wallet::summary::data::{
        BasicNoteSummary, OutgoingNoteSummary, SendType, TransactionKind, TransactionSummary,
    };

    let recipient_initial_funds = 100_000_000;
    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let recipient_ua = get_base_address(&recipient, PoolType::IRONWOOD).await;
    // The external destinations: the abandon-art wallet's sapling UA and
    // first taddr, the same derivations the live faucet answers with.
    let external_sapling = external_address(PoolType::SAPLING);
    let external_taddr = {
        let external_wallet =
            SyntheticWalletBuilder::new(zingo_test_vectors::seeds::ABANDON_ART_SEED).build();
        external_wallet
            .transparent_addresses()
            .values()
            .next()
            .unwrap()
            .clone()
    };

    // Funding at height 2, as in the live layout (one empty launch block).
    net.chain.write().await.mine_empty_blocks(1);
    fund(
        &net,
        vec![(&recipient_ua, recipient_initial_funds, None)],
        0,
    )
    .await;
    recipient.sync_and_await().await.unwrap();

    let placeholder_txid = txid_from_hex_encoded_str(TEST_TXID).unwrap();
    let summary_orchard_receipt = TransactionSummary {
        txid: placeholder_txid,
        datetime: 0,
        status: ConfirmationStatus::Confirmed(BlockHeight::from_u32(2)),
        blockheight: BlockHeight::from_u32(2),
        kind: TransactionKind::Received,
        value: recipient_initial_funds,
        fee: Some(10_000),
        zec_price: None,
        pools_sent_from: vec![],
        ironwood_notes: vec![BasicNoteSummary::from_parts(
            recipient_initial_funds,
            SpendStatus::Spent(placeholder_txid),
            0,
            None,
        )],
        orchard_notes: vec![],
        sapling_notes: vec![],
        transparent_coins: vec![],
        outgoing_ironwood_notes: vec![],
        outgoing_orchard_notes: vec![],
        outgoing_sapling_notes: vec![],
        outgoing_transparent_coins: vec![],
    };

    // Send to external sapling, mined at height 3.
    let first_send_to_sapling = 20_000;
    from_inputs::quick_send(
        &mut recipient,
        vec![(&external_sapling, first_send_to_sapling, None)],
    )
    .await
    .unwrap();
    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();
    let summary_external_sapling = TransactionSummary {
        txid: placeholder_txid,
        datetime: 0,
        status: ConfirmationStatus::Confirmed(BlockHeight::from_u32(3)),
        blockheight: BlockHeight::from_u32(3),
        kind: TransactionKind::Sent(SendType::Send),
        value: first_send_to_sapling,
        fee: Some(20_000),
        zec_price: None,
        pools_sent_from: vec![PoolType::IRONWOOD],
        ironwood_notes: vec![BasicNoteSummary::from_parts(
            99_960_000,
            SpendStatus::TransmittedSpent(placeholder_txid),
            0,
            None,
        )],
        orchard_notes: vec![],
        sapling_notes: vec![],
        transparent_coins: vec![],
        outgoing_ironwood_notes: vec![],
        outgoing_orchard_notes: vec![],
        outgoing_sapling_notes: vec![OutgoingNoteSummary {
            output_index: 0,
            value: first_send_to_sapling,
            memo: None,
            recipient: "zregtestsapling1sa4rckrf4zs6ny3l3ljnezupacvxfnjjn90lpeaa4ddtjeyww2ypzqr3jxfsta3t8dn3jk8cm4f".to_string(),
            recipient_unified_address: Some("uregtest183rtm3qhxxermx3nxwa706va0xnypt3td648tayetchlp28hue08vrcnwq02ryyk5rh3y0xhftay8a5ynjdg8kr3juq5x0d9ygd5ffht".to_string()),
            account_id: zip32::AccountId::ZERO,
            scope: SummaryScope::from(zip32::Scope::External),
        }],
        outgoing_transparent_coins: vec![],
    };

    // Send to external transparent, left in the mempool: Transmitted,
    // targeting height 4.
    let first_send_to_transparent = 20_000;
    let summary_external_transparent = TransactionSummary {
        txid: placeholder_txid,
        datetime: 0,
        status: ConfirmationStatus::Transmitted(BlockHeight::from_u32(4)),
        blockheight: BlockHeight::from_u32(4),
        kind: TransactionKind::Sent(SendType::Send),
        value: first_send_to_transparent,
        fee: Some(15_000),
        zec_price: None,
        pools_sent_from: vec![PoolType::IRONWOOD],
        ironwood_notes: vec![BasicNoteSummary::from_parts(
            99_925_000,
            SpendStatus::Unspent,
            0,
            None,
        )],
        orchard_notes: vec![],
        sapling_notes: vec![],
        transparent_coins: vec![],
        outgoing_ironwood_notes: vec![],
        outgoing_orchard_notes: vec![],
        outgoing_sapling_notes: vec![],
        outgoing_transparent_coins: vec![],
    };
    from_inputs::quick_send(
        &mut recipient,
        vec![(&external_taddr, first_send_to_transparent, None)],
    )
    .await
    .unwrap();

    assert_transaction_summary_equality(
        &recipient.transaction_summaries(false).await.unwrap().0[0],
        &summary_orchard_receipt,
    );
    assert_transaction_summary_equality(
        &recipient.transaction_summaries(false).await.unwrap().0[1],
        &summary_external_sapling,
    );
    assert_transaction_summary_equality(
        &recipient.transaction_summaries(false).await.unwrap().0[2],
        &summary_external_transparent,
    );

    // Mid-flight balances: everything sits in the unmined send's change.
    let expected_funds = recipient_initial_funds
        - first_send_to_sapling
        - 20_000
        - first_send_to_transparent
        - 15_000;
    {
        let recipient_wallet = recipient.wallet();
        let recipient_wallet = recipient_wallet.read().await;
        assert_eq!(
            recipient_wallet
                .unconfirmed_balance::<IronwoodNote>(zip32::AccountId::ZERO)
                .unwrap(),
            expected_funds.try_into().unwrap()
        );
        assert_eq!(
            recipient_wallet
                .confirmed_balance::<IronwoodNote>(zip32::AccountId::ZERO)
                .unwrap(),
            0.try_into().unwrap()
        );
    }

    // The pending transparent send confirms at height 4.
    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();

    // Second funding wave, with a memo, at height 5.
    let recipient_second_funding = 1_000_000;
    fund(
        &net,
        vec![(
            &recipient_ua,
            recipient_second_funding,
            Some("Second wave incoming"),
        )],
        0,
    )
    .await;
    recipient.sync_and_await().await.unwrap();
    let summary_orchard_receipt_2 = TransactionSummary {
        txid: placeholder_txid,
        datetime: 0,
        status: ConfirmationStatus::Confirmed(BlockHeight::from_u32(5)),
        blockheight: BlockHeight::from_u32(5),
        kind: TransactionKind::Received,
        value: recipient_second_funding,
        // The documented divergence: the mock faucet is fresh, so its
        // funding send is the plain two-action 10_000, not the live
        // fragmented-faucet 20_000.
        fee: Some(10_000),
        zec_price: None,
        pools_sent_from: vec![],
        ironwood_notes: vec![BasicNoteSummary::from_parts(
            recipient_second_funding,
            SpendStatus::Spent(placeholder_txid),
            0,
            Some("Second wave incoming".to_string()),
        )],
        orchard_notes: vec![],
        sapling_notes: vec![],
        transparent_coins: vec![],
        outgoing_ironwood_notes: vec![],
        outgoing_orchard_notes: vec![],
        outgoing_sapling_notes: vec![],
        outgoing_transparent_coins: vec![],
    };

    // Second wave of external sends: transparent and sapling mined into
    // the same block, height 6.
    let second_send_to_transparent = 20_000;
    let second_send_to_sapling = 20_000;
    from_inputs::quick_send(
        &mut recipient,
        vec![(&external_taddr, second_send_to_transparent, None)],
    )
    .await
    .unwrap();
    from_inputs::quick_send(
        &mut recipient,
        vec![(&external_sapling, second_send_to_sapling, None)],
    )
    .await
    .unwrap();
    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();
    let summary_external_transparent_2 = TransactionSummary {
        txid: placeholder_txid,
        datetime: 0,
        status: ConfirmationStatus::Confirmed(BlockHeight::from_u32(6)),
        blockheight: BlockHeight::from_u32(6),
        kind: TransactionKind::Sent(SendType::Send),
        value: second_send_to_transparent,
        fee: Some(15_000),
        zec_price: None,
        pools_sent_from: vec![PoolType::IRONWOOD],
        ironwood_notes: vec![BasicNoteSummary::from_parts(
            965_000,
            SpendStatus::Spent(placeholder_txid),
            0,
            None,
        )],
        orchard_notes: vec![],
        sapling_notes: vec![],
        transparent_coins: vec![],
        outgoing_ironwood_notes: vec![],
        outgoing_orchard_notes: vec![],
        outgoing_sapling_notes: vec![],
        outgoing_transparent_coins: vec![],
    };
    let summary_external_sapling_2 = TransactionSummary {
        txid: placeholder_txid,
        datetime: 0,
        status: ConfirmationStatus::Confirmed(BlockHeight::from_u32(6)),
        blockheight: BlockHeight::from_u32(6),
        kind: TransactionKind::Sent(SendType::Send),
        value: second_send_to_sapling,
        fee: Some(20_000),
        zec_price: None,
        pools_sent_from: vec![PoolType::IRONWOOD],
        ironwood_notes: vec![BasicNoteSummary::from_parts(
            99_885_000,
            SpendStatus::Unspent,
            0,
            None,
        )],
        orchard_notes: vec![],
        sapling_notes: vec![],
        transparent_coins: vec![],
        outgoing_ironwood_notes: vec![],
        outgoing_orchard_notes: vec![],
        outgoing_sapling_notes: vec![OutgoingNoteSummary {
            output_index: 0,
            value: second_send_to_sapling,
            memo: None,
            recipient: "zregtestsapling1sa4rckrf4zs6ny3l3ljnezupacvxfnjjn90lpeaa4ddtjeyww2ypzqr3jxfsta3t8dn3jk8cm4f".to_string(),
            recipient_unified_address: Some("uregtest183rtm3qhxxermx3nxwa706va0xnypt3td648tayetchlp28hue08vrcnwq02ryyk5rh3y0xhftay8a5ynjdg8kr3juq5x0d9ygd5ffht".to_string()),
            account_id: zip32::AccountId::ZERO,
            scope: SummaryScope::from(zip32::Scope::External),
        }],
        outgoing_transparent_coins: vec![],
    };

    // Third external transparent, mined at height 7.
    let external_transparent_3 = 20_000;
    from_inputs::quick_send(
        &mut recipient,
        vec![(&external_taddr, external_transparent_3, None)],
    )
    .await
    .unwrap();
    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();
    let summary_external_transparent_3 = TransactionSummary {
        txid: placeholder_txid,
        datetime: 0,
        status: ConfirmationStatus::Confirmed(BlockHeight::from_u32(7)),
        blockheight: BlockHeight::from_u32(7),
        kind: TransactionKind::Sent(SendType::Send),
        value: external_transparent_3,
        fee: Some(15_000),
        zec_price: None,
        pools_sent_from: vec![PoolType::IRONWOOD],
        ironwood_notes: vec![BasicNoteSummary::from_parts(
            930_000,
            SpendStatus::Unspent,
            0,
            None,
        )],
        orchard_notes: vec![],
        sapling_notes: vec![],
        transparent_coins: vec![],
        outgoing_ironwood_notes: vec![],
        outgoing_orchard_notes: vec![],
        outgoing_sapling_notes: vec![],
        outgoing_transparent_coins: vec![],
    };

    assert_transaction_summary_equality(
        &recipient.transaction_summaries(false).await.unwrap().0[3],
        &summary_orchard_receipt_2,
    );
    // Two sends share height 6, so summary order within the block is
    // not pinned; assert existence as the live test does.
    assert_transaction_summary_exists(&recipient, &summary_external_transparent_2).await;
    assert_transaction_summary_exists(&recipient, &summary_external_sapling_2).await;
    assert_transaction_summary_equality(
        &recipient.transaction_summaries(false).await.unwrap().0[6],
        &summary_external_transparent_3,
    );

    let second_wave_expected_funds = expected_funds + recipient_second_funding
        - second_send_to_sapling
        - second_send_to_transparent
        - external_transparent_3
        - 50_000;
    assert_eq!(
        recipient
            .wallet()
            .read()
            .await
            .confirmed_balance::<IronwoodNote>(zip32::AccountId::ZERO)
            .unwrap(),
        second_wave_expected_funds.try_into().unwrap(),
    );
}

/// Mock-chain twin of libtonode `slow::from_t_z_o_tz_to_zo_tzo_to_orchard`
/// (live original kept as the control): the full pool-promotion ledger,
/// every funding source and self-send combination, two shields, exact
/// per-step balances, and the cumulative confirmed-fee total, driven
/// through real scanning of the mock chain.
///
/// The `darkside_test` hazard of zingolabs/zingolib#2447 is gone: that
/// subtractive feature compiled out the transparent-address discovery
/// this test's funding depends on whenever feature unification enabled
/// it in multi-package builds, and the feature and its gates are now
/// deleted. The test stays ignored for an unrelated reason: its ledger
/// predates V6 and every step needs re-deriving per ADR 0009.
#[ignore = "The ledger's fees and amounts predate V6. Re-derive every step per ADR 0009 \
            before un-ignoring (step 10 under-drains, stranding 10_000 in sapling, because \
            V6's two-bundle fees lead the planner to leave the sapling note unspent)"]
#[tokio::test]
async fn from_t_z_o_tz_to_zo_tzo_to_orchard() {
    use crate::lightclient::error::{LightClientError, SendError};
    use crate::testutils::lightclient::get_fees_paid_by_client;
    use crate::wallet::error::ProposeSendError;
    use zcash_protocol::value::Zatoshis;

    let mut net = MockNet::launch().await;
    let mut client = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let pmc_unified = get_base_address(&client, PoolType::Shielded(ShieldedPool::Orchard)).await;
    let pmc_taddr = get_base_address(&client, PoolType::Transparent).await;
    let pmc_sapling = get_base_address(&client, PoolType::Shielded(ShieldedPool::Sapling)).await;

    net.chain.write().await.mine_empty_blocks(1);

    macro_rules! bump_and_check {
        (o: $o:tt i: $i:tt s: $s:tt t: $t:tt) => {
            net.chain.write().await.mine_mempool();
            client.sync_and_await().await.unwrap();
            check_client_balances!(client, i: $i o:$o s:$s t:$t);
        };
    }

    let mut total_expected_fee = 0;
    // 1 receive 50_000 transparent. Expanded rather than using
    // bump_and_check so a failure surfaces the mock's taddr-request
    // ledger and the wallet's record count (nextest shows this stderr
    // only when the test fails).
    fund(&net, vec![(&pmc_taddr, 50_000, None)], 0).await;
    net.chain.write().await.mine_mempool();
    client.sync_and_await().await.unwrap();
    {
        let chain = net.chain.read().await;
        eprintln!("step-1 diagnostics: mock tip {}", chain.tip());
        eprintln!("taddr requests served: {:#?}", chain.taddr_request_log());
        let wallet = client.wallet();
        let wallet = wallet.read().await;
        eprintln!("wallet transactions: {}", wallet.wallet_transactions.len());
    }
    check_client_balances!(client, i: 0 o: 0 s: 0 t: 50_000);
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 2 shield 50_000 transparent to orchard: 15_000 (1 t-in, 2 orchard)
    client.quick_shield(zip32::AccountId::ZERO).await.unwrap();
    bump_and_check!(o: 0 i: 35_000 s: 0 t: 0);
    total_expected_fee += 15_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 3 receive 50_000 sapling
    fund(&net, vec![(&pmc_sapling, 50_000, None)], 0).await;
    bump_and_check!(o: 0 i: 35_000 s: 50_000 t: 0);
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 4 migrate sapling to orchard: 20_000 (2 sapling, 2 orchard)
    from_inputs::quick_send(&mut client, vec![(&pmc_unified, 30_000, None)])
        .await
        .unwrap();
    bump_and_check!(o: 0 i: 65_000 s: 0 t: 0);
    total_expected_fee += 20_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 5 orchard self-send: 10_000
    from_inputs::quick_send(&mut client, vec![(&pmc_unified, 55_000, None)])
        .await
        .unwrap();
    bump_and_check!(o: 0 i: 55_000 s: 0 t: 0);
    total_expected_fee += 10_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 6 orchard to own transparent and sapling: 25_000
    from_inputs::quick_send(
        &mut client,
        vec![(&pmc_taddr, 10_000, None), (&pmc_sapling, 10_000, None)],
    )
    .await
    .unwrap();
    bump_and_check!(o: 0 i: 10_000 s: 10_000 t: 10_000);
    total_expected_fee += 25_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 7 receive 500_000 transparent
    fund(&net, vec![(&pmc_taddr, 500_000, None)], 0).await;
    bump_and_check!(o: 0 i: 10_000 s: 10_000 t: 510_000);
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 8 shield both coins: 20_000 (2 t-in, 2 orchard)
    client.quick_shield(zip32::AccountId::ZERO).await.unwrap();
    bump_and_check!(o: 0 i: 500_000 s: 10_000 t: 0);
    total_expected_fee += 20_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 9 orchard self-send: 10_000
    from_inputs::quick_send(&mut client, vec![(&pmc_unified, 30_000, None)])
        .await
        .unwrap();
    bump_and_check!(o: 0 i: 490_000 s: 10_000 t: 0);
    total_expected_fee += 10_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 10 ironwood demoted to own transparent, sapling stays put: 15_000
    from_inputs::quick_send(&mut client, vec![(&pmc_taddr, 465_000, None)])
        .await
        .unwrap();
    bump_and_check!(o: 0 i: 10_000 s: 10_000 t: 465_000);
    total_expected_fee += 15_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 10b transparent-to-transparent is refused: transparent funds are
    // not send-spendable, and the 20_000 shielded leftover cannot pay
    // the 10_000 payment plus its 25_000 fee.
    match from_inputs::quick_send(&mut client, vec![(&pmc_taddr, 10_000, None)]).await {
        Err(LightClientError::SendError(SendError::ProposeSendError(
            ProposeSendError::Proposal(
                zcash_client_backend::data_api::error::Error::InsufficientFunds {
                    available,
                    required,
                },
            ),
        ))) => {
            assert_eq!(available, Zatoshis::from_u64(20_000).unwrap());
            assert_eq!(required, Zatoshis::from_u64(35_000).unwrap());
        }
        other => panic!("expected InsufficientFunds, got {other:?}"),
    }
    bump_and_check!(o: 0 i: 10_000 s: 10_000 t: 465_000);
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 11 transparent-to-sapling likewise refused.
    match from_inputs::quick_send(&mut client, vec![(&pmc_sapling, 50_000, None)]).await {
        Err(LightClientError::SendError(SendError::ProposeSendError(
            ProposeSendError::Proposal(
                zcash_client_backend::data_api::error::Error::InsufficientFunds {
                    available,
                    required,
                },
            ),
        ))) => {
            assert_eq!(available, Zatoshis::from_u64(20_000).unwrap());
            assert_eq!(required, Zatoshis::from_u64(70_000).unwrap());
        }
        other => panic!("expected InsufficientFunds, got {other:?}"),
    }
    bump_and_check!(o: 0 i: 10_000 s: 10_000 t: 465_000);
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 12 shield: 15_000 (1 t-in, the ironwood pair)
    client.quick_shield(zip32::AccountId::ZERO).await.unwrap();
    bump_and_check!(o: 0 i: 460_000 s: 10_000 t: 0);
    total_expected_fee += 15_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 13 ironwood to own sapling: 20_000
    from_inputs::quick_send(&mut client, vec![(&pmc_sapling, 10_000, None)])
        .await
        .unwrap();
    bump_and_check!(o: 0 i: 430_000 s: 20_000 t: 0);
    total_expected_fee += 20_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 14 ironwood self-send: 10_000
    from_inputs::quick_send(&mut client, vec![(&pmc_unified, 20_000, None)])
        .await
        .unwrap();
    bump_and_check!(o: 0 i: 420_000 s: 20_000 t: 0);
    total_expected_fee += 10_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 15 sapling + ironwood to own sapling, not an exact drain: 20_000
    from_inputs::quick_send(&mut client, vec![(&pmc_sapling, 400_000, None)])
        .await
        .unwrap();
    bump_and_check!(o: 0 i: 20_000 s: 400_000 t: 0);
    total_expected_fee += 20_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);

    // 16 sapling self-send: 10_000
    from_inputs::quick_send(&mut client, vec![(&pmc_sapling, 350_000, None)])
        .await
        .unwrap();
    bump_and_check!(o: 0 i: 20_000 s: 390_000 t: 0);
    total_expected_fee += 10_000;
    assert_eq!(get_fees_paid_by_client(&client).await, total_expected_fee);
}

/// Deterministic reproduction of issue #2450 (no live original: the
/// live shape is a load-dependent flake, three libtonode tests
/// failing whenever a slow validator response crosses the wallet's
/// send timeout). The first submission is accepted into the mock
/// mempool but its response is lost. The wallet's retry then receives
/// the validator's duplicate rejection, verbatim as zainod surfaces it
/// (zingolabs/zaino#1392). That rejection is proof of successful
/// transmission: the send must return Ok, the transaction must not be
/// marked Failed, and it must confirm with ordinary balance
/// arithmetic.
#[tokio::test]
async fn send_survives_lost_response_and_duplicate_rejection() {
    use crate::testutils::mock_indexer::LostSendDestination;
    use zingo_status::confirmation_status::ConfirmationStatus;

    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    recipient.set_transmit_retry_interval(std::time::Duration::ZERO);
    let recipient_ua =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;
    recipient.sync_and_await().await.unwrap();
    check_client_balances!(recipient, i: 100_000 o: 0 s: 0 t: 0);

    net.chain.write().await.lose_next_send_response = Some(LostSendDestination::Mempool);

    let txids = from_inputs::quick_send(
        &mut recipient,
        vec![(&external_address(PoolType::ORCHARD), 20_000, None)],
    )
    .await
    .expect("a duplicate-in-mempool rejection proves transmission succeeded");

    // The wallet must not record the live transaction as Failed.
    {
        let wallet = recipient.wallet().read().await;
        for txid in txids.iter() {
            let status = wallet
                .wallet_transactions
                .get(txid)
                .expect("the transmitted transaction stays in the wallet")
                .status();
            assert!(
                !matches!(status, ConfirmationStatus::Failed(_)),
                "transaction {txid} marked Failed while live in the mempool"
            );
        }
    }

    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();
    // Identical arithmetic to `funded_send_confirms_on_the_mock_chain`:
    // the lost response and duplicate rejection must not perturb it.
    check_client_balances!(recipient, i: 70_000 o: 0 s: 0 t: 0);
}

/// Twin of [`send_survives_lost_response_and_duplicate_rejection`] for
/// the validator's earlier phase: the lost-response submission is
/// still in the download/verification queue when the retry arrives, so
/// the rejection reads "transaction dropped because it is already
/// queued for download" (zebra's pre-acceptance duplicate check),
/// observed live in the 2026-07-11 container runs, where verification
/// lagged the send by seconds under load. That rejection proves
/// delivery but not minability, so the wallet must hold success until
/// its probes see the storage-backed mempool rejection, and only then
/// return Ok, keeping send-Ok ⇒ minable-now. The mock answers two
/// queued rejections before promoting, so the probe loop is exercised
/// deterministically. Mining immediately after the send must therefore
/// confirm the transaction.
#[tokio::test]
async fn send_survives_lost_response_and_queued_duplicate_rejection() {
    use crate::testutils::mock_indexer::LostSendDestination;
    use zingo_status::confirmation_status::ConfirmationStatus;

    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    recipient.set_transmit_retry_interval(std::time::Duration::ZERO);
    let recipient_ua =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;
    recipient.sync_and_await().await.unwrap();
    check_client_balances!(recipient, i: 100_000 o: 0 s: 0 t: 0);

    {
        let mut chain = net.chain.write().await;
        chain.lose_next_send_response = Some(LostSendDestination::DownloadQueue);
        chain.queued_rejections_before_promotion = 2;
    }

    let txids = from_inputs::quick_send(
        &mut recipient,
        vec![(&external_address(PoolType::ORCHARD), 20_000, None)],
    )
    .await
    .expect("probing resubmissions reach the storage-backed verdict");

    // The wallet must not record the delivered transaction as Failed.
    {
        let wallet = recipient.wallet().read().await;
        for txid in txids.iter() {
            let status = wallet
                .wallet_transactions
                .get(txid)
                .expect("the transmitted transaction stays in the wallet")
                .status();
            assert!(
                !matches!(status, ConfirmationStatus::Failed(_)),
                "transaction {txid} marked Failed while queued for download"
            );
        }
    }

    // send-Ok means minable NOW: mining immediately (the very race
    // that broke test_scanning_in_watch_only_mode live) must include
    // the transaction, with no verification-delay allowance.
    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();
    check_client_balances!(recipient, i: 70_000 o: 0 s: 0 t: 0);
}

/// A failed transmit inside a note-splitting round must not leave any
/// transaction stranded in `Calculated`. The immediate migration sibling
/// (`migrate_immediately`) fails every unsent transaction so the
/// notes it reserved become spendable again. The split round in
/// `migrate_to_ironwood` must enforce the same invariant, or the
/// transactions queued behind the failing one keep their notes marked
/// spent by transactions that never reached the network, and a replan
/// silently excludes that value until expiry self-heals it (~40 blocks
/// plus a sync).
///
/// Setup: 17 fabricated legacy-Orchard (V2) notes make the provisional
/// planner (16-action total budget) emit a first reduction round of several
/// merge transactions — more than one, so a failure of the first can strand
/// the rest. The mock indexer's lost-response fault plus an
/// effectively-infinite download-queue rejection budget makes the FIRST
/// submission fail deterministically after the wallet's probe budget. The
/// transactions behind it must not stay stranded.
#[tokio::test]
async fn failed_split_round_transmit_strands_calculated_transactions() {
    use zcash_primitives::transaction::TxId;
    use zip32::AccountId;

    use pepper_sync::wallet::{OrchardNote, OutputInterface as _};
    use zingo_status::confirmation_status::ConfirmationStatus;

    use crate::testutils::mock_indexer::LostSendDestination;
    use crate::testutils::synthetic_wallet::inject_confirmed_orchard_notes;

    const NOTES: u32 = 17;
    const NOTE_VALUE: u64 = 120_000;
    const TIP: u32 = 41;

    // A real mock-net client, synced over an empty chain so the wallet
    // carries genuine wallet blocks and scan state, then handed 34
    // spendable legacy-Orchard notes whose nullifiers are really derived,
    // so pepper-sync's spend detection marks them when the round spends
    // them.
    let mut net = MockNet::launch().await;
    {
        let mut chain = net.chain.write().await;
        chain.rules.anchors = false;
        chain.mine_empty_blocks(TIP);
    }
    let mut client = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    client.set_transmit_retry_interval(std::time::Duration::ZERO);
    client
        .sync_and_await()
        .await
        .expect("initial sync succeeds");
    {
        let wallet_lock = client.wallet().clone();
        let mut wallet = wallet_lock.write().await;
        inject_confirmed_orchard_notes(&mut wallet, NOTES, NOTE_VALUE, TIP);
    }

    // Arm the deterministic transmit failure: the first send's response is
    // lost while the bytes sit in the validator's download queue, and the
    // queue never promotes, so every duplicate probe is rejected until the
    // wallet's probe budget is exhausted and it marks that transaction
    // Failed and errors out of transmit_transactions.
    {
        let mut chain = net.chain.write().await;
        chain.lose_next_send_response = Some(LostSendDestination::DownloadQueue);
        chain.queued_rejections_before_promotion = u8::MAX;
    }

    let err = client
        .migrate_to_ironwood(AccountId::ZERO)
        .await
        .expect_err("the first split transaction's transmit fails");
    eprintln!("migrate_to_ironwood returned: {err:?}");

    // Diagnostics and precondition: the round must have reached the
    // transmit stage (exactly one transaction Failed there).
    let wallet = client.wallet().read().await;
    let mut failed = Vec::new();
    let mut calculated = Vec::new();
    for tx in wallet.wallet_transactions.values() {
        match tx.status() {
            ConfirmationStatus::Calculated(_) => {
                let spent_inputs: Vec<(TxId, u64)> = wallet
                    .wallet_transactions
                    .values()
                    .flat_map(OrchardNote::transaction_outputs)
                    .filter(|note| note.spending_transaction() == Some(tx.txid()))
                    .map(|note| (note.output_id().txid(), note.value()))
                    .collect();
                eprintln!(
                    "stranded Calculated transaction {} spends {} notes still \
                     marked spent: {spent_inputs:?}",
                    tx.txid(),
                    spent_inputs.len(),
                );
                calculated.push(tx.txid());
            }
            ConfirmationStatus::Failed(_) => failed.push(tx.txid()),
            _ => (),
        }
    }
    assert!(
        !failed.is_empty(),
        "precondition: the transmit stage must have failed the first split \
         transaction (otherwise this test failed before transmit)"
    );

    // The invariant the immediate migration path enforces (fail_unsent_transactions) and
    // the split path must too: after a failed round, nothing may remain
    // Calculated. Its notes would stay spent by transactions that will
    // never transmit, and a replan silently excludes them.
    assert!(
        calculated.is_empty(),
        "a failed note-split round stranded {} transaction(s) in Calculated \
         with their input notes marked spent: {calculated:?}",
        calculated.len()
    );
}

/// Wallet settings for continuous sync: `shutdown_on_completion` unset.
fn continuous_sync_wallet_settings() -> crate::wallet::WalletSettings {
    let mut settings = crate::testutils::default_test_wallet_settings();
    settings.sync_config.shutdown_on_completion = false;
    settings
}

/// `sync_to_tip_and_await` returns at the chain tip when the wallet is
/// configured for continuous sync, and leaves the stored setting unchanged.
#[tokio::test]
async fn sync_to_tip_and_await_returns_under_continuous_sync() {
    let mut net = MockNet::launch().await;
    net.chain.write().await.mine_empty_blocks(10);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;

    tokio::time::timeout(
        std::time::Duration::from_secs(60),
        client.sync_to_tip_and_await(),
    )
    .await
    .expect("sync returns at the chain tip")
    .expect("sync succeeds");

    assert_eq!(
        client.sync_mode(),
        pepper_sync::wallet::SyncMode::NotRunning
    );
    assert!(
        !client
            .wallet()
            .read()
            .await
            .wallet_settings
            .sync_config
            .shutdown_on_completion,
        "the stored sync config must not be modified"
    );
}

/// `sync_to_tip_and_await` stops a running continuous sync, then syncs to
/// the chain tip and returns.
#[tokio::test]
async fn sync_to_tip_and_await_stops_running_continuous_sync() {
    let mut net = MockNet::launch().await;
    net.chain.write().await.mine_empty_blocks(10);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.sync().await.expect("continuous sync launches");

    tokio::time::timeout(
        std::time::Duration::from_secs(60),
        client.sync_to_tip_and_await(),
    )
    .await
    .expect("sync returns at the chain tip")
    .expect("sync succeeds");

    assert_eq!(
        client.sync_mode(),
        pepper_sync::wallet::SyncMode::NotRunning
    );
}

/// Transparent address discovery only covers blocks up to the transparent scan floor, the chain height at the start of
/// the sync session. Transparent funds received in a block mined during a continuous sync session are only detected
/// if transparent data is requested in the compact blocks above the floor, as the mock, like a real server, only
/// serves the data of the requested pools.
#[tokio::test]
async fn transparent_funds_mined_during_sync_session_are_detected() {
    let mut net = MockNet::launch().await;
    net.chain.write().await.mine_empty_blocks(10);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    let taddr = get_base_address(&client, PoolType::Transparent).await;
    // built before the sync session launches, as proving blocks the test runtime's only thread and would starve the
    // session's requests past their timeouts.
    let funding = faucet_funding_transaction(vec![(&taddr, 50_000, None)]).await;

    client.sync().await.expect("continuous sync launches");

    // the first sync status is published after the session has fetched the chain height, setting the floor.
    tokio::time::timeout(
        std::time::Duration::from_secs(60),
        client.subscribe_sync_status().wait_for(Option::is_some),
    )
    .await
    .expect("sync publishes its status")
    .expect("sync status channel open");

    // mined directly into a block, bypassing the mempool, so the funds can only be detected from the compact block.
    {
        let mut chain = net.chain.write().await;
        chain.mine_block(vec![funding]);
        chain.mine_empty_blocks(1);
    }

    tokio::time::timeout(std::time::Duration::from_secs(60), async {
        loop {
            if let crate::data::PollReport::Ready(result) = client.poll_sync() {
                panic!("sync returned before the transparent funds were detected: {result:?}");
            }
            let transparent_balance = client
                .account_balance(zip32::AccountId::ZERO)
                .await
                .unwrap()
                .confirmed_transparent_balance
                .unwrap()
                .into_u64();
            if transparent_balance == 50_000 {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("transparent funds mined during the sync session are detected");

    client.stop_sync().unwrap();
    client.await_sync().await.unwrap();
}

/// Blocks mined during a continuous sync session are above the transparent scan floor, so transparent address
/// discovery has not covered them, and the session may end before scanning them. The transparent address discovery
/// of the next session searches from the floor of the previous session, so transparent funds in those blocks are
/// detected.
///
/// The fetch of the new blocks is held so the first session is stopped before scanning them. More blocks than the
/// re-org allowance are mined above the funds, so they are below the blocks address discovery searches in case of
/// re-org.
#[tokio::test]
async fn transparent_funds_in_blocks_unscanned_by_previous_sync_session_are_detected() {
    use crate::testutils::mock_indexer::{Fault, Rpc};

    const INITIAL_CHAIN_HEIGHT: u32 = 10;
    const BLOCKS_MINED_ABOVE_FUNDS: u32 = pepper_sync::sync::MAX_REORG_ALLOWANCE + 50;
    const FETCH_HOLD: std::time::Duration = std::time::Duration::from_secs(5);

    let mut net = MockNet::launch().await;
    net.chain
        .write()
        .await
        .mine_empty_blocks(INITIAL_CHAIN_HEIGHT);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    let taddr = get_base_address(&client, PoolType::Transparent).await;
    client.sync().await.expect("continuous sync launches");
    wait_until_scanned_to(&client, INITIAL_CHAIN_HEIGHT).await;

    net.chain
        .write()
        .await
        .faults
        .inject(Rpc::BlockRange, Fault::Delay(FETCH_HOLD));
    // mined directly into a block, bypassing the mempool, so the funds can only be detected by address discovery or
    // from the compact block.
    fund(&net, vec![(&taddr, 50_000, None)], BLOCKS_MINED_ABOVE_FUNDS).await;
    let chain_height = net.chain.read().await.tip();
    tokio::time::timeout(std::time::Duration::from_secs(60), async {
        while client.latest_sync_status().is_none_or(|status| {
            status.scan_ranges.last().is_none_or(|range| {
                range.block_range().end != BlockHeight::from_u32(chain_height + 1)
            })
        }) {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("the sync session creates the scan range of the new blocks");
    client.stop_sync().unwrap();
    client.await_sync().await.unwrap();
    assert_eq!(
        client
            .wallet()
            .read()
            .await
            .sync_state
            .fully_scanned_height(),
        Some(BlockHeight::from_u32(INITIAL_CHAIN_HEIGHT)),
        "the sync session is stopped before the new blocks are scanned"
    );

    client.sync_to_tip_and_await().await.unwrap();

    check_client_balances!(client, i: 0 o: 0 s: 0 t: 50_000);
}

/// How a continuous sync session learns that the block at its chain tip was re-orged away.
enum ReorgDetection {
    /// The chain is extended past the wallet's height before the session next checks for new blocks. The continuity
    /// check of the new blocks detects the re-org.
    Continuity,
    /// The session checks for new blocks while the chain is shorter than the wallet's height and truncates the wallet
    /// to the chain height.
    LowerChainHeight,
}

/// Transparent funds are mined in the block at the chain height when a continuous sync session starts, so they are
/// found by transparent address discovery and their block sits at the transparent scan floor. The block is re-orged
/// away and the funding transaction is mined again at the same height.
///
/// Transparent address discovery is not performed again during the session, so the funds are only detected again if
/// the transparent scan floor is lowered for the compact block transparent data of the new block to be scanned.
///
/// Returns the client with the session stopped after scanning the new chain.
async fn transparent_funds_remined_at_transparent_scan_floor(
    reorg_detection: ReorgDetection,
) -> crate::lightclient::LightClient {
    const FUNDING_HEIGHT: u32 = 20;

    let mut net = MockNet::launch().await;
    net.chain
        .write()
        .await
        .mine_empty_blocks(FUNDING_HEIGHT - 1);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    let taddr = get_base_address(&client, PoolType::Transparent).await;
    let funding = faucet_funding_transaction(vec![(&taddr, 50_000, None)]).await;
    net.chain.write().await.mine_block(vec![funding.clone()]);
    assert_eq!(net.chain.read().await.tip(), FUNDING_HEIGHT);

    client.sync().await.expect("continuous sync launches");
    wait_until_scanned_to(&client, FUNDING_HEIGHT).await;
    check_client_balances!(client, i: 0 o: 0 s: 0 t: 50_000);

    match reorg_detection {
        ReorgDetection::Continuity => {
            let mut chain = net.chain.write().await;
            chain.reorg_to(FUNDING_HEIGHT - 1);
            chain.mine_block(vec![funding]);
            chain.mine_empty_blocks(1);
        }
        ReorgDetection::LowerChainHeight => {
            net.chain.write().await.reorg_to(FUNDING_HEIGHT - 1);
            wait_until_scanned_to(&client, FUNDING_HEIGHT - 1).await;
            let mut chain = net.chain.write().await;
            chain.mine_block(vec![funding]);
            chain.mine_empty_blocks(1);
        }
    }
    wait_until_scanned_to(&client, FUNDING_HEIGHT + 1).await;
    client.stop_sync().unwrap();
    client.await_sync().await.unwrap();

    client
}

#[tokio::test]
async fn transparent_funds_remined_at_transparent_scan_floor_are_detected_after_continuity_reorg() {
    let client =
        transparent_funds_remined_at_transparent_scan_floor(ReorgDetection::Continuity).await;

    check_client_balances!(client, i: 0 o: 0 s: 0 t: 50_000);
}

#[tokio::test]
async fn transparent_funds_remined_at_transparent_scan_floor_are_detected_after_lower_chain_height()
{
    let client =
        transparent_funds_remined_at_transparent_scan_floor(ReorgDetection::LowerChainHeight).await;

    check_client_balances!(client, i: 0 o: 0 s: 0 t: 50_000);
}

/// The chain height drops by one block during a continuous sync session while the scan of the range up to the old
/// chain tip is in flight. The wallet truncates its scan ranges to the lower chain height, so the scan results hold
/// a block the wallet has no scan range for. They are discarded and the truncated range is scanned again.
///
/// The scan fetches the two funding transactions, and each fetch is held for longer than half the interval between
/// new block checks, so a new block check runs while the scan is in flight.
#[tokio::test]
async fn scan_results_in_flight_when_chain_height_drops_are_discarded_and_rescanned() {
    use crate::testutils::mock_indexer::{Fault, Rpc};

    const BLOCKS_BELOW_FUNDS: u32 = 10;
    const BLOCKS_ABOVE_FUNDS: u32 = 9;
    const CHAIN_HEIGHT: u32 = BLOCKS_BELOW_FUNDS + 1 + BLOCKS_ABOVE_FUNDS;
    const FUNDING_TRANSACTIONS: usize = 2;
    const FETCH_HOLD: std::time::Duration =
        std::time::Duration::from_secs(pepper_sync::sync::CHECK_NEW_BLOCKS_INTERVAL / 2 + 1);

    let mut net = MockNet::launch().await;
    net.chain
        .write()
        .await
        .mine_empty_blocks(BLOCKS_BELOW_FUNDS);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    let ua = get_base_address(&client, PoolType::Shielded(ShieldedPool::Orchard)).await;
    let mut funding = Vec::new();
    for _ in 0..FUNDING_TRANSACTIONS {
        funding.push(faucet_funding_transaction(vec![(&ua, 100_000, None)]).await);
        net.chain
            .write()
            .await
            .faults
            .inject(Rpc::Transaction, Fault::Delay(FETCH_HOLD));
    }
    {
        let mut chain = net.chain.write().await;
        chain.mine_block(funding);
        chain.mine_empty_blocks(BLOCKS_ABOVE_FUNDS);
    }
    assert_eq!(net.chain.read().await.tip(), CHAIN_HEIGHT);

    client.sync().await.expect("continuous sync launches");
    // the scan has fetched its blocks once it fetches the funding transactions.
    tokio::time::timeout(std::time::Duration::from_secs(60), async {
        while net.chain.read().await.faults.pending(Rpc::Transaction) != 0 {
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }
    })
    .await
    .expect("the scan fetches the funding transactions");
    net.chain.write().await.reorg_to(CHAIN_HEIGHT - 1);

    tokio::time::timeout(std::time::Duration::from_secs(60), async {
        loop {
            if let crate::data::PollReport::Ready(result) = client.poll_sync() {
                panic!("sync returned before the lower chain was scanned: {result:?}");
            }
            {
                let wallet = client.wallet();
                let wallet = wallet.read().await;
                let scan_ranges = wallet.sync_state.scan_ranges();
                if scan_ranges.last().is_some_and(|range| {
                    range.block_range().end == BlockHeight::from_u32(CHAIN_HEIGHT)
                }) && scan_ranges
                    .iter()
                    .all(|range| range.priority() == pepper_sync::sync::ScanPriority::Scanned)
                {
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("the wallet scans to the lower chain height");
    client.stop_sync().unwrap();
    client.await_sync().await.unwrap();

    check_client_balances!(client, i: 200_000 o: 0 s: 0 t: 0);
}

/// A re-org lowers the chain height below a newly mined block after a continuous sync session has selected it for
/// scanning and before its fetch is served. The server has no block to serve, so the session ends with an error
/// that reports the lowered chain height and recommends syncing again with the same server. The next session
/// truncates the wallet to the server's chain height and syncs to it.
#[tokio::test]
async fn fetch_under_a_lowered_chain_height_recommends_syncing_again() {
    use pepper_sync::error::{ServerError, SyncError, SyncRecoveryObservables};

    use crate::lightclient::error::LightClientError;
    use crate::testutils::mock_indexer::{Fault, Rpc};

    const CHAIN_HEIGHT: u32 = 10;
    const FETCH_HOLD: std::time::Duration = std::time::Duration::from_secs(3);

    let mut net = MockNet::launch().await;
    net.chain.write().await.mine_empty_blocks(CHAIN_HEIGHT);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.sync().await.expect("continuous sync launches");
    wait_until_scanned_to(&client, CHAIN_HEIGHT).await;

    // holds the fetch of the new block until the re-org has removed it.
    {
        let mut chain = net.chain.write().await;
        chain
            .faults
            .inject(Rpc::BlockRange, Fault::Delay(FETCH_HOLD));
        chain.mine_empty_blocks(1);
    }
    tokio::time::timeout(std::time::Duration::from_secs(60), async {
        while client.latest_sync_status().is_none_or(|status| {
            status.scan_ranges.last().is_none_or(|range| {
                range.block_range().end != BlockHeight::from_u32(CHAIN_HEIGHT + 2)
            })
        }) {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("the sync session creates the scan range of the new block");
    net.chain.write().await.reorg_to(CHAIN_HEIGHT);

    let LightClientError::SyncError(error) = client
        .await_sync()
        .await
        .expect_err("the fetch of the removed block fails")
    else {
        panic!("the sync session ends with a sync error");
    };
    assert!(
        matches!(
            error,
            SyncError::ServerError(ServerError::ChainHeightBelowScanRange {
                chain_height,
                scan_range_end,
            }) if chain_height == BlockHeight::from_u32(CHAIN_HEIGHT)
                && scan_range_end == BlockHeight::from_u32(CHAIN_HEIGHT + 1)
        ),
        "{error:?}"
    );
    assert_eq!(
        error.recovery_recommendation(),
        SyncRecoveryObservables::MaybeRecoverableServer
    );

    let sync_result = client.sync_to_tip_and_await().await.unwrap();
    assert_eq!(
        sync_result.sync_end_height,
        BlockHeight::from_u32(CHAIN_HEIGHT)
    );
}

/// A sync session makes its session-start server requests with the wallet lock released, so the wallet is read while
/// a slow server holds the tree state and then the subtree root request.
#[tokio::test]
async fn session_start_requests_release_the_wallet_lock() {
    use crate::testutils::mock_indexer::{Fault, Rpc};

    const CHAIN_HEIGHT: u32 = 10;
    const FETCH_HOLD: std::time::Duration = std::time::Duration::from_secs(5);
    const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(1);

    let mut net = MockNet::launch().await;
    {
        let mut chain = net.chain.write().await;
        chain.mine_empty_blocks(CHAIN_HEIGHT);
        chain
            .faults
            .inject(Rpc::TreeState, Fault::Delay(FETCH_HOLD));
        chain
            .faults
            .inject(Rpc::SubtreeRoots, Fault::Delay(FETCH_HOLD));
    }
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.sync().await.expect("continuous sync launches");

    // the session waits on the held tree state request, then on the held subtree root request.
    for held_request in ["tree state", "subtree roots"] {
        tokio::time::sleep(FETCH_HOLD / 2).await;
        let wallet = client.wallet();
        let wallet_guard = tokio::time::timeout(LOCK_WAIT, wallet.read())
            .await
            .unwrap_or_else(|_| {
                panic!("the wallet lock is held across the {held_request} request")
            });
        assert!(
            wallet_guard
                .sync_state
                .fully_scanned_height()
                .is_some_and(|height| height < BlockHeight::from_u32(CHAIN_HEIGHT)),
            "no block is scanned while the {held_request} request is held"
        );
        drop(wallet_guard);
        tokio::time::sleep(FETCH_HOLD / 2).await;
    }

    client.sync_to_tip_and_await().await.unwrap();
    assert_eq!(
        client
            .wallet()
            .read()
            .await
            .sync_state
            .fully_scanned_height(),
        Some(BlockHeight::from_u32(CHAIN_HEIGHT))
    );
}

/// A stop requested while a slow server holds a session-start request ends the session at once, without scanning,
/// instead of waiting for the server.
#[tokio::test]
async fn stop_ends_the_session_during_a_held_session_start_request() {
    use crate::testutils::mock_indexer::{Fault, Rpc};

    const CHAIN_HEIGHT: u32 = 10;
    const FETCH_HOLD: std::time::Duration = std::time::Duration::from_secs(30);
    const STOP_WAIT: std::time::Duration = std::time::Duration::from_secs(5);

    let mut net = MockNet::launch().await;
    {
        let mut chain = net.chain.write().await;
        chain.mine_empty_blocks(CHAIN_HEIGHT);
        chain
            .faults
            .inject(Rpc::SubtreeRoots, Fault::Delay(FETCH_HOLD));
    }
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.sync().await.expect("continuous sync launches");
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    client.stop_sync().unwrap();
    let sync_result = tokio::time::timeout(STOP_WAIT, client.await_sync())
        .await
        .expect("the session ends while the server still holds the request")
        .expect("a stopped session returns its result");

    assert_eq!(sync_result.blocks_scanned, 0);
    assert!(
        client
            .wallet()
            .read()
            .await
            .sync_state
            .fully_scanned_height()
            .is_some_and(|height| height < BlockHeight::from_u32(CHAIN_HEIGHT)),
        "the session ended before scanning began"
    );
}

/// A re-org detected at session start truncates the wallet and resets its scan ranges before the session's tree
/// bounds are fetched, and the wallet lock is released for that request. The previous session's snapshot still
/// counts every block it scanned, so every live counter sits below the snapshot in that window. `sync_status` read
/// in the window returns a status with its session counters saturated at zero.
#[tokio::test]
async fn sync_status_holds_while_a_reorg_truncation_awaits_the_tree_bounds() {
    use pepper_sync::sync::ScanPriority;

    use crate::testutils::mock_indexer::{Fault, Rpc};

    const CHAIN_HEIGHT: u32 = 20;
    const FETCH_HOLD: std::time::Duration = std::time::Duration::from_secs(5);

    let mut net = MockNet::launch().await;
    net.chain.write().await.mine_empty_blocks(CHAIN_HEIGHT);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.sync().await.expect("continuous sync launches");
    wait_until_scanned_to(&client, CHAIN_HEIGHT).await;
    client.stop_sync().unwrap();
    client.await_sync().await.unwrap();

    // the chain tip is replaced at the same height, so the next session detects the re-org at its start, truncates
    // the wallet below the verify range and fetches the tree bounds of the blocks it no longer holds.
    {
        let mut chain = net.chain.write().await;
        chain.reorg_to(CHAIN_HEIGHT - 1);
        chain.mine_empty_blocks(1);
        chain
            .faults
            .inject(Rpc::TreeState, Fault::Delay(FETCH_HOLD));
    }
    client.sync().await.expect("the next session launches");

    let status_in_the_window = tokio::time::timeout(FETCH_HOLD, async {
        loop {
            let wallet = client.wallet();
            let wallet_guard = wallet.read().await;
            let status = pepper_sync::sync_status(&*wallet_guard)
                .await
                .expect("the status is computable while the tree bounds are fetched");
            if status
                .scan_ranges
                .iter()
                .any(|range| range.priority() == ScanPriority::Verify)
            {
                break status;
            }
            drop(wallet_guard);
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("the re-org truncation is read while the tree state request is held");
    assert!(
        status_in_the_window.total_blocks_scanned < CHAIN_HEIGHT,
        "the truncation has removed scanned blocks: {status_in_the_window:?}"
    );
    assert_eq!(
        status_in_the_window.session_blocks_scanned, 0,
        "the live count below the previous session's snapshot saturates"
    );

    wait_until_scanned_to(&client, CHAIN_HEIGHT).await;
    client.stop_sync().unwrap();
    let sync_result = client.await_sync().await.unwrap();
    assert!(
        sync_result.blocks_scanned > 0,
        "the replacing blocks are scanned"
    );
}

/// A wallet whose birthday is above sapling activation fetches its birthday frontier on its first session, after
/// the subtree roots. The session reads the wallet to decide that, then takes the write lock to insert the
/// frontier, so the read must not outlive the decision.
#[tokio::test]
async fn first_session_of_a_wallet_born_after_sapling_inserts_its_frontier_and_scans() {
    const BIRTHDAY: u32 = 5;
    const CHAIN_HEIGHT: u32 = 20;

    let mut net = MockNet::launch().await;
    net.chain.write().await.mine_empty_blocks(CHAIN_HEIGHT);
    let mut client = net
        .client_with_birthday(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            BIRTHDAY,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.sync().await.expect("continuous sync launches");

    wait_until_scanned_to(&client, CHAIN_HEIGHT).await;
    client.stop_sync().unwrap();
    let sync_result = client.await_sync().await.unwrap();
    assert_eq!(
        sync_result.sync_start_height,
        BlockHeight::from_u32(BIRTHDAY)
    );
    assert_eq!(
        sync_result.blocks_scanned,
        CHAIN_HEIGHT - BIRTHDAY + 1,
        "every block from the birthday to the tip is scanned"
    );
}

/// A stop during the chain height request of a wallet's first session ends the session before its first scan range
/// exists. The shutdown tail reads the wallet as it is, with no scan range and no initial sync state, and returns a
/// result that scanned nothing.
#[tokio::test]
async fn stop_during_the_first_chain_height_request_returns_an_empty_session() {
    use crate::testutils::mock_indexer::{Fault, Rpc};

    const CHAIN_HEIGHT: u32 = 10;
    const FETCH_HOLD: std::time::Duration = std::time::Duration::from_secs(30);
    const STOP_WAIT: std::time::Duration = std::time::Duration::from_secs(5);

    let mut net = MockNet::launch().await;
    {
        let mut chain = net.chain.write().await;
        chain.mine_empty_blocks(CHAIN_HEIGHT);
        chain
            .faults
            .inject(Rpc::LatestBlock, Fault::Delay(FETCH_HOLD));
    }
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.sync().await.expect("continuous sync launches");
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    client.stop_sync().unwrap();
    let sync_result = tokio::time::timeout(STOP_WAIT, client.await_sync())
        .await
        .expect("the session ends while the server still holds the request")
        .expect("a session stopped before its first scan range returns its result");

    assert_eq!(sync_result.blocks_scanned, 0);
    assert_eq!(sync_result.sync_start_height, sync_result.sync_end_height);
    assert!(
        client
            .wallet()
            .read()
            .await
            .sync_state
            .scan_ranges()
            .is_empty(),
        "no scan range was created before the stop"
    );

    client.sync_to_tip_and_await().await.unwrap();
    assert_eq!(
        client
            .wallet()
            .read()
            .await
            .sync_state
            .fully_scanned_height(),
        Some(BlockHeight::from_u32(CHAIN_HEIGHT)),
        "the next session syncs the wallet from scratch"
    );
}

/// Sync is rejected when the server's lightwallet protocol version is below v0.5.0, or not reported, as the server does
/// not serve the transparent and ironwood data sync requires. The error recommends switching servers.
#[tokio::test]
async fn sync_rejects_server_below_minimum_lightwallet_protocol_version() {
    use crate::lightclient::error::LightClientError;
    use pepper_sync::error::{ServerError, SyncError, SyncRecoveryObservables};

    for reported_version in ["v0.4.0", ""] {
        let mut net = MockNet::launch().await;
        {
            let mut chain = net.chain.write().await;
            chain.lightwallet_protocol_version = reported_version.to_string();
            chain.mine_empty_blocks(10);
        }
        let mut client = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;

        let error = client
            .sync_and_await()
            .await
            .expect_err("sync against an old server fails");
        let LightClientError::SyncError(sync_error) = &error else {
            panic!("expected a sync error, got {error:?}");
        };
        assert!(
            matches!(
                sync_error,
                SyncError::ServerError(ServerError::UnsupportedProtocolVersion { version })
                    if version == reported_version
            ),
            "expected UnsupportedProtocolVersion for '{reported_version}', got {sync_error:?}"
        );
        assert_eq!(
            sync_error.recovery_recommendation(),
            SyncRecoveryObservables::ServerUnavailable
        );
    }
}

/// Waits until every block up to `height` is scanned.
async fn wait_until_scanned_to(client: &crate::lightclient::LightClient, height: u32) {
    tokio::time::timeout(std::time::Duration::from_secs(60), async {
        loop {
            {
                let wallet = client.wallet();
                let wallet = wallet.read().await;
                let scan_ranges = wallet.sync_state.scan_ranges();
                if scan_ranges.last().is_some_and(|range| {
                    range.block_range().end == BlockHeight::from_u32(height + 1)
                }) && scan_ranges
                    .iter()
                    .all(|range| range.priority() == pepper_sync::sync::ScanPriority::Scanned)
                {
                    return;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await
    .unwrap_or_else(|_| panic!("blocks up to {height} were not scanned"));
}

/// When nullifiers are not mapped (a low performance level limits the nullifier map to zero), a range scanned before a
/// lower unscanned range is set `ScannedWithoutMapping` and its nullifiers are discarded. Once all lower ranges are
/// scanned, its nullifiers are re-fetched with `GetBlockRangeNullifiers` to detect spends of notes found in the lower
/// ranges.
///
/// The note is received in the chain tip range below the session's verification range. Its spend is mined while that
/// verification range is being fetched, so the new blocks are verified, and scanned without mapping, before the chain
/// tip range containing the note. The spend is only detected from the re-fetched nullifiers.
///
/// Returns the mock net, the client left syncing continuously with every block up to height 45 scanned, and the
/// client that built the spend.
async fn continuous_sync_with_refetched_nullifiers() -> (
    MockNet,
    crate::lightclient::LightClient,
    crate::lightclient::LightClient,
) {
    use crate::testutils::mock_indexer::{Fault, Rpc};

    let mut net = MockNet::launch().await;
    net.chain.write().await.mine_empty_blocks(10);
    let mut settings = continuous_sync_wallet_settings();
    settings.sync_config.performance_level = pepper_sync::config::PerformanceLevel::Low;
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(settings),
        )
        .await;
    client.sync_to_tip_and_await().await.unwrap();

    // a second client with the same seed builds the spend of the note.
    let mut spender = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let ua = get_base_address(&client, PoolType::Shielded(ShieldedPool::Orchard)).await;
    net.chain.write().await.mine_empty_blocks(14);
    fund(&net, vec![(&ua, 100_000, None)], 15).await;
    spender.sync_and_await().await.unwrap();
    from_inputs::quick_send(
        &mut spender,
        vec![(&external_address(PoolType::ORCHARD), 20_000, None)],
    )
    .await
    .unwrap();
    // the spend is mined and re-orged out to hold it back until the sync session is running. it never enters the
    // mempool while the client is syncing, so the spend can only be detected by scanning.
    let spend = {
        let mut chain = net.chain.write().await;
        chain.mine_mempool();
        chain.reorg_to(40)
    };
    assert_eq!(net.chain.read().await.tip(), 40);

    // the fetch of the verification range is delayed until the continuous sync interval has flagged new blocks, so the
    // new blocks are verified before the chain tip range [21, 41) containing the note is scanned.
    net.chain.write().await.faults.inject(
        Rpc::BlockRange,
        Fault::Delay(
            std::time::Duration::from_secs(pepper_sync::sync::CHECK_NEW_BLOCKS_INTERVAL)
                + std::time::Duration::from_secs(2),
        ),
    );
    client.sync().await.expect("continuous sync launches");
    tokio::time::timeout(
        std::time::Duration::from_secs(60),
        client.subscribe_sync_status().wait_for(Option::is_some),
    )
    .await
    .expect("sync publishes its status")
    .expect("sync status channel open");
    {
        let mut chain = net.chain.write().await;
        chain.mine_block(spend);
        chain.mine_empty_blocks(4);
    }

    wait_until_scanned_to(&client, 45).await;

    (net, client, spender)
}

/// The spend of the note is detected from the nullifiers re-fetched by [`continuous_sync_with_refetched_nullifiers`].
#[tokio::test]
async fn spend_in_range_scanned_without_mapping_is_detected_from_refetched_nullifiers() {
    let (_net, mut client, _spender) = continuous_sync_with_refetched_nullifiers().await;
    client.stop_sync().unwrap();
    client.await_sync().await.unwrap();

    // 100_000 funding minus the 20_000 payment and its 10_000 fee. if the spend was not detected, the spent note would
    // also be counted.
    check_client_balances!(client, i: 70_000 o: 0 s: 0 t: 0);
}

/// Re-fetched nullifiers carry no transparent data, so their scan results leave the scanner's transparent gap
/// addresses as they are. Transparent funds received by a gap address in a block mined after the nullifiers were
/// re-fetched are detected.
#[tokio::test]
async fn gap_address_funds_are_detected_after_nullifiers_are_refetched() {
    use zcash_keys::encoding::AddressCodec;

    let (net, mut client, spender) = continuous_sync_with_refetched_nullifiers().await;

    // the client only holds the first transparent address of the seed, so the second is a gap address.
    let (_, gap_taddr) = spender
        .wallet()
        .write()
        .await
        .generate_transparent_address(zip32::AccountId::ZERO, false)
        .unwrap();
    fund(
        &net,
        vec![(&gap_taddr.encode(&client.chain_type()), 50_000, None)],
        0,
    )
    .await;
    wait_until_scanned_to(&client, 46).await;
    client.stop_sync().unwrap();
    client.await_sync().await.unwrap();

    check_client_balances!(client, i: 70_000 o: 0 s: 0 t: 50_000);
}

/// Waits until the mock indexer serves `expected` open mempool streams.
async fn wait_until_open_mempool_streams(net: &MockNet, expected: usize) {
    tokio::time::timeout(std::time::Duration::from_secs(60), async {
        while net.chain.read().await.open_mempool_streams() != expected {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await
    .unwrap_or_else(|_| panic!("the indexer never served {expected} open mempool streams"));
}

/// A sync session that returns an error stops its mempool monitor, which closes the monitor's mempool stream.
///
/// The session idles at the chain tip with its mempool stream open. No block is mined and no transaction enters the
/// mempool, so the monitor has nothing to send and only the shutdown flag can stop it.
#[tokio::test]
async fn mempool_stream_closes_when_sync_returns_an_error() {
    use zaino_proto::tonic::Code;

    use crate::testutils::mock_indexer::{Fault, Rpc};

    let mut net = MockNet::launch().await;
    net.chain.write().await.mine_empty_blocks(2);
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.sync().await.expect("continuous sync launches");
    wait_until_open_mempool_streams(&net, 1).await;

    // the chain tip request of the session's next new block check fails.
    net.chain.write().await.faults.inject(
        Rpc::LatestBlock,
        Fault::Fail(Code::Unavailable, "mock outage".to_string()),
    );
    client
        .await_sync()
        .await
        .expect_err("the failed chain tip request ends the session");

    wait_until_open_mempool_streams(&net, 0).await;
}

/// A sync session shuts down while the indexer refuses every mempool stream request. The mempool monitor is retrying
/// the request when the session ends, and sync returns once the monitor has stopped.
#[tokio::test]
async fn sync_returns_while_the_indexer_refuses_the_mempool_stream() {
    use zaino_proto::tonic::Code;

    use crate::testutils::mock_indexer::{Fault, Rpc};

    const QUEUED_REFUSALS: usize = 100;

    let mut net = MockNet::launch().await;
    let mut client = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    {
        let mut chain = net.chain.write().await;
        chain.mine_empty_blocks(2);
        for _ in 0..QUEUED_REFUSALS {
            chain.faults.inject(
                Rpc::MempoolStream,
                Fault::Fail(Code::ResourceExhausted, "mock refusal".to_string()),
            );
        }
    }

    tokio::time::timeout(std::time::Duration::from_secs(30), client.sync_and_await())
        .await
        .expect("sync returns while the mempool stream is refused")
        .unwrap();
    assert!(
        net.chain.read().await.faults.pending(Rpc::MempoolStream) > 0,
        "the indexer was still refusing the mempool stream when sync returned"
    );
}

/// `migrate_to_ironwood` syncs before each round. Under continuous sync, with
/// a sync already running, that sync must still return, or the
/// migration never reaches its round. The setup mirrors `failed_split_round_transmit_strands_calculated_transactions`:
/// the first split transaction's transmit fails deterministically, so reaching
/// that failure proves the round's sync returned.
#[tokio::test]
async fn migrate_to_ironwood_returns_under_continuous_sync() {
    use zip32::AccountId;

    use zingo_status::confirmation_status::ConfirmationStatus;

    use crate::testutils::mock_indexer::LostSendDestination;
    use crate::testutils::synthetic_wallet::inject_confirmed_orchard_notes;

    const NOTES: u32 = 17;
    const NOTE_VALUE: u64 = 120_000;
    const TIP: u32 = 41;

    let mut net = MockNet::launch().await;
    {
        let mut chain = net.chain.write().await;
        chain.rules.anchors = false;
        chain.mine_empty_blocks(TIP);
    }
    let mut client = net
        .client(
            zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
            Some(continuous_sync_wallet_settings()),
        )
        .await;
    client.set_transmit_retry_interval(std::time::Duration::ZERO);
    client
        .sync_to_tip_and_await()
        .await
        .expect("initial sync succeeds");
    {
        let wallet_lock = client.wallet().clone();
        let mut wallet = wallet_lock.write().await;
        inject_confirmed_orchard_notes(&mut wallet, NOTES, NOTE_VALUE, TIP);
    }
    {
        let mut chain = net.chain.write().await;
        chain.lose_next_send_response = Some(LostSendDestination::DownloadQueue);
        chain.queued_rejections_before_promotion = u8::MAX;
    }
    client.sync().await.expect("continuous sync launches");

    tokio::time::timeout(
        std::time::Duration::from_secs(120),
        client.migrate_to_ironwood(AccountId::ZERO),
    )
    .await
    .expect("migrate_to_ironwood returns under continuous sync")
    .expect_err("the first split transaction's transmit fails");

    let wallet = client.wallet().read().await;
    assert!(
        wallet
            .wallet_transactions
            .values()
            .any(|tx| matches!(tx.status(), ConfirmationStatus::Failed(_))),
        "the round reached its transmit stage, so its sync returned"
    );
    assert!(!wallet.wallet_settings.sync_config.shutdown_on_completion);
}

/// The offline twins whose assertions read the editorial surface.
#[cfg(feature = "perspective")]
mod perspective {
    use std::num::NonZeroU32;
    use std::time::{Duration, Instant};

    use pepper_sync::config::{
        PerformanceLevel, SyncConfig, TransparentAddressDiscovery,
        TransparentAddressDiscoveryScopes,
    };
    use tracing_subscriber::EnvFilter;
    use zcash_keys::encoding::AddressCodec;
    use zip32::AccountId;

    use crate::lightclient::LightClient;
    use crate::perspective::value_transfer::{
        SelfSendValueTransfer, SentValueTransfer, ValueTransfer, ValueTransferKind, ValueTransfers,
    };
    use crate::testutils::synthetic_wallet::inject_confirmed_orchard_notes;
    use crate::wallet::WalletSettings;

    use super::*;

    const NOTE_VALUE: u64 = 1_000_000;
    const TIP: u32 = 41;

    /// A real mock-net client, synced over an empty chain, handed one
    /// spendable legacy-Orchard note whose nullifier is really derived, so
    /// pepper-sync's spend detection marks it when a migration spends it
    /// and the summary sees the transaction as Orchard-funded.
    async fn orchard_funded_client() -> (MockNet, LightClient) {
        let mut net = MockNet::launch().await;
        {
            let mut chain = net.chain.write().await;
            chain.rules.anchors = false;
            chain.mine_empty_blocks(TIP);
        }
        let mut client = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        client
            .sync_and_await()
            .await
            .expect("initial sync succeeds");
        {
            let wallet_lock = client.wallet().clone();
            let mut wallet = wallet_lock.write().await;
            inject_confirmed_orchard_notes(&mut wallet, 1, NOTE_VALUE, TIP);
        }
        (net, client)
    }

    /// The first value transfer classified as an Orchard→Ironwood migration.
    fn migration_transfer(value_transfers: &ValueTransfers) -> Option<&ValueTransfer> {
        value_transfers.iter().find(|vt| {
            vt.kind
                == ValueTransferKind::Sent(SentValueTransfer::SendToSelf(
                    SelfSendValueTransfer::Migration,
                ))
        })
    }

    /// Mock-chain twin of libtonode `slow::zero_value_receipts` (live
    /// original kept as the control): a zero-value receipt must surface as
    /// exactly one Received{0, Orchard} value transfer and must not perturb
    /// spendable arithmetic across a subsequent send.
    #[tokio::test]
    async fn zero_value_receipts() {
        let mut net = MockNet::launch().await;
        let mut recipient = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua = get_base_address(&recipient, PoolType::IRONWOOD).await;

        net.chain.write().await.mine_empty_blocks(1);
        fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;
        // The zero-value receipt, in its own block as on the live chain.
        fund(&net, vec![(&recipient_ua, 0, None)], 1).await;

        recipient.sync_and_await().await.unwrap();
        from_inputs::quick_send(
            &mut recipient,
            vec![(&external_address(PoolType::IRONWOOD), 1_000, None)],
        )
        .await
        .unwrap();
        net.chain.write().await.mine_mempool();
        net.chain.write().await.mine_empty_blocks(1);
        recipient.sync_and_await().await.unwrap();

        // Identical to the live pin: the recipient holds the 100_000 funding
        // note less the 1_000 payment and its 10_000 ZIP-317 fee.
        check_client_balances!(recipient, i: 89_000 o: 0 s: 0 t: 0);

        let value_transfers = recipient.value_transfers(true).await.unwrap();
        assert!(
            value_transfers
                .iter()
                .any(|vt| vt.kind == ValueTransferKind::Received && vt.value == 100_000)
        );
        assert_eq!(
            value_transfers
                .iter()
                .filter(|vt| vt.kind == ValueTransferKind::Received
                    && vt.value == 0
                    && vt.pools_received == [PoolType::IRONWOOD])
                .count(),
            1
        );
        assert!(value_transfers.iter().any(|vt| {
            vt.kind == ValueTransferKind::Sent(SentValueTransfer::Send)
                && vt.value == 1_000
                && vt.transaction_fee == Some(10_000)
        }));
    }

    /// A confirmed Orchard→Ironwood immediate migration transaction must surface in the
    /// history as a `migration` value transfer, not `memo-to-self` and not
    /// `basic`. Its self-received Ironwood output carries the canonical empty
    /// memo (`MemoBytes::empty()`), so this pins the self-send classification
    /// order in `value_transfers()`: the migration predicate must win over the
    /// received-memo check regardless of how that memo decodes.
    #[tokio::test]
    async fn immediate_migration_is_a_migration_value_transfer() {
        use zip32::AccountId;

        let (net, mut client) = orchard_funded_client().await;

        let summary = client
            .migrate_immediately(AccountId::ZERO)
            .await
            .expect("the immediate migration builds and transmits");
        assert_eq!(
            summary.txids.len(),
            1,
            "one note migrates in one transaction"
        );

        net.chain.write().await.mine_mempool();
        client.sync_and_await().await.unwrap();

        let value_transfers = client.value_transfers(false).await.unwrap();
        assert!(
            migration_transfer(&value_transfers).is_some(),
            "the immediate migration transaction must classify as a migration value transfer; got {:?}",
            value_transfers.iter().map(|vt| vt.kind).collect::<Vec<_>>(),
        );
    }

    /// An Orchard-funded self-send that lands in the Ironwood pool AND carries a
    /// received memo must still classify as `migration`, not `memo-to-self`: the
    /// migration predicate wins the self-send classification regardless of
    /// memos, and the memo itself stays on the value transfer. This is the
    /// ordering pin for `value_transfers()`: before the reorder the memo check
    /// fired first and relabeled the migration `memo-to-self`.
    #[tokio::test]
    async fn migration_with_memo_is_still_a_migration_value_transfer() {
        const MEMO: &str = "moving my own funds";

        let (_net, mut client) = orchard_funded_client().await;

        // A send to the wallet's own orchard receiver lands in the Ironwood pool
        // post-NU6.3, funded from the legacy Orchard note: an Orchard→Ironwood
        // self-send carrying a real memo. Asserted on the pending (transmitted)
        // record, the state the history shows right after transmission, and the
        // same classification path as a confirmed transaction. (Mining it would
        // conflict the injected note's fabricated orchard tree leaf with the
        // send's real orchard commitments at the same positions.)
        let own_ua = get_base_address(&client, PoolType::Shielded(ShieldedPool::Orchard)).await;
        from_inputs::quick_send(&mut client, vec![(&own_ua, 50_000, Some(MEMO))])
            .await
            .unwrap();

        let value_transfers = client.value_transfers(false).await.unwrap();
        let migration = migration_transfer(&value_transfers).unwrap_or_else(|| {
            panic!(
                "the memo-carrying Orchard→Ironwood self-send must classify as a \
                 migration value transfer; got {:?}",
                value_transfers.iter().map(|vt| vt.kind).collect::<Vec<_>>(),
            )
        });
        assert!(
            migration.memos.iter().any(|memo| memo == MEMO),
            "the migration value transfer must keep its memo; got {:?}",
            migration.memos,
        );
    }

    // TODO: this test is long due to mock chain not serving the mempoool stream correctly. if it closes the stream
    // when a block is mined the sync engine will automatically check for new blocks instead of waiting until the backup interval has passed.
    // setting the interval below the expected interval of blocks being mined will harm sync efficiency.
    #[tokio::test]
    async fn gap_address_compact_block_scanning() {
        tracing_subscriber::fmt()
            .with_env_filter(EnvFilter::from_default_env())
            .init();

        let mut net = MockNet::launch().await;
        let mut recipient = net
            .client(
                zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
                Some(WalletSettings {
                    sync_config: SyncConfig {
                        transparent_address_discovery: TransparentAddressDiscovery {
                            gap_limit: 3,
                            scopes: TransparentAddressDiscoveryScopes::default(),
                        },
                        performance_level: PerformanceLevel::High,
                        shutdown_on_completion: false,
                    },
                    min_confirmations: NonZeroU32::try_from(1)
                        .expect("hard-coded non-zero integer"),
                }),
            )
            .await;

        // start the recipient syncing continuously and wait for the chain to be fully scanned
        net.chain.write().await.mine_empty_blocks(10);
        recipient.sync().await.unwrap();
        while recipient
            .latest_sync_status()
            .is_none_or(|status| !status.is_complete())
        {
            tokio::time::sleep(Duration::from_millis(100)).await;
        }

        // generate gap_limit+2 new taddrs without adding them directly to the wallet and fund them to trigger gap
        // address scanning in the chain tip compact blocks
        let recipient_clone = net
            .client(
                zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED,
                Some(WalletSettings {
                    sync_config: SyncConfig {
                        transparent_address_discovery: TransparentAddressDiscovery {
                            gap_limit: 3,
                            scopes: TransparentAddressDiscoveryScopes::default(),
                        },
                        performance_level: PerformanceLevel::High,
                        shutdown_on_completion: false,
                    },
                    min_confirmations: NonZeroU32::try_from(1)
                        .expect("hard-coded non-zero integer"),
                }),
            )
            .await;
        let mut gap_taddrs = Vec::new();
        let mut funding_txs = Vec::new();
        for _ in 0..5 {
            let gap_taddr = recipient_clone
                .wallet()
                .write()
                .await
                .generate_transparent_address(AccountId::ZERO, false)
                .unwrap();
            gap_taddrs.push(gap_taddr);

            let funding_tx = faucet_funding_transaction(vec![(
                &gap_taddr.1.encode(&recipient.chain_type()),
                100_000,
                None,
            )])
            .await;
            funding_txs.push(funding_tx);
        }
        net.chain.write().await.mine_block(funding_txs);

        let timeout = Duration::from_secs(150);
        let assert_start = Instant::now();
        while !(recipient
            .latest_sync_status()
            .unwrap()
            .scan_ranges
            .last()
            .unwrap()
            .block_range()
            .end
            == 12.into()
            && recipient.latest_sync_status().unwrap().is_complete())
        {
            if assert_start.elapsed() >= timeout {
                panic!("test time exceeded expected time to scan newly mined blocks");
            }
            tokio::time::sleep(Duration::from_millis(2_000)).await;
        }

        recipient.stop_sync().unwrap();
        recipient.await_sync().await.unwrap();

        // check all funds have been received and addresses have been added to the wallet, including the addresses
        // beyond the gap limit to prove the new blocks are being rescanend until the gap limit is satisfied
        check_client_balances!(recipient, i: 0 o: 0 s: 0 t: 500_000);
        for (id, addr) in gap_taddrs {
            assert!(
                recipient
                    .wallet()
                    .read()
                    .await
                    .transparent_addresses()
                    .iter()
                    .any(|(wallet_addr_id, wallet_addr)| *wallet_addr_id == id
                        && *wallet_addr == addr.encode(&recipient.chain_type()))
            );
        }
    }
}

/// A mock-chain send travels the mixnet route and says so: the receipt
/// names the Destination that accepted the transaction and the
/// session's SOCKS5 endpoint. Mock-net clients run with Mixnet Mode
/// switched on, so the Destination draw, the escalation rounds, and the
/// cap all run for real; only the bytes take the mock indexer's channel
/// instead of the tunnel.
#[cfg(feature = "nym")]
#[tokio::test]
async fn a_mock_chain_send_reports_the_mixnet_route() {
    use crate::lightclient::send::TransmitRoute;

    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let recipient_ua =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;
    recipient.sync_and_await().await.unwrap();
    check_client_balances!(recipient, i: 100_000 o: 0 s: 0 t: 0);

    let reports = from_inputs::quick_send_reported(
        &mut recipient,
        vec![(&external_address(PoolType::ORCHARD), 20_000, None)],
    )
    .await
    .unwrap();

    for report in &reports {
        match &report.route {
            TransmitRoute::Mixnet {
                destination,
                via_socks5,
            } => {
                assert_eq!(
                    via_socks5,
                    &crate::mocks::transmission::MOCK_SOCKS5_ADDR.to_string()
                );
                assert_eq!(
                    destination,
                    net.indexer_uri()
                        .host()
                        .expect("the mock indexer has a host"),
                    "a regtest draw names the sync indexer alone"
                );
            }
            TransmitRoute::Nakednet { destination } => {
                panic!("a mixnet-on session leaked the transmission to nakednet at {destination}")
            }
        }
    }

    net.chain.write().await.mine_mempool();
    recipient.sync_and_await().await.unwrap();

    // 100_000 funding minus the 20_000 payment and its 10_000 one-orchard-
    // spend, two-logical-action ZIP-317 fee.
    check_client_balances!(recipient, i: 70_000 o: 0 s: 0 t: 0);
}

/// The falsifier for [`a_mock_chain_send_reports_the_mixnet_route`]: the
/// nakednet transmit policy routes a transmission over nakednet even while
/// the mixnet stands ready, and its receipt names the sync indexer rather
/// than a Destination.
#[cfg(feature = "nym")]
#[tokio::test]
async fn the_nakednet_policy_reports_the_nakednet_route_over_a_ready_mixnet() {
    use crate::lightclient::send::TransmitRoute;

    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let recipient_ua =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;

    net.chain.write().await.mine_empty_blocks(1);
    fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;
    recipient.sync_and_await().await.unwrap();

    assert!(recipient.read_mixnet_indicator().is_ready());
    recipient.set_transmit_policy(crate::mixnet::TransmitPolicy::Nakednet);

    let reports = from_inputs::quick_send_reported(
        &mut recipient,
        vec![(&external_address(PoolType::ORCHARD), 20_000, None)],
    )
    .await
    .unwrap();

    for report in &reports {
        assert!(
            matches!(report.route, TransmitRoute::Nakednet { .. }),
            "a nakednet-policy session reported {:?} instead of nakednet",
            report.route
        );
    }
}

fn checkpoint_exists<S>(store: &S, height: u32) -> bool
where
    S: ShardStore<CheckpointId = BlockHeight>,
{
    store
        .get_checkpoint(&BlockHeight::from_u32(height))
        .expect("infallible")
        .is_some()
}

#[tokio::test]
async fn shardtree_roundtrip_restores_retained_checkpoints() {
    fn all_checkpoints_stored<S>(store: &S, chain_height: u32) -> bool
    where
        S: ShardStore<CheckpointId = BlockHeight>,
    {
        for boundary in [144, 288] {
            if !checkpoint_exists(store, boundary) {
                return false;
            }
        }
        for rolling_window in
            (chain_height - SHARDTREE_CHECKPOINT_ROLLING_WINDOW_SIZE + 1)..=chain_height
        {
            if !checkpoint_exists(store, rolling_window) {
                return false;
            }
        }

        true
    }

    fn all_boundaries_retained<S>(store: &S, chain_height: u32) -> bool
    where
        S: ShardStore<CheckpointId = BlockHeight>,
    {
        let retained = store.retained_checkpoints().unwrap();
        let no_of_boundaries = chain_height / 144;
        for boundary_index in 0..no_of_boundaries {
            let boundary = (boundary_index + 1) * 144;
            if !retained.contains(&BlockHeight::from_u32(boundary)) {
                return false;
            }
        }

        true
    }

    let mut chain_height = 500;
    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;

    net.chain.write().await.mine_empty_blocks(chain_height - 2);
    recipient.sync_and_await().await.unwrap();

    // create shielded note commitments to trigger checkpoint pruning
    let recipient_ua =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
    fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;
    recipient.sync_and_await().await.unwrap();

    {
        let shard_trees = &recipient.wallet().read().await.shard_trees;
        assert!(all_checkpoints_stored(
            shard_trees.sapling.store(),
            chain_height
        ));
        assert!(all_checkpoints_stored(
            shard_trees.orchard.store(),
            chain_height
        ));
        assert!(all_checkpoints_stored(
            shard_trees.ironwood.store(),
            chain_height
        ));
        assert!(all_boundaries_retained(
            shard_trees.sapling.store(),
            chain_height
        ));
        assert!(all_boundaries_retained(
            shard_trees.orchard.store(),
            chain_height
        ));
        assert!(all_boundaries_retained(
            shard_trees.ironwood.store(),
            chain_height
        ));
    }

    recipient.save_task().await;
    recipient.wait_for_save().await;
    recipient.shutdown_save_task().await.unwrap();
    drop(recipient);

    let mut reloaded_recipient = net.client_from_file(0).await;
    // create shielded note commitments to trigger checkpoint pruning on first sync of reloaded client
    fund(&net, vec![(&recipient_ua, 100_000, None)], 1).await;
    chain_height += 2;
    reloaded_recipient.sync_and_await().await.unwrap();
    {
        let shard_trees = &reloaded_recipient.wallet().read().await.shard_trees;
        assert!(all_checkpoints_stored(
            shard_trees.sapling.store(),
            chain_height
        ));
        assert!(all_checkpoints_stored(
            shard_trees.orchard.store(),
            chain_height
        ));
        assert!(all_checkpoints_stored(
            shard_trees.ironwood.store(),
            chain_height
        ));
        assert!(all_boundaries_retained(
            shard_trees.sapling.store(),
            chain_height
        ));
        assert!(all_boundaries_retained(
            shard_trees.orchard.store(),
            chain_height
        ));
        assert!(all_boundaries_retained(
            shard_trees.ironwood.store(),
            chain_height
        ));
    }
}

#[tokio::test]
async fn store_all_checkpoints_in_verification_window_on_the_mock_chain() {
    const PAYMENT: u64 = 10_000;
    const DENSE_CYCLES: u32 = 3;
    const EMPTY_MIDDLE_BLOCKS: u32 = 86;

    async fn dense_cycle(net: &MockNet, orchard_address: &str, sapling_address: &str) {
        fund(net, vec![(orchard_address, PAYMENT, None)], 0).await;
        fund(net, vec![(sapling_address, PAYMENT, None)], 0).await;
        fund(
            net,
            vec![
                (orchard_address, PAYMENT, None),
                (sapling_address, PAYMENT, None),
            ],
            1,
        )
        .await;
    }

    let mut net = MockNet::launch().await;
    let mut recipient = net
        .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
        .await;
    let orchard_address =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
    let sapling_address =
        get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Sapling)).await;

    net.chain.write().await.mine_empty_blocks(1);
    for _ in 0..DENSE_CYCLES {
        dense_cycle(&net, &orchard_address, &sapling_address).await;
    }
    net.chain
        .write()
        .await
        .mine_empty_blocks(EMPTY_MIDDLE_BLOCKS);
    for _ in 0..DENSE_CYCLES {
        dense_cycle(&net, &orchard_address, &sapling_address).await;
    }
    recipient.sync_and_await().await.unwrap();

    let tip = net.chain.read().await.tip();
    let window_start = tip - pepper_sync::sync::MAX_REORG_ALLOWANCE + 1;
    let wallet = recipient.wallet().read().await;
    let shard_trees = &wallet.shard_trees;
    for height in window_start..=tip {
        assert!(
            checkpoint_exists(shard_trees.sapling.store(), height),
            "missing sapling checkpoint at height {height}"
        );
        assert!(
            checkpoint_exists(shard_trees.orchard.store(), height),
            "missing orchard checkpoint at height {height}"
        );
        assert!(
            checkpoint_exists(shard_trees.ironwood.store(), height),
            "missing ironwood checkpoint at height {height}"
        );
    }
}

mod strict_chain {
    use std::time::Duration;

    use zaino_proto::tonic::Code;
    use zcash_protocol::consensus::COINBASE_MATURITY_BLOCKS;
    use zcash_protocol::value::Zatoshis;
    use zingo_status::confirmation_status::ConfirmationStatus;

    use pepper_sync::wallet::KeyIdInterface;
    use pepper_sync::wallet::traits::SyncWallet;

    use crate::lightclient::LightClient;
    use crate::testutils::chain_generics::fixtures;
    use crate::testutils::mock_indexer::{Fault, LostSendDestination, Rpc};

    use super::*;

    const FUNDING: u64 = 100_000;
    const PAYMENT: u64 = 10_000;
    const REWARD_ZATS: u64 = 1_000_000;
    const REWARD: Zatoshis = Zatoshis::const_from_u64(REWARD_ZATS);

    async fn funded_sender(net: &mut MockNet) -> LightClient {
        let mut sender = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        sender.set_transmit_retry_interval(Duration::ZERO);
        let sender_ua = get_base_address(&sender, PoolType::Shielded(ShieldedPool::Orchard)).await;
        fund(net, vec![(&sender_ua, FUNDING, None)], 1).await;
        sender.sync_and_await().await.unwrap();
        check_client_balances!(sender, i: FUNDING o: 0 s: 0 t: 0);
        sender
    }

    #[tokio::test]
    async fn rejected_transaction_gets_failed_status() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        from_inputs::propose(
            &mut sender,
            vec![(&external_address(PoolType::ORCHARD), PAYMENT, None)],
        )
        .await
        .unwrap();
        let calculated = sender.calculate_stored_proposal().await.unwrap();
        let expiry = {
            let wallet = sender.wallet().read().await;
            wallet
                .wallet_transactions
                .get(&calculated[0])
                .unwrap()
                .transaction()
                .expiry_height()
        };
        {
            let mut chain = net.chain.write().await;
            let tip = chain.tip();
            chain.mine_empty_blocks(u32::from(expiry) - tip);
        }

        let err = sender
            .transmit_calculated(calculated.clone())
            .await
            .unwrap_err();
        assert!(format!("{err:?}").contains("expired"), "{err:?}");
        let wallet = sender.wallet().read().await;
        assert!(matches!(
            wallet
                .wallet_transactions
                .get(&calculated[0])
                .unwrap()
                .status(),
            ConfirmationStatus::Failed(_)
        ));
        assert_eq!(net.chain.read().await.mempool_len(), 0);
    }

    #[tokio::test]
    async fn transmitted_transaction_has_mempool_status_before_mining() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let txids = from_inputs::quick_send(
            &mut sender,
            vec![(&external_address(PoolType::ORCHARD), PAYMENT, None)],
        )
        .await
        .unwrap();
        assert_eq!(net.chain.read().await.mempool_len(), 1);

        sender.sync_and_await().await.unwrap();
        let summaries = sender.transaction_summaries(false).await.unwrap();
        let sent = summaries
            .iter()
            .find(|summary| summary.txid == txids[0])
            .unwrap();
        assert!(
            matches!(sent.status, ConfirmationStatus::Mempool(_)),
            "{:?}",
            sent.status
        );

        net.chain.write().await.mine_mempool();
        sender.sync_and_await().await.unwrap();
        let summaries = sender.transaction_summaries(false).await.unwrap();
        let sent = summaries
            .iter()
            .find(|summary| summary.txid == txids[0])
            .unwrap();
        assert!(matches!(sent.status, ConfirmationStatus::Confirmed(_)));
    }

    #[tokio::test]
    async fn sync_recovers_from_a_truncated_block_stream() {
        let mut net = MockNet::launch().await;
        let mut recipient = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        fund(&net, vec![(&recipient_ua, FUNDING, None)], 3).await;
        net.chain
            .write()
            .await
            .faults
            .inject(Rpc::BlockRange, Fault::TruncateStream { after: 1 });

        recipient.sync_and_await().await.unwrap();
        assert_eq!(net.chain.read().await.faults.pending(Rpc::BlockRange), 0);
        check_client_balances!(recipient, i: FUNDING o: 0 s: 0 t: 0);
    }

    #[tokio::test]
    async fn wait_for_sync_on_a_shared_reference_closes_the_status_channel() {
        let mut net = MockNet::launch().await;
        let mut client = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        net.chain.write().await.mine_empty_blocks(2);

        client.sync().await.unwrap();
        let mut status = client.subscribe_sync_status();
        let shared = &client;
        shared.wait_for_sync().await;

        assert!(
            status.changed().await.is_ok(),
            "the sync engine pushed a status update"
        );
        assert!(status.borrow_and_update().is_some());
        assert!(
            status.changed().await.is_err(),
            "the watch channel closed when sync finished"
        );
        client.await_sync().await.unwrap();
        assert_eq!(
            client.sync_mode(),
            pepper_sync::wallet::SyncMode::NotRunning
        );
    }

    #[tokio::test]
    async fn sync_fails_while_the_indexer_is_unavailable() {
        let mut net = MockNet::launch().await;
        let mut client = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        net.chain.write().await.mine_empty_blocks(2);
        {
            let mut chain = net.chain.write().await;
            for _ in 0..5 {
                chain.faults.inject(
                    Rpc::LatestBlock,
                    Fault::Fail(Code::Unavailable, "mock outage".to_string()),
                );
            }
        }
        assert!(client.sync_and_await().await.is_err());
    }

    #[tokio::test]
    async fn coinbase_reward_becomes_spendable_after_maturity() {
        let mut net = MockNet::launch().await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        miner.set_transmit_retry_interval(Duration::ZERO);
        let miner_taddr = get_base_address(&miner, PoolType::Transparent).await;
        let coinbase = {
            let mut chain = net.chain.write().await;
            let coinbase = chain.mine_block_rewarding(&miner_taddr, REWARD, vec![]);
            chain.mine_empty_blocks(1);
            coinbase
        };
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: 0 o: 0 s: 0 t: 0);
        let summaries = miner.transaction_summaries(false).await.unwrap();
        assert!(summaries.iter().any(|summary| summary.value == REWARD_ZATS
            && summary.status == ConfirmationStatus::Confirmed(BlockHeight::from_u32(1))));
        assert!(!coinbase.is_empty());

        net.chain
            .write()
            .await
            .mine_empty_blocks(COINBASE_MATURITY_BLOCKS);
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: 0 o: 0 s: 0 t: REWARD_ZATS);

        miner.quick_shield(zip32::AccountId::ZERO).await.unwrap();
        assert_eq!(net.chain.read().await.mempool_len(), 1);
        net.chain.write().await.mine_mempool();
        miner.sync_and_await().await.unwrap();
        let balance = miner.account_balance(zip32::AccountId::ZERO).await.unwrap();
        assert_eq!(balance.confirmed_transparent_balance.unwrap().into_u64(), 0);
        assert!(balance.total_ironwood_balance.unwrap().into_u64() > 0);
    }

    #[tokio::test]
    async fn generate_a_range_of_value_transfers_on_the_mock_chain() {
        fixtures::create_various_value_transfers::<MockNet>().await;
    }

    #[tokio::test]
    async fn send_shield_cycle_on_the_mock_chain() {
        fixtures::send_shield_cycle::<MockNet>(1).await;
    }

    use nonempty::NonEmpty;
    use pepper_sync::keys::transparent::TransparentScope;
    use pepper_sync::wallet::OutputInterface;
    use zcash_client_backend::data_api::OutputLockStore;
    use zcash_client_backend::zip321::{Payment, TransactionRequest};
    use zcash_primitives::transaction::TxId;

    use crate::wallet::LightWallet;

    const RETRIES_BEFORE_DELIVERY_CHECK: usize = 4;
    const ONE_INPUT_SEND_FEE: u64 = 10_000;
    const QUEUED_REJECTIONS: usize = 40;
    const ZAINO_EXPIRED_MESSAGE: &str = "unhandled rpc-specific zaino_fetch::jsonrpsee::response::SendTransactionError error: RPC Error (code: -26): transaction has expired";

    fn expected_after_one_send() -> u64 {
        FUNDING - PAYMENT - ONE_INPUT_SEND_FEE
    }

    fn ironwood_notes_unspent(wallet: &LightWallet) -> bool {
        wallet
            .wallet_transactions
            .values()
            .flat_map(IronwoodNote::transaction_outputs)
            .all(|note| note.spending_transaction().is_none())
    }

    fn refund_address_count(wallet: &LightWallet) -> usize {
        wallet
            .transparent_addresses()
            .keys()
            .filter(|id| id.scope() == TransparentScope::Refund)
            .count()
    }

    async fn status_of(client: &LightClient, txid: &TxId) -> ConfirmationStatus {
        client
            .wallet()
            .read()
            .await
            .wallet_transactions
            .get(txid)
            .unwrap()
            .status()
    }

    async fn calculated_send(sender: &mut LightClient) -> NonEmpty<TxId> {
        from_inputs::propose(
            sender,
            vec![(&external_address(PoolType::ORCHARD), PAYMENT, None)],
        )
        .await
        .unwrap();
        sender.calculate_stored_proposal().await.unwrap()
    }

    async fn expiry_of(sender: &LightClient, txid: &TxId) -> BlockHeight {
        sender
            .wallet()
            .read()
            .await
            .wallet_transactions
            .get(txid)
            .unwrap()
            .transaction()
            .expiry_height()
    }

    async fn transmit_after_expiry(net: &MockNet, sender: &mut LightClient) -> NonEmpty<TxId> {
        let calculated = calculated_send(sender).await;
        let expiry = expiry_of(sender, &calculated[0]).await;
        {
            let mut chain = net.chain.write().await;
            let tip = chain.tip();
            chain.mine_empty_blocks(u32::from(expiry) - tip);
        }
        sender
            .transmit_calculated(calculated.clone())
            .await
            .unwrap_err();
        assert!(matches!(
            status_of(sender, &calculated[0]).await,
            ConfirmationStatus::Failed(_)
        ));
        calculated
    }

    fn tex_request() -> TransactionRequest {
        use pepper_sync::keys::decode_address;
        use zcash_client_backend::address::Address;
        use zcash_transparent::address::TransparentAddress;

        let external_wallet =
            SyntheticWalletBuilder::new(zingo_test_vectors::seeds::ABANDON_ART_SEED).build();
        let taddr = external_wallet
            .transparent_addresses()
            .values()
            .next()
            .unwrap()
            .clone();
        let Address::Transparent(TransparentAddress::PublicKeyHash(taddr_bytes)) =
            decode_address(&external_wallet.chain_type(), &taddr).unwrap()
        else {
            panic!("a wallet-generated first taddr is p2pkh")
        };
        let tex_address = crate::testutils::interpret_taddr_as_tex_addr(
            taddr_bytes,
            &external_wallet.chain_type(),
        );
        TransactionRequest::new(vec![Payment::without_memo(
            zcash_address::ZcashAddress::try_from_encoded(&tex_address).unwrap(),
            Zatoshis::const_from_u64(PAYMENT),
        )])
        .unwrap()
    }

    async fn calculated_tex_send(sender: &mut LightClient) -> NonEmpty<TxId> {
        sender
            .propose_send(tex_request(), zip32::AccountId::ZERO)
            .await
            .unwrap();
        let calculated = sender.calculate_stored_proposal().await.unwrap();
        assert_eq!(calculated.len(), 2);
        calculated
    }

    fn inject_send_failures(chain: &mut crate::testutils::mock_indexer::MockChain, count: usize) {
        for _ in 0..count {
            chain.faults.inject(
                Rpc::SendTransaction,
                Fault::Fail(Code::Unavailable, "mock outage".to_string()),
            );
        }
    }

    #[tokio::test]
    async fn accepted_send_marked_failed_is_confirmed_after_mining() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let calculated = calculated_send(&mut sender).await;
        {
            let mut chain = net.chain.write().await;
            chain.lose_next_send_response = Some(LostSendDestination::Mempool);
            chain
                .faults
                .inject(Rpc::SendTransaction, Fault::Delay(Duration::ZERO));
            inject_send_failures(&mut chain, QUEUED_REJECTIONS);
        }

        sender
            .transmit_calculated(calculated.clone())
            .await
            .unwrap_err();
        assert!(matches!(
            status_of(&sender, &calculated[0]).await,
            ConfirmationStatus::Failed(_)
        ));
        assert_eq!(net.chain.read().await.mempool_len(), 1);
        assert!(ironwood_notes_unspent(&*sender.wallet().read().await));

        net.chain.write().await.mine_mempool();
        sender.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&sender, &calculated[0]).await,
            ConfirmationStatus::Confirmed(_)
        ));
        let expected = expected_after_one_send();
        check_client_balances!(sender, i: expected o: 0 s: 0 t: 0);
    }

    #[tokio::test]
    async fn released_inputs_are_reselected_after_a_rejection() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        transmit_after_expiry(&net, &mut sender).await;
        assert!(ironwood_notes_unspent(&*sender.wallet().read().await));

        sender.sync_and_await().await.unwrap();
        let resent = from_inputs::quick_send(
            &mut sender,
            vec![(&external_address(PoolType::ORCHARD), PAYMENT, None)],
        )
        .await
        .unwrap();
        assert_eq!(net.chain.read().await.mempool_len(), 1);
        net.chain.write().await.mine_mempool();
        sender.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&sender, &resent[0]).await,
            ConfirmationStatus::Confirmed(_)
        ));
        let expected = expected_after_one_send();
        check_client_balances!(sender, i: expected o: 0 s: 0 t: 0);
    }

    #[tokio::test]
    async fn later_step_rejected_leaves_earlier_step_transmitted() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let calculated = calculated_tex_send(&mut sender).await;
        {
            let mut chain = net.chain.write().await;
            chain
                .faults
                .inject(Rpc::SendTransaction, Fault::Delay(Duration::ZERO));
            inject_send_failures(&mut chain, QUEUED_REJECTIONS);
        }

        sender
            .transmit_calculated(calculated.clone())
            .await
            .unwrap_err();
        assert!(matches!(
            status_of(&sender, &calculated[0]).await,
            ConfirmationStatus::Transmitted(_)
        ));
        assert!(matches!(
            status_of(&sender, &calculated[1]).await,
            ConfirmationStatus::Failed(_)
        ));
        assert_eq!(net.chain.read().await.mempool_len(), 1);

        net.chain.write().await.mine_mempool();
        sender.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&sender, &calculated[0]).await,
            ConfirmationStatus::Confirmed(_)
        ));
        assert!(matches!(
            status_of(&sender, &calculated[1]).await,
            ConfirmationStatus::Failed(_)
        ));
        let balance = sender
            .account_balance(zip32::AccountId::ZERO)
            .await
            .unwrap();
        assert!(balance.confirmed_transparent_balance.unwrap().into_u64() > 0);
    }

    async fn failed_first_step_via_quick_send(net: &MockNet, sender: &mut LightClient) {
        inject_send_failures(&mut *net.chain.write().await, QUEUED_REJECTIONS);
        sender
            .quick_send(tex_request(), zip32::AccountId::ZERO, true)
            .await
            .unwrap_err();
    }

    fn steps_by_status(wallet: &LightWallet) -> (Vec<TxId>, Vec<TxId>) {
        let mut failed = Vec::new();
        let mut calculated = Vec::new();
        for transaction in wallet.wallet_transactions.values() {
            match transaction.status() {
                ConfirmationStatus::Failed(_) => failed.push(transaction.txid()),
                ConfirmationStatus::Calculated(_) => calculated.push(transaction.txid()),
                _ => (),
            }
        }
        (failed, calculated)
    }

    fn refund_address_ids(
        wallet: &LightWallet,
        account_id: zip32::AccountId,
    ) -> Vec<pepper_sync::keys::transparent::TransparentAddressId> {
        wallet
            .transparent_addresses()
            .keys()
            .filter(|id| id.scope() == TransparentScope::Refund && id.account_id() == account_id)
            .copied()
            .collect()
    }

    async fn confirmed_tex_send(net: &MockNet, sender: &mut LightClient) -> NonEmpty<TxId> {
        let steps = sender
            .quick_send(tex_request(), zip32::AccountId::ZERO, true)
            .await
            .unwrap();
        assert_eq!(steps.len(), 2);
        assert_eq!(net.chain.read().await.mempool_len(), 2);
        net.chain.write().await.mine_mempool();
        sender.sync_and_await().await.unwrap();
        steps
    }

    #[tokio::test]
    async fn tex_send_confirms_on_the_strict_mock_chain() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let steps = confirmed_tex_send(&net, &mut sender).await;
        for txid in &steps {
            assert!(matches!(
                status_of(&sender, txid).await,
                ConfirmationStatus::Confirmed(_)
            ));
        }
        let wallet = sender.wallet().read().await;
        assert_eq!(refund_address_ids(&wallet, zip32::AccountId::ZERO).len(), 1);
        assert_eq!(net.chain.read().await.mempool_len(), 0);
    }

    #[tokio::test]
    async fn failed_send_in_one_account_keeps_refund_addresses_of_other_accounts() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        confirmed_tex_send(&net, &mut sender).await;
        let other_account = zip32::AccountId::try_from(1).unwrap();
        let other_ua = {
            let mut wallet = sender.wallet().write().await;
            wallet.create_new_account().unwrap();
            let (_, address) = wallet
                .generate_unified_address(ReceiverSelection::all_shielded(), other_account)
                .unwrap();
            address.encode(&wallet.chain_type())
        };
        fund(&net, vec![(&other_ua, FUNDING, None)], 1).await;
        sender.sync_and_await().await.unwrap();
        assert_eq!(
            sender
                .account_balance(other_account)
                .await
                .unwrap()
                .confirmed_ironwood_balance
                .unwrap()
                .into_u64(),
            FUNDING
        );
        let first_account_refunds_before =
            refund_address_ids(&*sender.wallet().read().await, zip32::AccountId::ZERO);
        assert_eq!(first_account_refunds_before.len(), 1);

        inject_send_failures(&mut *net.chain.write().await, QUEUED_REJECTIONS);
        sender
            .quick_send(tex_request(), other_account, true)
            .await
            .unwrap_err();

        let wallet = sender.wallet().read().await;
        assert_eq!(
            refund_address_ids(&wallet, zip32::AccountId::ZERO),
            first_account_refunds_before
        );
        assert!(refund_address_ids(&wallet, other_account).is_empty());
    }

    #[tokio::test]
    async fn failed_first_step_via_quick_send_truncates_refund_addresses() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let refund_addresses_before = refund_address_count(&*sender.wallet().read().await);
        failed_first_step_via_quick_send(&net, &mut sender).await;
        let wallet = sender.wallet().read().await;
        assert!(ironwood_notes_unspent(&wallet));
        assert_eq!(refund_address_count(&wallet), refund_addresses_before);
        assert_eq!(net.chain.read().await.mempool_len(), 0);
    }

    #[tokio::test]
    async fn failed_first_step_via_quick_send_fails_the_second_step() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        failed_first_step_via_quick_send(&net, &mut sender).await;
        let (failed, calculated) = steps_by_status(&*sender.wallet().read().await);
        assert_eq!(failed.len(), 2);
        assert!(
            calculated.is_empty(),
            "the second step must not stay Calculated after the first step failed: {calculated:?}"
        );
    }

    #[tokio::test]
    async fn failed_first_step_via_transmit_calculated_truncates_refund_addresses() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let refund_addresses_before = refund_address_count(&*sender.wallet().read().await);
        let calculated = calculated_tex_send(&mut sender).await;
        inject_send_failures(&mut *net.chain.write().await, QUEUED_REJECTIONS);
        sender
            .transmit_calculated(calculated.clone())
            .await
            .unwrap_err();
        assert!(matches!(
            status_of(&sender, &calculated[0]).await,
            ConfirmationStatus::Failed(_)
        ));
        let wallet = sender.wallet().read().await;
        assert!(ironwood_notes_unspent(&wallet));
        assert_eq!(refund_address_count(&wallet), refund_addresses_before);
    }

    #[tokio::test]
    async fn output_locks_are_released_after_a_rejection() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        transmit_after_expiry(&net, &mut sender).await;
        let wallet = sender.wallet().read().await;
        assert!(
            wallet
                .get_locked_outputs(zip32::AccountId::ZERO)
                .unwrap()
                .is_empty()
        );
    }

    #[tokio::test]
    async fn failed_send_survives_a_wallet_file_round_trip() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let calculated = transmit_after_expiry(&net, &mut sender).await;
        sender.save_task().await;
        sender.wait_for_save().await;
        sender.shutdown_save_task().await.unwrap();
        drop(sender);

        let mut reloaded = net.client_from_file(0).await;
        reloaded.set_transmit_retry_interval(Duration::ZERO);
        assert!(matches!(
            status_of(&reloaded, &calculated[0]).await,
            ConfirmationStatus::Failed(_)
        ));
        assert!(ironwood_notes_unspent(&*reloaded.wallet().read().await));

        reloaded.sync_and_await().await.unwrap();
        from_inputs::quick_send(
            &mut reloaded,
            vec![(&external_address(PoolType::ORCHARD), PAYMENT, None)],
        )
        .await
        .unwrap();
        net.chain.write().await.mine_mempool();
        reloaded.sync_and_await().await.unwrap();
        let expected = expected_after_one_send();
        check_client_balances!(reloaded, i: expected o: 0 s: 0 t: 0);
    }

    #[tokio::test]
    async fn a_rejection_is_retried_three_times_before_failing() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let calculated = calculated_send(&mut sender).await;
        {
            let mut chain = net.chain.write().await;
            for _ in 0..QUEUED_REJECTIONS {
                chain.faults.inject(
                    Rpc::SendTransaction,
                    Fault::Fail(Code::Internal, ZAINO_EXPIRED_MESSAGE.to_string()),
                );
            }
        }

        sender
            .transmit_calculated(calculated.clone())
            .await
            .unwrap_err();
        let attempts =
            QUEUED_REJECTIONS - net.chain.read().await.faults.pending(Rpc::SendTransaction);
        assert!(attempts > 0);
        assert_eq!(attempts % RETRIES_BEFORE_DELIVERY_CHECK, 0);
        assert!(matches!(
            status_of(&sender, &calculated[0]).await,
            ConfirmationStatus::Failed(_)
        ));
    }

    use zcash_primitives::transaction::Transaction;
    use zcash_protocol::consensus::BranchId;

    const BLOCK_FETCH_FAILURES: usize = 8;

    fn expiry_of_bytes(net: &MockNet, bytes: &[u8]) -> BlockHeight {
        Transaction::read(
            bytes,
            BranchId::for_height(&net.chain_type(), BlockHeight::from_u32(1)),
        )
        .unwrap()
        .expiry_height()
    }

    async fn pending_txid(client: &LightClient) -> TxId {
        client
            .wallet()
            .read()
            .await
            .wallet_transactions
            .values()
            .find(|transaction| transaction.status().is_pending())
            .unwrap()
            .txid()
    }

    async fn mine_past_expiry(net: &MockNet, expiry: BlockHeight) {
        let mut chain = net.chain.write().await;
        chain.mine_mempool();
        let tip = chain.tip();
        chain.mine_empty_blocks(u32::from(expiry) - tip);
    }

    async fn fail_next_block_fetches(net: &MockNet) {
        let mut chain = net.chain.write().await;
        for _ in 0..BLOCK_FETCH_FAILURES {
            chain.faults.inject(
                Rpc::BlockRange,
                Fault::Fail(Code::Unavailable, "mock outage".to_string()),
            );
        }
    }

    #[tokio::test]
    async fn received_transaction_is_not_failed_by_a_session_that_never_scans_its_block() {
        let mut net = MockNet::launch().await;
        let mut recipient = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.chain.write().await.mine_empty_blocks(1);
        recipient.sync_and_await().await.unwrap();

        let funding = faucet_funding_transaction(vec![(&recipient_ua, FUNDING, None)]).await;
        let expiry = expiry_of_bytes(&net, &funding);
        net.chain.write().await.enter_mempool(funding);
        recipient.sync_and_await().await.unwrap();
        let txid = pending_txid(&recipient).await;
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Mempool(_)
        ));

        mine_past_expiry(&net, expiry).await;
        fail_next_block_fetches(&net).await;
        assert!(recipient.sync_and_await().await.is_err());
        assert!(
            !matches!(
                status_of(&recipient, &txid).await,
                ConfirmationStatus::Failed(_)
            ),
            "a received transaction mined in an unscanned block was marked Failed"
        );

        net.chain.write().await.faults.clear(Rpc::BlockRange);
        recipient.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Confirmed(_)
        ));
        check_client_balances!(recipient, i: FUNDING o: 0 s: 0 t: 0);
    }

    #[tokio::test]
    async fn received_transaction_that_expires_unmined_is_failed() {
        let mut net = MockNet::launch().await;
        let mut recipient = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.chain.write().await.mine_empty_blocks(1);
        recipient.sync_and_await().await.unwrap();

        let funding = faucet_funding_transaction(vec![(&recipient_ua, FUNDING, None)]).await;
        let expiry = expiry_of_bytes(&net, &funding);
        net.chain.write().await.enter_mempool(funding);
        recipient.sync_and_await().await.unwrap();
        let txid = pending_txid(&recipient).await;
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Mempool(_)
        ));

        {
            let mut chain = net.chain.write().await;
            let tip = chain.tip();
            chain.mine_empty_blocks(u32::from(expiry) - tip);
            assert_eq!(chain.mempool_len(), 0);
        }
        recipient.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Failed(_)
        ));
        check_client_balances!(recipient, i: 0 o: 0 s: 0 t: 0);

        net.chain.write().await.mine_empty_blocks(1);
        recipient.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Failed(_)
        ));
    }

    #[tokio::test]
    async fn mined_send_inputs_stay_spent_through_a_session_that_never_scans_its_block() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let sent = from_inputs::quick_send(
            &mut sender,
            vec![(&external_address(PoolType::ORCHARD), PAYMENT, None)],
        )
        .await
        .unwrap();
        let expiry = expiry_of(&sender, &sent[0]).await;

        mine_past_expiry(&net, expiry).await;
        fail_next_block_fetches(&net).await;
        assert!(sender.sync_and_await().await.is_err());
        assert!(
            !matches!(
                status_of(&sender, &sent[0]).await,
                ConfirmationStatus::Failed(_)
            ),
            "a mined send in an unscanned block was marked Failed"
        );
        assert!(!ironwood_notes_unspent(&*sender.wallet().read().await));
        let expected = expected_after_one_send();
        check_client_balances!(sender, i: expected o: 0 s: 0 t: 0);

        net.chain.write().await.faults.clear(Rpc::BlockRange);
        sender.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&sender, &sent[0]).await,
            ConfirmationStatus::Confirmed(_)
        ));
        check_client_balances!(sender, i: expected o: 0 s: 0 t: 0);
    }

    use crate::wallet::summary::data::{SendType, TransactionKind, TransactionSummary};

    async fn summary_of(client: &LightClient, txid: &TxId) -> TransactionSummary {
        client
            .transaction_summaries(false)
            .await
            .unwrap()
            .iter()
            .find(|summary| summary.txid == *txid)
            .unwrap()
            .clone()
    }

    /// Failing a transaction releases its inputs, so the wallet no longer
    /// records any spend in it. Its outgoing note already keeps it out of
    /// `Received`, so what this guards is the rest of the sent shape: the
    /// funding pool and the fee stay attributed to the failed send.
    #[tokio::test]
    async fn failed_send_reads_as_sent() {
        let mut net = MockNet::launch().await;
        let mut sender = funded_sender(&mut net).await;
        let calculated = transmit_after_expiry(&net, &mut sender).await;
        assert!(ironwood_notes_unspent(&*sender.wallet().read().await));

        let failed = summary_of(&sender, &calculated[0]).await;
        assert!(matches!(failed.status, ConfirmationStatus::Failed(_)));
        assert_eq!(failed.kind, TransactionKind::Sent(SendType::Send));
        assert_eq!(failed.value, PAYMENT);
        assert_eq!(failed.fee, Some(ONE_INPUT_SEND_FEE));
        assert_eq!(failed.pools_sent_from, vec![PoolType::IRONWOOD]);

        // Sync releases nothing further and does not reclassify the failure.
        sender.sync_and_await().await.unwrap();
        let failed = summary_of(&sender, &calculated[0]).await;
        assert_eq!(failed.kind, TransactionKind::Sent(SendType::Send));
    }

    /// The report in issue #2756: a wallet holding only transparent funds
    /// shields, the shield fails, and history shows a receipt that paid a
    /// fee. The failed shield must read as a shield.
    #[tokio::test]
    async fn failed_shield_reads_as_shield() {
        let mut net = MockNet::launch().await;
        let mut shielder = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        shielder.set_transmit_retry_interval(Duration::ZERO);
        let taddr = get_base_address(&shielder, PoolType::Transparent).await;
        fund(&net, vec![(&taddr, FUNDING, None)], 1).await;
        shielder.sync_and_await().await.unwrap();
        check_client_balances!(shielder, i: 0 o: 0 s: 0 t: FUNDING);

        shielder
            .propose_shield(zip32::AccountId::ZERO)
            .await
            .unwrap();
        let calculated = shielder.calculate_stored_proposal().await.unwrap();
        let expiry = expiry_of(&shielder, &calculated[0]).await;
        mine_past_expiry(&net, expiry).await;
        shielder
            .transmit_calculated(calculated.clone())
            .await
            .unwrap_err();

        let failed = summary_of(&shielder, &calculated[0]).await;
        assert!(matches!(failed.status, ConfirmationStatus::Failed(_)));
        assert_eq!(failed.kind, TransactionKind::Sent(SendType::Shield));
        assert!(failed.fee.is_some());
        assert_eq!(failed.pools_sent_from, vec![PoolType::TRANSPARENT]);
        assert_eq!(failed.outgoing_transparent_coins, vec![]);

        // The released coin is still the wallet's whole transparent balance.
        shielder.sync_and_await().await.unwrap();
        check_client_balances!(shielder, i: 0 o: 0 s: 0 t: FUNDING);
    }

    const HELD_FETCH: Duration = Duration::from_secs(8);
    const TRANSACTION_FETCH_FAILURES: usize = 8;
    const HOLD_POLL: Duration = Duration::from_millis(10);
    const HOLD_WAIT_LIMIT: Duration = Duration::from_secs(4);
    const BLOCKS_BELOW_EXPIRY_AT_LAST_SYNC: u32 = 5;
    const REORG_VERIFY_BLOCKS: u32 = 10;

    async fn fully_scanned_height(client: &LightClient) -> BlockHeight {
        client
            .wallet()
            .read()
            .await
            .get_sync_state()
            .unwrap()
            .fully_scanned_height()
            .unwrap()
    }

    async fn wait_until_scanned_through(client: &LightClient, height: BlockHeight) {
        let started = tokio::time::Instant::now();
        while fully_scanned_height(client).await < height {
            assert!(
                started.elapsed() < HOLD_WAIT_LIMIT,
                "the sync engine did not scan through {height} in time"
            );
            tokio::time::sleep(HOLD_POLL).await;
        }
    }

    async fn wait_until_fetch_is_held(net: &MockNet) {
        let started = tokio::time::Instant::now();
        while net.chain.read().await.faults.pending(Rpc::Transaction) > 0 {
            assert!(
                started.elapsed() < HOLD_WAIT_LIMIT,
                "the sync engine did not request the transaction in time"
            );
            tokio::time::sleep(HOLD_POLL).await;
        }
    }

    /// Syncs a recipient whose last known chain height is a few blocks below
    /// the expiry of a funding transaction that is still in the mempool.
    async fn mempool_transaction_near_expiry(
        net: &mut MockNet,
    ) -> (LightClient, String, TxId, BlockHeight) {
        let mut recipient = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.chain.write().await.mine_empty_blocks(1);
        recipient.sync_and_await().await.unwrap();

        let funding = faucet_funding_transaction(vec![(&recipient_ua, FUNDING, None)]).await;
        let expiry = expiry_of_bytes(net, &funding);
        {
            let mut chain = net.chain.write().await;
            chain.enter_mempool(funding);
            let last_sync_height = u32::from(expiry) - BLOCKS_BELOW_EXPIRY_AT_LAST_SYNC;
            let tip = chain.tip();
            assert!(last_sync_height > tip);
            chain.mine_empty_blocks(last_sync_height - tip);
        }
        recipient.sync_and_await().await.unwrap();
        let txid = pending_txid(&recipient).await;
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Mempool(_)
        ));
        (recipient, recipient_ua, txid, expiry)
    }

    /// Mines past `expiry`, then funds `recipient_ua` in a block above the
    /// reorg verification range so that block is scanned by a separate task
    /// after the expiry height is already scanned.
    async fn mine_past_expiry_and_fund_above_verify_range(
        net: &MockNet,
        recipient_ua: &str,
        expiry: BlockHeight,
    ) {
        {
            let mut chain = net.chain.write().await;
            let verify_end =
                u32::from(expiry) - BLOCKS_BELOW_EXPIRY_AT_LAST_SYNC + REORG_VERIFY_BLOCKS;
            let tip = chain.tip();
            chain.mine_empty_blocks(verify_end - tip);
            assert_eq!(chain.mempool_len(), 0);
        }
        fund(net, vec![(recipient_ua, FUNDING, None)], 0).await;
    }

    #[tokio::test]
    async fn stopped_session_that_scanned_past_expiry_fails_the_transaction() {
        let mut net = MockNet::launch().await;
        let (mut recipient, recipient_ua, txid, expiry) =
            mempool_transaction_near_expiry(&mut net).await;
        mine_past_expiry_and_fund_above_verify_range(&net, &recipient_ua, expiry).await;
        net.chain
            .write()
            .await
            .faults
            .inject(Rpc::Transaction, Fault::Delay(HELD_FETCH));

        recipient.sync().await.unwrap();
        wait_until_scanned_through(&recipient, expiry).await;
        recipient.stop_sync().unwrap();
        recipient.await_sync().await.unwrap();
        assert!(fully_scanned_height(&recipient).await >= expiry);
        assert!(
            matches!(
                status_of(&recipient, &txid).await,
                ConfirmationStatus::Failed(_)
            ),
            "a stopped session scanned past the expiry height without failing the transaction"
        );

        recipient.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Failed(_)
        ));
        check_client_balances!(recipient, i: FUNDING o: 0 s: 0 t: 0);
    }

    #[tokio::test]
    async fn failed_session_that_scanned_past_expiry_fails_the_transaction() {
        let mut net = MockNet::launch().await;
        let (mut recipient, recipient_ua, txid, expiry) =
            mempool_transaction_near_expiry(&mut net).await;
        mine_past_expiry_and_fund_above_verify_range(&net, &recipient_ua, expiry).await;
        {
            let mut chain = net.chain.write().await;
            for _ in 0..TRANSACTION_FETCH_FAILURES {
                chain.faults.inject(
                    Rpc::Transaction,
                    Fault::Fail(Code::Unavailable, "mock outage".to_string()),
                );
            }
        }

        assert!(recipient.sync_and_await().await.is_err());
        assert!(fully_scanned_height(&recipient).await >= expiry);
        assert!(
            matches!(
                status_of(&recipient, &txid).await,
                ConfirmationStatus::Failed(_)
            ),
            "a failed session scanned past the expiry height without failing the transaction"
        );

        net.chain.write().await.faults.clear(Rpc::Transaction);
        recipient.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Failed(_)
        ));
        check_client_balances!(recipient, i: FUNDING o: 0 s: 0 t: 0);
    }

    #[tokio::test]
    async fn stopped_session_does_not_fail_a_transaction_mined_in_an_unscanned_block() {
        let mut net = MockNet::launch().await;
        let (mut recipient, _, txid, expiry) = mempool_transaction_near_expiry(&mut net).await;
        {
            let mut chain = net.chain.write().await;
            let tip = chain.tip();
            chain.mine_empty_blocks(u32::from(expiry) - 1 - tip);
            chain.mine_mempool();
            assert_eq!(chain.tip(), u32::from(expiry));
        }
        net.chain
            .write()
            .await
            .faults
            .inject(Rpc::Transaction, Fault::Delay(HELD_FETCH));

        recipient.sync().await.unwrap();
        wait_until_fetch_is_held(&net).await;
        recipient.stop_sync().unwrap();
        recipient.await_sync().await.unwrap();
        assert!(fully_scanned_height(&recipient).await < expiry);
        assert!(
            !matches!(
                status_of(&recipient, &txid).await,
                ConfirmationStatus::Failed(_)
            ),
            "a transaction mined in an unscanned block was marked Failed by a stopped session"
        );

        recipient.sync_and_await().await.unwrap();
        assert!(matches!(
            status_of(&recipient, &txid).await,
            ConfirmationStatus::Confirmed(_)
        ));
        check_client_balances!(recipient, i: FUNDING o: 0 s: 0 t: 0);
    }
}

/// The mainnet broadcast rule, end to end over mock indexers.
mod mainnet_broadcast_offline {
    use super::*;
    use crate::destination::servers::{DestinationServerSet, IndexerConfig, Location, Role, Trust};
    use crate::lightclient::LightClient;
    use crate::lightclient::error::LightClientError;
    use crate::lightclient::send::{TransmitReport, TransmitRoute};
    use nonempty::NonEmpty;

    const SUPPRESSOR: &str = "suppressor.example";
    const ACCEPTOR: &str = "acceptor.example";

    struct Stage {
        sync: MockNet,
        suppressing: MockNet,
        accepting: MockNet,
    }

    impl Stage {
        fn set_over(&self, entries: &[(&MockNet, &str)]) -> DestinationServerSet {
            DestinationServerSet::registry_for_tests(
                Trust::Untrusted,
                entries
                    .iter()
                    .map(|(net, operator)| (net.indexer_uri(), *operator)),
            )
            .with_indexer(IndexerConfig::new(self.sync.indexer_uri()).location(Location::Remote))
        }

        async fn received(&self) -> (usize, usize, u32) {
            (
                self.sync.chain.read().await.mempool_len(),
                self.accepting.chain.read().await.mempool_len(),
                self.suppressing.chain.read().await.rejected_sends,
            )
        }
    }

    async fn stage() -> (Stage, LightClient) {
        let mut sync = MockNet::launch().await;
        let suppressing = MockNet::launch().await;
        suppressing.chain.write().await.reject_all_sends = true;
        let accepting = MockNet::launch().await;

        let mut recipient = sync
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        fund_mirrored(
            &[&sync, &suppressing, &accepting],
            vec![(&recipient_ua, 100_000, None)],
            1,
        )
        .await;
        recipient.sync_and_await().await.unwrap();
        recipient.set_transmit_retry_interval(std::time::Duration::from_millis(10));
        (
            Stage {
                sync,
                suppressing,
                accepting,
            },
            recipient,
        )
    }

    async fn send(
        recipient: &mut LightClient,
    ) -> Result<NonEmpty<TransmitReport>, LightClientError> {
        from_inputs::quick_send_reported(
            recipient,
            vec![(&external_address(PoolType::ORCHARD), 20_000, None)],
        )
        .await
    }

    #[tokio::test]
    async fn a_nakednet_send_goes_to_the_untrusted_sync_indexer_alone() {
        let (stage, mut recipient) = stage().await;
        #[cfg(feature = "nym")]
        recipient.set_transmit_policy(crate::mixnet::TransmitPolicy::Nakednet);
        recipient.set_destination_servers_for_tests(stage.set_over(&[
            (&stage.suppressing, SUPPRESSOR),
            (&stage.accepting, ACCEPTOR),
        ]));

        let reports = send(&mut recipient).await.unwrap();

        assert!(
            reports
                .iter()
                .all(|report| matches!(report.route, TransmitRoute::Nakednet { .. }))
        );
        assert_eq!(stage.received().await, (reports.len(), 0, 0));
    }

    #[tokio::test]
    async fn a_trusted_broadcast_indexer_receives_the_send_alone() {
        let (stage, mut recipient) = stage().await;
        #[cfg(feature = "nym")]
        recipient.set_transmit_policy(crate::mixnet::TransmitPolicy::Nakednet);
        recipient.set_destination_servers_for_tests(
            stage
                .set_over(&[(&stage.suppressing, SUPPRESSOR)])
                .with_indexer(
                    IndexerConfig::new(stage.accepting.indexer_uri())
                        .role(Role::Broadcast)
                        .trust(Trust::Trusted)
                        .location(Location::Remote),
                ),
        );

        let reports = send(&mut recipient).await.unwrap();

        assert_eq!(stage.received().await, (0, reports.len(), 0));
    }

    #[cfg(feature = "nym")]
    #[tokio::test]
    async fn a_mixnet_send_routes_around_the_suppressor_and_never_the_sync_indexer() {
        let (stage, mut recipient) = stage().await;
        recipient.set_destination_servers_for_tests(stage.set_over(&[
            (&stage.suppressing, SUPPRESSOR),
            (&stage.accepting, ACCEPTOR),
        ]));

        let reports = send(&mut recipient).await.unwrap();

        assert!(
            reports
                .iter()
                .all(|report| matches!(report.route, TransmitRoute::Mixnet { .. }))
        );
        let (sync, accepting, _) = stage.received().await;
        assert_eq!((sync, accepting), (0, reports.len()));
    }

    #[cfg(feature = "nym")]
    #[tokio::test]
    async fn an_all_suppressing_mixnet_draw_fails_closed() {
        let (stage, mut recipient) = stage().await;
        recipient
            .set_destination_servers_for_tests(stage.set_over(&[(&stage.suppressing, SUPPRESSOR)]));

        let refused = send(&mut recipient)
            .await
            .expect_err("a suppressed transmission surfaces");
        assert!(
            matches!(
                refused,
                LightClientError::SendError(
                    crate::lightclient::error::SendError::TransmissionError(_)
                )
            ),
            "the refusal is the typed transmission failure: {refused}"
        );
        let (sync, _, rejected) = stage.received().await;
        assert_eq!(
            sync, 0,
            "a refused draw never falls back to the sync indexer"
        );
        assert!(rejected > 0, "the suppressing Destination was contacted");
    }
}

/// The real mixnet wire, end to end through a loopback SOCKS5 relay.
#[cfg(feature = "nym")]
mod mixnet_wire_offline {
    use super::*;
    use crate::destination::health::FaultDomain;
    use crate::destination::servers::{DestinationServerSet, IndexerConfig, Location, Role, Trust};
    use crate::lightclient::LightClient;
    use crate::lightclient::error::LightClientError;
    use crate::lightclient::migrate::transmission_route::{
        MigrationWire, RoutedTransmissionClient,
    };
    use crate::lightclient::send::{TransmitReport, TransmitRoute};
    use crate::testutils::mock_indexer::Rules;
    use crate::testutils::socks5_relay::{Destination, Socks5Relay, destination_of};
    use crate::wallet::migration::transmission::{
        PartTransmissionError, TransmissionClient as _, TransmissionRoute,
    };
    use nonempty::NonEmpty;

    const ACCEPTOR_URI: &str = "https://localhost:443";
    const SUPPRESSOR_URI: &str = "https://127.0.0.1:443";
    const UNROUTED_URI: &str = "https://unrouted.example:443";
    const ACCEPTOR: &str = "acceptor.example";
    const SUPPRESSOR: &str = "suppressor.example";
    const UNROUTED: &str = "unrouted.example";
    const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

    fn uri(text: &str) -> http::Uri {
        text.parse().expect("a static uri")
    }

    struct Stage {
        sync: MockNet,
        accepting: MockNet,
        suppressing: MockNet,
        relay: Socks5Relay,
    }

    impl Stage {
        fn set_over(&self, entries: &[(&str, &str)]) -> DestinationServerSet {
            DestinationServerSet::registry_for_tests(
                Trust::Untrusted,
                entries
                    .iter()
                    .map(|(text, operator)| (uri(text), *operator)),
            )
            .with_indexer(IndexerConfig::new(self.sync.indexer_uri()).location(Location::Remote))
        }

        fn sync_destination(&self) -> Destination {
            destination_of(&self.sync.indexer_uri())
        }
    }

    async fn relayed() -> (Socks5Relay, MockNet, MockNet) {
        let accepting = MockNet::launch_tls().await;
        let suppressing = MockNet::launch_tls().await;
        suppressing.chain.write().await.reject_all_sends = true;
        let relay = Socks5Relay::launch().await;
        relay.route(&uri(ACCEPTOR_URI), accepting.addr());
        relay.route(&uri(SUPPRESSOR_URI), suppressing.addr());
        (relay, accepting, suppressing)
    }

    async fn stage() -> (Stage, LightClient) {
        let mut sync = MockNet::launch().await;
        let (relay, accepting, suppressing) = relayed().await;
        let mut recipient = sync
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        fund_mirrored(
            &[&sync, &accepting, &suppressing],
            vec![(&recipient_ua, 100_000, None)],
            1,
        )
        .await;
        recipient.sync_and_await().await.unwrap();
        recipient.set_transmit_retry_interval(std::time::Duration::from_millis(10));
        recipient
            .switch_on_mixnet_through_for_tests(relay.addr())
            .await;
        (
            Stage {
                sync,
                accepting,
                suppressing,
                relay,
            },
            recipient,
        )
    }

    async fn send(
        recipient: &mut LightClient,
    ) -> Result<NonEmpty<TransmitReport>, LightClientError> {
        from_inputs::quick_send_reported(
            recipient,
            vec![(&external_address(PoolType::ORCHARD), 20_000, None)],
        )
        .await
    }

    #[tokio::test]
    async fn a_mixnet_send_crosses_the_tunnel_to_a_registry_destination() {
        let (stage, mut recipient) = stage().await;
        recipient.set_destination_servers_for_tests(
            stage.set_over(&[(ACCEPTOR_URI, ACCEPTOR), (SUPPRESSOR_URI, SUPPRESSOR)]),
        );

        let reports = send(&mut recipient).await.unwrap();

        for report in &reports {
            assert_eq!(
                report.route,
                TransmitRoute::Mixnet {
                    destination: "localhost".to_string(),
                    via_socks5: stage.relay.addr().to_string(),
                }
            );
        }
        assert_eq!(
            stage.accepting.chain.read().await.mempool_len(),
            reports.len()
        );
        assert_eq!(stage.sync.chain.read().await.mempool_len(), 0);
        let allowed = [
            destination_of(&uri(ACCEPTOR_URI)),
            destination_of(&uri(SUPPRESSOR_URI)),
        ];
        let requested = stage.relay.requested();
        assert!(!requested.is_empty());
        assert!(
            requested
                .iter()
                .all(|destination| allowed.contains(destination)),
            "the exit learned a destination outside the registry: {requested:?}"
        );
        assert!(!requested.contains(&stage.sync_destination()));
    }

    #[tokio::test]
    async fn failed_arms_are_attributed_to_the_component_that_failed() {
        let (stage, mut recipient) = stage().await;
        recipient.set_destination_servers_for_tests(
            stage.set_over(&[(SUPPRESSOR_URI, SUPPRESSOR), (UNROUTED_URI, UNROUTED)]),
        );

        let refused = send(&mut recipient)
            .await
            .expect_err("no Destination accepts");
        assert!(
            matches!(
                refused,
                LightClientError::SendError(
                    crate::lightclient::error::SendError::TransmissionError(_)
                )
            ),
            "{refused}"
        );
        let attempts = recipient.indexer_history_handle().load();
        let fault_of = |host: &str| {
            attempts
                .iter()
                .find(|attempt| attempt.host.as_str() == host)
                .unwrap_or_else(|| panic!("no attempt against {host}: {attempts:?}"))
                .fault_domain
        };
        assert_eq!(fault_of("127.0.0.1"), Some(FaultDomain::Destination));
        assert_eq!(fault_of("unrouted.example"), Some(FaultDomain::Tunnel));
        assert!(stage.suppressing.chain.read().await.rejected_sends > 0);
        assert!(
            stage
                .relay
                .requested()
                .contains(&destination_of(&uri(UNROUTED_URI))),
            "the unroutable arm asked the exit for its Destination"
        );
    }

    #[tokio::test]
    async fn a_trusted_broadcast_indexer_receives_the_mixnet_send_alone() {
        let (stage, mut recipient) = stage().await;
        recipient.set_destination_servers_for_tests(
            stage
                .set_over(&[(SUPPRESSOR_URI, SUPPRESSOR)])
                .with_indexer(
                    IndexerConfig::new(uri(ACCEPTOR_URI))
                        .role(Role::Broadcast)
                        .trust(Trust::Trusted)
                        .location(Location::Remote),
                ),
        );

        let reports = send(&mut recipient).await.unwrap();

        assert_eq!(
            stage.accepting.chain.read().await.mempool_len(),
            reports.len()
        );
        assert_eq!(stage.suppressing.chain.read().await.rejected_sends, 0);
        let acceptor = destination_of(&uri(ACCEPTOR_URI));
        assert!(
            stage
                .relay
                .requested()
                .iter()
                .all(|destination| *destination == acceptor),
            "{:?}",
            stage.relay.requested()
        );
    }

    #[tokio::test]
    async fn the_network_probe_measures_the_registry_through_the_tunnel() {
        let (stage, mut recipient) = stage().await;
        recipient.set_destination_servers_for_tests(
            stage.set_over(&[(ACCEPTOR_URI, ACCEPTOR), (SUPPRESSOR_URI, SUPPRESSOR)]),
        );

        let probes = recipient
            .probe_destinations(None, PROBE_TIMEOUT)
            .await
            .expect("a ready mixnet probes");

        let mut hosts: Vec<&str> = probes.iter().map(|probe| probe.host.as_str()).collect();
        hosts.sort_unstable();
        assert_eq!(hosts, vec!["127.0.0.1", "localhost"]);
        for probe in &probes {
            assert!(probe.leg.outcome.is_ok(), "{probe:?}");
        }
        assert!(!stage.relay.requested().contains(&stage.sync_destination()));
    }

    #[tokio::test]
    async fn a_migration_part_crosses_the_tunnel() {
        const REJECTION_CODE: i32 = -26;
        const REJECTOR_URI: &str = "https://localhost:8443";

        let (relay, accepting, suppressing) = relayed().await;
        let rejecting = MockNet::launch_tls().await;
        for net in [&accepting, &suppressing, &rejecting] {
            net.chain.write().await.rules = Rules::LAX;
        }
        rejecting.chain.write().await.answer_sends_with_error_code = Some(REJECTION_CODE);
        relay.route(&uri(REJECTOR_URI), rejecting.addr());
        let part =
            faucet_funding_transaction(vec![(&external_address(PoolType::ORCHARD), 20_000, None)])
                .await;
        let expiry = BlockHeight::from_u32(1);
        let client_for = |target: &str| {
            RoutedTransmissionClient::new(
                MigrationWire::Mixnet(crate::mixnet::MixnetConduit::over(relay.addr()).dial()),
                vec![uri(target)],
            )
        };

        let receipt = client_for(ACCEPTOR_URI)
            .submit(part.clone(), expiry)
            .await
            .expect("the acceptor takes the part");
        assert_eq!(
            receipt.route,
            TransmissionRoute::Mixnet {
                destination: "localhost".to_string(),
                via_socks5: relay.addr().to_string(),
            }
        );
        assert_eq!(accepting.chain.read().await.mempool_len(), 1);

        assert!(matches!(
            client_for(REJECTOR_URI).submit(part.clone(), expiry).await,
            Err(PartTransmissionError::Rejected(_))
        ));
        assert!(matches!(
            client_for(SUPPRESSOR_URI)
                .submit(part.clone(), expiry)
                .await,
            Err(PartTransmissionError::Transport(_))
        ));
        assert!(matches!(
            client_for(UNROUTED_URI).submit(part, expiry).await,
            Err(PartTransmissionError::Transport(_))
        ));
    }
}

mod shielded_coinbase {
    use zcash_protocol::PoolType;
    use zcash_protocol::ShieldedPool;
    use zcash_protocol::value::Zatoshis;

    use crate::check_client_balances;
    use crate::testutils::lightclient::get_base_address;
    use crate::testutils::mock_activation_heights_deferring_nu6_3;
    use crate::testutils::mock_indexer::{MockChain, MockNet};

    const REWARD_ZATS: u64 = 625_000;
    const REWARD: Zatoshis = Zatoshis::const_from_u64(REWARD_ZATS);
    const DEFERRED_NU6_3: u32 = 130;

    #[tokio::test]
    async fn a_shielded_coinbase_pays_the_miner_in_ironwood_after_the_activation() {
        let mut net = MockNet::launch().await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let miner_ua = get_base_address(&miner, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.chain.write().await.mine_empty_blocks(1);
        let coinbase = net
            .mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
            .await;
        assert!(!coinbase.is_empty());
        net.chain.write().await.mine_empty_blocks(1);
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: REWARD_ZATS o: 0 s: 0 t: 0);
    }

    #[tokio::test]
    async fn a_shielded_coinbase_pays_the_miner_in_orchard_before_the_activation() {
        let mut net = MockNet::launch_with(MockChain::with_activation_heights(
            mock_activation_heights_deferring_nu6_3(DEFERRED_NU6_3),
        ))
        .await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let miner_ua = get_base_address(&miner, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.chain.write().await.mine_empty_blocks(1);
        net.mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
            .await;
        net.chain.write().await.mine_empty_blocks(1);
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: 0 o: REWARD_ZATS s: 0 t: 0);
    }
}

mod boundary_pruning {
    use incrementalmerkletree::Position;
    use pepper_sync::sync::MAX_SHARDTREE_CHECKPOINTS;
    use pepper_sync::wallet::{NoteInterface, OrchardNote, OutputId, OutputInterface};
    use shardtree::store::ShardStore as _;
    use zaino_proto::tonic::Code;
    use zcash_client_backend::data_api::anchor_retention::{
        AnchorRetention, AnchorRetentionInterval,
    };
    use zcash_protocol::PoolType;
    use zcash_protocol::ShieldedPool;
    use zcash_protocol::consensus::BlockHeight;

    use crate::check_client_balances;
    use crate::lightclient::LightClient;
    use crate::testutils::lightclient::get_base_address;
    use crate::testutils::migration::inject_scheduled_migration;
    use crate::testutils::mock_activation_heights_deferring_nu6_3;
    use crate::testutils::mock_indexer::{
        Fault, MockChain, MockNet, Rpc, faucet_funding_transaction_on,
    };
    use crate::wallet::LightWallet;
    use crate::wallet::migration::parts::SkipReason;
    use crate::wallet::migration::{MigrationParams, PartState, PrepareResult, bucket_index};

    const HIDDEN_BLOCKS: u32 = 10;
    const PRUNED_BUCKET_MODULUS: u32 = (MAX_SHARDTREE_CHECKPOINTS + 1).next_power_of_two();
    const ANCHOR_BUCKET: u64 = 2;
    const WINDOW_BUCKET: u64 = ANCHOR_BUCKET + 1;
    const ANCHOR_BOUNDARY: u32 = ANCHOR_BUCKET as u32 * PRUNED_BUCKET_MODULUS;
    const DEFERRED_NU6_3: u32 = 200;
    const BIRTHDAY_CHECKPOINT_RUNWAY: u32 = MAX_SHARDTREE_CHECKPOINTS;
    const _: () = assert!(
        BIRTHDAY_CHECKPOINT_RUNWAY + 2 < DEFERRED_NU6_3,
        "the funding must sit above every checkpoint the birthday verification leaves and still confirm before NU6.3 activates"
    );
    const TARGET_TIP: u32 =
        WINDOW_BUCKET as u32 * PRUNED_BUCKET_MODULUS + (PRUNED_BUCKET_MODULUS - HIDDEN_BLOCKS) / 2;
    const _: () = assert!(
        ANCHOR_BOUNDARY >= DEFERRED_NU6_3,
        "the transmit path skips an anchor below the NU6.3 activation before it looks at the tree"
    );
    const _: () = assert!(
        TARGET_TIP - ANCHOR_BOUNDARY > MAX_SHARDTREE_CHECKPOINTS,
        "the leap must leave the anchor boundary below pepper-sync's rolling checkpoint window"
    );
    const _: () = assert!(
        TARGET_TIP + HIDDEN_BLOCKS < (WINDOW_BUCKET as u32 + 1) * PRUNED_BUCKET_MODULUS,
        "the hidden blocks must keep the tip inside the transmission window"
    );

    async fn funding_note(
        client: &LightClient,
        funding: u64,
    ) -> ((u64, OutputId, [u8; 32]), Position) {
        let wallet = client.wallet().read().await;
        wallet
            .wallet_transactions
            .values()
            .flat_map(|transaction| OrchardNote::transaction_outputs(transaction).to_vec())
            .find(|note| note.value() == funding)
            .map(|note| {
                (
                    (
                        note.value(),
                        note.output_id(),
                        note.nullifier()
                            .expect("scanned wallet notes carry nullifiers")
                            .to_bytes(),
                    ),
                    note.position()
                        .expect("scanned wallet notes carry tree positions"),
                )
            })
            .expect("the recipient holds its funding note")
    }

    fn orchard_checkpoints_holding(
        wallet: &LightWallet,
        at_or_below: BlockHeight,
        position: Position,
    ) -> Vec<BlockHeight> {
        let store = wallet.shard_trees.orchard.store();
        let count = store.checkpoint_count().expect("infallible");
        (0..count)
            .filter_map(|depth| store.get_checkpoint_at_depth(depth).expect("infallible"))
            .filter(|(id, checkpoint)| {
                *id <= at_or_below && checkpoint.position().is_some_and(|held| held >= position)
            })
            .map(|(id, _)| id)
            .collect()
    }

    #[tokio::test]
    async fn unavailable_boundary_tree_state_skips_without_sync_on_the_mock_chain() {
        let anchor_boundary = BlockHeight::from_u32(ANCHOR_BOUNDARY);
        let retention = AnchorRetention::new(
            BlockHeight::from_u32(DEFERRED_NU6_3),
            AnchorRetentionInterval::default(),
        );
        assert!(
            retention
                .retained_in_range(BlockHeight::from_u32(0)..=anchor_boundary)
                .is_empty(),
            "the canonical retention grid must pin no checkpoint at or below the anchor boundary"
        );

        let mut net = MockNet::launch_with(MockChain::with_activation_heights(
            mock_activation_heights_deferring_nu6_3(DEFERRED_NU6_3),
        ))
        .await;
        let mut params = MigrationParams::provisional(net.chain_type());
        params.bucket_modulus = PRUNED_BUCKET_MODULUS;
        let funding = params.max_residual_value + params.part_fee;
        let mut recipient = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        {
            let mut chain = net.chain.write().await;
            chain.mine_empty_blocks(BIRTHDAY_CHECKPOINT_RUNWAY);
            let funding_transaction = faucet_funding_transaction_on(
                chain.activation_heights(),
                chain.next_height(),
                vec![(&recipient_ua, funding, None)],
            )
            .await;
            chain.mine_block(vec![funding_transaction]);
            let funded_tip = chain.tip();
            assert!(
                funded_tip < DEFERRED_NU6_3,
                "the funding must confirm before NU6.3 activates, but the chain is at {funded_tip}"
            );
            chain.mine_empty_blocks(TARGET_TIP - funded_tip);
        }
        recipient.sync_and_await().await.unwrap();
        check_client_balances!(recipient, i: 0 o: funding s: 0 t: 0);

        let known_height = recipient
            .wallet()
            .read()
            .await
            .sync_state
            .last_known_chain_height()
            .expect("the recipient has synced");
        assert_eq!(
            bucket_index(known_height, PRUNED_BUCKET_MODULUS),
            WINDOW_BUCKET,
            "the chain must sit inside the transmission window"
        );
        let (bound, position) = funding_note(&recipient, funding).await;
        assert_eq!(
            orchard_checkpoints_holding(
                &*recipient.wallet().read().await,
                anchor_boundary,
                position
            ),
            Vec::<BlockHeight>::new(),
            "no checkpoint at or below the anchor boundary may hold the bound note"
        );
        let (funding_value, output_id, nullifier) = bound;
        let denomination = funding_value - params.part_fee;
        inject_scheduled_migration(
            &recipient,
            params,
            vec![(denomination, output_id, nullifier)],
            Some(WINDOW_BUCKET),
            Some(ANCHOR_BUCKET),
        )
        .await;

        {
            let mut chain = net.chain.write().await;
            chain.mine_empty_blocks(HIDDEN_BLOCKS);
            chain.faults.inject(
                Rpc::BlockRange,
                Fault::Fail(
                    Code::Unavailable,
                    "a hidden sync fetched blocks".to_string(),
                ),
            );
        }

        #[cfg(feature = "nym")]
        recipient.set_transmit_policy(crate::mixnet::TransmitPolicy::Nakednet);
        let sent = recipient.transmit_due_parts().await.unwrap();
        assert!(sent.is_empty(), "nothing must be transmitted: {sent:?}");
        assert_eq!(
            net.chain.read().await.faults.pending(Rpc::BlockRange),
            1,
            "the transmit path must never fetch blocks"
        );
        let mut wallet = recipient.wallet().write().await;
        let state = wallet.migration.as_ref().unwrap();
        let part = &state.parts[0];
        assert_eq!(part.state, PartState::Assigned, "a skip writes nothing");
        assert_eq!(part.attempts, 0, "a skip records no attempt");
        assert!(part.anchor_witness.is_none());
        assert_eq!(
            wallet.sync_state.last_known_chain_height(),
            Some(known_height),
            "the transmit path must never synchronize"
        );

        let (account, params, mut probe) = (state.account, state.params.clone(), part.clone());
        match wallet
            .prepare_part(account, &mut probe, &params)
            .expect("an unavailable boundary is a skip, not an error")
        {
            PrepareResult::Skip(SkipReason::MissedBoundary { boundary }) => {
                assert_eq!(boundary, anchor_boundary);
            }
            PrepareResult::Skip(other) => {
                panic!("the part skipped for the wrong reason: {other:?}")
            }
            PrepareResult::Ready { .. } => {
                panic!("the anchor boundary's tree state must be unavailable")
            }
        }
    }
}

/// Twins moved from regtest under the removal directive, one commit each.
mod moved_from_regtest {
    use std::time::Duration;

    use zcash_primitives::transaction::fees::zip317::MARGINAL_FEE;
    use zcash_protocol::PoolType;
    use zcash_protocol::consensus::COINBASE_MATURITY_BLOCKS;
    use zcash_protocol::value::Zatoshis;
    use zip32::AccountId;

    use zcash_primitives::transaction::fees::zip317::MINIMUM_FEE;
    use zcash_protocol::ShieldedPool;

    use super::{external_address, fund};
    use crate::check_client_balances;
    use crate::testutils::lightclient::{from_inputs, get_base_address, get_fees_paid_by_client};
    use crate::testutils::mock_activation_heights_deferring_nu6_3;
    use crate::testutils::mock_indexer::{MockChain, MockNet};

    const REWARD_ZATS: u64 = 625_000;
    const REWARD: Zatoshis = Zatoshis::const_from_u64(REWARD_ZATS);
    const COINBASES: u64 = 4;
    const DEFERRED_NU6_3: u32 = 130;
    /// Four transparent inputs and one shielded output: four transparent logical actions plus the
    /// two-action shielded minimum.
    const SHIELD_LOGICAL_ACTIONS: u64 = 6;

    #[tokio::test]
    async fn mine_to_transparent_and_shield() {
        let mut net = MockNet::launch().await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        miner.set_transmit_retry_interval(Duration::ZERO);
        let miner_taddr = get_base_address(&miner, PoolType::Transparent).await;
        {
            let mut chain = net.chain.write().await;
            for _ in 0..COINBASES {
                chain.mine_block_rewarding(&miner_taddr, REWARD, vec![]);
            }
            chain.mine_empty_blocks(COINBASE_MATURITY_BLOCKS);
        }
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: 0 o: 0 s: 0 t: (COINBASES * REWARD_ZATS));

        miner.quick_shield(AccountId::ZERO).await.unwrap();
        net.chain.write().await.mine_mempool();
        miner.sync_and_await().await.unwrap();

        let fee = get_fees_paid_by_client(&miner).await;
        assert_eq!(
            fee,
            Option::unwrap(MARGINAL_FEE * SHIELD_LOGICAL_ACTIONS).into_u64()
        );
        check_client_balances!(miner, i: (COINBASES * REWARD_ZATS - fee) o: 0 s: 0 t: 0);
    }
    #[tokio::test]
    async fn sapling_dust_fee_collection() {
        const FEES_FOR_ORCHARD: u64 = 10;
        const DUST_DIVISOR: u64 = 10;
        const FEES_SENT: u64 = 5;
        let fee = u64::from(MINIMUM_FEE);
        let for_orchard = fee * FEES_FOR_ORCHARD;
        let for_sapling = fee / DUST_DIVISOR;

        let mut net = MockNet::launch().await;
        let mut recipient = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_sapling =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Sapling)).await;
        let recipient_unified =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        check_client_balances!(recipient, i: 0 o: 0 s: 0 t: 0);

        net.chain.write().await.mine_empty_blocks(1);
        fund(
            &net,
            vec![
                (&recipient_unified, for_orchard, Some("Plenty for orchard.")),
                (&recipient_sapling, for_sapling, Some("Dust for sapling.")),
            ],
            0,
        )
        .await;
        recipient.sync_and_await().await.unwrap();
        check_client_balances!(recipient, i: for_orchard o: 0 s: 0 t: 0);

        from_inputs::quick_send(
            &mut recipient,
            vec![(
                &external_address(PoolType::ORCHARD),
                fee * FEES_SENT,
                Some("Five times fee."),
            )],
        )
        .await
        .unwrap();
        net.chain.write().await.mine_mempool();
        recipient.sync_and_await().await.unwrap();
        let remaining_ironwood = for_orchard - (FEES_SENT + 1) * fee;
        check_client_balances!(recipient, i: remaining_ironwood o: 0 s: 0 t: 0);
    }
    #[tokio::test]
    async fn send_and_sync_with_multiple_notes_no_panic() {
        const NOTE: u64 = 40_000;
        const PAYMENT: u64 = 50_000;
        let fee = u64::from(MINIMUM_FEE);

        let mut net = MockNet::launch().await;
        let mut recipient = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let recipient_ua =
            get_base_address(&recipient, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.chain.write().await.mine_empty_blocks(1);
        fund(&net, vec![(&recipient_ua, NOTE, None)], 0).await;
        fund(&net, vec![(&recipient_ua, NOTE, None)], 0).await;
        recipient.sync_and_await().await.unwrap();
        check_client_balances!(recipient, i: (2 * NOTE) o: 0 s: 0 t: 0);

        from_inputs::quick_send(
            &mut recipient,
            vec![(&external_address(PoolType::ORCHARD), PAYMENT, None)],
        )
        .await
        .unwrap();
        net.chain.write().await.mine_mempool();
        recipient.sync_and_await().await.unwrap();
        // The payment plus its fee exceeds either note alone, so the send
        // consumed both and returned the rest as change.
        check_client_balances!(recipient, i: (2 * NOTE - PAYMENT - fee) o: 0 s: 0 t: 0);
    }
    #[tokio::test]
    async fn mine_to_transparent() {
        use crate::lightclient::LightClient;
        use pepper_sync::wallet::TransparentCoin;

        const FIRST_BLOCKS: u64 = 3;
        let mut net = MockNet::launch().await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let miner_taddr = get_base_address(&miner, PoolType::Transparent).await;
        {
            let mut chain = net.chain.write().await;
            for _ in 0..FIRST_BLOCKS {
                chain.mine_block_rewarding(&miner_taddr, REWARD, vec![]);
            }
        }
        miner.sync_and_await().await.unwrap();
        async fn unfiltered(miner: &LightClient) -> u64 {
            miner
                .wallet()
                .read()
                .await
                .get_filtered_balance::<TransparentCoin, _>(|_, _| true, AccountId::ZERO)
                .unwrap()
                .into_u64()
        }
        assert_eq!(unfiltered(&miner).await, FIRST_BLOCKS * REWARD_ZATS);

        net.chain
            .write()
            .await
            .mine_block_rewarding(&miner_taddr, REWARD, vec![]);
        miner.sync_and_await().await.unwrap();
        assert_eq!(unfiltered(&miner).await, (FIRST_BLOCKS + 1) * REWARD_ZATS);
    }
    #[tokio::test]
    async fn mine_to_transparent_coinbase_maturity() {
        use crate::lightclient::LightClient;
        use pepper_sync::wallet::TransparentCoin;

        const FIRST_BLOCKS: u64 = 3;
        let mut net = MockNet::launch().await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let miner_taddr = get_base_address(&miner, PoolType::Transparent).await;
        {
            let mut chain = net.chain.write().await;
            for _ in 0..FIRST_BLOCKS {
                chain.mine_block_rewarding(&miner_taddr, REWARD, vec![]);
            }
        }
        miner.sync_and_await().await.unwrap();
        async fn mature(miner: &LightClient) -> u64 {
            miner
                .wallet()
                .read()
                .await
                .confirmed_balance_excluding_dust::<TransparentCoin>(AccountId::ZERO)
                .unwrap()
                .into_u64()
        }
        check_client_balances!(miner, i: 0 o: 0 s: 0 t: 0);
        assert_eq!(mature(&miner).await, 0);

        net.chain
            .write()
            .await
            .mine_empty_blocks(COINBASE_MATURITY_BLOCKS);
        miner.sync_and_await().await.unwrap();
        assert_eq!(mature(&miner).await, FIRST_BLOCKS * REWARD_ZATS);
    }
    #[tokio::test]
    async fn mine_to_orchard() {
        const ORCHARD_BLOCKS: u64 = 3;
        let mut net = MockNet::launch_with(MockChain::with_activation_heights(
            mock_activation_heights_deferring_nu6_3(DEFERRED_NU6_3),
        ))
        .await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let miner_sapling =
            get_base_address(&miner, PoolType::Shielded(ShieldedPool::Sapling)).await;
        let miner_ua = get_base_address(&miner, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.mine_block_rewarding_shielded(&miner_sapling, REWARD, vec![])
            .await;
        for _ in 0..ORCHARD_BLOCKS {
            net.mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
                .await;
        }
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: 0 o: (ORCHARD_BLOCKS * REWARD_ZATS) s: REWARD_ZATS t: 0);

        net.mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
            .await;
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: 0 o: ((ORCHARD_BLOCKS + 1) * REWARD_ZATS) s: REWARD_ZATS t: 0);
    }
    #[tokio::test]
    async fn mine_to_ironwood() {
        const IRONWOOD_BLOCKS: u64 = 3;
        let mut net = MockNet::launch().await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let miner_sapling =
            get_base_address(&miner, PoolType::Shielded(ShieldedPool::Sapling)).await;
        let miner_ua = get_base_address(&miner, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.mine_block_rewarding_shielded(&miner_sapling, REWARD, vec![])
            .await;
        for _ in 0..IRONWOOD_BLOCKS {
            net.mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
                .await;
        }
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: (IRONWOOD_BLOCKS * REWARD_ZATS) o: 0 s: REWARD_ZATS t: 0);

        net.mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
            .await;
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: ((IRONWOOD_BLOCKS + 1) * REWARD_ZATS) o: 0 s: REWARD_ZATS t: 0);
    }
    #[tokio::test]
    async fn ironwood_miner_coinbase_distribution() {
        use crate::testutils::mock_activation_heights_with;
        use crate::testutils::mock_indexer::MockChain;

        const NU6_3: u32 = 5;
        const ORCHARD_BLOCKS: u64 = (NU6_3 - 2) as u64;
        let mut net = MockNet::launch_with(MockChain::with_activation_heights(
            mock_activation_heights_with(|era| era.set_nu6_3(Some(NU6_3)).set_nu7(None)),
        ))
        .await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let miner_sapling =
            get_base_address(&miner, PoolType::Shielded(ShieldedPool::Sapling)).await;
        let miner_ua = get_base_address(&miner, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.mine_block_rewarding_shielded(&miner_sapling, REWARD, vec![])
            .await;
        for _ in 0..ORCHARD_BLOCKS {
            net.mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
                .await;
        }
        assert_eq!(net.chain.read().await.tip(), NU6_3 - 1);
        miner.sync_and_await().await.unwrap();
        // Every coinbase so far predates the activation, so the unified
        // address's rewards are legacy Orchard notes and the Ironwood pool
        // is empty.
        check_client_balances!(miner, i: 0 o: (ORCHARD_BLOCKS * REWARD_ZATS) s: REWARD_ZATS t: 0);

        // The activation block's coinbase lands in Ironwood.
        net.mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
            .await;
        miner.sync_and_await().await.unwrap();
        check_client_balances!(miner, i: REWARD_ZATS o: (ORCHARD_BLOCKS * REWARD_ZATS) s: REWARD_ZATS t: 0);
    }
    #[tokio::test]
    async fn send_mined_ironwood_to_ironwood() {
        const IRONWOOD_BLOCKS: u64 = 3;
        const AMOUNT_TO_SEND: u64 = 10_000;
        let fee = u64::from(MINIMUM_FEE);
        let mut net = MockNet::launch().await;
        let mut miner = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let miner_ua = get_base_address(&miner, PoolType::Shielded(ShieldedPool::Orchard)).await;
        for _ in 0..IRONWOOD_BLOCKS {
            net.mine_block_rewarding_shielded(&miner_ua, REWARD, vec![])
                .await;
        }
        miner.sync_and_await().await.unwrap();
        let funded = IRONWOOD_BLOCKS * REWARD_ZATS;
        check_client_balances!(miner, i: funded o: 0 s: 0 t: 0);

        from_inputs::quick_send(
            &mut miner,
            vec![(&miner_ua, AMOUNT_TO_SEND, Some("Scenario test: engage!"))],
        )
        .await
        .unwrap();
        // The miner mines the confirming block itself, collecting a fresh
        // reward plus the fee it paid.
        let reward_with_fee = Zatoshis::from_u64(REWARD_ZATS + fee).unwrap();
        net.mine_mempool_rewarding_shielded(&miner_ua, reward_with_fee)
            .await;
        miner.sync_and_await().await.unwrap();
        let balance = miner.account_balance(AccountId::ZERO).await.unwrap();
        assert_eq!(balance.unconfirmed_ironwood_balance, Some(Zatoshis::ZERO));
        assert_eq!(
            balance.confirmed_ironwood_balance.unwrap().into_u64(),
            funded + REWARD_ZATS
        );
    }
    #[tokio::test]
    async fn verify_old_wallet_uses_server_height_in_send() {
        const FUNDING: u64 = 100_000;
        const SYNCED_BLOCKS: u32 = 5;
        const HIDDEN_BLOCKS: u32 = 2;
        const PAYMENT: u64 = 10_000;

        let mut net = MockNet::launch().await;
        let mut sender = net
            .client(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED, None)
            .await;
        let sender_ua = get_base_address(&sender, PoolType::Shielded(ShieldedPool::Orchard)).await;
        net.chain.write().await.mine_empty_blocks(1);
        fund(&net, vec![(&sender_ua, FUNDING, None)], SYNCED_BLOCKS).await;
        sender.sync_and_await().await.unwrap();
        let synced_height = sender
            .wallet()
            .read()
            .await
            .sync_state
            .fully_scanned_height()
            .unwrap();
        assert_eq!(u32::from(synced_height), net.chain.read().await.tip());

        // Blocks the wallet has not seen: it stays at the height it last
        // synced to, two behind the server's tip.
        net.chain.write().await.mine_empty_blocks(HIDDEN_BLOCKS);
        let stale_height = sender
            .wallet()
            .read()
            .await
            .sync_state
            .fully_scanned_height()
            .unwrap();
        assert_eq!(stale_height, synced_height);
        assert_eq!(
            u32::from(stale_height) + HIDDEN_BLOCKS,
            net.chain.read().await.tip()
        );

        // A send built from the server's height, not the wallet's, is one
        // the chain accepts into its mempool.
        from_inputs::quick_send(
            &mut sender,
            vec![(
                &external_address(PoolType::ORCHARD),
                PAYMENT,
                Some("Interrupting sync!!"),
            )],
        )
        .await
        .unwrap();
        assert_eq!(net.chain.read().await.mempool_len(), 1);
    }
}