zakura-rpc 5.0.0

The Zakura node's JSON Remote Procedure Call (JSON-RPC) interface. Internal crate, published to support cargo install zakura
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
//! Zebra supported RPC methods.
//!
//! Based on the [`zcashd` RPC methods](https://zcash.github.io/rpc/)
//! as used by `lightwalletd.`
//!
//! Some parts of the `zcashd` RPC documentation are outdated.
//! So this implementation follows the `zcashd` server and `lightwalletd` client implementations.
//!
//! # Developing this module
//!
//! If RPCs are added or changed, ensure the following:
//!
//! - Request types can be instantiated from dependent crates, and
//!   response types are fully-readable (up to each leaf component), meaning
//!   every field on response types can be read, and any types used in response
//!   types has an appropriate API for either directly accessing their fields, or
//!   has an appropriate API for accessing any relevant data.
//!
//!   This should be achieved, wherever possible, by:
//!   - Using `derive(Getters, new)` to keep new code succinct and consistent.
//!     Ensure that fields on response types that implement `Copy` are tagged
//!     with `#[getter(copy)]` field attributes to avoid unnecessary references.
//!     This should be easily noticeable in the `serialization_tests` test crate, where
//!     any fields implementing `Copy` but not tagged with `#[getter(Copy)]` will
//!     be returned by reference, and will require dereferencing with the dereference
//!     operator, `*`. If a value returned by a getter method requires dereferencing,
//!     the associated field in the response type should likely be tagged with `#[getter(Copy)]`.
//!   - If a field is added, use `#[new(...)]` so that it's not added to the
//!     constructor. If that is unavoidable, then it will require a major
//!     version bump.
//!
//! - A test has been added to the `serialization_tests` test crate to ensure the above.

use std::{
    cmp,
    collections::{HashMap, HashSet},
    fmt,
    ops::RangeInclusive,
    sync::Arc,
    time::Duration,
};

use chrono::Utc;
use derive_getters::Getters;
use derive_new::new;
use futures::{future::OptionFuture, stream::FuturesOrdered, StreamExt, TryFutureExt};
use hex::{FromHex, ToHex};
use indexmap::IndexMap;
use jsonrpsee::core::{async_trait, RpcResult as Result};
use jsonrpsee_proc_macros::rpc;
use jsonrpsee_types::{ErrorCode, ErrorObject};
use schemars::JsonSchema;
use serde::Deserialize;
use tokio::{
    sync::{broadcast, mpsc, watch},
    task::JoinHandle,
};
use tower::ServiceExt;
use tracing::Instrument;

use zakura_chain::{
    amount::{Amount, NegativeAllowed},
    block::{self, Block, Commitment, Height, SerializedBlock, TryIntoHeight},
    chain_sync_status::ChainSyncStatus,
    chain_tip::{ChainTip, NetworkChainTipHeightEstimator},
    parameters::{
        subsidy::{
            block_subsidy, founders_reward, funding_stream_values, miner_subsidy,
            FundingStreamReceiver,
        },
        ConsensusBranchId, Network, NetworkUpgrade, POW_AVERAGING_WINDOW,
    },
    serialization::{BytesInDisplayOrder, ZcashDeserialize, ZcashDeserializeInto, ZcashSerialize},
    subtree::NoteCommitmentSubtreeIndex,
    transaction::{self, SerializedTransaction, Transaction, UnminedTx},
    transparent::{self, Address, OutputIndex},
    value_balance::ValueBalance,
    work::{
        difficulty::{CompactDifficulty, ExpandedDifficulty, ParameterDifficulty, U256},
        equihash::Solution,
    },
};
use zakura_consensus::{
    funding_stream_address, router::service_trait::BlockVerifierService, RouterError,
};
use zakura_network::{address_book_peers::AddressBookPeers, types::PeerServices, PeerSocketAddr};
use zakura_node_services::mempool::{self, CreatedOrSpent, MempoolService};
use zakura_state::{
    AnyTx, HashOrHeight, OutputLocation, ReadRequest, ReadResponse, ReadState as ReadStateService,
    State as StateService, TransactionLocation,
};
use zcash_address::{unified::Encoding, TryFromAddress};
use zcash_protocol::consensus::{self, Parameters};

use crate::{
    client::TransactionTemplate,
    client::Treestate,
    config,
    methods::types::{
        validate_address::validate_address, z_validate_address::z_validate_address, zec::Zec,
    },
    queue::Queue,
    server::{
        self,
        error::{MapError, OkOrError},
    },
};

pub(crate) mod hex_data;
pub(crate) mod trees;
pub(crate) mod types;

use hex_data::HexData;
use trees::{GetSubtreesByIndexResponse, GetTreestateResponse, SubtreeRpcData};
use types::{
    get_block_template::{
        constants::{
            DEFAULT_SOLUTION_RATE_WINDOW_SIZE, MEMPOOL_LONG_POLL_INTERVAL,
            ZCASHD_FUNDING_STREAM_ORDER,
        },
        proposal::proposal_block_from_template,
        BlockTemplateResponse, BlockTemplateTimeSource, GetBlockTemplateHandler,
        GetBlockTemplateParameters, GetBlockTemplateResponse,
    },
    get_blockchain_info::GetBlockchainInfoBalance,
    get_mempool_info::GetMempoolInfoResponse,
    get_mining_info::GetMiningInfoResponse,
    get_raw_mempool::{self, GetRawMempoolResponse},
    long_poll::LongPollInput,
    network_info::{GetNetworkInfoResponse, NetworkInfo},
    peer_info::PeerInfo,
    submit_block::{SubmitBlockErrorResponse, SubmitBlockParameters, SubmitBlockResponse},
    subsidy::GetBlockSubsidyResponse,
    transaction::TransactionObject,
    unified_address::ZListUnifiedReceiversResponse,
    validate_address::ValidateAddressResponse,
    z_validate_address::ZValidateAddressResponse,
};

include!(concat!(env!("OUT_DIR"), "/rpc_openrpc.rs"));

// TODO: Review the parameter descriptions below, and update them as needed:
// https://github.com/ZcashFoundation/zebra/issues/10320
pub(super) const PARAM_VERBOSE_DESC: &str =
    "Boolean flag to indicate verbosity, true for a json object, false for hex encoded data.";
pub(super) const PARAM_POOL_DESC: &str = "The pool from which subtrees should be returned. \
Either \"sapling\", \"orchard\", or \"ironwood\".";
pub(super) const PARAM_START_INDEX_DESC: &str =
    "The index of the first 2^16-leaf subtree to return.";
pub(super) const PARAM_LIMIT_DESC: &str = "The maximum number of subtrees to return.";
pub(super) const PARAM_REQUEST_DESC: &str = "The request object containing the parameters.";
pub(super) const PARAM_INDEX_DESC: &str = "The index of the subtree to return.";
pub(super) const PARAM_RAW_TRANSACTION_HEX_DESC: &str = "The hex-encoded raw transaction bytes.";
#[allow(non_upper_case_globals)]
pub(super) const PARAM__ALLOW_HIGH_FEES_DESC: &str = "Whether to allow high fees.";
pub(super) const PARAM_NUM_BLOCKS_DESC: &str = "The number of blocks to return.";
pub(super) const PARAM_HEIGHT_DESC: &str = "The height of the block to return.";
pub(super) const PARAM_COMMAND_DESC: &str = "The command to execute.";
#[allow(non_upper_case_globals)]
pub(super) const PARAM__PARAMETERS_DESC: &str = "The parameters for the command.";
pub(super) const PARAM_BLOCK_HASH_DESC: &str = "The hash of the block to return.";
pub(super) const PARAM_ADDRESS_DESC: &str = "The address to return.";
pub(super) const PARAM_ADDRESS_STRINGS_DESC: &str = "The addresses to return.";
pub(super) const PARAM_ADDR_DESC: &str = "The address to return.";
pub(super) const PARAM_HEX_DATA_DESC: &str = "The hex-encoded data to return.";
pub(super) const PARAM_TXID_DESC: &str = "The transaction ID to return.";
pub(super) const PARAM_HASH_OR_HEIGHT_DESC: &str = "The block hash or height to return.";
pub(super) const PARAM_PARAMETERS_DESC: &str = "The parameters for the command.";
pub(super) const PARAM_VERBOSITY_DESC: &str = "Whether to include verbose output.";
pub(super) const PARAM_N_DESC: &str = "The output index in the transaction.";
pub(super) const PARAM_INCLUDE_MEMPOOL_DESC: &str =
    "Whether to include mempool transactions in the response.";

#[cfg(test)]
mod tests;

#[rpc(server)]
/// RPC method signatures.
pub trait Rpc {
    /// Returns software information from the RPC server, as a [`GetInfo`] JSON struct.
    ///
    /// zcashd reference: [`getinfo`](https://zcash.github.io/rpc/getinfo.html)
    /// method: post
    /// tags: control
    ///
    /// # Notes
    ///
    /// [The zcashd reference](https://zcash.github.io/rpc/getinfo.html) might not show some fields
    /// in Zebra's [`GetInfo`]. Zebra uses the field names and formats from the
    /// [zcashd code](https://github.com/zcash/zcash/blob/v4.6.0-1/src/rpc/misc.cpp#L86-L87).
    ///
    /// Some fields from the zcashd reference are missing from Zebra's [`GetInfo`]. It only contains the fields
    /// [required for lightwalletd support.](https://github.com/zcash/lightwalletd/blob/v0.4.9/common/common.go#L91-L95)
    #[method(name = "getinfo")]
    async fn get_info(&self) -> Result<GetInfoResponse>;

    /// Returns blockchain state information, as a [`GetBlockchainInfoResponse`] JSON struct.
    ///
    /// zcashd reference: [`getblockchaininfo`](https://zcash.github.io/rpc/getblockchaininfo.html)
    /// method: post
    /// tags: blockchain
    ///
    /// # Notes
    ///
    /// Some fields from the zcashd reference are missing from Zebra's [`GetBlockchainInfoResponse`]. It only contains the fields
    /// [required for lightwalletd support.](https://github.com/zcash/lightwalletd/blob/v0.4.9/common/common.go#L72-L89)
    ///
    /// Zebra includes an `ironwood` value pool entry. Like other value pool
    /// entries, it can be present with a zero balance.
    #[method(name = "getblockchaininfo")]
    async fn get_blockchain_info(&self) -> Result<GetBlockchainInfoResponse>;

    /// Returns the total balance of a provided `addresses` in an [`AddressBalance`] instance.
    ///
    /// zcashd reference: [`getaddressbalance`](https://zcash.github.io/rpc/getaddressbalance.html)
    /// method: post
    /// tags: address
    ///
    /// # Parameters
    ///
    /// - `address_strings`: (object, example={"addresses": ["tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ"]}) A JSON map with a single entry
    ///     - `addresses`: (array of strings) A list of base-58 encoded addresses.
    ///
    /// # Notes
    ///
    /// zcashd also accepts a single string parameter instead of an array of strings, but Zebra
    /// doesn't because lightwalletd always calls this RPC with an array of addresses.
    ///
    /// zcashd also returns the total amount of Zatoshis received by the addresses, but Zebra
    /// doesn't because lightwalletd doesn't use that information.
    ///
    /// The RPC documentation says that the returned object has a string `balance` field, but
    /// zcashd actually [returns an
    /// integer](https://github.com/zcash/lightwalletd/blob/bdaac63f3ee0dbef62bde04f6817a9f90d483b00/common/common.go#L128-L130).
    #[method(name = "getaddressbalance")]
    async fn get_address_balance(
        &self,
        address_strings: GetAddressBalanceRequest,
    ) -> Result<GetAddressBalanceResponse>;

    /// Sends the raw bytes of a signed transaction to the local node's mempool, if the transaction is valid.
    /// Returns the [`SentTransactionHash`] for the transaction, as a JSON string.
    ///
    /// zcashd reference: [`sendrawtransaction`](https://zcash.github.io/rpc/sendrawtransaction.html)
    /// method: post
    /// tags: transaction
    ///
    /// # Parameters
    ///
    /// - `raw_transaction_hex`: (string, required, example="signedhex") The hex-encoded raw transaction bytes.
    /// - `allow_high_fees`: (bool, optional) A legacy parameter accepted by zcashd but ignored by Zebra.
    ///
    /// # Notes
    ///
    /// zcashd accepts an optional `allowhighfees` parameter. Zebra doesn't support this parameter,
    /// because lightwalletd doesn't use it.
    #[method(name = "sendrawtransaction")]
    async fn send_raw_transaction(
        &self,
        raw_transaction_hex: String,
        _allow_high_fees: Option<bool>,
    ) -> Result<SendRawTransactionResponse>;

    /// Returns the requested block by hash or height, as a [`GetBlock`] JSON string.
    /// If the block is not in Zebra's state, returns
    /// [error code `-8`.](https://github.com/zcash/zcash/issues/5758) if a height was
    /// passed or -5 if a hash was passed.
    ///
    /// zcashd reference: [`getblock`](https://zcash.github.io/rpc/getblock.html)
    /// method: post
    /// tags: blockchain
    ///
    /// # Parameters
    ///
    /// - `hash_or_height`: (string, required, example="1") The hash or height for the block to be returned.
    /// - `verbosity`: (number, optional, default=1, example=1) 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data.
    ///
    /// # Notes
    ///
    /// The `size` field is only returned with verbosity=2.
    ///
    /// The undocumented `chainwork` field is not returned.
    ///
    /// With verbosity=2, transaction objects include `ironwood` only when the
    /// transaction contains Ironwood shielded data. Block `trees` can include an
    /// Ironwood tree entry when the state has one for the requested block.
    #[method(name = "getblock")]
    async fn get_block(
        &self,
        hash_or_height: String,
        verbosity: Option<u8>,
    ) -> Result<GetBlockResponse>;

    /// Returns the requested block header by hash or height, as a [`GetBlockHeader`] JSON string.
    /// If the block is not in Zebra's state,
    /// returns [error code `-8`.](https://github.com/zcash/zcash/issues/5758)
    /// if a height was passed or -5 if a hash was passed.
    ///
    /// zcashd reference: [`getblockheader`](https://zcash.github.io/rpc/getblockheader.html)
    /// method: post
    /// tags: blockchain
    ///
    /// # Parameters
    ///
    /// - `hash_or_height`: (string, required, example="1") The hash or height for the block to be returned.
    /// - `verbose`: (bool, optional, default=false, example=true) false for hex encoded data, true for a json object
    ///
    /// # Notes
    ///
    /// The undocumented `chainwork` field is not returned.
    #[method(name = "getblockheader")]
    async fn get_block_header(
        &self,
        hash_or_height: String,
        verbose: Option<bool>,
    ) -> Result<GetBlockHeaderResponse>;

    /// Returns the hash of the current best blockchain tip block, as a [`GetBlockHash`] JSON string.
    ///
    /// zcashd reference: [`getbestblockhash`](https://zcash.github.io/rpc/getbestblockhash.html)
    /// method: post
    /// tags: blockchain
    #[method(name = "getbestblockhash")]
    fn get_best_block_hash(&self) -> Result<GetBlockHashResponse>;

    /// Returns the height and hash of the current best blockchain tip block, as a [`GetBlockHeightAndHashResponse`] JSON struct.
    ///
    /// zcashd reference: none
    /// method: post
    /// tags: blockchain
    #[method(name = "getbestblockheightandhash")]
    fn get_best_block_height_and_hash(&self) -> Result<GetBlockHeightAndHashResponse>;

    /// Returns details on the active state of the TX memory pool.
    ///
    /// zcash reference: [`getmempoolinfo`](https://zcash.github.io/rpc/getmempoolinfo.html)
    #[method(name = "getmempoolinfo")]
    async fn get_mempool_info(&self) -> Result<GetMempoolInfoResponse>;

    /// Returns all transaction ids in the memory pool, as a JSON array.
    ///
    /// # Parameters
    ///
    /// - `verbose`: (boolean, optional, default=false) true for a json object, false for array of transaction ids.
    ///
    /// zcashd reference: [`getrawmempool`](https://zcash.github.io/rpc/getrawmempool.html)
    /// method: post
    /// tags: blockchain
    #[method(name = "getrawmempool")]
    async fn get_raw_mempool(&self, verbose: Option<bool>) -> Result<GetRawMempoolResponse>;

    /// Returns information about the given block's Sapling, Orchard, and when
    /// available Ironwood tree state.
    ///
    /// zcashd reference: [`z_gettreestate`](https://zcash.github.io/rpc/z_gettreestate.html)
    /// method: post
    /// tags: blockchain
    ///
    /// # Parameters
    ///
    /// - `hash | height`: (string, required, example="00000000febc373a1da2bd9f887b105ad79ddc26ac26c2b28652d64e5207c5b5") The block hash or height.
    ///
    /// # Notes
    ///
    /// The zcashd doc reference above says that the parameter "`height` can be
    /// negative where -1 is the last known valid block". On the other hand,
    /// `lightwalletd` only uses positive heights, so Zebra does not support
    /// negative heights.
    ///
    /// The `ironwood` field contains empty commitments unless Ironwood tree
    /// state is available for the requested block.
    #[method(name = "z_gettreestate")]
    async fn z_get_treestate(&self, hash_or_height: String) -> Result<GetTreestateResponse>;

    /// Returns information about a range of shielded subtrees.
    ///
    /// zcashd reference: [`z_getsubtreesbyindex`](https://zcash.github.io/rpc/z_getsubtreesbyindex.html) - TODO: fix link
    /// method: post
    /// tags: blockchain
    ///
    /// # Parameters
    ///
    /// - `pool`: (string, required) The pool from which subtrees should be returned.
    ///   Either "sapling", "orchard", or "ironwood".
    /// - `start_index`: (number, required) The index of the first 2^16-leaf subtree to return.
    /// - `limit`: (number, optional) The maximum number of subtree values to return.
    ///
    /// # Notes
    ///
    /// While Zebra is doing its initial subtree index rebuild, subtrees will become available
    /// starting at the chain tip. This RPC will return an empty list if the `start_index` subtree
    /// exists, but has not been rebuilt yet. This matches `zcashd`'s behaviour when subtrees aren't
    /// available yet. (But `zcashd` does its rebuild before syncing any blocks.)
    #[method(name = "z_getsubtreesbyindex")]
    async fn z_get_subtrees_by_index(
        &self,
        pool: String,
        start_index: NoteCommitmentSubtreeIndex,
        limit: Option<NoteCommitmentSubtreeIndex>,
    ) -> Result<GetSubtreesByIndexResponse>;

    /// Returns the raw transaction data, as a [`GetRawTransaction`] JSON string or structure.
    ///
    /// zcashd reference: [`getrawtransaction`](https://zcash.github.io/rpc/getrawtransaction.html)
    /// method: post
    /// tags: transaction
    ///
    /// # Parameters
    ///
    /// - `txid`: (string, required, example="mytxid") The transaction ID of the transaction to be returned.
    /// - `verbose`: (number, optional, default=0, example=1) If 0, return a string of hex-encoded data, otherwise return a JSON object.
    /// - `blockhash` (string, optional) The block in which to look for the transaction
    ///
    /// # Notes
    ///
    /// Verbose transaction output includes `ironwood` only when the transaction
    /// contains Ironwood shielded data.
    #[method(name = "getrawtransaction")]
    async fn get_raw_transaction(
        &self,
        txid: String,
        verbose: Option<u8>,
        block_hash: Option<String>,
    ) -> Result<GetRawTransactionResponse>;

    /// Returns the transaction ids made by the provided transparent addresses.
    ///
    /// zcashd reference: [`getaddresstxids`](https://zcash.github.io/rpc/getaddresstxids.html)
    /// method: post
    /// tags: address
    ///
    /// # Parameters
    ///
    /// - `request`: (required) Either:
    ///     - A single address string (e.g., `"tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ"`), or
    ///     - An object with the following named fields:
    ///         - `addresses`: (array of strings, required) The addresses to get transactions from.
    ///         - `start`: (numeric, optional) The lower height to start looking for transactions (inclusive).
    ///         - `end`: (numeric, optional) The upper height to stop looking for transactions (inclusive).
    ///
    /// Example of the object form:
    /// ```json
    /// {
    ///   "addresses": ["tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ"],
    ///   "start": 1000,
    ///   "end": 2000
    /// }
    /// ```
    ///
    /// # Notes
    ///
    /// - Only the multi-argument format is used by lightwalletd and this is what we currently support:
    /// <https://github.com/zcash/lightwalletd/blob/631bb16404e3d8b045e74a7c5489db626790b2f6/common/common.go#L97-L102>
    /// - It is recommended that users call the method with start/end heights such that the response can't be too large.
    #[method(name = "getaddresstxids")]
    async fn get_address_tx_ids(&self, request: GetAddressTxIdsRequest) -> Result<Vec<String>>;

    /// Returns all unspent outputs for a list of addresses.
    ///
    /// zcashd reference: [`getaddressutxos`](https://zcash.github.io/rpc/getaddressutxos.html)
    /// method: post
    /// tags: address
    ///
    /// # Parameters
    ///
    /// - `request`: (required) Either:
    ///     - A single address string (e.g., `"tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ"`), or
    ///     - An object with the following named fields:
    ///         - `addresses`: (array, required, example=[\"tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ\"]) The addresses to get outputs from.
    ///         - `chaininfo`: (boolean, optional, default=false) Include chain info with results
    ///
    /// # Notes
    ///
    /// lightwalletd always uses the multi-address request, without chaininfo:
    /// <https://github.com/zcash/lightwalletd/blob/master/frontend/service.go#L402>
    #[method(name = "getaddressutxos")]
    async fn get_address_utxos(
        &self,
        request: GetAddressUtxosRequest,
    ) -> Result<GetAddressUtxosResponse>;

    /// Stop the running zakurad process.
    ///
    /// # Notes
    ///
    /// - Works for non windows targets only.
    /// - Works only if the network of the running zakurad process is `Regtest`.
    ///
    /// zcashd reference: [`stop`](https://zcash.github.io/rpc/stop.html)
    /// method: post
    /// tags: control
    #[method(name = "stop")]
    fn stop(&self) -> Result<String>;

    /// Returns the height of the most recent block in the best valid block chain (equivalently,
    /// the number of blocks in this chain excluding the genesis block).
    ///
    /// zcashd reference: [`getblockcount`](https://zcash.github.io/rpc/getblockcount.html)
    /// method: post
    /// tags: blockchain
    #[method(name = "getblockcount")]
    fn get_block_count(&self) -> Result<u32>;

    /// Returns the hash of the block of a given height iff the index argument correspond
    /// to a block in the best chain.
    ///
    /// zcashd reference: [`getblockhash`](https://zcash-rpc.github.io/getblockhash.html)
    /// method: post
    /// tags: blockchain
    ///
    /// # Parameters
    ///
    /// - `index`: (numeric, required, example=1) The block index.
    ///
    /// # Notes
    ///
    /// - If `index` is positive then index = block height.
    /// - If `index` is negative then -1 is the last known valid block.
    #[method(name = "getblockhash")]
    async fn get_block_hash(&self, index: i32) -> Result<GetBlockHashResponse>;

    /// Returns a block template for mining new Zcash blocks.
    ///
    /// # Parameters
    ///
    /// - `jsonrequestobject`: (string, optional) A JSON object containing arguments.
    ///
    /// zcashd reference: [`getblocktemplate`](https://zcash-rpc.github.io/getblocktemplate.html)
    /// method: post
    /// tags: mining
    ///
    /// # Notes
    ///
    /// Arguments to this RPC are currently ignored.
    /// Long polling, block proposals, server lists, and work IDs are not supported.
    ///
    /// Miners can make arbitrary changes to blocks, as long as:
    /// - the data sent to `submitblock` is a valid Zcash block, and
    /// - the parent block is a valid block that Zebra already has, or will receive soon.
    ///
    /// Zebra verifies blocks in parallel, and keeps recent chains in parallel,
    /// so moving between chains and forking chains is very cheap.
    #[method(name = "getblocktemplate")]
    async fn get_block_template(
        &self,
        parameters: Option<GetBlockTemplateParameters>,
    ) -> Result<GetBlockTemplateResponse>;

    /// Submits block to the node to be validated and committed.
    /// Returns the [`SubmitBlockResponse`] for the operation, as a JSON string.
    ///
    /// zcashd reference: [`submitblock`](https://zcash.github.io/rpc/submitblock.html)
    /// method: post
    /// tags: mining
    ///
    /// # Parameters
    ///
    /// - `hexdata`: (string, required)
    /// - `jsonparametersobject`: (string, optional) - currently ignored
    ///
    /// # Notes
    ///
    ///  - `jsonparametersobject` holds a single field, workid, that must be included in submissions if provided by the server.
    #[method(name = "submitblock")]
    async fn submit_block(
        &self,
        hex_data: HexData,
        _parameters: Option<SubmitBlockParameters>,
    ) -> Result<SubmitBlockResponse>;

    /// Returns mining-related information.
    ///
    /// zcashd reference: [`getmininginfo`](https://zcash.github.io/rpc/getmininginfo.html)
    /// method: post
    /// tags: mining
    #[method(name = "getmininginfo")]
    async fn get_mining_info(&self) -> Result<GetMiningInfoResponse>;

    /// Returns the estimated network solutions per second based on the last `num_blocks` before
    /// `height`.
    ///
    /// If `num_blocks` is not supplied, uses 120 blocks. If it is 0 or -1, uses the difficulty
    /// averaging window.
    /// If `height` is not supplied or is -1, uses the tip height.
    ///
    /// zcashd reference: [`getnetworksolps`](https://zcash.github.io/rpc/getnetworksolps.html)
    /// method: post
    /// tags: mining
    #[method(name = "getnetworksolps")]
    async fn get_network_sol_ps(&self, num_blocks: Option<i32>, height: Option<i32>)
        -> Result<u64>;

    /// Returns the estimated network solutions per second based on the last `num_blocks` before
    /// `height`.
    ///
    /// This method name is deprecated, use [`getnetworksolps`](Self::get_network_sol_ps) instead.
    /// See that method for details.
    ///
    /// zcashd reference: [`getnetworkhashps`](https://zcash.github.io/rpc/getnetworkhashps.html)
    /// method: post
    /// tags: mining
    #[method(name = "getnetworkhashps")]
    async fn get_network_hash_ps(
        &self,
        num_blocks: Option<i32>,
        height: Option<i32>,
    ) -> Result<u64> {
        self.get_network_sol_ps(num_blocks, height).await
    }

    /// Returns an object containing various state info regarding P2P networking.
    ///
    /// zcashd reference: [`getnetworkinfo`](https://zcash.github.io/rpc/getnetworkinfo.html)
    /// method: post
    /// tags: network
    #[method(name = "getnetworkinfo")]
    async fn get_network_info(&self) -> Result<GetNetworkInfoResponse>;

    /// Returns data about each connected network node.
    ///
    /// zcashd reference: [`getpeerinfo`](https://zcash.github.io/rpc/getpeerinfo.html)
    /// method: post
    /// tags: network
    #[method(name = "getpeerinfo")]
    async fn get_peer_info(&self) -> Result<Vec<PeerInfo>>;

    /// Requests that a ping be sent to all other nodes, to measure ping time.
    ///
    /// Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.
    /// Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.
    ///
    /// zcashd reference: [`ping`](https://zcash.github.io/rpc/ping.html)
    /// method: post
    /// tags: network
    #[method(name = "ping")]
    async fn ping(&self) -> Result<()>;

    /// Checks if a zcash transparent address of type P2PKH, P2SH or TEX is valid.
    /// Returns information about the given address if valid.
    ///
    /// zcashd reference: [`validateaddress`](https://zcash.github.io/rpc/validateaddress.html)
    /// method: post
    /// tags: util
    ///
    /// # Parameters
    ///
    /// - `address`: (string, required) The zcash address to validate.
    #[method(name = "validateaddress")]
    async fn validate_address(&self, address: String) -> Result<ValidateAddressResponse>;

    /// Checks if a zcash address of type P2PKH, P2SH, TEX, SAPLING or UNIFIED is valid.
    /// Returns information about the given address if valid.
    ///
    /// zcashd reference: [`z_validateaddress`](https://zcash.github.io/rpc/z_validateaddress.html)
    /// method: post
    /// tags: util
    ///
    /// # Parameters
    ///
    /// - `address`: (string, required) The zcash address to validate.
    ///
    /// # Notes
    ///
    /// - No notes
    #[method(name = "z_validateaddress")]
    async fn z_validate_address(&self, address: String) -> Result<ZValidateAddressResponse>;

    /// Returns the block subsidy reward of the block at `height`, taking into account the mining slow start.
    /// Returns an error if `height` is less than the height of the first halving for the current network.
    ///
    /// zcashd reference: [`getblocksubsidy`](https://zcash.github.io/rpc/getblocksubsidy.html)
    /// method: post
    /// tags: mining
    ///
    /// # Parameters
    ///
    /// - `height`: (numeric, optional, example=1) Can be any valid current or future height.
    ///
    /// # Notes
    ///
    /// If `height` is not supplied, uses the tip height.
    #[method(name = "getblocksubsidy")]
    async fn get_block_subsidy(&self, height: Option<u32>) -> Result<GetBlockSubsidyResponse>;

    /// Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
    ///
    /// zcashd reference: [`getdifficulty`](https://zcash.github.io/rpc/getdifficulty.html)
    /// method: post
    /// tags: blockchain
    #[method(name = "getdifficulty")]
    async fn get_difficulty(&self) -> Result<f64>;

    /// Returns the list of individual payment addresses given a unified address.
    ///
    /// zcashd reference: [`z_listunifiedreceivers`](https://zcash.github.io/rpc/z_listunifiedreceivers.html)
    /// method: post
    /// tags: wallet
    ///
    /// # Parameters
    ///
    /// - `address`: (string, required) The zcash unified address to get the list from.
    ///
    /// # Notes
    ///
    /// - No notes
    #[method(name = "z_listunifiedreceivers")]
    async fn z_list_unified_receivers(
        &self,
        address: String,
    ) -> Result<ZListUnifiedReceiversResponse>;

    /// Invalidates a block if it is not yet finalized, removing it from the non-finalized
    /// state if it is present and rejecting it during contextual validation if it is submitted.
    ///
    /// # Parameters
    ///
    /// - `block_hash`: (hex-encoded block hash, required) The block hash to invalidate.
    // TODO: Invalidate block hashes even if they're not present in the non-finalized state (#9553).
    #[method(name = "invalidateblock")]
    async fn invalidate_block(&self, block_hash: String) -> Result<()>;

    /// Reconsiders a previously invalidated block if it exists in the cache of previously invalidated blocks.
    ///
    /// # Parameters
    ///
    /// - `block_hash`: (hex-encoded block hash, required) The block hash to reconsider.
    #[method(name = "reconsiderblock")]
    async fn reconsider_block(&self, block_hash: String) -> Result<Vec<block::Hash>>;

    #[method(name = "generate")]
    /// Mine blocks immediately. Returns the block hashes of the generated blocks.
    ///
    /// # Parameters
    ///
    /// - `num_blocks`: (numeric, required, example=1) Number of blocks to be generated.
    ///
    /// # Notes
    ///
    /// Only works if the network of the running zakurad process is `Regtest`.
    ///
    /// zcashd reference: [`generate`](https://zcash.github.io/rpc/generate.html)
    /// method: post
    /// tags: generating
    async fn generate(&self, num_blocks: u32) -> Result<Vec<GetBlockHashResponse>>;

    #[method(name = "addnode")]
    /// Add or remove a node from the address book.
    ///
    /// # Parameters
    ///
    /// - `addr`: (string, required) The address of the node to add or remove.
    /// - `command`: (string, required) The command to execute, either "add", "onetry", or "remove".
    ///
    /// # Notes
    ///
    /// Only the "add" command is currently supported.
    ///
    /// zcashd reference: [`addnode`](https://zcash.github.io/rpc/addnode.html)
    /// method: post
    /// tags: network
    async fn add_node(&self, addr: PeerSocketAddr, command: AddNodeCommand) -> Result<()>;

    /// Returns an OpenRPC schema as a description of this service.
    #[method(name = "rpc.discover")]
    fn openrpc(&self) -> openrpsee::openrpc::Response;
    /// Returns details about an unspent transaction output.
    ///
    /// zcashd reference: [`gettxout`](https://zcash.github.io/rpc/gettxout.html)
    /// method: post
    /// tags: transaction
    ///
    /// # Parameters
    ///
    /// - `txid`: (string, required, example="mytxid") The transaction ID that contains the output.
    /// - `n`: (number, required) The output index number.
    /// - `include_mempool` (bool, optional, default=true) Whether to include the mempool in the search.
    #[method(name = "gettxout")]
    async fn get_tx_out(
        &self,
        txid: String,
        n: u32,
        include_mempool: Option<bool>,
    ) -> Result<GetTxOutResponse>;
}

/// RPC method implementations.
#[derive(Clone)]
pub struct RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
where
    Mempool: MempoolService,
    State: StateService,
    ReadState: ReadStateService,
    Tip: ChainTip + Clone + Send + Sync + 'static,
    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
    BlockVerifierRouter: BlockVerifierService,
    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
{
    // Configuration
    //
    /// Zebra's application version, with build metadata.
    build_version: String,

    /// Zebra's RPC user agent.
    user_agent: String,

    /// The configured network for this RPC service.
    network: Network,

    /// Test-only option that makes Zebra say it is at the chain tip,
    /// no matter what the estimated height or local clock is.
    debug_force_finished_sync: bool,

    // Services
    //
    /// A handle to the mempool service.
    mempool: Mempool,

    /// A handle to the state service.
    state: State,

    /// A handle to the state service.
    read_state: ReadState,

    /// Allows efficient access to the best tip of the blockchain.
    latest_chain_tip: Tip,

    // Tasks
    //
    /// A sender component of a channel used to send transactions to the mempool queue.
    queue_sender: broadcast::Sender<UnminedTx>,

    /// Peer address book.
    address_book: AddressBook,

    /// The last warning or error event logged by the server.
    last_warn_error_log_rx: LoggedLastEvent,

    /// Handler for the `getblocktemplate` RPC.
    gbt: GetBlockTemplateHandler<BlockVerifierRouter, SyncStatus>,
}

/// A type alias for the last event logged by the server.
pub type LoggedLastEvent = watch::Receiver<Option<(String, tracing::Level, chrono::DateTime<Utc>)>>;

impl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus> fmt::Debug
    for RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
where
    Mempool: MempoolService,
    State: StateService,
    ReadState: ReadStateService,
    Tip: ChainTip + Clone + Send + Sync + 'static,
    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
    BlockVerifierRouter: BlockVerifierService,
    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Skip fields without Debug impls, and skip channels
        f.debug_struct("RpcImpl")
            .field("build_version", &self.build_version)
            .field("user_agent", &self.user_agent)
            .field("network", &self.network)
            .field("debug_force_finished_sync", &self.debug_force_finished_sync)
            .field("getblocktemplate", &self.gbt)
            .finish()
    }
}

impl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
    RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
where
    Mempool: MempoolService,
    State: StateService,
    ReadState: ReadStateService,
    Tip: ChainTip + Clone + Send + Sync + 'static,
    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
    BlockVerifierRouter: BlockVerifierService,
    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
{
    /// Create a new instance of the RPC handler.
    //
    // TODO:
    // - put some of the configs or services in their own struct?
    #[allow(clippy::too_many_arguments)]
    pub fn new<VersionString, UserAgentString>(
        network: Network,
        mining_config: config::mining::Config,
        debug_force_finished_sync: bool,
        build_version: VersionString,
        user_agent: UserAgentString,
        mempool: Mempool,
        state: State,
        read_state: ReadState,
        block_verifier_router: BlockVerifierRouter,
        sync_status: SyncStatus,
        latest_chain_tip: Tip,
        address_book: AddressBook,
        last_warn_error_log_rx: LoggedLastEvent,
        mined_block_sender: Option<mpsc::Sender<(block::Hash, block::Height)>>,
    ) -> (Self, JoinHandle<()>)
    where
        VersionString: ToString + Clone + Send + 'static,
        UserAgentString: ToString + Clone + Send + 'static,
    {
        let (runner, queue_sender) = Queue::start();

        let mut build_version = build_version.to_string();
        let user_agent = user_agent.to_string();

        // Match zcashd's version format, if the version string has anything in it
        if !build_version.is_empty() && !build_version.starts_with('v') {
            build_version.insert(0, 'v');
        }

        let gbt = GetBlockTemplateHandler::new(
            &network,
            mining_config.clone(),
            block_verifier_router,
            sync_status,
            mined_block_sender,
        );

        let rpc_impl = RpcImpl {
            build_version,
            user_agent,
            network: network.clone(),
            debug_force_finished_sync,
            mempool: mempool.clone(),
            state: state.clone(),
            read_state: read_state.clone(),
            latest_chain_tip: latest_chain_tip.clone(),
            queue_sender,
            address_book,
            last_warn_error_log_rx,
            gbt,
        };

        // run the process queue
        let rpc_tx_queue_task_handle = tokio::spawn(
            runner
                .run(mempool, read_state, latest_chain_tip, network)
                .in_current_span(),
        );

        (rpc_impl, rpc_tx_queue_task_handle)
    }

    /// Returns a reference to the configured network.
    pub fn network(&self) -> &Network {
        &self.network
    }
}

#[async_trait]
impl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus> RpcServer
    for RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
where
    Mempool: MempoolService,
    State: StateService,
    ReadState: ReadStateService,
    Tip: ChainTip + Clone + Send + Sync + 'static,
    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
    BlockVerifierRouter: BlockVerifierService,
    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
{
    async fn get_info(&self) -> Result<GetInfoResponse> {
        let version = GetInfoResponse::version_from_string(&self.build_version)
            .expect("invalid version string");

        let connections = self.address_book.recently_live_peers(Utc::now()).len();

        let last_error_recorded = self.last_warn_error_log_rx.borrow().clone();
        let (last_error_log, _level, last_error_log_time) = last_error_recorded.unwrap_or((
            GetInfoResponse::default().errors,
            tracing::Level::INFO,
            Utc::now(),
        ));

        let tip_height = self
            .latest_chain_tip
            .best_tip_height()
            .unwrap_or(Height::MIN);
        let testnet = self.network.is_a_test_network();

        // This field is behind the `ENABLE_WALLET` feature flag in zcashd:
        // https://github.com/zcash/zcash/blob/v6.1.0/src/rpc/misc.cpp#L113
        // However it is not documented as optional:
        // https://github.com/zcash/zcash/blob/v6.1.0/src/rpc/misc.cpp#L70
        // For compatibility, we keep the field in the response, but always return 0.
        let pay_tx_fee = 0.0;

        let relay_fee = zakura_chain::transaction::zip317::MIN_MEMPOOL_TX_FEE_RATE as f64
            / (zakura_chain::amount::COIN as f64);
        let difficulty = chain_tip_difficulty(self.network.clone(), self.read_state.clone(), true)
            .await
            .expect("should always be Ok when `should_use_default` is true");

        let response = GetInfoResponse {
            version,
            build: self.build_version.clone(),
            subversion: self.user_agent.clone(),
            protocol_version: zakura_network::constants::CURRENT_NETWORK_PROTOCOL_VERSION.0,
            blocks: tip_height.0,
            connections,
            proxy: None,
            difficulty,
            testnet,
            pay_tx_fee,
            relay_fee,
            errors: last_error_log,
            errors_timestamp: last_error_log_time.timestamp(),
        };

        Ok(response)
    }

    #[allow(clippy::unwrap_in_result)]
    async fn get_blockchain_info(&self) -> Result<GetBlockchainInfoResponse> {
        let debug_force_finished_sync = self.debug_force_finished_sync;
        let network = &self.network;

        let (usage_info_rsp, is_pruned_rsp, tip_pool_values_rsp, chain_tip_difficulty) = {
            use zakura_state::ReadRequest::*;
            let state_call = |request| self.read_state.clone().oneshot(request);
            tokio::join!(
                state_call(UsageInfo),
                state_call(IsPruned),
                state_call(TipPoolValues),
                chain_tip_difficulty(network.clone(), self.read_state.clone(), true)
            )
        };

        let (size_on_disk, is_pruned, (tip_height, tip_hash), value_balance, difficulty) = {
            use zakura_state::ReadResponse::*;

            let UsageInfo(size_on_disk) = usage_info_rsp.map_misc_error()? else {
                unreachable!("unmatched response to a UsageInfo request")
            };

            let IsPruned(is_pruned) = is_pruned_rsp.map_misc_error()? else {
                unreachable!("unmatched response to an IsPruned request")
            };

            let (tip, value_balance) = match tip_pool_values_rsp {
                Ok(TipPoolValues {
                    tip_height,
                    tip_hash,
                    value_balance,
                }) => ((tip_height, tip_hash), value_balance),
                Ok(_) => unreachable!("unmatched response to a TipPoolValues request"),
                Err(_) => ((Height::MIN, network.genesis_hash()), Default::default()),
            };

            let difficulty = chain_tip_difficulty
                .expect("should always be Ok when `should_use_default` is true");

            (size_on_disk, is_pruned, tip, value_balance, difficulty)
        };

        let now = Utc::now();
        let (estimated_height, verification_progress) = self
            .latest_chain_tip
            .best_tip_height_and_block_time()
            .map(|(tip_height, tip_block_time)| {
                let height =
                    NetworkChainTipHeightEstimator::new(tip_block_time, tip_height, network)
                        .estimate_height_at(now);

                // If we're testing the mempool, force the estimated height to be the actual tip height, otherwise,
                // check if the estimated height is below Zebra's latest tip height, or if the latest tip's block time is
                // later than the current time on the local clock.
                let height =
                    if tip_block_time > now || height < tip_height || debug_force_finished_sync {
                        tip_height
                    } else {
                        height
                    };

                (height, f64::from(tip_height.0) / f64::from(height.0))
            })
            // TODO: Add a `genesis_block_time()` method on `Network` to use here.
            .unwrap_or((Height::MIN, 0.0));

        let verification_progress = if network.is_regtest() {
            1.0
        } else {
            verification_progress
        };

        // `upgrades` object
        //
        // Get the network upgrades in height order, like `zcashd`.
        let mut upgrades = IndexMap::new();
        for (activation_height, network_upgrade) in network.full_activation_list() {
            // Zebra defines network upgrades based on incompatible consensus rule changes,
            // but zcashd defines them based on ZIPs.
            //
            // All the network upgrades with a consensus branch ID are the same in Zebra and zcashd.
            if let Some(branch_id) = network_upgrade.branch_id() {
                // zcashd's RPC seems to ignore Disabled network upgrades, so Zebra does too.
                let status = if tip_height >= activation_height {
                    NetworkUpgradeStatus::Active
                } else {
                    NetworkUpgradeStatus::Pending
                };

                let upgrade = NetworkUpgradeInfo {
                    name: network_upgrade,
                    activation_height,
                    status,
                };
                upgrades.insert(ConsensusBranchIdHex(branch_id), upgrade);
            }
        }

        // `consensus` object
        let next_block_height =
            (tip_height + 1).expect("valid chain tips are a lot less than Height::MAX");
        let consensus = TipConsensusBranch {
            chain_tip: ConsensusBranchIdHex(
                NetworkUpgrade::current(network, tip_height)
                    .branch_id()
                    .unwrap_or(ConsensusBranchId::RPC_MISSING_ID),
            ),
            next_block: ConsensusBranchIdHex(
                NetworkUpgrade::current(network, next_block_height)
                    .branch_id()
                    .unwrap_or(ConsensusBranchId::RPC_MISSING_ID),
            ),
        };

        let response = GetBlockchainInfoResponse {
            chain: network.bip70_network_name(),
            blocks: tip_height,
            best_block_hash: tip_hash,
            estimated_height,
            chain_supply: GetBlockchainInfoBalance::chain_supply(value_balance),
            value_pools: GetBlockchainInfoBalance::value_pools(value_balance, None),
            upgrades,
            consensus,
            headers: tip_height,
            difficulty,
            verification_progress,
            // TODO: store work in the finalized state for each height (#7109)
            chain_work: 0,
            pruned: is_pruned,
            size_on_disk,
            // TODO: Investigate whether this needs to be implemented (it's sprout-only in zcashd)
            commitments: 0,
        };

        Ok(response)
    }

    async fn get_address_balance(
        &self,
        address_strings: GetAddressBalanceRequest,
    ) -> Result<GetAddressBalanceResponse> {
        let valid_addresses = address_strings.valid_addresses()?;

        let request = zakura_state::ReadRequest::AddressBalance(valid_addresses);
        let response = self
            .read_state
            .clone()
            .oneshot(request)
            .await
            .map_misc_error()?;

        match response {
            zakura_state::ReadResponse::AddressBalance { balance, received } => {
                Ok(GetAddressBalanceResponse {
                    balance: u64::from(balance),
                    received,
                })
            }
            _ => unreachable!("Unexpected response from state service: {response:?}"),
        }
    }

    // TODO: use HexData or GetRawTransaction::Bytes to handle the transaction data argument
    async fn send_raw_transaction(
        &self,
        raw_transaction_hex: String,
        _allow_high_fees: Option<bool>,
    ) -> Result<SendRawTransactionResponse> {
        let mempool = self.mempool.clone();
        let queue_sender = self.queue_sender.clone();

        // Reference for the legacy error code:
        // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/rawtransaction.cpp#L1259-L1260>
        let raw_transaction_bytes = Vec::from_hex(raw_transaction_hex)
            .map_error(server::error::LegacyCode::Deserialization)?;
        let raw_transaction = Transaction::zcash_deserialize(&*raw_transaction_bytes)
            .map_error(server::error::LegacyCode::Deserialization)?;

        let transaction_hash = raw_transaction.hash();

        // send transaction to the rpc queue, ignore any error.
        let unmined_transaction = UnminedTx::from(raw_transaction.clone());
        let _ = queue_sender.send(unmined_transaction);

        let transaction_parameter = mempool::Gossip::Tx(raw_transaction.into());
        let request = mempool::Request::Queue(vec![transaction_parameter]);

        let response = mempool.oneshot(request).await.map_misc_error()?;

        let mut queue_results = match response {
            mempool::Response::Queued(results) => results,
            _ => unreachable!("incorrect response variant from mempool service"),
        };

        assert_eq!(
            queue_results.len(),
            1,
            "mempool service returned more results than expected"
        );

        let queue_result = queue_results
            .pop()
            .expect("there should be exactly one item in Vec")
            .inspect_err(|err| tracing::debug!("sent transaction to mempool: {:?}", &err))
            .map_misc_error()?
            .await
            .map_misc_error()?;

        tracing::debug!("sent transaction to mempool: {:?}", &queue_result);

        queue_result
            .map(|_| SendRawTransactionResponse(transaction_hash))
            // Reference for the legacy error code:
            // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/rawtransaction.cpp#L1290-L1301>
            // Note that this error code might not exactly match the one returned by zcashd
            // since zcashd's error code selection logic is more granular. We'd need to
            // propagate the error coming from the verifier to be able to return more specific
            // error codes.
            .map_error(server::error::LegacyCode::Verify)
    }

    // # Performance
    //
    // `lightwalletd` calls this RPC with verosity 1 for its initial sync of 2 million blocks, the
    // performance of this RPC with verbosity 1 significantly affects `lightwalletd`s sync time.
    async fn get_block(
        &self,
        hash_or_height: String,
        verbosity: Option<u8>,
    ) -> Result<GetBlockResponse> {
        let verbosity = verbosity.unwrap_or(1);
        let network = self.network.clone();
        let original_hash_or_height = hash_or_height.clone();

        // If verbosity requires a call to `get_block_header`, resolve it here
        let get_block_header_future = if matches!(verbosity, 1 | 2) {
            Some(self.get_block_header(original_hash_or_height.clone(), Some(true)))
        } else {
            None
        };

        let hash_or_height =
            HashOrHeight::new(&hash_or_height, self.latest_chain_tip.best_tip_height())
                // Reference for the legacy error code:
                // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/blockchain.cpp#L629>
                .map_error(server::error::LegacyCode::InvalidParameter)?;

        if verbosity == 0 {
            let request = zakura_state::ReadRequest::Block(hash_or_height);
            let response = self
                .read_state
                .clone()
                .oneshot(request)
                .await
                .map_misc_error()?;

            match response {
                zakura_state::ReadResponse::Block(Some(block)) => {
                    Ok(GetBlockResponse::Raw(block.into()))
                }
                zakura_state::ReadResponse::Block(None) => {
                    Err("Block not found").map_error(server::error::LegacyCode::InvalidParameter)
                }
                _ => unreachable!("unmatched response to a block request"),
            }
        } else if let Some(get_block_header_future) = get_block_header_future {
            let get_block_header_result: Result<GetBlockHeaderResponse> =
                get_block_header_future.await;

            let GetBlockHeaderResponse::Object(block_header) = get_block_header_result? else {
                panic!("must return Object")
            };

            let BlockHeaderObject {
                hash,
                confirmations,
                height,
                version,
                merkle_root,
                block_commitments,
                final_sapling_root,
                sapling_tree_size,
                time,
                nonce,
                solution,
                bits,
                difficulty,
                previous_block_hash,
                next_block_hash,
            } = *block_header;

            // # Concurrency
            //
            // We look up by block hash so the hash, transaction IDs, and confirmations
            // are consistent.
            let hash_or_height = hash.into();
            let transactions_request = match verbosity {
                1 => zakura_state::ReadRequest::TransactionIdsForBlock(hash_or_height),
                2 => zakura_state::ReadRequest::BlockAndSize(hash_or_height),
                _other => panic!("get_block_header_fut should be none"),
            };

            let mut requests = vec![
                // Get transaction IDs from the transaction index by block hash
                //
                // # Concurrency
                //
                // A block's transaction IDs are never modified, so all possible responses are
                // valid. Clients that query block heights must be able to handle chain forks,
                // including getting transaction IDs from any chain fork.
                transactions_request,
                // Orchard trees
                zakura_state::ReadRequest::OrchardTree(hash_or_height),
            ];

            let nu6_3_active =
                network.is_nu_active(consensus::NetworkUpgrade::Nu6_3, height.into());

            if nu6_3_active {
                // Ironwood trees
                requests.push(zakura_state::ReadRequest::IronwoodTree(hash_or_height));
            }

            requests.extend([
                // Block info
                zakura_state::ReadRequest::BlockInfo(previous_block_hash.into()),
                zakura_state::ReadRequest::BlockInfo(hash_or_height),
            ]);

            let mut futs = FuturesOrdered::new();

            for request in requests {
                futs.push_back(self.read_state.clone().oneshot(request));
            }

            let tx_ids_response = futs.next().await.expect("`futs` should not be empty");
            let (tx, size): (Vec<_>, Option<usize>) = match tx_ids_response.map_misc_error()? {
                zakura_state::ReadResponse::TransactionIdsForBlock(tx_ids) => (
                    tx_ids
                        .ok_or_misc_error("block not found")?
                        .iter()
                        .map(|tx_id| GetBlockTransaction::Hash(*tx_id))
                        .collect(),
                    None,
                ),
                zakura_state::ReadResponse::BlockAndSize(block_and_size) => {
                    let (block, size) = block_and_size.ok_or_misc_error("Block not found")?;
                    let block_time = block.header.time;
                    let transactions = block
                        .transactions
                        .iter()
                        .map(|tx| {
                            GetBlockTransaction::Object(Box::new(
                                TransactionObject::from_transaction(
                                    tx.clone(),
                                    Some(height),
                                    Some(confirmations),
                                    &network,
                                    Some(block_time),
                                    Some(hash),
                                    Some(true),
                                    tx.hash(),
                                ),
                            ))
                        })
                        .collect();
                    (transactions, Some(size))
                }
                _ => unreachable!("unmatched response to a transaction_ids_for_block request"),
            };

            let orchard_tree_response = futs.next().await.expect("`futs` should not be empty");
            let zakura_state::ReadResponse::OrchardTree(orchard_tree) =
                orchard_tree_response.map_misc_error()?
            else {
                unreachable!("unmatched response to a OrchardTree request");
            };

            let nu5_activation = NetworkUpgrade::Nu5.activation_height(&network);

            // This could be `None` if there's a chain reorg between state queries.
            let orchard_tree = orchard_tree.ok_or_misc_error("missing Orchard tree")?;

            let final_orchard_root = match nu5_activation {
                Some(activation_height) if height >= activation_height => {
                    Some(orchard_tree.root().into())
                }
                _other => None,
            };

            let sapling = SaplingTrees {
                size: sapling_tree_size,
            };

            let orchard_tree_size = orchard_tree.count();
            let orchard = OrchardTrees {
                size: orchard_tree_size,
            };

            let ironwood = if nu6_3_active {
                let ironwood_tree_response = futs.next().await.expect("`futs` should not be empty");
                let zakura_state::ReadResponse::IronwoodTree(ironwood_tree) =
                    ironwood_tree_response.map_misc_error()?
                else {
                    unreachable!("unmatched response to an IronwoodTree request");
                };

                // This could be `None` if there's a chain reorg between state queries.
                let ironwood_tree = ironwood_tree.ok_or_misc_error("missing Ironwood tree")?;
                Some(IronwoodTrees {
                    size: ironwood_tree.count(),
                })
            } else {
                None
            };

            let trees = GetBlockTrees {
                sapling,
                orchard,
                ironwood,
            };

            let block_info_response = futs.next().await.expect("`futs` should not be empty");
            let zakura_state::ReadResponse::BlockInfo(prev_block_info) =
                block_info_response.map_misc_error()?
            else {
                unreachable!("unmatched response to a BlockInfo request");
            };
            let block_info_response = futs.next().await.expect("`futs` should not be empty");
            let zakura_state::ReadResponse::BlockInfo(block_info) =
                block_info_response.map_misc_error()?
            else {
                unreachable!("unmatched response to a BlockInfo request");
            };

            let delta = block_info.as_ref().and_then(|d| {
                let value_pools = d.value_pools().constrain::<NegativeAllowed>().ok()?;
                let prev_value_pools = prev_block_info
                    .map(|d| d.value_pools().constrain::<NegativeAllowed>())
                    .unwrap_or(Ok(ValueBalance::<NegativeAllowed>::zero()))
                    .ok()?;
                (value_pools - prev_value_pools).ok()
            });
            let size = size.or(block_info.as_ref().map(|d| d.size() as usize));

            Ok(GetBlockResponse::Object(Box::new(BlockObject {
                hash,
                confirmations,
                height: Some(height),
                version: Some(version),
                merkle_root: Some(merkle_root),
                time: Some(time),
                nonce: Some(nonce),
                solution: Some(solution),
                bits: Some(bits),
                difficulty: Some(difficulty),
                n_tx: tx.len(),
                tx,
                trees,
                chain_supply: block_info
                    .as_ref()
                    .map(|d| GetBlockchainInfoBalance::chain_supply(*d.value_pools())),
                value_pools: block_info
                    .map(|d| GetBlockchainInfoBalance::value_pools(*d.value_pools(), delta)),
                size: size.map(|size| size as i64),
                block_commitments: Some(block_commitments),
                final_sapling_root: Some(final_sapling_root),
                final_orchard_root,
                previous_block_hash: Some(previous_block_hash),
                next_block_hash,
            })))
        } else {
            Err("invalid verbosity value").map_error(server::error::LegacyCode::InvalidParameter)
        }
    }

    async fn get_block_header(
        &self,
        hash_or_height: String,
        verbose: Option<bool>,
    ) -> Result<GetBlockHeaderResponse> {
        let verbose = verbose.unwrap_or(true);
        let network = self.network.clone();

        let hash_or_height =
            HashOrHeight::new(&hash_or_height, self.latest_chain_tip.best_tip_height())
                // Reference for the legacy error code:
                // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/blockchain.cpp#L629>
                .map_error(server::error::LegacyCode::InvalidParameter)?;
        let zakura_state::ReadResponse::BlockHeader {
            header,
            hash,
            height,
            next_block_hash,
        } = self
            .read_state
            .clone()
            .oneshot(zakura_state::ReadRequest::BlockHeader(hash_or_height))
            .await
            .map_err(|_| "block height not in best chain")
            .map_error(
                // ## Compatibility with `zcashd`.
                //
                // Since this function is reused by getblock(), we return the errors
                // expected by it (they differ whether a hash or a height was passed).
                if hash_or_height.hash().is_some() {
                    server::error::LegacyCode::InvalidAddressOrKey
                } else {
                    server::error::LegacyCode::InvalidParameter
                },
            )?
        else {
            panic!("unexpected response to BlockHeader request")
        };

        let response = if !verbose {
            GetBlockHeaderResponse::Raw(HexData(header.zcash_serialize_to_vec().map_misc_error()?))
        } else {
            let zakura_state::ReadResponse::SaplingTree(sapling_tree) = self
                .read_state
                .clone()
                // Use the resolved hash so a reorg cannot combine this header
                // with the Sapling tree from a different block at the same
                // height.
                .oneshot(zakura_state::ReadRequest::SaplingTree(hash.into()))
                .await
                .map_misc_error()?
            else {
                panic!("unexpected response to SaplingTree request")
            };

            // This could be `None` if there's a chain reorg between state queries.
            let sapling_tree = sapling_tree.ok_or_misc_error("missing Sapling tree")?;

            let zakura_state::ReadResponse::Depth(depth) = self
                .read_state
                .clone()
                .oneshot(zakura_state::ReadRequest::Depth(hash))
                .await
                .map_misc_error()?
            else {
                panic!("unexpected response to SaplingTree request")
            };

            // From <https://zcash.github.io/rpc/getblock.html>
            // TODO: Deduplicate const definition, consider refactoring this to avoid duplicate logic
            const NOT_IN_BEST_CHAIN_CONFIRMATIONS: i64 = -1;

            // Confirmations are one more than the depth.
            // Depth is limited by height, so it will never overflow an i64.
            let confirmations = depth
                .map(|depth| i64::from(depth) + 1)
                .unwrap_or(NOT_IN_BEST_CHAIN_CONFIRMATIONS);

            let mut nonce = *header.nonce;
            nonce.reverse();

            let sapling_activation = NetworkUpgrade::Sapling.activation_height(&network);
            let sapling_tree_size = sapling_tree.count();
            let final_sapling_root: [u8; 32] =
                if sapling_activation.is_some() && height >= sapling_activation.unwrap() {
                    let mut root: [u8; 32] = sapling_tree.root().into();
                    root.reverse();
                    root
                } else {
                    [0; 32]
                };

            let difficulty = header.difficulty_threshold.relative_to_network(&network);

            let block_commitments = match header.commitment(&network, height).expect(
                "Unexpected failure while parsing the blockcommitments field in get_block_header",
            ) {
                Commitment::PreSaplingReserved(bytes) => bytes,
                Commitment::FinalSaplingRoot(_) => final_sapling_root,
                Commitment::ChainHistoryActivationReserved => [0; 32],
                Commitment::ChainHistoryRoot(root) => root.bytes_in_display_order(),
                Commitment::ChainHistoryBlockTxAuthCommitment(hash) => {
                    hash.bytes_in_display_order()
                }
            };

            let block_header = BlockHeaderObject {
                hash,
                confirmations,
                height,
                version: header.version,
                merkle_root: header.merkle_root,
                block_commitments,
                final_sapling_root,
                sapling_tree_size,
                time: header.time.timestamp(),
                nonce,
                solution: header.solution,
                bits: header.difficulty_threshold,
                difficulty,
                previous_block_hash: header.previous_block_hash,
                next_block_hash,
            };

            GetBlockHeaderResponse::Object(Box::new(block_header))
        };

        Ok(response)
    }

    fn get_best_block_hash(&self) -> Result<GetBlockHashResponse> {
        self.latest_chain_tip
            .best_tip_hash()
            .map(GetBlockHashResponse)
            .ok_or_misc_error("No blocks in state")
    }

    fn get_best_block_height_and_hash(&self) -> Result<GetBlockHeightAndHashResponse> {
        self.latest_chain_tip
            .best_tip_height_and_hash()
            .map(|(height, hash)| GetBlockHeightAndHashResponse { height, hash })
            .ok_or_misc_error("No blocks in state")
    }

    async fn get_mempool_info(&self) -> Result<GetMempoolInfoResponse> {
        let mut mempool = self.mempool.clone();

        let response = mempool
            .ready()
            .and_then(|service| service.call(mempool::Request::QueueStats))
            .await
            .map_misc_error()?;

        if let mempool::Response::QueueStats {
            size,
            bytes,
            usage,
            fully_notified,
        } = response
        {
            Ok(GetMempoolInfoResponse {
                size,
                bytes,
                usage,
                fully_notified,
            })
        } else {
            unreachable!("unexpected response to QueueStats request")
        }
    }

    async fn get_raw_mempool(&self, verbose: Option<bool>) -> Result<GetRawMempoolResponse> {
        #[allow(unused)]
        let verbose = verbose.unwrap_or(false);

        use zakura_chain::block::MAX_BLOCK_BYTES;

        let mut mempool = self.mempool.clone();

        let request = if verbose {
            mempool::Request::FullTransactions
        } else {
            mempool::Request::TransactionIds
        };

        // `zcashd` doesn't check if it is synced to the tip here, so we don't either.
        let response = mempool
            .ready()
            .and_then(|service| service.call(request))
            .await
            .map_misc_error()?;

        match response {
            mempool::Response::FullTransactions {
                mut transactions,
                transaction_dependencies,
                last_seen_tip_hash: _,
            } => {
                if verbose {
                    let transactions_by_id = transactions
                        .iter()
                        .map(|unmined_tx| (unmined_tx.transaction.id.mined_id(), unmined_tx))
                        .collect::<HashMap<_, _>>();
                    let map = transactions
                        .iter()
                        .map(|unmined_tx| {
                            (
                                unmined_tx.transaction.id.mined_id().encode_hex(),
                                get_raw_mempool::MempoolObject::from_verified_unmined_tx(
                                    unmined_tx,
                                    &transactions_by_id,
                                    &transaction_dependencies,
                                ),
                            )
                        })
                        .collect::<HashMap<_, _>>();
                    Ok(GetRawMempoolResponse::Verbose(map))
                } else {
                    // Sort transactions in descending order by fee/size, using
                    // hash in serialized byte order as a tie-breaker. Note that
                    // this is only done in not verbose because in verbose mode
                    // a dictionary is returned, where order does not matter.
                    transactions.sort_by_cached_key(|tx| {
                        // zcashd uses modified fee here but Zebra doesn't currently
                        // support prioritizing transactions
                        cmp::Reverse((
                            i64::from(tx.miner_fee) as u128 * MAX_BLOCK_BYTES as u128
                                / tx.transaction.size as u128,
                            // transaction hashes are compared in their serialized byte-order.
                            tx.transaction.id.mined_id(),
                        ))
                    });
                    let tx_ids: Vec<String> = transactions
                        .iter()
                        .map(|unmined_tx| unmined_tx.transaction.id.mined_id().encode_hex())
                        .collect();

                    Ok(GetRawMempoolResponse::TxIds(tx_ids))
                }
            }

            mempool::Response::TransactionIds(unmined_transaction_ids) => {
                let mut tx_ids: Vec<String> = unmined_transaction_ids
                    .iter()
                    .map(|id| id.mined_id().encode_hex())
                    .collect();

                // Sort returned transaction IDs in numeric/string order.
                tx_ids.sort();

                Ok(GetRawMempoolResponse::TxIds(tx_ids))
            }

            _ => unreachable!("unmatched response to a transactionids request"),
        }
    }

    async fn get_raw_transaction(
        &self,
        txid: String,
        verbose: Option<u8>,
        block_hash: Option<String>,
    ) -> Result<GetRawTransactionResponse> {
        let mut mempool = self.mempool.clone();
        let verbose = verbose.unwrap_or(0) != 0;

        // Reference for the legacy error code:
        // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/rawtransaction.cpp#L544>
        let txid = transaction::Hash::from_hex(txid)
            .map_error(server::error::LegacyCode::InvalidAddressOrKey)?;

        // Check the mempool first.
        if block_hash.is_none() {
            match mempool
                .ready()
                .and_then(|service| {
                    service.call(mempool::Request::TransactionsByMinedId([txid].into()))
                })
                .await
                .map_misc_error()?
            {
                mempool::Response::Transactions(txns) => {
                    if let Some(tx) = txns.first() {
                        return Ok(if verbose {
                            GetRawTransactionResponse::Object(Box::new(
                                TransactionObject::from_transaction(
                                    tx.transaction.clone(),
                                    None,
                                    None,
                                    &self.network,
                                    None,
                                    None,
                                    Some(false),
                                    txid,
                                ),
                            ))
                        } else {
                            let hex = tx.transaction.clone().into();
                            GetRawTransactionResponse::Raw(hex)
                        });
                    }
                }

                _ => unreachable!("unmatched response to a `TransactionsByMinedId` request"),
            };
        }

        let caller_block_context = if let Some(block_hash) = block_hash {
            let block_hash = block::Hash::from_hex(block_hash)
                .map_error(server::error::LegacyCode::InvalidAddressOrKey)?;
            match self
                .read_state
                .clone()
                .oneshot(zakura_state::ReadRequest::AnyChainTransactionIdsForBlock(
                    block_hash.into(),
                ))
                .await
                .map_misc_error()?
            {
                zakura_state::ReadResponse::AnyChainTransactionIdsForBlock(tx_ids) => {
                    let (ids, in_best_chain) = tx_ids.ok_or_error(
                        server::error::LegacyCode::InvalidAddressOrKey,
                        "block not found",
                    )?;

                    ids.iter().find(|id| **id == txid).ok_or_error(
                        server::error::LegacyCode::InvalidAddressOrKey,
                        "txid not found",
                    )?;

                    Some((block_hash, in_best_chain))
                }
                _ => {
                    unreachable!("unmatched response to a `AnyChainTransactionIdsForBlock` request")
                }
            }
        } else {
            None
        };

        // If the tx wasn't in the mempool, check the state.
        match self
            .read_state
            .clone()
            .oneshot(zakura_state::ReadRequest::AnyChainTransaction(txid))
            .await
            .map_misc_error()?
        {
            zakura_state::ReadResponse::AnyChainTransaction(Some(tx)) => Ok(if verbose {
                if let Some((caller_block_hash, in_best_chain)) = caller_block_context {
                    // Use the caller-provided block context to avoid TOCTOU races
                    // between the validation query and the transaction fetch.
                    let (raw_tx, height, confirmations, block_time) = match &tx {
                        AnyTx::Mined(mined) if in_best_chain => (
                            mined.tx.clone(),
                            Some(mined.height),
                            Some(mined.confirmations.into()),
                            Some(mined.block_time),
                        ),
                        _ => {
                            let raw_tx: Arc<Transaction> = tx.into();
                            (raw_tx, None, None, None)
                        }
                    };

                    GetRawTransactionResponse::Object(Box::new(
                        TransactionObject::from_transaction(
                            raw_tx,
                            height,
                            confirmations,
                            &self.network,
                            block_time,
                            Some(caller_block_hash),
                            Some(in_best_chain),
                            txid,
                        ),
                    ))
                } else {
                    match tx {
                        AnyTx::Mined(tx) => {
                            let block_hash = match self
                                .read_state
                                .clone()
                                .oneshot(zakura_state::ReadRequest::BestChainBlockHash(tx.height))
                                .await
                                .map_misc_error()?
                            {
                                zakura_state::ReadResponse::BlockHash(block_hash) => block_hash,
                                _ => {
                                    unreachable!(
                                        "unmatched response to a `BestChainBlockHash` request"
                                    )
                                }
                            };

                            GetRawTransactionResponse::Object(Box::new(
                                TransactionObject::from_transaction(
                                    tx.tx.clone(),
                                    Some(tx.height),
                                    Some(tx.confirmations.into()),
                                    &self.network,
                                    // TODO: Performance gain:
                                    // https://github.com/ZcashFoundation/zebra/pull/9458#discussion_r2059352752
                                    Some(tx.block_time),
                                    block_hash,
                                    Some(true),
                                    txid,
                                ),
                            ))
                        }
                        AnyTx::Side((tx, block_hash)) => GetRawTransactionResponse::Object(
                            Box::new(TransactionObject::from_transaction(
                                tx.clone(),
                                None,
                                None,
                                &self.network,
                                None,
                                Some(block_hash),
                                Some(false),
                                txid,
                            )),
                        ),
                    }
                }
            } else {
                let tx: Arc<Transaction> = tx.into();
                let hex = tx.into();
                GetRawTransactionResponse::Raw(hex)
            }),

            zakura_state::ReadResponse::AnyChainTransaction(None) => {
                Err("Transaction not found in mempool or best chain")
                    .map_error(server::error::LegacyCode::InvalidAddressOrKey)
            }

            _ => unreachable!("unmatched response to a `Transaction` read request"),
        }
    }

    async fn z_get_treestate(&self, hash_or_height: String) -> Result<GetTreestateResponse> {
        let mut read_state = self.read_state.clone();
        let network = self.network.clone();

        let hash_or_height =
            HashOrHeight::new(&hash_or_height, self.latest_chain_tip.best_tip_height())
                // Reference for the legacy error code:
                // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/blockchain.cpp#L629>
                .map_error(server::error::LegacyCode::InvalidParameter)?;

        // Fetch the block referenced by [`hash_or_height`] from the state.
        //
        // # Concurrency
        //
        // For consistency, this lookup must be performed first, then all the other lookups must
        // be based on the hash.
        //
        // TODO: If this RPC is called a lot, just get the block header, rather than the whole block.
        let block = match read_state
            .ready()
            .and_then(|service| service.call(zakura_state::ReadRequest::Block(hash_or_height)))
            .await
            .map_misc_error()?
        {
            zakura_state::ReadResponse::Block(Some(block)) => block,
            zakura_state::ReadResponse::Block(None) => {
                // Reference for the legacy error code:
                // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/blockchain.cpp#L629>
                return Err("the requested block is not in the main chain")
                    .map_error(server::error::LegacyCode::InvalidParameter);
            }
            _ => unreachable!("unmatched response to a block request"),
        };

        let hash = hash_or_height
            .hash_or_else(|_| Some(block.hash()))
            .expect("block hash");

        let height = hash_or_height
            .height_or_else(|_| block.coinbase_height())
            .expect("verified blocks have a coinbase height");

        let time = u32::try_from(block.header.time.timestamp())
            .expect("Timestamps of valid blocks always fit into u32.");

        let sapling = if network.is_nu_active(consensus::NetworkUpgrade::Sapling, height.into()) {
            match read_state
                .ready()
                .and_then(|service| {
                    service.call(zakura_state::ReadRequest::SaplingTree(hash.into()))
                })
                .await
                .map_misc_error()?
            {
                zakura_state::ReadResponse::SaplingTree(tree) => {
                    tree.map(|t| (t.to_rpc_bytes(), t.root().bytes_in_display_order().to_vec()))
                }
                _ => unreachable!("unmatched response to a Sapling tree request"),
            }
        } else {
            None
        };
        let (sapling_tree, sapling_root) =
            sapling.map_or((None, None), |(tree, root)| (Some(tree), Some(root)));

        let orchard = if network.is_nu_active(consensus::NetworkUpgrade::Nu5, height.into()) {
            match read_state
                .ready()
                .and_then(|service| {
                    service.call(zakura_state::ReadRequest::OrchardTree(hash.into()))
                })
                .await
                .map_misc_error()?
            {
                zakura_state::ReadResponse::OrchardTree(tree) => {
                    tree.map(|t| (t.to_rpc_bytes(), t.root().bytes_in_display_order().to_vec()))
                }
                _ => unreachable!("unmatched response to an Orchard tree request"),
            }
        } else {
            None
        };
        let (orchard_tree, orchard_root) =
            orchard.map_or((None, None), |(tree, root)| (Some(tree), Some(root)));

        let ironwood = if network.is_nu_active(consensus::NetworkUpgrade::Nu6_3, height.into()) {
            match read_state
                .ready()
                .and_then(|service| {
                    service.call(zakura_state::ReadRequest::IronwoodTree(hash.into()))
                })
                .await
                .map_misc_error()?
            {
                zakura_state::ReadResponse::IronwoodTree(tree) => {
                    tree.map(|t| (t.to_rpc_bytes(), t.root().bytes_in_display_order().to_vec()))
                }
                _ => unreachable!("unmatched response to an Ironwood tree request"),
            }
        } else {
            None
        };

        let ironwood = ironwood.map_or_else(Treestate::default, |(tree, root)| {
            Treestate::new(trees::Commitments::new(Some(root), Some(tree)))
        });

        Ok(GetTreestateResponse::new(
            hash,
            height,
            time,
            // We can't currently return Sprout data because we don't store it for
            // old heights.
            None,
            Treestate::new(trees::Commitments::new(sapling_root, sapling_tree)),
            Treestate::new(trees::Commitments::new(orchard_root, orchard_tree)),
            ironwood,
        ))
    }

    async fn z_get_subtrees_by_index(
        &self,
        pool: String,
        start_index: NoteCommitmentSubtreeIndex,
        limit: Option<NoteCommitmentSubtreeIndex>,
    ) -> Result<GetSubtreesByIndexResponse> {
        let mut read_state = self.read_state.clone();

        const POOL_LIST: &[&str] = &["sapling", "orchard", "ironwood"];

        if pool == "sapling" {
            let request = zakura_state::ReadRequest::SaplingSubtrees { start_index, limit };
            let response = read_state
                .ready()
                .and_then(|service| service.call(request))
                .await
                .map_misc_error()?;

            let subtrees = match response {
                zakura_state::ReadResponse::SaplingSubtrees(subtrees) => subtrees,
                _ => unreachable!("unmatched response to a subtrees request"),
            };

            let subtrees = subtrees
                .values()
                .map(|subtree| SubtreeRpcData {
                    root: subtree.root.to_bytes().encode_hex(),
                    end_height: subtree.end_height,
                })
                .collect();

            Ok(GetSubtreesByIndexResponse {
                pool,
                start_index,
                subtrees,
            })
        } else if pool == "orchard" {
            let request = zakura_state::ReadRequest::OrchardSubtrees { start_index, limit };
            let response = read_state
                .ready()
                .and_then(|service| service.call(request))
                .await
                .map_misc_error()?;

            let subtrees = match response {
                zakura_state::ReadResponse::OrchardSubtrees(subtrees) => subtrees,
                _ => unreachable!("unmatched response to a subtrees request"),
            };

            let subtrees = subtrees
                .values()
                .map(|subtree| SubtreeRpcData {
                    root: subtree.root.encode_hex(),
                    end_height: subtree.end_height,
                })
                .collect();

            Ok(GetSubtreesByIndexResponse {
                pool,
                start_index,
                subtrees,
            })
        } else if pool == "ironwood" {
            let request = zakura_state::ReadRequest::IronwoodSubtrees { start_index, limit };
            let response = read_state
                .ready()
                .and_then(|service| service.call(request))
                .await
                .map_misc_error()?;

            let subtrees = match response {
                zakura_state::ReadResponse::IronwoodSubtrees(subtrees) => subtrees,
                _ => unreachable!("unmatched response to a subtrees request"),
            };

            let subtrees = subtrees
                .values()
                .map(|subtree| SubtreeRpcData {
                    root: subtree.root.encode_hex(),
                    end_height: subtree.end_height,
                })
                .collect();

            Ok(GetSubtreesByIndexResponse {
                pool,
                start_index,
                subtrees,
            })
        } else {
            Err(ErrorObject::owned(
                server::error::LegacyCode::Misc.into(),
                format!("invalid pool name, must be one of: {POOL_LIST:?}").as_str(),
                None::<()>,
            ))
        }
    }

    async fn get_address_tx_ids(&self, request: GetAddressTxIdsRequest) -> Result<Vec<String>> {
        let mut read_state = self.read_state.clone();
        let latest_chain_tip = self.latest_chain_tip.clone();

        let height_range = build_height_range(
            request.start,
            request.end,
            best_chain_tip_height(&latest_chain_tip)?,
        )?;

        let valid_addresses = request.valid_addresses()?;

        let request = zakura_state::ReadRequest::TransactionIdsByAddresses {
            addresses: valid_addresses,
            height_range,
        };
        let response = read_state
            .ready()
            .and_then(|service| service.call(request))
            .await
            .map_misc_error()?;

        let hashes = match response {
            zakura_state::ReadResponse::AddressesTransactionIds(hashes) => {
                let mut last_tx_location = TransactionLocation::from_usize(Height(0), 0);

                hashes
                    .iter()
                    .map(|(tx_loc, tx_id)| {
                        // Check that the returned transactions are in chain order.
                        assert!(
                            *tx_loc > last_tx_location,
                            "Transactions were not in chain order:\n\
                                 {tx_loc:?} {tx_id:?} was after:\n\
                                 {last_tx_location:?}",
                        );

                        last_tx_location = *tx_loc;

                        tx_id.to_string()
                    })
                    .collect()
            }
            _ => unreachable!("unmatched response to a TransactionsByAddresses request"),
        };

        Ok(hashes)
    }

    async fn get_address_utxos(
        &self,
        utxos_request: GetAddressUtxosRequest,
    ) -> Result<GetAddressUtxosResponse> {
        let mut read_state = self.read_state.clone();
        let mut response_utxos = vec![];

        let valid_addresses = utxos_request.valid_addresses()?;

        // get utxos data for addresses
        let request = zakura_state::ReadRequest::UtxosByAddresses(valid_addresses);
        let response = read_state
            .ready()
            .and_then(|service| service.call(request))
            .await
            .map_misc_error()?;
        let utxos = match response {
            zakura_state::ReadResponse::AddressUtxos(utxos) => utxos,
            _ => unreachable!("unmatched response to a UtxosByAddresses request"),
        };

        let mut last_output_location = OutputLocation::from_usize(Height(0), 0, 0);

        for utxo_data in utxos.utxos() {
            let address = utxo_data.0;
            let txid = *utxo_data.1;
            let height = utxo_data.2.height();
            let output_index = utxo_data.2.output_index();
            let script = utxo_data.3.lock_script.clone();
            let satoshis = u64::from(utxo_data.3.value);

            let output_location = *utxo_data.2;
            // Check that the returned UTXOs are in chain order.
            assert!(
                output_location > last_output_location,
                "UTXOs were not in chain order:\n\
                     {output_location:?} {address:?} {txid:?} was after:\n\
                     {last_output_location:?}",
            );

            let entry = Utxo {
                address,
                txid,
                output_index,
                script,
                satoshis,
                height,
            };
            response_utxos.push(entry);

            last_output_location = output_location;
        }

        if !utxos_request.chain_info {
            Ok(GetAddressUtxosResponse::Utxos(response_utxos))
        } else {
            let (height, hash) = utxos
                .last_height_and_hash()
                .ok_or_misc_error("No blocks in state")?;

            Ok(GetAddressUtxosResponse::UtxosAndChainInfo(
                GetAddressUtxosResponseObject {
                    utxos: response_utxos,
                    hash,
                    height,
                },
            ))
        }
    }

    fn stop(&self) -> Result<String> {
        #[cfg(not(target_os = "windows"))]
        if self.network.is_regtest() {
            match nix::sys::signal::raise(nix::sys::signal::SIGINT) {
                Ok(_) => Ok("Zakura server stopping".to_string()),
                Err(error) => Err(ErrorObject::owned(
                    ErrorCode::InternalError.code(),
                    format!("Failed to shut down: {error}").as_str(),
                    None::<()>,
                )),
            }
        } else {
            Err(ErrorObject::borrowed(
                ErrorCode::MethodNotFound.code(),
                "stop is only available on regtest networks",
                None,
            ))
        }
        #[cfg(target_os = "windows")]
        Err(ErrorObject::borrowed(
            ErrorCode::MethodNotFound.code(),
            "stop is not available in windows targets",
            None,
        ))
    }

    fn get_block_count(&self) -> Result<u32> {
        best_chain_tip_height(&self.latest_chain_tip).map(|height| height.0)
    }

    async fn get_block_hash(&self, index: i32) -> Result<GetBlockHashResponse> {
        let mut read_state = self.read_state.clone();
        let latest_chain_tip = self.latest_chain_tip.clone();

        // TODO: look up this height as part of the state request?
        let tip_height = best_chain_tip_height(&latest_chain_tip)?;

        let height = height_from_signed_int(index, tip_height)?;

        let request = zakura_state::ReadRequest::BestChainBlockHash(height);
        let response = read_state
            .ready()
            .and_then(|service| service.call(request))
            .await
            .map_error(server::error::LegacyCode::default())?;

        match response {
            zakura_state::ReadResponse::BlockHash(Some(hash)) => Ok(GetBlockHashResponse(hash)),
            zakura_state::ReadResponse::BlockHash(None) => Err(ErrorObject::borrowed(
                server::error::LegacyCode::InvalidParameter.into(),
                "Block not found",
                None,
            )),
            _ => unreachable!("unmatched response to a block request"),
        }
    }

    async fn get_block_template(
        &self,
        parameters: Option<GetBlockTemplateParameters>,
    ) -> Result<GetBlockTemplateResponse> {
        use types::get_block_template::{
            check_parameters, check_synced_to_tip, fetch_chain_info, fetch_mempool_transactions,
            validate_block_proposal, zip317::select_mempool_transactions,
        };

        // Clone Services
        let mempool = self.mempool.clone();
        let mut latest_chain_tip = self.latest_chain_tip.clone();
        let sync_status = self.gbt.sync_status();
        let read_state = self.read_state.clone();

        if let Some(HexData(block_proposal_bytes)) = parameters
            .as_ref()
            .and_then(GetBlockTemplateParameters::block_proposal_data)
        {
            return validate_block_proposal(
                self.gbt.block_verifier_router(),
                block_proposal_bytes,
                &self.network,
                latest_chain_tip,
                sync_status,
            )
            .await;
        }

        // To implement long polling correctly, we split this RPC into multiple phases.
        check_parameters(&parameters)?;

        let client_long_poll_id = parameters.as_ref().and_then(|params| params.long_poll_id);

        let miner_params = self
            .gbt
            .miner_params()
            .ok_or_error(0, "miner parameters are required for get_block_template")?;

        // - Checks and fetches that can change during long polling
        //
        // Set up the loop.
        let mut max_time_reached = false;

        // The loop returns the server long poll ID, which should be different to the client one.
        let (server_long_poll_id, chain_info, mempool_txs, mempool_tx_deps, submit_old) = loop {
            // Check if we are synced to the tip.
            // The result of this check can change during long polling.
            //
            // Optional TODO:
            // - add `async changed()` method to ChainSyncStatus (like `ChainTip`)
            check_synced_to_tip(&self.network, latest_chain_tip.clone(), sync_status.clone())?;
            // TODO: return an error if we have no peers, like `zcashd` does,
            //       and add a developer config that mines regardless of how many peers we have.
            // https://github.com/zcash/zcash/blob/6fdd9f1b81d3b228326c9826fa10696fc516444b/src/miner.cpp#L865-L880

            // We're just about to fetch state data, then maybe wait for any changes.
            // Mark all the changes before the fetch as seen.
            // Changes are also ignored in any clones made after the mark.
            latest_chain_tip.mark_best_tip_seen();

            // Fetch the state data and local time for the block template:
            // - if the tip block hash changes, we must return from long polling,
            // - if the local clock changes on testnet, we might return from long polling
            //
            // We always return after 90 minutes on mainnet, even if we have the same response,
            // because the max time has been reached.
            let chain_info @ zakura_state::GetBlockTemplateChainInfo {
                tip_hash,
                tip_height,
                max_time,
                cur_time,
                ..
            } = fetch_chain_info(read_state.clone()).await?;

            // Fetch the mempool data for the block template:
            // - if the mempool transactions change, we might return from long polling.
            //
            // If the chain fork has just changed, miners want to get the new block as fast
            // as possible, rather than wait for transactions to re-verify. This increases
            // miner profits (and any delays can cause chain forks). So we don't wait between
            // the chain tip changing and getting mempool transactions.
            //
            // Optional TODO:
            // - add a `MempoolChange` type with an `async changed()` method (like `ChainTip`)
            let Some((mempool_txs, mempool_tx_deps)) =
                fetch_mempool_transactions(mempool.clone(), tip_hash)
                    .await?
                    // If the mempool and state responses are out of sync:
                    // - if we are not long polling, omit mempool transactions from the template,
                    // - if we are long polling, continue to the next iteration of the loop to make fresh state and mempool requests.
                    .or_else(|| client_long_poll_id.is_none().then(Default::default))
            else {
                continue;
            };

            // - Long poll ID calculation
            let server_long_poll_id = LongPollInput::new(
                tip_height,
                tip_hash,
                max_time,
                mempool_txs.iter().map(|tx| tx.transaction.id),
            )
            .generate_id();

            // The loop finishes if:
            // - the client didn't pass a long poll ID,
            // - the server long poll ID is different to the client long poll ID, or
            // - the previous loop iteration waited until the max time.
            if Some(&server_long_poll_id) != client_long_poll_id.as_ref() || max_time_reached {
                // On testnet, the max time changes the block difficulty, so old shares are invalid.
                // On mainnet, this means there has been 90 minutes without a new block or mempool
                // transaction, which is very unlikely. So the miner should probably reset anyway.
                let submit_old = if max_time_reached {
                    Some(false)
                } else {
                    client_long_poll_id
                        .as_ref()
                        .map(|old_long_poll_id| server_long_poll_id.submit_old(old_long_poll_id))
                };

                break (
                    server_long_poll_id,
                    chain_info,
                    mempool_txs,
                    mempool_tx_deps,
                    submit_old,
                );
            }

            // - Polling wait conditions
            //
            // TODO: when we're happy with this code, split it into a function.
            //
            // Periodically check the mempool for changes.
            //
            // Optional TODO:
            // Remove this polling wait if we switch to using futures to detect sync status
            // and mempool changes.
            let wait_for_mempool_request =
                tokio::time::sleep(Duration::from_secs(MEMPOOL_LONG_POLL_INTERVAL));

            // Return immediately if the chain tip has changed.
            // The clone preserves the seen status of the chain tip.
            let mut wait_for_new_tip = latest_chain_tip.clone();
            let wait_for_new_tip = wait_for_new_tip.best_tip_changed();
            // `+2`: we expect the tip to advance by one block before waking us up.
            let precomputed_height = Height(chain_info.tip_height.0 + 2);
            let wait_for_new_tip = async {
                // Precompute the coinbase tx for an empty block that will sit on the new tip. We
                // will return this provisional block upon a chain tip change so that miners can
                // mine on the newest tip, and don't waste their effort on a shorter chain while we
                // compute a new template for a properly filled block. We do this precomputation
                // before we start waiting for a new tip since computing the coinbase tx takes a few
                // seconds if the miner mines to a shielded address, and we want to return fast
                // when the tip changes.
                let precompute_coinbase = |network, height, params| {
                    tokio::task::spawn_blocking(move || {
                        TransactionTemplate::new_coinbase(&network, height, &params, Amount::zero())
                            .expect("valid coinbase tx")
                    })
                };

                let precomputed_coinbase = precompute_coinbase(
                    self.network.clone(),
                    precomputed_height,
                    miner_params.clone(),
                )
                .await
                .expect("valid coinbase tx");

                let _ = wait_for_new_tip.await;

                precomputed_coinbase
            };

            // Wait for the maximum block time to elapse. This can change the block header
            // on testnet. (On mainnet it can happen due to a network disconnection, or a
            // rapid drop in hash rate.)
            //
            // This duration might be slightly lower than the actual maximum,
            // if cur_time was clamped to min_time. In that case the wait is very long,
            // and it's ok to return early.
            //
            // It can also be zero if cur_time was clamped to max_time. In that case,
            // we want to wait for another change, and ignore this timeout. So we use an
            // `OptionFuture::None`.
            let duration_until_max_time = max_time.saturating_duration_since(cur_time);
            let wait_for_max_time: OptionFuture<_> = if duration_until_max_time.seconds() > 0 {
                Some(tokio::time::sleep(duration_until_max_time.to_std()))
            } else {
                None
            }
            .into();

            // Optional TODO:
            // `zcashd` generates the next coinbase transaction while waiting for changes.
            // When Zebra supports shielded coinbase, we might want to do this in parallel.
            // But the coinbase value depends on the selected transactions, so this needs
            // further analysis to check if it actually saves us any time.

            tokio::select! {
                // Poll the futures in the listed order, for efficiency.
                // We put the most frequent conditions first.
                biased;

                // This timer elapses every few seconds
                _elapsed = wait_for_mempool_request => {
                    tracing::debug!(
                        ?max_time,
                        ?cur_time,
                        ?server_long_poll_id,
                        ?client_long_poll_id,
                        MEMPOOL_LONG_POLL_INTERVAL,
                        "checking for a new mempool change after waiting a few seconds"
                    );
                }

                precomputed_coinbase = wait_for_new_tip => {
                    let chain_info = fetch_chain_info(read_state.clone()).await?;

                    let server_long_poll_id = LongPollInput::new(
                        chain_info.tip_height,
                        chain_info.tip_hash,
                        chain_info.max_time,
                        vec![]
                    )
                    .generate_id();

                    let submit_old = client_long_poll_id
                        .as_ref()
                        .map(|old_long_poll_id| server_long_poll_id.submit_old(old_long_poll_id));

                    // Discard the precomputed coinbase if our `+2` guess was wrong
                    // (multi-block advance, reorg, or spurious notification) — its
                    // BIP-34 height and subsidies wouldn't match the block.
                    let next_height = chain_info.tip_height.next().map_misc_error()?;
                    let precomputed_coinbase = (next_height == precomputed_height)
                        .then_some(precomputed_coinbase);

                    // Respond instantly with an empty block upon a chain tip change so that
                    // the miner doesn't waste their effort trying to extend a shorter
                    // chain.
                    return Ok(BlockTemplateResponse::new_internal(
                        &self.network,
                        precomputed_coinbase,
                        miner_params,
                        &chain_info,
                        server_long_poll_id,
                        vec![],
                        submit_old,
                    )
                    .into())
                }

                // The max time does not elapse during normal operation on mainnet,
                // and it rarely elapses on testnet.
                Some(_elapsed) = wait_for_max_time => {
                    // This log is very rare so it's ok to be info.
                    tracing::info!(
                        ?max_time,
                        ?cur_time,
                        ?server_long_poll_id,
                        ?client_long_poll_id,
                        "returning from long poll because max time was reached"
                    );

                    max_time_reached = true;
                }
            }
        };

        // - Processing fetched data to create a transaction template
        //
        // Apart from random weighted transaction selection,
        // the template only depends on the previously fetched data.
        // This processing never fails.

        tracing::debug!(
            mempool_tx_hashes = ?mempool_txs
                .iter()
                .map(|tx| tx.transaction.id.mined_id())
                .collect::<Vec<_>>(),
            "selecting transactions for the template from the mempool"
        );

        let height = chain_info.tip_height.next().map_misc_error()?;

        // Randomly select some mempool transactions.
        let mempool_txs = select_mempool_transactions(
            &self.network,
            height,
            miner_params,
            mempool_txs,
            mempool_tx_deps,
        );

        tracing::debug!(
            selected_mempool_tx_hashes = ?mempool_txs
                .iter()
                .map(|#[cfg(not(test))] tx, #[cfg(test)] (_, tx)| tx.transaction.id.mined_id())
                .collect::<Vec<_>>(),
            "selected transactions for the template from the mempool"
        );

        // - After this point, the template only depends on the previously fetched data.

        Ok(BlockTemplateResponse::new_internal(
            &self.network,
            None,
            miner_params,
            &chain_info,
            server_long_poll_id,
            mempool_txs,
            submit_old,
        )
        .into())
    }

    async fn submit_block(
        &self,
        HexData(block_bytes): HexData,
        _parameters: Option<SubmitBlockParameters>,
    ) -> Result<SubmitBlockResponse> {
        let mut block_verifier_router = self.gbt.block_verifier_router();

        let block: Block = match block_bytes.zcash_deserialize_into() {
            Ok(block_bytes) => block_bytes,
            Err(error) => {
                tracing::info!(
                    ?error,
                    "submit block failed: block bytes could not be deserialized into a structurally valid block"
                );

                return Ok(SubmitBlockErrorResponse::Rejected.into());
            }
        };

        let height = block
            .coinbase_height()
            .ok_or_error(0, "coinbase height not found")?;
        let block_hash = block.hash();

        let block_verifier_router_response = block_verifier_router
            .ready()
            .await
            .map_err(|error| ErrorObject::owned(0, error.to_string(), None::<()>))?
            .call(zakura_consensus::Request::Commit(Arc::new(block)))
            .await;

        let chain_error = match block_verifier_router_response {
            // Currently, this match arm returns `null` (Accepted) for blocks committed
            // to any chain, but Accepted is only for blocks in the best chain.
            //
            // TODO (#5487):
            // - Inconclusive: check if the block is on a side-chain
            // The difference is important to miners, because they want to mine on the best chain.
            Ok(hash) => {
                tracing::info!(?hash, ?height, "submit block accepted");

                self.gbt
                    .advertise_mined_block(hash, height)
                    .map_error_with_prefix(0, "failed to send mined block to gossip task")?;

                return Ok(SubmitBlockResponse::Accepted);
            }

            // Turns BoxError into Result<VerifyChainError, BoxError>,
            // by downcasting from Any to VerifyChainError.
            Err(box_error) => {
                let error = box_error
                    .downcast::<RouterError>()
                    .map(|boxed_chain_error| *boxed_chain_error);

                tracing::info!(
                    ?error,
                    ?block_hash,
                    ?height,
                    "submit block failed verification"
                );

                error
            }
        };

        let response = match chain_error {
            Ok(source) if source.is_duplicate_request() => SubmitBlockErrorResponse::Duplicate,

            // Currently, these match arms return Reject for the older duplicate in a queue,
            // but queued duplicates should be DuplicateInconclusive.
            //
            // Optional TODO (#5487):
            // - DuplicateInconclusive: turn these non-finalized state duplicate block errors
            //   into BlockError enum variants, and handle them as DuplicateInconclusive:
            //   - "block already sent to be committed to the state"
            //   - "replaced by newer request"
            // - keep the older request in the queue,
            //   and return a duplicate error for the newer request immediately.
            //   This improves the speed of the RPC response.
            //
            // Checking the download queues and BlockVerifierRouter buffer for duplicates
            // might require architectural changes to Zebra, so we should only do it
            // if mining pools really need it.
            Ok(_verify_chain_error) => SubmitBlockErrorResponse::Rejected,

            // This match arm is currently unreachable, but if future changes add extra error types,
            // we want to turn them into `Rejected`.
            Err(_unknown_error_type) => SubmitBlockErrorResponse::Rejected,
        };

        Ok(response.into())
    }

    async fn get_mining_info(&self) -> Result<GetMiningInfoResponse> {
        let network = self.network.clone();
        let mut read_state = self.read_state.clone();

        let chain_tip = self.latest_chain_tip.clone();
        let tip_height = chain_tip.best_tip_height().unwrap_or(Height(0)).0;

        let mut current_block_tx = None;
        if tip_height > 0 {
            let mined_tx_ids = chain_tip.best_tip_mined_transaction_ids();
            current_block_tx =
                (!mined_tx_ids.is_empty()).then(|| mined_tx_ids.len().saturating_sub(1));
        }

        let solution_rate_fut = self.get_network_sol_ps(None, None);
        // Get the current block size.
        let mut current_block_size = None;
        if tip_height > 0 {
            let request = zakura_state::ReadRequest::TipBlockSize;
            let response: zakura_state::ReadResponse = read_state
                .ready()
                .and_then(|service| service.call(request))
                .await
                .map_error(server::error::LegacyCode::default())?;
            current_block_size = match response {
                zakura_state::ReadResponse::TipBlockSize(Some(block_size)) => Some(block_size),
                _ => None,
            };
        }

        Ok(GetMiningInfoResponse::new_internal(
            tip_height,
            current_block_size,
            current_block_tx,
            network,
            solution_rate_fut.await?,
        ))
    }

    async fn get_network_sol_ps(
        &self,
        num_blocks: Option<i32>,
        height: Option<i32>,
    ) -> Result<u64> {
        // Default number of blocks is 120 if not supplied.
        let mut num_blocks = num_blocks.unwrap_or(DEFAULT_SOLUTION_RATE_WINDOW_SIZE);
        // But if it is 0 or negative, it uses the proof of work averaging window.
        if num_blocks < 1 {
            num_blocks = i32::try_from(POW_AVERAGING_WINDOW).expect("fits in i32");
        }
        let num_blocks =
            usize::try_from(num_blocks).expect("just checked for negatives, i32 fits in usize");

        // Default height is the tip height if not supplied. Negative values also mean the tip
        // height. Since negative values aren't valid heights, we can just use the conversion.
        let height = height.and_then(|height| height.try_into_height().ok());

        let mut read_state = self.read_state.clone();

        let request = ReadRequest::SolutionRate { num_blocks, height };

        let response = read_state
            .ready()
            .and_then(|service| service.call(request))
            .await
            .map_err(|error| ErrorObject::owned(0, error.to_string(), None::<()>))?;

        let solution_rate = match response {
            // zcashd returns a 0 rate when the calculation is invalid
            ReadResponse::SolutionRate(solution_rate) => solution_rate.unwrap_or(0),

            _ => unreachable!("unmatched response to a solution rate request"),
        };

        Ok(solution_rate
            .try_into()
            .expect("per-second solution rate always fits in u64"))
    }

    async fn get_network_info(&self) -> Result<GetNetworkInfoResponse> {
        let version = GetInfoResponse::version_from_string(&self.build_version)
            .expect("invalid version string");

        let subversion = self.user_agent.clone();

        let protocol_version = zakura_network::constants::CURRENT_NETWORK_PROTOCOL_VERSION.0;

        // TODO: return actual supported local services when Zebra exposes them
        let local_services = format!("{:016x}", PeerServices::NODE_NETWORK);

        // Deprecated: zcashd always returns 0.
        let timeoffset = 0;

        let connections = self.address_book.recently_live_peers(Utc::now()).len();

        // TODO: make `limited`, `reachable`, and `proxy` dynamic if Zebra supports network filtering
        let networks = vec![
            NetworkInfo::new("ipv4".to_string(), false, true, "".to_string(), false),
            NetworkInfo::new("ipv6".to_string(), false, true, "".to_string(), false),
            NetworkInfo::new("onion".to_string(), false, false, "".to_string(), false),
        ];

        let relay_fee = zakura_chain::transaction::zip317::MIN_MEMPOOL_TX_FEE_RATE as f64
            / (zakura_chain::amount::COIN as f64);

        // TODO: populate local addresses when Zebra supports exposing bound or advertised addresses
        let local_addresses = vec![];

        // TODO: return network-level warnings, if Zebra supports them in the future
        let warnings = "".to_string();

        let response = GetNetworkInfoResponse {
            version,
            subversion,
            protocol_version,
            local_services,
            timeoffset,
            connections,
            networks,
            relay_fee,
            local_addresses,
            warnings,
        };

        Ok(response)
    }

    async fn get_peer_info(&self) -> Result<Vec<PeerInfo>> {
        let address_book = self.address_book.clone();
        Ok(address_book
            .recently_live_peers(chrono::Utc::now())
            .into_iter()
            .map(PeerInfo::from)
            .collect())
    }

    async fn ping(&self) -> Result<()> {
        tracing::debug!("Receiving ping request via RPC");

        // TODO: Send Message::Ping(nonce) to all connected peers,
        // and track response round-trip time for getpeerinfo's pingtime/pingwait fields.

        Ok(())
    }

    async fn validate_address(&self, raw_address: String) -> Result<ValidateAddressResponse> {
        let network = self.network.clone();

        validate_address(network, raw_address)
    }

    async fn z_validate_address(&self, raw_address: String) -> Result<ZValidateAddressResponse> {
        let network = self.network.clone();

        z_validate_address(network, raw_address)
    }

    async fn get_block_subsidy(&self, height: Option<u32>) -> Result<GetBlockSubsidyResponse> {
        let net = self.network.clone();

        let height = match height {
            Some(h) => Height(h),
            None => best_chain_tip_height(&self.latest_chain_tip)?,
        };

        let subsidy = block_subsidy(height, &net).map_misc_error()?;

        let (lockbox_streams, mut funding_streams): (Vec<_>, Vec<_>) =
            funding_stream_values(height, &net, subsidy)
                .map_misc_error()?
                .into_iter()
                // Separate the funding streams into deferred and non-deferred streams
                .partition(|(receiver, _)| matches!(receiver, FundingStreamReceiver::Deferred));

        let [lockbox_total, funding_streams_total] =
            [&lockbox_streams, &funding_streams].map(|streams| {
                streams
                    .iter()
                    .map(|&(_, amount)| amount)
                    .sum::<std::result::Result<Amount<_>, _>>()
                    .map(Zec::from)
                    .map_misc_error()
            });

        // Use the same funding stream order as zcashd
        funding_streams.sort_by_key(|(receiver, _funding_stream)| {
            ZCASHD_FUNDING_STREAM_ORDER
                .iter()
                .position(|zcashd_receiver| zcashd_receiver == receiver)
        });

        let is_nu6 = NetworkUpgrade::current(&net, height) == NetworkUpgrade::Nu6;

        // Format the funding streams and lockbox streams
        let [funding_streams, lockbox_streams] =
            [funding_streams, lockbox_streams].map(|streams| {
                streams
                    .into_iter()
                    .map(|(receiver, value)| {
                        let address = funding_stream_address(height, &net, receiver);
                        types::subsidy::FundingStream::new_internal(
                            is_nu6, receiver, value, address,
                        )
                    })
                    .collect()
            });

        Ok(GetBlockSubsidyResponse {
            miner: miner_subsidy(height, &net, subsidy)
                .map_misc_error()?
                .into(),
            founders: founders_reward(&net, height).into(),
            funding_streams,
            lockbox_streams,
            funding_streams_total: funding_streams_total?,
            lockbox_total: lockbox_total?,
            total_block_subsidy: subsidy.into(),
        })
    }

    async fn get_difficulty(&self) -> Result<f64> {
        chain_tip_difficulty(self.network.clone(), self.read_state.clone(), false).await
    }

    async fn z_list_unified_receivers(
        &self,
        address: String,
    ) -> Result<ZListUnifiedReceiversResponse> {
        use zcash_address::unified::Container;

        let (network, unified_address): (
            zcash_protocol::consensus::NetworkType,
            zcash_address::unified::Address,
        ) = zcash_address::unified::Encoding::decode(address.clone().as_str())
            .map_err(|error| ErrorObject::owned(0, error.to_string(), None::<()>))?;

        let mut p2pkh = None;
        let mut p2sh = None;
        let mut orchard = None;
        let mut sapling = None;

        for item in unified_address.items() {
            match item {
                zcash_address::unified::Receiver::Orchard(_data) => {
                    let addr = zcash_address::unified::Address::try_from_items(vec![item])
                        .expect("using data already decoded as valid");
                    orchard = Some(addr.encode(&network));
                }
                zcash_address::unified::Receiver::Sapling(data) => {
                    let addr = zakura_chain::primitives::Address::try_from_sapling(network, data)
                        .map_error(server::error::LegacyCode::InvalidParameter)?;
                    sapling = Some(addr.payment_address().unwrap_or_default());
                }
                zcash_address::unified::Receiver::P2pkh(data) => {
                    let addr = zakura_chain::primitives::Address::try_from_transparent_p2pkh(
                        network, data,
                    )
                    .expect("using data already decoded as valid");
                    p2pkh = Some(addr.payment_address().unwrap_or_default());
                }
                zcash_address::unified::Receiver::P2sh(data) => {
                    let addr =
                        zakura_chain::primitives::Address::try_from_transparent_p2sh(network, data)
                            .expect("using data already decoded as valid");
                    p2sh = Some(addr.payment_address().unwrap_or_default());
                }
                _ => (),
            }
        }

        Ok(ZListUnifiedReceiversResponse::new(
            orchard, sapling, p2pkh, p2sh,
        ))
    }

    async fn invalidate_block(&self, block_hash: String) -> Result<()> {
        let block_hash = block_hash
            .parse()
            .map_error(server::error::LegacyCode::InvalidParameter)?;

        self.state
            .clone()
            .oneshot(zakura_state::Request::InvalidateBlock(block_hash))
            .await
            .map(|rsp| assert_eq!(rsp, zakura_state::Response::Invalidated(block_hash)))
            .map_misc_error()
    }

    async fn reconsider_block(&self, block_hash: String) -> Result<Vec<block::Hash>> {
        let block_hash = block_hash
            .parse()
            .map_error(server::error::LegacyCode::InvalidParameter)?;

        self.state
            .clone()
            .oneshot(zakura_state::Request::ReconsiderBlock(block_hash))
            .await
            .map(|rsp| match rsp {
                zakura_state::Response::Reconsidered(block_hashes) => block_hashes,
                _ => unreachable!("unmatched response to a reconsider block request"),
            })
            .map_misc_error()
    }

    async fn generate(&self, num_blocks: u32) -> Result<Vec<Hash>> {
        let mut rpc = self.clone();
        let network = self.network.clone();

        if !network.disable_pow() {
            return Err(ErrorObject::borrowed(
                0,
                "generate is only supported on networks where PoW is disabled",
                None,
            ));
        }

        let mut block_hashes = Vec::new();
        for _ in 0..num_blocks {
            // Use random coinbase data in order to ensure the coinbase transaction is unique. This
            // is useful for tests that exercise forks, since otherwise the coinbase txs of blocks
            // with the same height across different forks would be identical.
            rpc.gbt.randomize_coinbase_data();

            let block_template = rpc
                .get_block_template(None)
                .await
                .map_error(server::error::LegacyCode::default())?;

            let GetBlockTemplateResponse::TemplateMode(block_template) = block_template else {
                return Err(ErrorObject::borrowed(
                    0,
                    "error generating block template",
                    None,
                ));
            };

            let proposal_block = proposal_block_from_template(
                &block_template,
                BlockTemplateTimeSource::CurTime,
                &network,
            )
            .map_error(server::error::LegacyCode::default())?;

            let hex_proposal_block = HexData(
                proposal_block
                    .zcash_serialize_to_vec()
                    .map_error(server::error::LegacyCode::default())?,
            );

            let r = rpc
                .submit_block(hex_proposal_block, None)
                .await
                .map_error(server::error::LegacyCode::default())?;
            match r {
                SubmitBlockResponse::Accepted => { /* pass */ }
                SubmitBlockResponse::ErrorResponse(response) => {
                    return Err(ErrorObject::owned(
                        server::error::LegacyCode::Misc.into(),
                        format!("block was rejected: {response:?}"),
                        None::<()>,
                    ));
                }
            }

            block_hashes.push(GetBlockHashResponse(proposal_block.hash()));
        }

        Ok(block_hashes)
    }

    async fn add_node(
        &self,
        addr: zakura_network::PeerSocketAddr,
        command: AddNodeCommand,
    ) -> Result<()> {
        if self.network.is_regtest() {
            match command {
                AddNodeCommand::Add => {
                    tracing::info!(?addr, "adding peer address to the address book");
                    if self.address_book.clone().add_peer(addr) {
                        Ok(())
                    } else {
                        return Err(ErrorObject::owned(
                            server::error::LegacyCode::ClientNodeAlreadyAdded.into(),
                            format!("peer address was already present in the address book: {addr}"),
                            None::<()>,
                        ));
                    }
                }
            }
        } else {
            return Err(ErrorObject::owned(
                ErrorCode::InvalidParams.code(),
                "addnode command is only supported on regtest",
                None::<()>,
            ));
        }
    }

    fn openrpc(&self) -> openrpsee::openrpc::Response {
        let mut generator = openrpsee::openrpc::Generator::new();

        let methods = METHODS
            .into_iter()
            .map(|(name, method)| method.generate(&mut generator, name))
            .collect();

        Ok(openrpsee::openrpc::OpenRpc {
            openrpc: "1.3.2",
            info: openrpsee::openrpc::Info {
                title: env!("CARGO_PKG_NAME"),
                description: env!("CARGO_PKG_DESCRIPTION"),
                version: env!("CARGO_PKG_VERSION"),
            },
            methods,
            components: generator.into_components(),
        })
    }
    async fn get_tx_out(
        &self,
        txid: String,
        n: u32,
        include_mempool: Option<bool>,
    ) -> Result<GetTxOutResponse> {
        let txid = transaction::Hash::from_hex(txid)
            .map_error(server::error::LegacyCode::InvalidParameter)?;

        let outpoint = transparent::OutPoint {
            hash: txid,
            index: n,
        };

        // Optional mempool path
        if include_mempool.unwrap_or(true) {
            let rsp = self
                .mempool
                .clone()
                .oneshot(mempool::Request::UnspentOutput(outpoint))
                .await
                .map_misc_error()?;

            match rsp {
                // Return the output found in the mempool
                mempool::Response::TransparentOutput(Some(CreatedOrSpent::Created {
                    output,
                    tx_version,
                    last_seen_hash,
                })) => {
                    return Ok(GetTxOutResponse(Some(
                        types::transaction::OutputObject::from_output(
                            &output,
                            last_seen_hash.to_string(),
                            0,
                            tx_version,
                            false,
                            self.network(),
                        ),
                    )))
                }
                mempool::Response::TransparentOutput(Some(CreatedOrSpent::Spent)) => {
                    return Ok(GetTxOutResponse(None))
                }
                mempool::Response::TransparentOutput(None) => {}
                _ => unreachable!("unmatched response to an `UnspentOutput` request"),
            };
        }

        // TODO: Ensure that the returned tip hash is always valid for the response, i.e. that Zebra can't return a tip that
        //       hadn't yet included the queried transaction output.

        // Get the best block tip hash
        let tip_rsp = self
            .read_state
            .clone()
            .oneshot(zakura_state::ReadRequest::Tip)
            .await
            .map_misc_error()?;

        let best_block_hash = match tip_rsp {
            zakura_state::ReadResponse::Tip(tip) => tip.ok_or_misc_error("No blocks in state")?.1,
            _ => unreachable!("unmatched response to a `Tip` request"),
        };

        // State path
        let rsp = self
            .read_state
            .clone()
            .oneshot(zakura_state::ReadRequest::Transaction(txid))
            .await
            .map_misc_error()?;

        match rsp {
            zakura_state::ReadResponse::Transaction(Some(tx)) => {
                let outputs = tx.tx.outputs();
                let index: usize = n.try_into().expect("u32 always fits in usize");
                let output = match outputs.get(index) {
                    Some(output) => output,
                    // return null if the output is not found
                    None => return Ok(GetTxOutResponse(None)),
                };

                // Prune state outputs that are spent
                let is_spent = {
                    let rsp = self
                        .read_state
                        .clone()
                        .oneshot(zakura_state::ReadRequest::IsTransparentOutputSpent(
                            outpoint,
                        ))
                        .await
                        .map_misc_error()?;

                    match rsp {
                        zakura_state::ReadResponse::IsTransparentOutputSpent(spent) => spent,
                        _ => unreachable!(
                            "unmatched response to an `IsTransparentOutputSpent` request"
                        ),
                    }
                };

                if is_spent {
                    return Ok(GetTxOutResponse(None));
                }

                Ok(GetTxOutResponse(Some(
                    types::transaction::OutputObject::from_output(
                        output,
                        best_block_hash.to_string(),
                        tx.confirmations,
                        tx.tx.version(),
                        tx.tx.is_coinbase(),
                        self.network(),
                    ),
                )))
            }
            zakura_state::ReadResponse::Transaction(None) => Ok(GetTxOutResponse(None)),
            _ => unreachable!("unmatched response to a `Transaction` request"),
        }
    }
}

// TODO: Move the code below to separate modules.

/// Returns the best chain tip height of `latest_chain_tip`,
/// or an RPC error if there are no blocks in the state.
pub fn best_chain_tip_height<Tip>(latest_chain_tip: &Tip) -> Result<Height>
where
    Tip: ChainTip + Clone + Send + Sync + 'static,
{
    latest_chain_tip
        .best_tip_height()
        .ok_or_misc_error("No blocks in state")
}

/// Response to a `getinfo` RPC request.
///
/// See the notes for the [`Rpc::get_info` method].
#[allow(clippy::too_many_arguments)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
pub struct GetInfoResponse {
    /// The node version
    #[getter(rename = "raw_version")]
    version: u64,

    /// The node version build number
    build: String,

    /// The server sub-version identifier, used as the network protocol user-agent
    subversion: String,

    /// The protocol version
    #[serde(rename = "protocolversion")]
    protocol_version: u32,

    /// The current number of blocks processed in the server
    blocks: u32,

    /// The total (inbound and outbound) number of connections the node has
    connections: usize,

    /// The proxy (if any) used by the server. Currently always `None` in Zebra.
    #[serde(skip_serializing_if = "Option::is_none")]
    proxy: Option<String>,

    /// The current network difficulty
    difficulty: f64,

    /// True if the server is running in testnet mode, false otherwise
    testnet: bool,

    /// The minimum transaction fee in ZEC/kB
    #[serde(rename = "paytxfee")]
    pay_tx_fee: f64,

    /// The minimum relay fee for non-free transactions in ZEC/kB
    #[serde(rename = "relayfee")]
    relay_fee: f64,

    /// The last error or warning message, or "no errors" if there are no errors
    errors: String,

    /// The time of the last error or warning message, or "no errors timestamp" if there are no errors
    #[serde(rename = "errorstimestamp")]
    errors_timestamp: i64,
}

#[deprecated(note = "Use `GetInfoResponse` instead")]
pub use self::GetInfoResponse as GetInfo;

impl Default for GetInfoResponse {
    fn default() -> Self {
        GetInfoResponse {
            version: 0,
            build: "some build version".to_string(),
            subversion: "some subversion".to_string(),
            protocol_version: 0,
            blocks: 0,
            connections: 0,
            proxy: None,
            difficulty: 0.0,
            testnet: false,
            pay_tx_fee: 0.0,
            relay_fee: 0.0,
            errors: "no errors".to_string(),
            errors_timestamp: Utc::now().timestamp(),
        }
    }
}

impl GetInfoResponse {
    /// Constructs [`GetInfo`] from its constituent parts.
    #[allow(clippy::too_many_arguments)]
    #[deprecated(note = "Use `GetInfoResponse::new` instead")]
    pub fn from_parts(
        version: u64,
        build: String,
        subversion: String,
        protocol_version: u32,
        blocks: u32,
        connections: usize,
        proxy: Option<String>,
        difficulty: f64,
        testnet: bool,
        pay_tx_fee: f64,
        relay_fee: f64,
        errors: String,
        errors_timestamp: i64,
    ) -> Self {
        Self {
            version,
            build,
            subversion,
            protocol_version,
            blocks,
            connections,
            proxy,
            difficulty,
            testnet,
            pay_tx_fee,
            relay_fee,
            errors,
            errors_timestamp,
        }
    }

    /// Returns the contents of ['GetInfo'].
    pub fn into_parts(
        self,
    ) -> (
        u64,
        String,
        String,
        u32,
        u32,
        usize,
        Option<String>,
        f64,
        bool,
        f64,
        f64,
        String,
        i64,
    ) {
        (
            self.version,
            self.build,
            self.subversion,
            self.protocol_version,
            self.blocks,
            self.connections,
            self.proxy,
            self.difficulty,
            self.testnet,
            self.pay_tx_fee,
            self.relay_fee,
            self.errors,
            self.errors_timestamp,
        )
    }

    /// Create the node version number.
    fn version_from_string(build_string: &str) -> Option<u64> {
        let semver_version = semver::Version::parse(build_string.strip_prefix('v')?).ok()?;
        let build_number = semver_version
            .build
            .as_str()
            .split('.')
            .next()
            .and_then(|num_str| num_str.parse::<u64>().ok())
            .unwrap_or_default();

        // https://github.com/zcash/zcash/blob/v6.1.0/src/clientversion.h#L55-L59
        let version_number = 1_000_000 * semver_version.major
            + 10_000 * semver_version.minor
            + 100 * semver_version.patch
            + build_number;

        Some(version_number)
    }
}

/// Type alias for the array of `GetBlockchainInfoBalance` objects
pub type BlockchainValuePoolBalances = [GetBlockchainInfoBalance; 6];

fn deserialize_blockchain_value_pool_balances<'de, D>(
    deserializer: D,
) -> std::result::Result<BlockchainValuePoolBalances, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value_pools = Vec::<GetBlockchainInfoBalance>::deserialize(deserializer)?;
    blockchain_value_pool_balances_from_vec(value_pools)
}

fn deserialize_optional_blockchain_value_pool_balances<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<BlockchainValuePoolBalances>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Option::<Vec<GetBlockchainInfoBalance>>::deserialize(deserializer)?
        .map(blockchain_value_pool_balances_from_vec)
        .transpose()
}

fn blockchain_value_pool_balances_from_vec<E>(
    mut value_pools: Vec<GetBlockchainInfoBalance>,
) -> std::result::Result<BlockchainValuePoolBalances, E>
where
    E: serde::de::Error,
{
    match value_pools.len() {
        5 => {
            let ironwood_delta = value_pools
                .iter()
                .any(|pool| pool.value_delta().is_some() || pool.value_delta_zat().is_some())
                .then(Amount::zero);

            value_pools.push(GetBlockchainInfoBalance::ironwood(
                Amount::zero(),
                ironwood_delta,
            ));
        }
        6 => {}
        len => return Err(E::invalid_length(len, &"five or six value pool balances")),
    }

    value_pools
        .try_into()
        .map_err(|_| E::custom("invalid value pool balance count"))
}

/// Response to a `getblockchaininfo` RPC request.
///
/// See the notes for the [`Rpc::get_blockchain_info` method].
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters)]
pub struct GetBlockchainInfoResponse {
    /// Current network name as defined in BIP70 (main, test, regtest)
    chain: String,

    /// The current number of blocks processed in the server, numeric
    #[getter(copy)]
    blocks: Height,

    /// The current number of headers we have validated in the best chain, that is,
    /// the height of the best chain.
    #[getter(copy)]
    headers: Height,

    /// The estimated network solution rate in Sol/s.
    difficulty: f64,

    /// The verification progress relative to the estimated network chain tip.
    #[serde(rename = "verificationprogress")]
    verification_progress: f64,

    /// The total amount of work in the best chain, hex-encoded.
    #[serde(rename = "chainwork")]
    chain_work: u64,

    /// Whether this node is pruned, currently always false in Zebra.
    pruned: bool,

    /// The estimated size of the block and undo files on disk
    size_on_disk: u64,

    /// The current number of note commitments in the commitment tree
    commitments: u64,

    /// The hash of the currently best block, in big-endian order, hex-encoded
    #[serde(rename = "bestblockhash", with = "hex")]
    #[getter(copy)]
    best_block_hash: block::Hash,

    /// If syncing, the estimated height of the chain, else the current best height, numeric.
    ///
    /// In Zebra, this is always the height estimate, so it might be a little inaccurate.
    #[serde(rename = "estimatedheight")]
    #[getter(copy)]
    estimated_height: Height,

    /// Chain supply balance
    #[serde(rename = "chainSupply")]
    chain_supply: GetBlockchainInfoBalance,

    /// Value pool balances
    #[serde(rename = "valuePools")]
    #[serde(deserialize_with = "deserialize_blockchain_value_pool_balances")]
    value_pools: BlockchainValuePoolBalances,

    /// Status of network upgrades
    upgrades: IndexMap<ConsensusBranchIdHex, NetworkUpgradeInfo>,

    /// Branch IDs of the current and upcoming consensus rules
    #[getter(copy)]
    consensus: TipConsensusBranch,
}

impl Default for GetBlockchainInfoResponse {
    fn default() -> Self {
        Self {
            chain: "main".to_string(),
            blocks: Height(1),
            best_block_hash: block::Hash([0; 32]),
            estimated_height: Height(1),
            chain_supply: GetBlockchainInfoBalance::chain_supply(Default::default()),
            value_pools: GetBlockchainInfoBalance::zero_pools(),
            upgrades: IndexMap::new(),
            consensus: TipConsensusBranch {
                chain_tip: ConsensusBranchIdHex(ConsensusBranchId::default()),
                next_block: ConsensusBranchIdHex(ConsensusBranchId::default()),
            },
            headers: Height(1),
            difficulty: 0.0,
            verification_progress: 0.0,
            chain_work: 0,
            pruned: false,
            size_on_disk: 0,
            commitments: 0,
        }
    }
}

impl GetBlockchainInfoResponse {
    /// Creates a new [`GetBlockchainInfoResponse`] instance.
    // We don't use derive(new) because the method already existed but the arguments
    // have a different order. No reason to unnecessarily break existing code.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        chain: String,
        blocks: Height,
        best_block_hash: block::Hash,
        estimated_height: Height,
        chain_supply: GetBlockchainInfoBalance,
        value_pools: BlockchainValuePoolBalances,
        upgrades: IndexMap<ConsensusBranchIdHex, NetworkUpgradeInfo>,
        consensus: TipConsensusBranch,
        headers: Height,
        difficulty: f64,
        verification_progress: f64,
        chain_work: u64,
        pruned: bool,
        size_on_disk: u64,
        commitments: u64,
    ) -> Self {
        Self {
            chain,
            blocks,
            best_block_hash,
            estimated_height,
            chain_supply,
            value_pools,
            upgrades,
            consensus,
            headers,
            difficulty,
            verification_progress,
            chain_work,
            pruned,
            size_on_disk,
            commitments,
        }
    }
}

/// A request for [`RpcServer::get_address_balance`].
#[derive(Clone, Debug, Eq, PartialEq, Hash, serde::Deserialize, serde::Serialize, JsonSchema)]
#[serde(from = "DGetAddressBalanceRequest")]
pub struct GetAddressBalanceRequest {
    /// A list of transparent address strings.
    addresses: Vec<String>,
}

impl From<DGetAddressBalanceRequest> for GetAddressBalanceRequest {
    fn from(address_strings: DGetAddressBalanceRequest) -> Self {
        match address_strings {
            DGetAddressBalanceRequest::Addresses { addresses } => {
                GetAddressBalanceRequest { addresses }
            }
            DGetAddressBalanceRequest::Address(address) => GetAddressBalanceRequest {
                addresses: vec![address],
            },
        }
    }
}

/// An intermediate type used to deserialize [`AddressStrings`].
#[derive(Clone, Debug, Eq, PartialEq, Hash, serde::Deserialize, JsonSchema)]
#[serde(untagged)]
enum DGetAddressBalanceRequest {
    /// A list of address strings.
    Addresses { addresses: Vec<String> },
    /// A single address string.
    Address(String),
}

/// A request to get the transparent balance of a set of addresses.
#[deprecated(note = "Use `GetAddressBalanceRequest` instead.")]
pub type AddressStrings = GetAddressBalanceRequest;

/// A collection of validatable addresses
pub trait ValidateAddresses {
    /// Given a list of addresses as strings:
    /// - check if provided list have all valid transparent addresses.
    /// - return valid addresses as a set of `Address`.
    fn valid_addresses(&self) -> Result<HashSet<Address>> {
        // Reference for the legacy error code:
        // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/misc.cpp#L783-L784>
        let valid_addresses: HashSet<Address> = self
            .addresses()
            .iter()
            .map(|address| {
                address
                    .parse()
                    .map_error(server::error::LegacyCode::InvalidAddressOrKey)
            })
            .collect::<Result<_>>()?;

        Ok(valid_addresses)
    }

    /// Returns string-encoded Zcash addresses in the type implementing this trait.
    fn addresses(&self) -> &[String];
}

impl ValidateAddresses for GetAddressBalanceRequest {
    fn addresses(&self) -> &[String] {
        &self.addresses
    }
}

impl GetAddressBalanceRequest {
    /// Creates a new `AddressStrings` given a vector.
    pub fn new(addresses: Vec<String>) -> GetAddressBalanceRequest {
        GetAddressBalanceRequest { addresses }
    }

    /// Creates a new [`AddressStrings`] from a given vector, returns an error if any addresses are incorrect.
    #[deprecated(
        note = "Use `AddressStrings::new` instead. Validity will be checked by the server."
    )]
    pub fn new_valid(addresses: Vec<String>) -> Result<GetAddressBalanceRequest> {
        let req = Self { addresses };
        req.valid_addresses()?;
        Ok(req)
    }
}

/// The transparent balance of a set of addresses.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Eq,
    PartialEq,
    Hash,
    serde::Serialize,
    serde::Deserialize,
    Getters,
    new,
)]
pub struct GetAddressBalanceResponse {
    /// The total transparent balance.
    balance: u64,
    /// The total received balance, including change.
    pub received: u64,
}

#[deprecated(note = "Use `GetAddressBalanceResponse` instead.")]
pub use self::GetAddressBalanceResponse as AddressBalance;

/// Parameters of [`RpcServer::get_address_utxos`] RPC method.
#[derive(
    Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, new, JsonSchema,
)]
#[serde(from = "DGetAddressUtxosRequest")]
pub struct GetAddressUtxosRequest {
    /// A list of addresses to get transactions from.
    addresses: Vec<String>,
    /// The height to start looking for transactions.
    #[serde(default)]
    #[serde(rename = "chainInfo")]
    chain_info: bool,
}

impl From<DGetAddressUtxosRequest> for GetAddressUtxosRequest {
    fn from(request: DGetAddressUtxosRequest) -> Self {
        match request {
            DGetAddressUtxosRequest::Single(addr) => GetAddressUtxosRequest {
                addresses: vec![addr],
                chain_info: false,
            },
            DGetAddressUtxosRequest::Object {
                addresses,
                chain_info,
            } => GetAddressUtxosRequest {
                addresses,
                chain_info,
            },
        }
    }
}

/// An intermediate type used to deserialize [`GetAddressUtxosRequest`].
#[derive(Debug, serde::Deserialize, JsonSchema)]
#[serde(untagged)]
enum DGetAddressUtxosRequest {
    /// A single address string.
    Single(String),
    /// A full request object with address list and chainInfo flag.
    Object {
        /// A list of addresses to get transactions from.
        addresses: Vec<String>,
        /// The height to start looking for transactions.
        #[serde(default)]
        #[serde(rename = "chainInfo")]
        chain_info: bool,
    },
}

impl ValidateAddresses for GetAddressUtxosRequest {
    fn addresses(&self) -> &[String] {
        &self.addresses
    }
}

/// A hex-encoded [`ConsensusBranchId`] string.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ConsensusBranchIdHex(#[serde(with = "hex")] ConsensusBranchId);

impl ConsensusBranchIdHex {
    /// Returns a new instance of ['ConsensusBranchIdHex'].
    pub fn new(consensus_branch_id: u32) -> Self {
        ConsensusBranchIdHex(consensus_branch_id.into())
    }

    /// Returns the value of the ['ConsensusBranchId'].
    pub fn inner(&self) -> u32 {
        self.0.into()
    }
}

/// Information about [`NetworkUpgrade`] activation.
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NetworkUpgradeInfo {
    /// Name of upgrade, string.
    ///
    /// Ignored by lightwalletd, but useful for debugging.
    name: NetworkUpgrade,

    /// Block height of activation, numeric.
    #[serde(rename = "activationheight")]
    activation_height: Height,

    /// Status of upgrade, string.
    status: NetworkUpgradeStatus,
}

impl NetworkUpgradeInfo {
    /// Constructs [`NetworkUpgradeInfo`] from its constituent parts.
    pub fn from_parts(
        name: NetworkUpgrade,
        activation_height: Height,
        status: NetworkUpgradeStatus,
    ) -> Self {
        Self {
            name,
            activation_height,
            status,
        }
    }

    /// Returns the contents of ['NetworkUpgradeInfo'].
    pub fn into_parts(self) -> (NetworkUpgrade, Height, NetworkUpgradeStatus) {
        (self.name, self.activation_height, self.status)
    }
}

/// The activation status of a [`NetworkUpgrade`].
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum NetworkUpgradeStatus {
    /// The network upgrade is currently active.
    ///
    /// Includes all network upgrades that have previously activated,
    /// even if they are not the most recent network upgrade.
    #[serde(rename = "active")]
    Active,

    /// The network upgrade does not have an activation height.
    #[serde(rename = "disabled")]
    Disabled,

    /// The network upgrade has an activation height, but we haven't reached it yet.
    #[serde(rename = "pending")]
    Pending,
}

/// The [`ConsensusBranchId`]s for the tip and the next block.
///
/// These branch IDs are different when the next block is a network upgrade activation block.
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TipConsensusBranch {
    /// Branch ID used to validate the current chain tip, big-endian, hex-encoded.
    #[serde(rename = "chaintip")]
    chain_tip: ConsensusBranchIdHex,

    /// Branch ID used to validate the next block, big-endian, hex-encoded.
    #[serde(rename = "nextblock")]
    next_block: ConsensusBranchIdHex,
}

impl TipConsensusBranch {
    /// Constructs [`TipConsensusBranch`] from its constituent parts.
    pub fn from_parts(chain_tip: u32, next_block: u32) -> Self {
        Self {
            chain_tip: ConsensusBranchIdHex::new(chain_tip),
            next_block: ConsensusBranchIdHex::new(next_block),
        }
    }

    /// Returns the contents of ['TipConsensusBranch'].
    pub fn into_parts(self) -> (u32, u32) {
        (self.chain_tip.inner(), self.next_block.inner())
    }
}

/// Response to a `sendrawtransaction` RPC request.
///
/// Contains the hex-encoded hash of the sent transaction.
///
/// See the notes for the [`Rpc::send_raw_transaction` method].
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SendRawTransactionResponse(#[serde(with = "hex")] transaction::Hash);

#[deprecated(note = "Use `SendRawTransactionResponse` instead")]
pub use self::SendRawTransactionResponse as SentTransactionHash;

impl Default for SendRawTransactionResponse {
    fn default() -> Self {
        Self(transaction::Hash::from([0; 32]))
    }
}

impl SendRawTransactionResponse {
    /// Constructs a new [`SentTransactionHash`].
    pub fn new(hash: transaction::Hash) -> Self {
        SendRawTransactionResponse(hash)
    }

    /// Returns the contents of ['SentTransactionHash'].
    #[deprecated(note = "Use `SentTransactionHash::hash` instead")]
    pub fn inner(&self) -> transaction::Hash {
        self.hash()
    }

    /// Returns the contents of ['SentTransactionHash'].
    pub fn hash(&self) -> transaction::Hash {
        self.0
    }
}

/// Response to a `getblock` RPC request.
///
/// See the notes for the [`RpcServer::get_block`] method.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum GetBlockResponse {
    /// The request block, hex-encoded.
    Raw(#[serde(with = "hex")] SerializedBlock),
    /// The block object.
    Object(Box<BlockObject>),
}

#[deprecated(note = "Use `GetBlockResponse` instead")]
pub use self::GetBlockResponse as GetBlock;

impl Default for GetBlockResponse {
    fn default() -> Self {
        GetBlockResponse::Object(Box::new(BlockObject {
            hash: block::Hash([0; 32]),
            confirmations: 0,
            height: None,
            time: None,
            n_tx: 0,
            tx: Vec::new(),
            trees: GetBlockTrees::default(),
            size: None,
            version: None,
            merkle_root: None,
            block_commitments: None,
            final_sapling_root: None,
            final_orchard_root: None,
            nonce: None,
            bits: None,
            difficulty: None,
            chain_supply: None,
            value_pools: None,
            previous_block_hash: None,
            next_block_hash: None,
            solution: None,
        }))
    }
}

/// A Block object returned by the `getblock` RPC request.
#[allow(clippy::too_many_arguments)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
pub struct BlockObject {
    /// The hash of the requested block.
    #[getter(copy)]
    #[serde(with = "hex")]
    hash: block::Hash,

    /// The number of confirmations of this block in the best chain,
    /// or -1 if it is not in the best chain.
    confirmations: i64,

    /// The block size. TODO: fill it
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    size: Option<i64>,

    /// The height of the requested block.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    height: Option<Height>,

    /// The version field of the requested block.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    version: Option<u32>,

    /// The merkle root of the requested block.
    #[serde(with = "opthex", rename = "merkleroot")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    merkle_root: Option<block::merkle::Root>,

    /// The blockcommitments field of the requested block. Its interpretation changes
    /// depending on the network and height.
    #[serde(with = "opthex", rename = "blockcommitments")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    block_commitments: Option<[u8; 32]>,

    // `authdataroot` would be here. Undocumented. TODO: decide if we want to support it
    //
    /// The root of the Sapling commitment tree after applying this block.
    #[serde(with = "opthex", rename = "finalsaplingroot")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    final_sapling_root: Option<[u8; 32]>,

    /// The root of the Orchard commitment tree after applying this block.
    #[serde(with = "opthex", rename = "finalorchardroot")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    final_orchard_root: Option<[u8; 32]>,

    // `chainhistoryroot` would be here. Undocumented. TODO: decide if we want to support it
    //
    /// The number of transactions in this block.
    #[serde(rename = "nTx")]
    n_tx: usize,

    /// List of transactions in block order, hex-encoded if verbosity=1 or
    /// as objects if verbosity=2.
    tx: Vec<GetBlockTransaction>,

    /// The height of the requested block.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    time: Option<i64>,

    /// The nonce of the requested block header.
    #[serde(with = "opthex")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    nonce: Option<[u8; 32]>,

    /// The Equihash solution in the requested block header.
    /// Note: presence of this field in getblock is not documented in zcashd.
    #[serde(with = "opthex")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    solution: Option<Solution>,

    /// The difficulty threshold of the requested block header displayed in compact form.
    #[serde(with = "opthex")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    bits: Option<CompactDifficulty>,

    /// Floating point number that represents the difficulty limit for this block as a multiple
    /// of the minimum difficulty for the network.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    difficulty: Option<f64>,

    // `chainwork` would be here, but we don't plan on supporting it
    // `anchor` would be here. Not planned to be supported.
    //
    /// Chain supply balance
    #[serde(rename = "chainSupply")]
    #[serde(skip_serializing_if = "Option::is_none")]
    chain_supply: Option<GetBlockchainInfoBalance>,

    /// Value pool balances
    #[serde(rename = "valuePools")]
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_optional_blockchain_value_pool_balances"
    )]
    value_pools: Option<BlockchainValuePoolBalances>,

    /// Information about the note commitment trees.
    #[getter(copy)]
    trees: GetBlockTrees,

    /// The previous block hash of the requested block header.
    #[serde(rename = "previousblockhash", skip_serializing_if = "Option::is_none")]
    #[serde(with = "opthex")]
    #[getter(copy)]
    previous_block_hash: Option<block::Hash>,

    /// The next block hash after the requested block header.
    #[serde(rename = "nextblockhash", skip_serializing_if = "Option::is_none")]
    #[serde(with = "opthex")]
    #[getter(copy)]
    next_block_hash: Option<block::Hash>,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
/// The transaction list in a `getblock` call. Can be a list of transaction
/// IDs or the full transaction details depending on verbosity.
pub enum GetBlockTransaction {
    /// The transaction hash, hex-encoded.
    Hash(#[serde(with = "hex")] transaction::Hash),
    /// The block object.
    Object(Box<TransactionObject>),
}

/// Response to a `getblockheader` RPC request.
///
/// See the notes for the [`RpcServer::get_block_header`] method.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum GetBlockHeaderResponse {
    /// The request block header, hex-encoded.
    Raw(hex_data::HexData),

    /// The block header object.
    Object(Box<BlockHeaderObject>),
}

#[deprecated(note = "Use `GetBlockHeaderResponse` instead")]
pub use self::GetBlockHeaderResponse as GetBlockHeader;

#[allow(clippy::too_many_arguments)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
/// Verbose response to a `getblockheader` RPC request.
///
/// See the notes for the [`RpcServer::get_block_header`] method.
pub struct BlockHeaderObject {
    /// The hash of the requested block.
    #[serde(with = "hex")]
    #[getter(copy)]
    hash: block::Hash,

    /// The number of confirmations of this block in the best chain,
    /// or -1 if it is not in the best chain.
    confirmations: i64,

    /// The height of the requested block.
    #[getter(copy)]
    height: Height,

    /// The version field of the requested block.
    version: u32,

    /// The merkle root of the requesteed block.
    #[serde(with = "hex", rename = "merkleroot")]
    #[getter(copy)]
    merkle_root: block::merkle::Root,

    /// The blockcommitments field of the requested block. Its interpretation changes
    /// depending on the network and height.
    #[serde(with = "hex", rename = "blockcommitments")]
    #[getter(copy)]
    block_commitments: [u8; 32],

    /// The root of the Sapling commitment tree after applying this block.
    #[serde(with = "hex", rename = "finalsaplingroot")]
    #[getter(copy)]
    final_sapling_root: [u8; 32],

    /// The number of Sapling notes in the Sapling note commitment tree
    /// after applying this block. Used by the `getblock` RPC method.
    #[serde(skip)]
    sapling_tree_size: u64,

    /// The block time of the requested block header in non-leap seconds since Jan 1 1970 GMT.
    time: i64,

    /// The nonce of the requested block header.
    #[serde(with = "hex")]
    #[getter(copy)]
    nonce: [u8; 32],

    /// The Equihash solution in the requested block header.
    #[serde(with = "hex")]
    #[getter(copy)]
    solution: Solution,

    /// The difficulty threshold of the requested block header displayed in compact form.
    #[serde(with = "hex")]
    #[getter(copy)]
    bits: CompactDifficulty,

    /// Floating point number that represents the difficulty limit for this block as a multiple
    /// of the minimum difficulty for the network.
    difficulty: f64,

    /// The previous block hash of the requested block header.
    #[serde(rename = "previousblockhash")]
    #[serde(with = "hex")]
    #[getter(copy)]
    previous_block_hash: block::Hash,

    /// The next block hash after the requested block header.
    #[serde(rename = "nextblockhash", skip_serializing_if = "Option::is_none")]
    #[getter(copy)]
    #[serde(with = "opthex")]
    next_block_hash: Option<block::Hash>,
}

#[deprecated(note = "Use `BlockHeaderObject` instead")]
pub use BlockHeaderObject as GetBlockHeaderObject;

impl Default for GetBlockHeaderResponse {
    fn default() -> Self {
        GetBlockHeaderResponse::Object(Box::default())
    }
}

impl Default for BlockHeaderObject {
    fn default() -> Self {
        let difficulty: ExpandedDifficulty = zakura_chain::work::difficulty::U256::one().into();

        BlockHeaderObject {
            hash: block::Hash([0; 32]),
            confirmations: 0,
            height: Height::MIN,
            version: 4,
            merkle_root: block::merkle::Root([0; 32]),
            block_commitments: Default::default(),
            final_sapling_root: Default::default(),
            sapling_tree_size: Default::default(),
            time: 0,
            nonce: [0; 32],
            solution: Solution::for_proposal(),
            bits: difficulty.to_compact(),
            difficulty: 1.0,
            previous_block_hash: block::Hash([0; 32]),
            next_block_hash: Some(block::Hash([0; 32])),
        }
    }
}

/// Response to a `getbestblockhash` and `getblockhash` RPC request.
///
/// Contains the hex-encoded hash of the requested block.
///
/// Also see the notes for the [`RpcServer::get_best_block_hash`] and `get_block_hash` methods.
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(transparent)]
pub struct GetBlockHashResponse(#[serde(with = "hex")] pub(crate) block::Hash);

impl GetBlockHashResponse {
    /// Constructs a new [`GetBlockHashResponse`] from a block hash.
    pub fn new(hash: block::Hash) -> Self {
        GetBlockHashResponse(hash)
    }

    /// Returns the contents of [`GetBlockHashResponse`].
    pub fn hash(&self) -> block::Hash {
        self.0
    }
}

#[deprecated(note = "Use `GetBlockHashResponse` instead")]
pub use self::GetBlockHashResponse as GetBlockHash;

/// A block hash used by this crate that encodes as hex by default.
pub type Hash = GetBlockHashResponse;

/// Response to a `getbestblockheightandhash` RPC request.
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, new)]
pub struct GetBlockHeightAndHashResponse {
    /// The best chain tip block height
    #[getter(copy)]
    height: block::Height,
    /// The best chain tip block hash
    #[getter(copy)]
    hash: block::Hash,
}

#[deprecated(note = "Use `GetBlockHeightAndHashResponse` instead.")]
pub use GetBlockHeightAndHashResponse as GetBestBlockHeightAndHash;

impl Default for GetBlockHeightAndHashResponse {
    fn default() -> Self {
        Self {
            height: block::Height::MIN,
            hash: block::Hash([0; 32]),
        }
    }
}

impl Default for GetBlockHashResponse {
    fn default() -> Self {
        GetBlockHashResponse(block::Hash([0; 32]))
    }
}

/// Response to a `getrawtransaction` RPC request.
///
/// See the notes for the [`Rpc::get_raw_transaction` method].
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum GetRawTransactionResponse {
    /// The raw transaction, encoded as hex bytes.
    Raw(#[serde(with = "hex")] SerializedTransaction),
    /// The transaction object.
    Object(Box<TransactionObject>),
}

#[deprecated(note = "Use `GetRawTransactionResponse` instead")]
pub use self::GetRawTransactionResponse as GetRawTransaction;

impl Default for GetRawTransactionResponse {
    fn default() -> Self {
        Self::Object(Box::default())
    }
}

/// Response to a `getaddressutxos` RPC request.
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum GetAddressUtxosResponse {
    /// Response when `chainInfo` is false or not provided.
    Utxos(Vec<Utxo>),
    /// Response when `chainInfo` is true.
    UtxosAndChainInfo(GetAddressUtxosResponseObject),
}

/// Response to a `getaddressutxos` RPC request, when `chainInfo` is true.
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
pub struct GetAddressUtxosResponseObject {
    utxos: Vec<Utxo>,
    #[serde(with = "hex")]
    #[getter(copy)]
    hash: block::Hash,
    #[getter(copy)]
    height: block::Height,
}

/// A UTXO returned by the `getaddressutxos` RPC request.
///
/// See the notes for the [`Rpc::get_address_utxos` method].
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
pub struct Utxo {
    /// The transparent address, base58check encoded
    address: transparent::Address,

    /// The output txid, in big-endian order, hex-encoded
    #[serde(with = "hex")]
    #[getter(copy)]
    txid: transaction::Hash,

    /// The transparent output index, numeric
    #[serde(rename = "outputIndex")]
    #[getter(copy)]
    output_index: OutputIndex,

    /// The transparent output script, hex encoded
    #[serde(with = "hex")]
    script: transparent::Script,

    /// The amount of zatoshis in the transparent output
    satoshis: u64,

    /// The block height, numeric.
    ///
    /// We put this field last, to match the zcashd order.
    #[getter(copy)]
    height: Height,
}

#[deprecated(note = "Use `Utxo` instead")]
pub use self::Utxo as GetAddressUtxos;

impl Default for Utxo {
    fn default() -> Self {
        Self {
            address: transparent::Address::from_pub_key_hash(
                zakura_chain::parameters::NetworkKind::default(),
                [0u8; 20],
            ),
            txid: transaction::Hash::from([0; 32]),
            output_index: OutputIndex::from_u64(0),
            script: transparent::Script::new(&[0u8; 10]),
            satoshis: u64::default(),
            height: Height(0),
        }
    }
}

impl Utxo {
    /// Constructs a new instance of [`GetAddressUtxos`].
    #[deprecated(note = "Use `Utxo::new` instead")]
    pub fn from_parts(
        address: transparent::Address,
        txid: transaction::Hash,
        output_index: OutputIndex,
        script: transparent::Script,
        satoshis: u64,
        height: Height,
    ) -> Self {
        Utxo {
            address,
            txid,
            output_index,
            script,
            satoshis,
            height,
        }
    }

    /// Returns the contents of [`GetAddressUtxos`].
    pub fn into_parts(
        &self,
    ) -> (
        transparent::Address,
        transaction::Hash,
        OutputIndex,
        transparent::Script,
        u64,
        Height,
    ) {
        (
            self.address,
            self.txid,
            self.output_index,
            self.script.clone(),
            self.satoshis,
            self.height,
        )
    }
}

/// Parameters of [`RpcServer::get_address_tx_ids`] RPC method.
///
/// See [`RpcServer::get_address_tx_ids`] for more details.
#[derive(
    Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, new, JsonSchema,
)]
#[serde(from = "DGetAddressTxIdsRequest")]
pub struct GetAddressTxIdsRequest {
    /// A list of addresses. The RPC method will get transactions IDs that sent or received
    /// funds to or from these addresses.
    addresses: Vec<String>,
    // The height to start looking for transactions.
    start: Option<u32>,
    // The height to end looking for transactions.
    end: Option<u32>,
}

impl GetAddressTxIdsRequest {
    /// Constructs [`GetAddressTxIdsRequest`] from its constituent parts.
    #[deprecated(note = "Use `GetAddressTxIdsRequest::new` instead.")]
    pub fn from_parts(addresses: Vec<String>, start: u32, end: u32) -> Self {
        GetAddressTxIdsRequest {
            addresses,
            start: Some(start),
            end: Some(end),
        }
    }

    /// Returns the contents of [`GetAddressTxIdsRequest`].
    pub fn into_parts(&self) -> (Vec<String>, u32, u32) {
        (
            self.addresses.clone(),
            self.start.unwrap_or(0),
            self.end.unwrap_or(0),
        )
    }
}

impl From<DGetAddressTxIdsRequest> for GetAddressTxIdsRequest {
    fn from(request: DGetAddressTxIdsRequest) -> Self {
        match request {
            DGetAddressTxIdsRequest::Single(addr) => GetAddressTxIdsRequest {
                addresses: vec![addr],
                start: None,
                end: None,
            },
            DGetAddressTxIdsRequest::Object {
                addresses,
                start,
                end,
            } => GetAddressTxIdsRequest {
                addresses,
                start,
                end,
            },
        }
    }
}

/// An intermediate type used to deserialize [`GetAddressTxIdsRequest`].
#[derive(Debug, serde::Deserialize, JsonSchema)]
#[serde(untagged)]
enum DGetAddressTxIdsRequest {
    /// A single address string.
    Single(String),
    /// A full request object with address list and optional height range.
    Object {
        /// A list of addresses to get transactions from.
        addresses: Vec<String>,
        /// The height to start looking for transactions.
        start: Option<u32>,
        /// The height to end looking for transactions.
        end: Option<u32>,
    },
}

impl ValidateAddresses for GetAddressTxIdsRequest {
    fn addresses(&self) -> &[String] {
        &self.addresses
    }
}

/// Information about note commitment trees if any.
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct GetBlockTrees {
    #[serde(skip_serializing_if = "SaplingTrees::is_empty")]
    sapling: SaplingTrees,
    #[serde(skip_serializing_if = "OrchardTrees::is_empty")]
    orchard: OrchardTrees,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    ironwood: Option<IronwoodTrees>,
}

impl Default for GetBlockTrees {
    fn default() -> Self {
        GetBlockTrees {
            sapling: SaplingTrees { size: 0 },
            orchard: OrchardTrees { size: 0 },
            ironwood: None,
        }
    }
}

impl GetBlockTrees {
    /// Constructs a new instance of ['GetBlockTrees'].
    pub fn new(sapling: u64, orchard: u64, ironwood: Option<u64>) -> Self {
        GetBlockTrees {
            sapling: SaplingTrees { size: sapling },
            orchard: OrchardTrees { size: orchard },
            ironwood: ironwood.map(|size| IronwoodTrees { size }),
        }
    }

    /// Returns sapling data held by ['GetBlockTrees'].
    pub fn sapling(self) -> u64 {
        self.sapling.size
    }

    /// Returns orchard data held by ['GetBlockTrees'].
    pub fn orchard(self) -> u64 {
        self.orchard.size
    }

    /// Returns ironwood data held by ['GetBlockTrees'].
    pub fn ironwood(self) -> Option<u64> {
        self.ironwood.map(|ironwood| ironwood.size)
    }
}

/// Sapling note commitment tree information.
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct SaplingTrees {
    size: u64,
}

impl SaplingTrees {
    fn is_empty(&self) -> bool {
        self.size == 0
    }
}

/// Orchard note commitment tree information.
#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct OrchardTrees {
    size: u64,
}

impl OrchardTrees {
    fn is_empty(&self) -> bool {
        self.size == 0
    }
}

/// Ironwood note commitment tree information.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct IronwoodTrees {
    size: u64,
}

/// Build a valid height range from the given optional start and end numbers.
///
/// # Parameters
///
/// - `start`: Optional starting height. If not provided, defaults to 0.
/// - `end`: Optional ending height. A value of 0 or absence of a value indicates to use `chain_height`.
/// - `chain_height`: The maximum permissible height.
///
/// # Returns
///
/// A `RangeInclusive<Height>` from the clamped start to the clamped end.
///
/// # Errors
///
/// Returns an error if the computed start is greater than the computed end.
fn build_height_range(
    start: Option<u32>,
    end: Option<u32>,
    chain_height: Height,
) -> Result<RangeInclusive<Height>> {
    // Convert optional values to Height, using 0 (as Height(0)) when missing.
    // If start is above chain_height, clamp it to chain_height.
    let start = Height(start.unwrap_or(0)).min(chain_height);

    // For `end`, treat a zero value or missing value as `chain_height`:
    let end = match end {
        Some(0) | None => chain_height,
        Some(val) => Height(val).min(chain_height),
    };

    if start > end {
        return Err(ErrorObject::owned(
            ErrorCode::InvalidParams.code(),
            format!("start {start:?} must be less than or equal to end {end:?}"),
            None::<()>,
        ));
    }

    Ok(start..=end)
}

/// Given a potentially negative index, find the corresponding `Height`.
///
/// This function is used to parse the integer index argument of `get_block_hash`.
/// This is based on zcashd's implementation:
/// <https://github.com/zcash/zcash/blob/c267c3ee26510a974554f227d40a89e3ceb5bb4d/src/rpc/blockchain.cpp#L589-L618>
//
// TODO: also use this function in `get_block` and `z_get_treestate`
pub fn height_from_signed_int(index: i32, tip_height: Height) -> Result<Height> {
    if index >= 0 {
        let height = index.try_into().map_err(|_| {
            ErrorObject::borrowed(
                ErrorCode::InvalidParams.code(),
                "Index conversion failed",
                None,
            )
        })?;
        if height > tip_height.0 {
            return Err(ErrorObject::borrowed(
                ErrorCode::InvalidParams.code(),
                "Provided index is greater than the current tip",
                None,
            ));
        }
        Ok(Height(height))
    } else {
        // `index + 1` can't overflow, because `index` is always negative here.
        let height = i32::try_from(tip_height.0)
            .map_err(|_| {
                ErrorObject::borrowed(
                    ErrorCode::InvalidParams.code(),
                    "Tip height conversion failed",
                    None,
                )
            })?
            .checked_add(index + 1);

        let sanitized_height = match height {
            None => {
                return Err(ErrorObject::borrowed(
                    ErrorCode::InvalidParams.code(),
                    "Provided index is not valid",
                    None,
                ));
            }
            Some(h) => {
                if h < 0 {
                    return Err(ErrorObject::borrowed(
                        ErrorCode::InvalidParams.code(),
                        "Provided negative index ends up with a negative height",
                        None,
                    ));
                }
                let h: u32 = h.try_into().map_err(|_| {
                    ErrorObject::borrowed(
                        ErrorCode::InvalidParams.code(),
                        "Height conversion failed",
                        None,
                    )
                })?;
                if h > tip_height.0 {
                    return Err(ErrorObject::borrowed(
                        ErrorCode::InvalidParams.code(),
                        "Provided index is greater than the current tip",
                        None,
                    ));
                }

                h
            }
        };

        Ok(Height(sanitized_height))
    }
}

/// A helper module to serialize and deserialize `Option<T: ToHex>` as a hex string.
pub mod opthex {
    use hex::{FromHex, ToHex};
    use serde::{de, Deserialize, Deserializer, Serializer};

    #[allow(missing_docs)]
    pub fn serialize<S, T>(data: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: ToHex,
    {
        match data {
            Some(data) => {
                let s = data.encode_hex::<String>();
                serializer.serialize_str(&s)
            }
            None => serializer.serialize_none(),
        }
    }

    #[allow(missing_docs)]
    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
    where
        D: Deserializer<'de>,
        T: FromHex,
    {
        let opt = Option::<String>::deserialize(deserializer)?;
        match opt {
            Some(s) => T::from_hex(&s)
                .map(Some)
                .map_err(|_e| de::Error::custom("failed to convert hex string")),
            None => Ok(None),
        }
    }
}

/// A helper module to serialize and deserialize `[u8; N]` as a hex string.
pub mod arrayhex {
    use serde::{Deserializer, Serializer};
    use std::fmt;

    #[allow(missing_docs)]
    pub fn serialize<S, const N: usize>(data: &[u8; N], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let hex_string = hex::encode(data);
        serializer.serialize_str(&hex_string)
    }

    #[allow(missing_docs)]
    pub fn deserialize<'de, D, const N: usize>(deserializer: D) -> Result<[u8; N], D::Error>
    where
        D: Deserializer<'de>,
    {
        struct HexArrayVisitor<const N: usize>;

        impl<const N: usize> serde::de::Visitor<'_> for HexArrayVisitor<N> {
            type Value = [u8; N];

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                write!(formatter, "a hex string representing exactly {N} bytes")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                let vec = hex::decode(v).map_err(E::custom)?;
                vec.clone().try_into().map_err(|_| {
                    E::invalid_length(vec.len(), &format!("expected {N} bytes").as_str())
                })
            }
        }

        deserializer.deserialize_str(HexArrayVisitor::<N>)
    }
}

/// Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
pub async fn chain_tip_difficulty<State>(
    network: Network,
    mut state: State,
    should_use_default: bool,
) -> Result<f64>
where
    State: ReadStateService,
{
    let request = ReadRequest::ChainInfo;

    // # TODO
    // - add a separate request like BestChainNextMedianTimePast, but skipping the
    //   consistency check, because any block's difficulty is ok for display
    // - return 1.0 for a "not enough blocks in the state" error, like `zcashd`:
    // <https://github.com/zcash/zcash/blob/7b28054e8b46eb46a9589d0bdc8e29f9fa1dc82d/src/rpc/blockchain.cpp#L40-L41>
    let response = state
        .ready()
        .and_then(|service| service.call(request))
        .await;

    let response = match (should_use_default, response) {
        (_, Ok(res)) => res,
        (true, Err(_)) => {
            return Ok((U256::from(network.target_difficulty_limit()) >> 128).as_u128() as f64);
        }
        (false, Err(error)) => return Err(ErrorObject::owned(0, error.to_string(), None::<()>)),
    };

    let chain_info = match response {
        ReadResponse::ChainInfo(info) => info,
        _ => unreachable!("unmatched response to a chain info request"),
    };

    // This RPC is typically used for display purposes, so it is not consensus-critical.
    // But it uses the difficulty consensus rules for its calculations.
    //
    // Consensus:
    // https://zips.z.cash/protocol/protocol.pdf#nbits
    //
    // The zcashd implementation performs to_expanded() on f64,
    // and then does an inverse division:
    // https://github.com/zcash/zcash/blob/d6e2fada844373a8554ee085418e68de4b593a6c/src/rpc/blockchain.cpp#L46-L73
    //
    // But in Zebra we divide the high 128 bits of each expanded difficulty. This gives
    // a similar result, because the lower 128 bits are insignificant after conversion
    // to `f64` with a 53-bit mantissa.
    //
    // `pow_limit >> 128 / difficulty >> 128` is the same as the work calculation
    // `(2^256 / pow_limit) / (2^256 / difficulty)`, but it's a bit more accurate.
    //
    // To simplify the calculation, we don't scale for leading zeroes. (Bitcoin's
    // difficulty currently uses 68 bits, so even it would still have full precision
    // using this calculation.)

    // Get expanded difficulties (256 bits), these are the inverse of the work
    let pow_limit: U256 = network.target_difficulty_limit().into();
    let Some(difficulty) = chain_info.expected_difficulty.to_expanded() else {
        return Ok(0.0);
    };

    // Shift out the lower 128 bits (256 bits, but the top 128 are all zeroes)
    let pow_limit = pow_limit >> 128;
    let difficulty = U256::from(difficulty) >> 128;

    // Convert to u128 then f64.
    // We could also convert U256 to String, then parse as f64, but that's slower.
    let pow_limit = pow_limit.as_u128() as f64;
    let difficulty = difficulty.as_u128() as f64;

    // Invert the division to give approximately: `work(difficulty) / work(pow_limit)`
    Ok(pow_limit / difficulty)
}

/// Commands for the `addnode` RPC method.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, JsonSchema)]
pub enum AddNodeCommand {
    /// Add a node to the address book.
    #[serde(rename = "add")]
    Add,
}

/// Response to a `gettxout` RPC request.
///
/// See the notes for the [`Rpc::get_tx_out` method].
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct GetTxOutResponse(Option<types::transaction::OutputObject>);