package octez-shell-libs

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file block_services.ml

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
(*****************************************************************************)
(*                                                                           *)
(* Open Source License                                                       *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com>     *)
(* Copyright (c) 2018-2021 Nomadic Labs. <contact@nomadic-labs.com>          *)
(*                                                                           *)
(* Permission is hereby granted, free of charge, to any person obtaining a   *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense,  *)
(* and/or sell copies of the Software, and to permit persons to whom the     *)
(* Software is furnished to do so, subject to the following conditions:      *)
(*                                                                           *)
(* The above copyright notice and this permission notice shall be included   *)
(* in all copies or substantial portions of the Software.                    *)
(*                                                                           *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL   *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING   *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER       *)
(* DEALINGS IN THE SOFTWARE.                                                 *)
(*                                                                           *)
(*****************************************************************************)

open Data_encoding
module Proof = Tezos_context_sigs.Context.Proof_types

type version = Version_0 | Version_1 | Version_2

let string_of_version = function
  | Version_0 -> "0"
  | Version_1 -> "1"
  | Version_2 -> "2"

type supported_version = {version : version; use_legacy_attestation_name : bool}

type version_informations = {
  supported : supported_version list;
  latest : version;
  default : version;
}

let mk_version_informations ~supported ~(latest : version) ~(default : version)
    () =
  assert (
    List.mem
      ~equal:( == )
      latest
      (List.map (fun supported -> supported.version) supported)) ;
  assert (
    List.mem
      ~equal:( == )
      default
      (List.map (fun supported -> supported.version) supported)) ;
  {supported; latest; default}

let version_0 = {version = Version_0; use_legacy_attestation_name = true}

let version_1 = {version = Version_1; use_legacy_attestation_name = false}

let pp_supported_version fmt ~complete {supported; latest; default} =
  let open Format in
  (pp_print_list
     ~pp_sep:(fun fmt () -> fprintf fmt ",")
     (fun fmt {version; use_legacy_attestation_name} ->
       fprintf
         fmt
         " version %S %s%s"
         (string_of_version version)
         (match (version = default, not (version = latest)) with
         | true, true -> "(default but deprecated)"
         | true, false -> "(default)"
         | false, true -> "(deprecated)"
         | false, false -> "")
         (if complete then
          if use_legacy_attestation_name then
            " that will output attestation operations as \"endorsement\" in \
             the \"kind\" field"
          else " that will output \"attestation\" in the \"kind\" field"
         else "")))
    fmt
    supported

let unsupported_version_msg version supported =
  Format.asprintf
    "Unsupported version %s (supported versions %a)"
    version
    (pp_supported_version ~complete:false)
    supported

let is_supported_version (version : version)
    (supported : supported_version list) =
  List.exists (fun supported -> version == supported.version) supported

let version_of_string version_informations version =
  let open Result_syntax in
  let* version_t =
    match version with
    | "0" -> Ok Version_0
    | "1" -> Ok Version_1
    | "2" -> Ok Version_2
    | _ -> Error (unsupported_version_msg version version_informations)
  in
  if is_supported_version version_t version_informations.supported then
    Ok version_t
  else Error (unsupported_version_msg version version_informations)

let version_arg supported =
  let open Tezos_rpc.Arg in
  make
    ~descr:
      (Format.asprintf
         "Supported RPC versions are%a"
         (pp_supported_version ~complete:true)
         supported)
    ~name:"version"
    ~destruct:(version_of_string supported)
    ~construct:string_of_version
    ()

(* This function creates an encoding that use the [latest_encoding] in binary
   and that can use [latest_encoding] and any [old_encodings] in JSON. The
   version value is only used to decide which encoding to use in JSON. *)
let encoding_versioning ~encoding_name ~latest_encoding ~old_encodings =
  let make_case ~version ~encoding =
    case
      ~title:
        (Format.sprintf
           "%s_encoding_v%s"
           encoding_name
           (string_of_version version))
      Json_only
      encoding
      (function v, value when v == version -> Some value | _v, _value -> None)
      (fun value -> (version, value))
  in
  let latest_version, latest_encoding = latest_encoding in
  splitted
    ~binary:
      (conv
         (fun (_, value) -> value)
         (fun value -> (latest_version, value))
         latest_encoding)
    ~json:
      (union
         (make_case ~version:latest_version ~encoding:latest_encoding
         :: List.map
              (fun (version, encoding) -> make_case ~version ~encoding)
              old_encodings))

(* TODO: V2.Tree32 has been chosen arbitrarily ; maybe it's not the best option *)
module Merkle_proof_encoding =
  Tezos_context_merkle_proof_encoding.Merkle_proof_encoding.V2.Tree32

type chain = [`Main | `Test | `Hash of Chain_id.t]

let metadata_rpc_arg =
  let construct = function `Always -> "always" | `Never -> "never" in
  let destruct arg =
    Result.catch_f
      (fun () ->
        match arg with
        | "always" -> `Always
        | "never" -> `Never
        | s -> invalid_arg (Format.sprintf "unrecognize parameter %s" s))
      (fun exn ->
        Format.sprintf "Invalid argument: %s" (Printexc.to_string exn))
  in
  let description = "defines the way metadata are queried" in
  let name = "metadata_rpc_arg" in
  Tezos_rpc.Arg.make ~descr:description ~name ~construct ~destruct ()

let parse_chain s =
  try
    match s with
    | "main" -> Ok `Main
    | "test" -> Ok `Test
    | h -> Ok (`Hash (Chain_id.of_b58check_exn h))
  with _ -> Error "Cannot parse chain identifier."

let chain_to_string = function
  | `Main -> "main"
  | `Test -> "test"
  | `Hash h -> Chain_id.to_b58check h

let chain_arg =
  let name = "chain_id" in
  let descr =
    "A chain identifier. This is either a chain hash in Base58Check notation \
     or a one the predefined aliases: 'main', 'test'."
  in
  let construct = chain_to_string in
  let destruct = parse_chain in
  Tezos_rpc.Arg.make ~name ~descr ~construct ~destruct ()

type block =
  [ `Genesis
  | `Head of int
  | `Alias of [`Caboose | `Checkpoint | `Savepoint] * int
  | `Hash of Block_hash.t * int
  | `Level of Int32.t ]

let parse_block s =
  let delims = ['~'; '-'; '+'] in
  let count_delims s =
    List.map
      (fun d ->
        (String.fold_left (fun i c -> if c = d then i + 1 else i) 0 s, d))
      delims
  in
  let split_on_delim counts =
    match List.fold_left (fun i (v, _) -> i + v) 0 counts with
    | 0 -> ([s], ' ')
    | 1 ->
        let delim =
          WithExceptions.Option.get ~loc:__LOC__
          @@ List.assoc ~equal:Int.equal 1 counts
        in
        (String.split_no_empty delim s, delim)
    | _ -> raise Exit
  in
  (* Converts a string representing a block level into a Int32. Fails
     if the resulting integer is negative. *)
  let to_valid_level_id s =
    let l = Int32.of_string s in
    if Compare.Int32.(l < 0l) then raise Exit else l
  in
  (* Converts an Int32 into a level identifier. If [?offset] is given,
     returns the level identifier minus that offset. *)
  let to_level ?offset l =
    if Compare.Int32.(l = 0l) then Ok `Genesis
    else
      match offset with
      | Some ofs -> Ok (`Level Int32.(sub l ofs))
      | None -> Ok (`Level l)
  in
  try
    match split_on_delim (count_delims s) with
    | ["genesis"], _ -> Ok `Genesis
    | ["genesis"; n], '+' -> Ok (`Level (Int32.of_string n))
    | ["head"], _ -> Ok (`Head 0)
    | ["head"; n], '~' | ["head"; n], '-' -> Ok (`Head (int_of_string n))
    | ["checkpoint"], _ -> Ok (`Alias (`Checkpoint, 0))
    | ["checkpoint"; n], '~' | ["checkpoint"; n], '-' ->
        Ok (`Alias (`Checkpoint, int_of_string n))
    | ["checkpoint"; n], '+' -> Ok (`Alias (`Checkpoint, -int_of_string n))
    | ["savepoint"], _ -> Ok (`Alias (`Savepoint, 0))
    | ["savepoint"; n], '~' | ["savepoint"; n], '-' ->
        Ok (`Alias (`Savepoint, int_of_string n))
    | ["savepoint"; n], '+' -> Ok (`Alias (`Savepoint, -int_of_string n))
    | ["caboose"], _ -> Ok (`Alias (`Caboose, 0))
    | ["caboose"; n], '~' | ["caboose"; n], '-' ->
        Ok (`Alias (`Caboose, int_of_string n))
    | ["caboose"; n], '+' -> Ok (`Alias (`Caboose, -int_of_string n))
    | [hol], _ -> (
        match Block_hash.of_b58check_opt hol with
        | Some h -> Ok (`Hash (h, 0))
        | None -> to_level (to_valid_level_id s))
    | [hol; n], '~' | [hol; n], '-' -> (
        match Block_hash.of_b58check_opt hol with
        | Some h -> Ok (`Hash (h, int_of_string n))
        | None ->
            let offset = to_valid_level_id n in
            to_level ~offset (to_valid_level_id hol))
    | [hol; n], '+' -> (
        match Block_hash.of_b58check_opt hol with
        | Some h -> Ok (`Hash (h, -int_of_string n))
        | None ->
            let offset = Int32.neg (to_valid_level_id n) in
            to_level ~offset (to_valid_level_id hol))
    | _ -> raise Exit
  with _ -> Error ("Cannot parse block identifier: " ^ s)

type range = [`Level of Int32.t] * [`Level of Int32.t]

let parse_block_range r =
  try
    match String.split '.' r with
    | [starts; ""; ends] ->
        let to_level s =
          let l = Int32.of_string s in
          if Compare.Int32.(l < 0l) then raise Exit ;
          `Level l
        in
        Ok (to_level starts, to_level ends)
    | _ -> raise Exit
  with _ ->
    Error
      (Format.asprintf
         "Cannot parse block range: %S (expected <level>..<level>)"
         r)

type block_or_range = Block of block | Range of range

let parse_block_or_range r =
  if String.contains r '.' then
    Result.map (fun r -> Range r) (parse_block_range r)
  else Result.map (fun b -> Block b) (parse_block r)

let alias_to_string = function
  | `Checkpoint -> "checkpoint"
  | `Savepoint -> "savepoint"
  | `Caboose -> "caboose"

let to_string = function
  | `Genesis -> "genesis"
  | `Alias (a, 0) -> alias_to_string a
  | `Alias (a, n) when n < 0 -> Printf.sprintf "%s+%d" (alias_to_string a) (-n)
  | `Alias (a, n) -> Printf.sprintf "%s~%d" (alias_to_string a) n
  | `Head 0 -> "head"
  | `Head n when n < 0 -> Printf.sprintf "head+%d" (-n)
  | `Head n -> Printf.sprintf "head~%d" n
  | `Hash (h, 0) -> Block_hash.to_b58check h
  | `Hash (h, n) when n < 0 ->
      Printf.sprintf "%s+%d" (Block_hash.to_b58check h) (-n)
  | `Hash (h, n) -> Printf.sprintf "%s~%d" (Block_hash.to_b58check h) n
  | `Level i -> Printf.sprintf "%d" (Int32.to_int i)

let blocks_arg =
  let name = "block_id" in
  let descr =
    "A block identifier. This is either a block hash in Base58Check notation, \
     one the predefined aliases: 'genesis', 'head' or a block level (index in \
     the chain). One might also use 'head~N' or '<hash>~N' where N is an \
     integer to denote the Nth predecessor of the designated block.Also, \
     '<hash>+N' denotes the Nth successor of a block."
  in
  let construct = to_string in
  let destruct = parse_block in
  Tezos_rpc.Arg.make ~name ~descr ~construct ~destruct ()

type chain_prefix = unit * chain

type prefix = chain_prefix * block

let chain_path = Tezos_rpc.Path.(root / "chains" /: chain_arg)

let mempool_path p = Tezos_rpc.Path.(p / "mempool")

let live_blocks_path p = Tezos_rpc.Path.(p / "live_blocks")

let dir_path : (chain_prefix, chain_prefix) Tezos_rpc.Path.t =
  Tezos_rpc.Path.(open_root / "blocks")

let path = Tezos_rpc.Path.(dir_path /: blocks_arg)

type operation_list_quota = {max_size : int; max_op : int option}

let operation_list_quota_encoding =
  conv
    (fun {max_size; max_op} -> (max_size, max_op))
    (fun (max_size, max_op) -> {max_size; max_op})
    (obj2 (req "max_size" int31) (opt "max_op" int31))

let raw_context_encoding =
  let open Proof in
  mu "raw_context" (fun encoding ->
      union
        [
          case
            (Tag 0)
            bytes
            ~title:"Key"
            (function Key k -> Some k | _ -> None)
            (fun k -> Key k);
          case
            (Tag 1)
            (assoc encoding)
            ~title:"Dir"
            (function Dir map -> Some (String.Map.bindings map) | _ -> None)
            (fun bindings ->
              Dir
                (List.fold_left
                   (fun wip_map (k, v) -> String.Map.add k v wip_map)
                   String.Map.empty
                   bindings));
          case
            (Tag 2)
            null
            ~title:"Cut"
            (function Cut -> Some () | _ -> None)
            (fun () -> Cut);
        ])

let raw_context_insert =
  let open Proof in
  let default = Dir String.Map.empty in
  (* not tail recursive but over the length of [k], which is small *)
  let rec aux (k, v) ctx =
    let d = match ctx with Dir d -> d | Key _ | Cut -> String.Map.empty in
    match k with
    | [] -> v
    | [kh] -> Dir (String.Map.add kh v d)
    | kh :: ktl ->
        Dir
          (String.Map.update
             kh
             (fun ctxtopt ->
               let ctx' = Option.value ctxtopt ~default in
               Some (aux (ktl, v) ctx'))
             d)
  in
  aux

let stringmap_encoding value_encoding =
  let open Data_encoding in
  conv
    String.Map.bindings
    (fun l ->
      List.fold_left
        (fun acc (k, v) -> String.Map.add k v acc)
        String.Map.empty
        l)
    (list (tup2 string value_encoding))

let merkle_tree_encoding : Proof.merkle_tree Data_encoding.t =
  let open Proof in
  let open Data_encoding in
  let hash_tag = 0 and hash_encoding = tup2 bool string in
  let data_tag = 1 and data_encoding = raw_context_encoding in
  let continue_tag = 2 in
  mu "merkle_tree" (fun encoding ->
      let continue_encoding = encoding in
      stringmap_encoding
        (matching
           (function
             | Hash (kind, content) ->
                 matched
                   hash_tag
                   hash_encoding
                   ( (match kind with Contents -> true | Node -> false),
                     content )
             | Data raw_context -> matched data_tag data_encoding raw_context
             | Continue dir -> matched continue_tag encoding dir)
           [
             case
               (Tag hash_tag)
               ~title:"Hash"
               hash_encoding
               (function Hash (k, h) -> Some (k = Contents, h) | _ -> None)
               (fun (k, h) ->
                 let kind = if k then Contents else Node in
                 Hash (kind, h));
             case
               (Tag data_tag)
               data_encoding
               ~title:"Data"
               (function Data raw_context -> Some raw_context | _ -> None)
               (fun raw_context -> Data raw_context);
             case
               (Tag continue_tag)
               continue_encoding
               ~title:"Continue"
               (function Continue dir -> Some dir | _ -> None)
               (fun dir -> Continue dir);
           ]))

module type PROTO = sig
  val hash : Protocol_hash.t

  type block_header_data

  val block_header_data_encoding : block_header_data Data_encoding.t

  type block_header_metadata

  val block_header_metadata_encoding_with_legacy_attestation_name :
    block_header_metadata Data_encoding.t

  val block_header_metadata_encoding : block_header_metadata Data_encoding.t

  type operation_data

  type operation_receipt

  type operation = {
    shell : Operation.shell_header;
    protocol_data : operation_data;
  }

  val operation_data_encoding : operation_data Data_encoding.t

  val operation_data_encoding_with_legacy_attestation_name :
    operation_data Data_encoding.t

  val operation_receipt_encoding : operation_receipt Data_encoding.t

  val operation_receipt_encoding_with_legacy_attestation_name :
    operation_receipt Data_encoding.t

  val operation_data_and_receipt_encoding :
    (operation_data * operation_receipt) Data_encoding.t

  val operation_data_and_receipt_encoding_with_legacy_attestation_name :
    (operation_data * operation_receipt) Data_encoding.t
end

type protocols = {
  current_protocol : Protocol_hash.t;
  next_protocol : Protocol_hash.t;
}

let raw_protocol_encoding =
  conv
    (fun {current_protocol; next_protocol} -> (current_protocol, next_protocol))
    (fun (current_protocol, next_protocol) -> {current_protocol; next_protocol})
    (obj2
       (req "protocol" Protocol_hash.encoding)
       (req "next_protocol" Protocol_hash.encoding))

module Make (Proto : PROTO) (Next_proto : PROTO) = struct
  let protocol_hash = Protocol_hash.to_b58check Proto.hash

  let next_protocol_hash = Protocol_hash.to_b58check Next_proto.hash

  type raw_block_header = {
    shell : Block_header.shell_header;
    protocol_data : Proto.block_header_data;
  }

  let raw_block_header_encoding =
    def "raw_block_header"
    @@ conv
         (fun {shell; protocol_data} -> (shell, protocol_data))
         (fun (shell, protocol_data) -> {shell; protocol_data})
         (merge_objs
            Block_header.shell_header_encoding
            Proto.block_header_data_encoding)

  type block_header = {
    chain_id : Chain_id.t;
    hash : Block_hash.t;
    shell : Block_header.shell_header;
    protocol_data : Proto.block_header_data;
  }

  let block_header_encoding =
    def "block_header"
    @@ conv
         (fun {chain_id; hash; shell; protocol_data} ->
           (((), chain_id, hash), {shell; protocol_data}))
         (fun (((), chain_id, hash), {shell; protocol_data}) ->
           {chain_id; hash; shell; protocol_data})
         (merge_objs
            (obj3
               (req "protocol" (constant protocol_hash))
               (req "chain_id" Chain_id.encoding)
               (req "hash" Block_hash.encoding))
            raw_block_header_encoding)

  type block_metadata = {
    protocol_data : Proto.block_header_metadata;
    test_chain_status : Test_chain_status.t;
    (* for the next block: *)
    max_operations_ttl : int;
    max_operation_data_length : int;
    max_block_header_length : int;
    operation_list_quota : operation_list_quota list;
  }

  let block_metadata_encoding ~use_legacy_attestation_name =
    def
      (if use_legacy_attestation_name then
       "block_header_metadata_with_legacy_attestation_name"
      else "block_header_metadata")
    @@ conv
         (fun {
                protocol_data;
                test_chain_status;
                max_operations_ttl;
                max_operation_data_length;
                max_block_header_length;
                operation_list_quota;
              } ->
           ( ( (),
               (),
               test_chain_status,
               max_operations_ttl,
               max_operation_data_length,
               max_block_header_length,
               operation_list_quota ),
             protocol_data ))
         (fun ( ( (),
                  (),
                  test_chain_status,
                  max_operations_ttl,
                  max_operation_data_length,
                  max_block_header_length,
                  operation_list_quota ),
                protocol_data ) ->
           {
             protocol_data;
             test_chain_status;
             max_operations_ttl;
             max_operation_data_length;
             max_block_header_length;
             operation_list_quota;
           })
         (merge_objs
            (obj7
               (req "protocol" (constant protocol_hash))
               (req "next_protocol" (constant next_protocol_hash))
               (req "test_chain_status" Test_chain_status.encoding)
               (req "max_operations_ttl" int31)
               (req "max_operation_data_length" int31)
               (req "max_block_header_length" int31)
               (req
                  "max_operation_list_length"
                  (dynamic_size (list operation_list_quota_encoding))))
            (if use_legacy_attestation_name then
             Proto.block_header_metadata_encoding_with_legacy_attestation_name
            else Proto.block_header_metadata_encoding))

  let next_operation_encoding_with_legacy_attestation_name =
    let open Data_encoding in
    def "next_operation_with_legacy_attestation_name"
    @@ conv
         (fun Next_proto.{shell; protocol_data} -> ((), (shell, protocol_data)))
         (fun ((), (shell, protocol_data)) -> {shell; protocol_data})
         (merge_objs
            (obj1 (req "protocol" (constant next_protocol_hash)))
            (merge_objs
               (dynamic_size Operation.shell_header_encoding)
               (dynamic_size
                  Next_proto
                  .operation_data_encoding_with_legacy_attestation_name)))

  let next_operation_encoding =
    let open Data_encoding in
    def "next_operation"
    @@ conv
         (fun Next_proto.{shell; protocol_data} -> ((), (shell, protocol_data)))
         (fun ((), (shell, protocol_data)) -> {shell; protocol_data})
         (merge_objs
            (obj1 (req "protocol" (constant next_protocol_hash)))
            (merge_objs
               (dynamic_size Operation.shell_header_encoding)
               (dynamic_size Next_proto.operation_data_encoding)))

  type operation_receipt =
    | Empty
    | Too_large
    | Receipt of Proto.operation_receipt

  type operation = {
    chain_id : Chain_id.t;
    hash : Operation_hash.t;
    shell : Operation.shell_header;
    protocol_data : Proto.operation_data;
    receipt : operation_receipt;
  }

  let operation_data_encoding ~use_legacy_attestation_name =
    let operation_data_encoding =
      if use_legacy_attestation_name then
        Proto.operation_data_encoding_with_legacy_attestation_name
      else Proto.operation_data_encoding
    in
    let operation_data_and_receipt_encoding =
      if use_legacy_attestation_name then
        Proto.operation_data_and_receipt_encoding_with_legacy_attestation_name
      else Proto.operation_data_and_receipt_encoding
    in
    let open Data_encoding in
    union
      ~tag_size:`Uint8
      [
        case
          ~title:"Operation with too large metadata"
          (Tag 0)
          (merge_objs
             operation_data_encoding
             (obj1 (req "metadata" (constant "too large"))))
          (function
            | operation_data, Too_large -> Some (operation_data, ()) | _ -> None)
          (fun (operation_data, ()) -> (operation_data, Too_large));
        case
          ~title:"Operation without metadata"
          (Tag 1)
          operation_data_encoding
          (function operation_data, Empty -> Some operation_data | _ -> None)
          (fun operation_data -> (operation_data, Empty));
        case
          ~title:"Operation with metadata"
          (Tag 2)
          operation_data_and_receipt_encoding
          (function
            | operation_data, Receipt receipt -> Some (operation_data, receipt)
            | _ -> None)
          (function
            | operation_data, receipt -> (operation_data, Receipt receipt));
      ]

  let operation_encoding ~use_legacy_attestation_name =
    def
      (if use_legacy_attestation_name then
       "operation_with_legacy_attestation_name"
      else "operation")
    @@
    let open Data_encoding in
    conv
      (fun {chain_id; hash; shell; protocol_data; receipt} ->
        (((), chain_id, hash), (shell, (protocol_data, receipt))))
      (fun (((), chain_id, hash), (shell, (protocol_data, receipt))) ->
        {chain_id; hash; shell; protocol_data; receipt})
      (merge_objs
         (obj3
            (req "protocol" (constant protocol_hash))
            (req "chain_id" Chain_id.encoding)
            (req "hash" Operation_hash.encoding))
         (merge_objs
            (dynamic_size Operation.shell_header_encoding)
            (dynamic_size
               (operation_data_encoding ~use_legacy_attestation_name))))

  let operation_encoding_with_legacy_attestation_name =
    operation_encoding ~use_legacy_attestation_name:true

  let operation_encoding = operation_encoding ~use_legacy_attestation_name:false

  type block_info = {
    chain_id : Chain_id.t;
    hash : Block_hash.t;
    header : raw_block_header;
    metadata : block_metadata option;
    operations : operation list list;
  }

  let block_info_encoding ~use_legacy_attestation_name =
    let operation_encoding =
      if use_legacy_attestation_name then
        operation_encoding_with_legacy_attestation_name
      else operation_encoding
    in
    conv
      (fun {chain_id; hash; header; metadata; operations} ->
        ((), chain_id, hash, header, metadata, operations))
      (fun ((), chain_id, hash, header, metadata, operations) ->
        {chain_id; hash; header; metadata; operations})
      (obj6
         (req "protocol" (constant protocol_hash))
         (req "chain_id" Chain_id.encoding)
         (req "hash" Block_hash.encoding)
         (req "header" (dynamic_size raw_block_header_encoding))
         (opt
            "metadata"
            (dynamic_size
               (block_metadata_encoding ~use_legacy_attestation_name)))
         (req "operations" (list (dynamic_size (list operation_encoding)))))

  let block_info_encoding =
    encoding_versioning
      ~encoding_name:"block_info"
      ~latest_encoding:
        (Version_1, block_info_encoding ~use_legacy_attestation_name:false)
      ~old_encodings:
        [(Version_0, block_info_encoding ~use_legacy_attestation_name:true)]

  module S = struct
    let path : prefix Tezos_rpc.Path.context = Tezos_rpc.Path.open_root

    let hash =
      Tezos_rpc.Service.get_service
        ~description:"The block's hash, its unique identifier."
        ~query:Tezos_rpc.Query.empty
        ~output:Block_hash.encoding
        Tezos_rpc.Path.(path / "hash")

    let header =
      Tezos_rpc.Service.get_service
        ~description:"The whole block header."
        ~query:Tezos_rpc.Query.empty
        ~output:block_header_encoding
        Tezos_rpc.Path.(path / "header")

    let raw_header =
      Tezos_rpc.Service.get_service
        ~description:"The whole block header (unparsed)."
        ~query:Tezos_rpc.Query.empty
        ~output:bytes
        Tezos_rpc.Path.(path / "header" / "raw")

    let block_metadata_encoding =
      encoding_versioning
        ~encoding_name:"block_metadata_encoding"
        ~latest_encoding:
          (Version_1, block_metadata_encoding ~use_legacy_attestation_name:false)
        ~old_encodings:
          [
            ( Version_0,
              block_metadata_encoding ~use_legacy_attestation_name:true );
          ]

    let metadata_versions =
      mk_version_informations
        ~supported:[version_0; version_1]
        ~latest:Version_1
        ~default:Version_1
        ()

    let metadata_query =
      let open Tezos_rpc.Query in
      query (fun version ->
          object
            method version = version
          end)
      |+ field
           "version"
           (version_arg metadata_versions)
           metadata_versions.default
           (fun t -> t#version)
      |> seal

    let metadata =
      Tezos_rpc.Service.get_service
        ~description:"All the metadata associated to the block."
        ~query:metadata_query
        ~output:block_metadata_encoding
        Tezos_rpc.Path.(path / "metadata")

    let metadata_hash =
      Tezos_rpc.Service.get_service
        ~description:
          "Hash of the metadata associated to the block. This is only set on \
           blocks starting from environment V1."
        ~query:Tezos_rpc.Query.empty
        ~output:Block_metadata_hash.encoding
        Tezos_rpc.Path.(path / "metadata_hash")

    let protocols =
      Tezos_rpc.Service.get_service
        ~description:"Current and next protocol."
        ~query:Tezos_rpc.Query.empty
        ~output:raw_protocol_encoding
        Tezos_rpc.Path.(path / "protocols")

    let resulting_context_hash =
      Tezos_rpc.Service.get_service
        ~description:"Context hash resulting of the block application."
        ~query:Tezos_rpc.Query.empty
        ~output:Context_hash.encoding
        Tezos_rpc.Path.(path / "resulting_context_hash")

    module Header = struct
      let path = Tezos_rpc.Path.(path / "header")

      let shell_header =
        Tezos_rpc.Service.get_service
          ~description:"The shell-specific fragment of the block header."
          ~query:Tezos_rpc.Query.empty
          ~output:Block_header.shell_header_encoding
          Tezos_rpc.Path.(path / "shell")

      let protocol_data =
        Tezos_rpc.Service.get_service
          ~description:"The version-specific fragment of the block header."
          ~query:Tezos_rpc.Query.empty
          ~output:
            (conv
               (fun h -> ((), h))
               (fun ((), h) -> h)
               (merge_objs
                  (obj1 (req "protocol" (constant protocol_hash)))
                  Proto.block_header_data_encoding))
          Tezos_rpc.Path.(path / "protocol_data")

      let raw_protocol_data =
        Tezos_rpc.Service.get_service
          ~description:
            "The version-specific fragment of the block header (unparsed)."
          ~query:Tezos_rpc.Query.empty
          ~output:bytes
          Tezos_rpc.Path.(path / "protocol_data" / "raw")
    end

    let operations_versions =
      mk_version_informations
        ~supported:[version_0; version_1]
        ~latest:Version_1
        ~default:Version_1
        ()

    let force_operation_metadata_query =
      let open Tezos_rpc.Query in
      query (fun version force_metadata metadata ->
          object
            method version = version

            method force_metadata = force_metadata

            method metadata = metadata
          end)
      |+ field
           "version"
           (version_arg operations_versions)
           operations_versions.default
           (fun t -> t#version)
      |+ flag
           "force_metadata"
           ~descr:
             "DEPRECATED: Forces to recompute the operations metadata if it \
              was considered as too large."
           (fun x -> x#force_metadata)
      |+ opt_field
           "metadata"
           ~descr:
             "Specifies whether or not if the operations metadata should be \
              returned. To get the metadata, even if it is needed to recompute \
              them, use \"always\". To avoid getting the metadata, use \
              \"never\". By default, the metadata will be returned depending \
              on the node's metadata size limit policy."
           metadata_rpc_arg
           (fun x -> x#metadata)
      |> seal

    module Operations = struct
      let path = Tezos_rpc.Path.(path / "operations")

      let operations =
        let output =
          encoding_versioning
            ~encoding_name:"operations"
            ~latest_encoding:
              (Version_1, list (dynamic_size (list operation_encoding)))
            ~old_encodings:
              [
                ( Version_0,
                  list
                    (dynamic_size
                       (list operation_encoding_with_legacy_attestation_name))
                );
              ]
        in
        Tezos_rpc.Service.get_service
          ~description:"All the operations included in the block."
          ~query:force_operation_metadata_query
          ~output
          path

      let list_arg =
        let name = "list_offset" in
        let descr = "Index `n` of the requested validation pass." in
        let construct = string_of_int in
        let destruct s =
          try Ok (int_of_string s)
          with _ -> Error (Format.sprintf "Invalid list offset (%s)" s)
        in
        Tezos_rpc.Arg.make ~name ~descr ~construct ~destruct ()

      let offset_arg =
        let name = "operation_offset" in
        let descr =
          "Index `m` of the requested operation in its validation pass."
        in
        let construct = string_of_int in
        let destruct s =
          try Ok (int_of_string s)
          with _ -> Error (Format.sprintf "Invalid operation offset (%s)" s)
        in
        Tezos_rpc.Arg.make ~name ~descr ~construct ~destruct ()

      let operations_in_pass =
        let output =
          encoding_versioning
            ~encoding_name:"operations_in_pass"
            ~latest_encoding:(Version_1, list operation_encoding)
            ~old_encodings:
              [
                (Version_0, list operation_encoding_with_legacy_attestation_name);
              ]
        in
        Tezos_rpc.Service.get_service
          ~description:
            "All the operations included in `n-th` validation pass of the \
             block."
          ~query:force_operation_metadata_query
          ~output
          Tezos_rpc.Path.(path /: list_arg)

      let operation =
        let output =
          encoding_versioning
            ~encoding_name:"operation"
            ~latest_encoding:(Version_1, operation_encoding)
            ~old_encodings:
              [(Version_0, operation_encoding_with_legacy_attestation_name)]
        in
        Tezos_rpc.Service.get_service
          ~description:
            "The `m-th` operation in the `n-th` validation pass of the block."
          ~query:force_operation_metadata_query
          ~output
          Tezos_rpc.Path.(path /: list_arg /: offset_arg)
    end

    module Operation_hashes = struct
      let path = Tezos_rpc.Path.(path / "operation_hashes")

      let operation_hashes =
        Tezos_rpc.Service.get_service
          ~description:"The hashes of all the operations included in the block."
          ~query:Tezos_rpc.Query.empty
          ~output:(list (list Operation_hash.encoding))
          path

      let operation_hashes_in_pass =
        Tezos_rpc.Service.get_service
          ~description:
            "All the operations included in `n-th` validation pass of the \
             block."
          ~query:Tezos_rpc.Query.empty
          ~output:(list Operation_hash.encoding)
          Tezos_rpc.Path.(path /: Operations.list_arg)

      let operation_hash =
        Tezos_rpc.Service.get_service
          ~description:
            "The hash of then `m-th` operation in the `n-th` validation pass \
             of the block."
          ~query:Tezos_rpc.Query.empty
          ~output:Operation_hash.encoding
          Tezos_rpc.Path.(path /: Operations.list_arg /: Operations.offset_arg)
    end

    module Operation_metadata_hashes = struct
      let root =
        Tezos_rpc.Service.get_service
          ~description:
            "The root hash of the operations metadata from the block. This is \
             only set on blocks starting from environment V1."
          ~query:Tezos_rpc.Query.empty
          ~output:Operation_metadata_list_list_hash.encoding
          Tezos_rpc.Path.(path / "operations_metadata_hash")

      let path = Tezos_rpc.Path.(path / "operation_metadata_hashes")

      let operation_metadata_hashes =
        Tezos_rpc.Service.get_service
          ~description:
            "The hashes of all the operation metadata included in the block. \
             This is only set on blocks starting from environment V1."
          ~query:Tezos_rpc.Query.empty
          ~output:(list (list Operation_metadata_hash.encoding))
          path

      let operation_metadata_hashes_in_pass =
        Tezos_rpc.Service.get_service
          ~description:
            "All the operation metadata included in `n-th` validation pass of \
             the block. This is only set on blocks starting from environment \
             V1."
          ~query:Tezos_rpc.Query.empty
          ~output:(list Operation_metadata_hash.encoding)
          Tezos_rpc.Path.(path /: Operations.list_arg)

      let operation_metadata_hash =
        Tezos_rpc.Service.get_service
          ~description:
            "The hash of then `m-th` operation metadata in the `n-th` \
             validation pass of the block. This is only set on blocks starting \
             from environment V1."
          ~query:Tezos_rpc.Query.empty
          ~output:Operation_metadata_hash.encoding
          Tezos_rpc.Path.(path /: Operations.list_arg /: Operations.offset_arg)
    end

    module Helpers = struct
      let path = Tezos_rpc.Path.(path / "helpers")

      module Forge = struct
        let block_header =
          Tezos_rpc.Service.post_service
            ~description:"Forge a block header"
            ~query:Tezos_rpc.Query.empty
            ~input:Block_header.encoding
            ~output:(obj1 (req "block" bytes))
            Tezos_rpc.Path.(path / "forge_block_header")
      end

      module Preapply = struct
        let path = Tezos_rpc.Path.(path / "preapply")

        let preapply_operation_encoding =
          union
            [
              case
                ~title:"operation_data_encoding"
                (Tag 0)
                next_operation_encoding
                Option.some
                Fun.id;
              case
                ~title:"operation_data_encoding_with_legacy_attestation_name"
                Json_only
                next_operation_encoding_with_legacy_attestation_name
                Option.some
                Fun.id;
            ]

        let block_result_encoding =
          obj2
            (req "shell_header" Block_header.shell_header_encoding)
            (req
               "operations"
               (list (Preapply_result.encoding Tezos_rpc.Error.encoding)))

        type block_param = {
          protocol_data : Next_proto.block_header_data;
          operations : Next_proto.operation list list;
        }

        let block_param_encoding =
          conv
            (fun {protocol_data; operations} -> (protocol_data, operations))
            (fun (protocol_data, operations) -> {protocol_data; operations})
            (obj2
               (req
                  "protocol_data"
                  (conv
                     (fun h -> ((), h))
                     (fun ((), h) -> h)
                     (merge_objs
                        (obj1 (req "protocol" (constant next_protocol_hash)))
                        (dynamic_size Next_proto.block_header_data_encoding))))
               (req
                  "operations"
                  (list (dynamic_size (list preapply_operation_encoding)))))

        let block_query =
          let open Tezos_rpc.Query in
          query (fun sort timestamp ->
              object
                method sort_operations = sort

                method timestamp = timestamp
              end)
          |+ flag "sort" (fun t -> t#sort_operations)
          |+ opt_field "timestamp" Time.Protocol.rpc_arg (fun t -> t#timestamp)
          |> seal

        let block =
          Tezos_rpc.Service.post_service
            ~description:
              "Simulate the validation of a block that would contain the given \
               operations and return the resulting fitness and context hash."
            ~query:block_query
            ~input:block_param_encoding
            ~output:block_result_encoding
            Tezos_rpc.Path.(path / "block")

        let preapply_versions =
          mk_version_informations
            ~supported:[version_0; version_1]
            ~latest:Version_1
            ~default:Version_1
            ()

        let operations_query =
          let open Tezos_rpc.Query in
          query (fun version ->
              object
                method version = version
              end)
          |+ field
               "version"
               (version_arg preapply_versions)
               preapply_versions.default
               (fun t -> t#version)
          |> seal

        let preapplied_operations_encoding =
          encoding_versioning
            ~encoding_name:"preapplied_operations"
            ~latest_encoding:
              ( Version_1,
                list
                  (dynamic_size Next_proto.operation_data_and_receipt_encoding)
              )
            ~old_encodings:
              [
                ( Version_0,
                  list
                    (dynamic_size
                       Next_proto
                       .operation_data_and_receipt_encoding_with_legacy_attestation_name)
                );
              ]

        let operations =
          Tezos_rpc.Service.post_service
            ~description:
              "Simulate the application of the operations with the context of \
               the given block and return the result of each operation \
               application."
            ~query:operations_query
            ~input:(list preapply_operation_encoding)
            ~output:preapplied_operations_encoding
            Tezos_rpc.Path.(path / "operations")
      end

      let complete =
        let prefix_arg =
          let destruct s = Ok s and construct s = s in
          Tezos_rpc.Arg.make ~name:"prefix" ~destruct ~construct ()
        in
        Tezos_rpc.Service.get_service
          ~description:
            "Try to complete a prefix of a Base58Check-encoded data. This RPC \
             is actually able to complete hashes of block, operations, \
             public_keys and contracts."
          ~query:Tezos_rpc.Query.empty
          ~output:(list string)
          Tezos_rpc.Path.(path / "complete" /: prefix_arg)
    end

    module Context = struct
      let path = Tezos_rpc.Path.(path / "context")

      let raw_bytes_path = Tezos_rpc.Path.(path / "raw" / "bytes")

      let merkle_tree_v1_path = Tezos_rpc.Path.(path / "merkle_tree")

      (* The duplication of the ["/merkle_tree"] RPC path is due to MR !5535.
         This MR introduces a breaking change in the former [merkle_tree] RPC,
         because it changes the data type it returns.
         In order to avoid breaking clients that still use the old code,
         we keep the old RPC at path ["/merkle_tree"], and introduce the new one
         at path ["/merkle_tree_v2"].
         Once we are sure that all clients have migrated to the new code, we will
         1) duplicate the behaviour of ["/merkle_tree_v2"] onto ["/merkle_tree"],
            and make the clients call ["/merkle_tree"],
         2) once all clients have applied patch 1), remove ["/merkle_tree_v2"]
            altogether. *)
      let merkle_tree_v2_path = Tezos_rpc.Path.(path / "merkle_tree_v2")

      let context_path_arg : string Tezos_rpc.Arg.t =
        let name = "context_path" in
        let descr = "A path inside the context" in
        let construct s = s in
        let destruct s = Ok s in
        Tezos_rpc.Arg.make ~name ~descr ~construct ~destruct ()

      let raw_context_query : < depth : int option > Tezos_rpc.Query.t =
        let open Tezos_rpc.Query in
        query (fun depth ->
            object
              method depth = depth
            end)
        |+ opt_field "depth" Tezos_rpc.Arg.uint (fun t -> t#depth)
        |> seal

      let read =
        Tezos_rpc.Service.get_service
          ~description:"Returns the raw context."
          ~query:raw_context_query
          ~output:raw_context_encoding
          Tezos_rpc.Path.(raw_bytes_path /:* context_path_arg)

      let merkle_tree_query : < holey : bool option > Tezos_rpc.Query.t =
        let open Tezos_rpc.Query in
        query (fun holey ->
            object
              method holey = holey
            end)
        |+ opt_field
             ~descr:"Send only hashes, omit data of key"
             "holey"
             Tezos_rpc.Arg.bool
             (fun t -> t#holey)
        |> seal

      let merkle_tree =
        Tezos_rpc.Service.get_service
          ~description:"Returns the merkle tree of a piece of context."
          ~query:merkle_tree_query
          ~output:(option merkle_tree_encoding)
          Tezos_rpc.Path.(merkle_tree_v1_path /:* context_path_arg)

      let merkle_tree_v2 =
        Tezos_rpc.Service.get_service
          ~description:"Returns the Irmin merkle tree of a piece of context."
          ~query:merkle_tree_query
          ~output:(option Merkle_proof_encoding.tree_proof_encoding)
          Tezos_rpc.Path.(merkle_tree_v2_path /:* context_path_arg)
    end

    let info =
      Tezos_rpc.Service.get_service
        ~description:
          "All the information about a block. The associated metadata may not \
           be present depending on the history mode and block's distance from \
           the head."
        ~query:force_operation_metadata_query
        ~output:block_info_encoding
        path

    module Mempool = struct
      type t = {
        validated : (Operation_hash.t * Next_proto.operation) list;
        refused : (Next_proto.operation * error list) Operation_hash.Map.t;
        outdated : (Next_proto.operation * error list) Operation_hash.Map.t;
        branch_refused :
          (Next_proto.operation * error list) Operation_hash.Map.t;
        branch_delayed :
          (Next_proto.operation * error list) Operation_hash.Map.t;
        unprocessed : Next_proto.operation Operation_hash.Map.t;
      }

      let pending_operations_encoding ~use_legacy_name ~use_validated =
        let next_operation_encoding =
          if use_legacy_name then
            next_operation_encoding_with_legacy_attestation_name
          else next_operation_encoding
        in
        let operations_with_error_encoding kind =
          req
            kind
            (conv
               (fun map -> Operation_hash.Map.bindings map)
               (fun list -> list |> List.to_seq |> Operation_hash.Map.of_seq)
               (list
                  (merge_objs
                     (obj1 (req "hash" Operation_hash.encoding))
                     (merge_objs
                        next_operation_encoding
                        (obj1 (req "error" Tezos_rpc.Error.encoding))))))
        in
        conv
          (fun {
                 validated;
                 refused;
                 outdated;
                 branch_refused;
                 branch_delayed;
                 unprocessed;
               } ->
            ( validated,
              refused,
              outdated,
              branch_refused,
              branch_delayed,
              unprocessed ))
          (fun ( validated,
                 refused,
                 outdated,
                 branch_refused,
                 branch_delayed,
                 unprocessed ) ->
            {
              validated;
              refused;
              outdated;
              branch_refused;
              branch_delayed;
              unprocessed;
            })
          (obj6
             (req
                (if use_validated then "validated" else "applied")
                (list
                   (conv
                      (fun (hash, (op : Next_proto.operation)) ->
                        ((hash, op.shell), op.protocol_data))
                      (fun ((hash, shell), protocol_data) ->
                        (hash, {shell; protocol_data}))
                      (merge_objs
                         (merge_objs
                            (obj1 (req "hash" Operation_hash.encoding))
                            Operation.shell_header_encoding)
                         (dynamic_size
                            (if use_legacy_name then
                             Next_proto
                             .operation_data_encoding_with_legacy_attestation_name
                            else Next_proto.operation_data_encoding))))))
             (operations_with_error_encoding "refused")
             (operations_with_error_encoding "outdated")
             (operations_with_error_encoding "branch_refused")
             (operations_with_error_encoding "branch_delayed")
             (req
                "unprocessed"
                (conv
                   (fun map -> Operation_hash.Map.bindings map)
                   (fun list ->
                     list |> List.to_seq |> Operation_hash.Map.of_seq)
                   (list
                      (merge_objs
                         (obj1 (req "hash" Operation_hash.encoding))
                         next_operation_encoding)))))

      let version_2_encoding =
        pending_operations_encoding ~use_legacy_name:false ~use_validated:true

      let version_1_encoding =
        pending_operations_encoding ~use_legacy_name:true ~use_validated:false

      (* This encoding should be always the one by default. *)
      let encoding = version_1_encoding

      let pending_operations_versions =
        mk_version_informations
          ~supported:
            [
              {version = Version_1; use_legacy_attestation_name = true};
              {version = Version_2; use_legacy_attestation_name = false};
            ]
          ~latest:Version_2
          ~default:Version_2
          ()

      let pending_query =
        let open Tezos_rpc.Query in
        query
          (fun
            version
            validated
            refused
            outdated
            branch_refused
            branch_delayed
            validation_passes
          ->
            object
              method version = version

              method validated = validated

              method refused = refused

              method outdated = outdated

              method branch_refused = branch_refused

              method branch_delayed = branch_delayed

              method validation_passes = validation_passes
            end)
        |+ field
             "version"
             (version_arg pending_operations_versions)
             pending_operations_versions.default
             (fun t -> t#version)
        |+ field
             ~descr:"Include validated operations (true by default)"
             "validated"
             Tezos_rpc.Arg.bool
             true
             (fun t -> t#validated)
        |+ field
             ~descr:"Include refused operations (true by default)"
             "refused"
             Tezos_rpc.Arg.bool
             true
             (fun t -> t#refused)
        |+ field
             ~descr:"Include outdated operations (true by default)"
             "outdated"
             Tezos_rpc.Arg.bool
             true
             (fun t -> t#outdated)
        |+ field
             ~descr:"Include branch refused operations (true by default)"
             "branch_refused"
             Tezos_rpc.Arg.bool
             true
             (fun t -> t#branch_refused)
        |+ field
             ~descr:"Include branch delayed operations (true by default)"
             "branch_delayed"
             Tezos_rpc.Arg.bool
             true
             (fun t -> t#branch_delayed)
        |+ multi_field
             ~descr:
               "Include operations filtered by validation pass (all by default)"
             "validation_pass"
             Tezos_rpc.Arg.int
             (fun t -> t#validation_passes)
        |> seal

      let pending_operations_encoding =
        encoding_versioning
          ~encoding_name:"pending_operations"
          ~latest_encoding:(Version_2, version_2_encoding)
          ~old_encodings:[(Version_1, version_1_encoding)]

      let pending_operations path =
        Tezos_rpc.Service.get_service
          ~description:"List the prevalidated operations."
          ~query:pending_query
          ~output:pending_operations_encoding
          Tezos_rpc.Path.(path / "pending_operations")

      let ban_operation path =
        Tezos_rpc.Service.post_service
          ~description:
            "Remove an operation from the mempool if present. Also add it to \
             the set of banned operations to prevent it from being \
             fetched/processed/injected in the future. Note: If the baker has \
             already received the operation, then it's necessary to restart it \
             to flush the operation from it."
          ~query:Tezos_rpc.Query.empty
          ~input:Operation_hash.encoding
          ~output:unit
          Tezos_rpc.Path.(path / "ban_operation")

      let unban_operation path =
        Tezos_rpc.Service.post_service
          ~description:
            "Remove an operation from the set of banned operations (nothing \
             happens if it was not banned)."
          ~query:Tezos_rpc.Query.empty
          ~input:Operation_hash.encoding
          ~output:unit
          Tezos_rpc.Path.(path / "unban_operation")

      let unban_all_operations path =
        Tezos_rpc.Service.post_service
          ~description:"Clear the set of banned operations."
          ~query:Tezos_rpc.Query.empty
          ~input:Data_encoding.empty
          ~output:unit
          Tezos_rpc.Path.(path / "unban_all_operations")

      let monitor_operations_versions =
        mk_version_informations
          ~supported:[version_0; version_1]
          ~latest:Version_1
          ~default:Version_1
          ()

      let mempool_query =
        let open Tezos_rpc.Query in
        query
          (fun
            version
            validated
            refused
            outdated
            branch_refused
            branch_delayed
            validation_passes
          ->
            object
              method version = version

              method validated = validated

              method refused = refused

              method outdated = outdated

              method branch_refused = branch_refused

              method branch_delayed = branch_delayed

              method validation_passes = validation_passes
            end)
        |+ field
             "version"
             (version_arg monitor_operations_versions)
             monitor_operations_versions.default
             (fun t -> t#version)
        |+ field
             ~descr:"Include validated operations (set by default)"
             "validated"
             Tezos_rpc.Arg.bool
             true
             (fun t -> t#validated)
        |+ field
             ~descr:"Include refused operations"
             "refused"
             Tezos_rpc.Arg.bool
             false
             (fun t -> t#refused)
        |+ field
             ~descr:"Include outdated operations"
             "outdated"
             Tezos_rpc.Arg.bool
             false
             (fun t -> t#outdated)
        |+ field
             ~descr:"Include branch refused operations"
             "branch_refused"
             Tezos_rpc.Arg.bool
             false
             (fun t -> t#branch_refused)
        |+ field
             ~descr:"Include branch delayed operations (set by default)"
             "branch_delayed"
             Tezos_rpc.Arg.bool
             true
             (fun t -> t#branch_delayed)
        |+ multi_field
             ~descr:
               "Include operations filtered by validation pass (all by default)"
             "validation_pass"
             Tezos_rpc.Arg.int
             (fun t -> t#validation_passes)
        |> seal

      (* We extend the object so that the fields of 'next_operation'
         stay toplevel, for backward compatibility. *)

      let monitor_operations_encoding ~use_legacy_name =
        merge_objs
          (merge_objs
             (obj1 (req "hash" Operation_hash.encoding))
             (if use_legacy_name then
              next_operation_encoding_with_legacy_attestation_name
             else next_operation_encoding))
          (obj1 (dft "error" Tezos_rpc.Error.opt_encoding None))

      let processed_operation_encoding =
        encoding_versioning
          ~encoding_name:"monitor_operations"
          ~latest_encoding:
            ( Version_1,
              list (monitor_operations_encoding ~use_legacy_name:false) )
          ~old_encodings:
            [
              ( Version_0,
                list (monitor_operations_encoding ~use_legacy_name:true) );
            ]

      let monitor_operations path =
        Tezos_rpc.Service.get_service
          ~description:"Monitor the mempool operations."
          ~query:mempool_query
          ~output:processed_operation_encoding
          Tezos_rpc.Path.(path / "monitor_operations")

      let get_filter_query =
        let open Tezos_rpc.Query in
        query (fun include_default ->
            object
              method include_default = include_default
            end)
        |+ field
             ~descr:"Show fields equal to their default value (set by default)"
             "include_default"
             Tezos_rpc.Arg.bool
             true
             (fun t -> t#include_default)
        |> seal

      let get_filter path =
        Tezos_rpc.Service.get_service
          ~description:
            {|Get the configuration of the mempool's filter and bounds. Values of the form [ "21", "20" ] are rational numbers given as a numerator and a denominator, e.g. 21/20 = 1.05. The minimal_fees (in mutez), minimal_nanotez_per_gas_unit, and minimal_nanotez_per_byte are requirements that a manager operation must meet to be considered by the mempool. replace_by_fee_factor is how much better a manager operation must be to replace a previous valid operation **from the same manager** (both its fee and its fee/gas ratio must exceed the old operation's by at least this factor). max_operations and max_total_bytes are the bounds on respectively the number of valid operations in the mempool and the sum of their sizes in bytes.|}
          ~query:get_filter_query
          ~output:json
          Tezos_rpc.Path.(path / "filter")

      let set_filter path =
        Tezos_rpc.Service.post_service
          ~description:
            {|Set the configuration of the mempool's filter and bounds. **If any of the fields is absent from the input JSON, then it is set to the default value for this field (i.e. its value in the default configuration), even if it previously had a different value.** If the input JSON does not describe a valid configuration, then the configuration is left unchanged. This RPC also returns the new configuration of the mempool (which may differ from the input if the latter omits fields or is invalid). You may call [octez-client rpc get '/chains/main/mempool/filter?include_default=true'] to see an example of JSON describing a valid configuration. See the description of that RPC for details on each configurable value.|}
          ~query:Tezos_rpc.Query.empty
          ~input:json
          ~output:json
          Tezos_rpc.Path.(path / "filter")

      let request_operations_query =
        let open Tezos_rpc.Query in
        query (fun peer_id ->
            object
              method peer_id = peer_id
            end)
        |+ opt_field "peer_id" P2p_peer_id.rpc_arg (fun t -> t#peer_id)
        |> seal

      let request_operations path =
        Tezos_rpc.Service.post_service
          ~description:
            "Request the operations of our peers or a specific peer if \
             specified via a query parameter."
          ~input:Data_encoding.empty
          ~query:request_operations_query
          ~output:Data_encoding.empty
          Tezos_rpc.Path.(path / "request_operations")
    end

    let live_blocks =
      Tezos_rpc.Service.get_service
        ~description:
          "List the ancestors of the given block which, if referred to as the \
           branch in an operation header, are recent enough for that operation \
           to be included in the current block."
        ~query:Tezos_rpc.Query.empty
        ~output:Block_hash.Set.encoding
        Tezos_rpc.Path.(live_blocks_path open_root)
  end

  let path = Tezos_rpc.Path.prefix chain_path path

  let make_call0 s ctxt a b q p =
    let s = Tezos_rpc.Service.prefix path s in
    Tezos_rpc.Context.make_call2 s ctxt a b q p

  let make_call1 s ctxt a b c q p =
    let s = Tezos_rpc.Service.prefix path s in
    Tezos_rpc.Context.make_call3 s ctxt a b c q p

  let make_call2 s ctxt a b c d q p =
    let s = Tezos_rpc.Service.prefix path s in
    Tezos_rpc.Context.make_call s ctxt (((((), a), b), c), d) q p

  let hash ctxt =
    let f = make_call0 S.hash ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () ->
      match block with
      | `Hash (h, 0) -> Lwt.return_ok h
      | _ -> f chain block () ()

  let header ctxt =
    let f = make_call0 S.header ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

  let raw_header ctxt =
    let f = make_call0 S.raw_header ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

  let metadata ctxt ?(version = S.metadata_versions.default) =
    let open Lwt_result_syntax in
    let f = make_call0 S.metadata ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () ->
      let* (Version_0 | Version_1 | Version_2), res =
        f
          chain
          block
          (object
             method version = version
          end)
          ()
      in
      return res

  let metadata_hash ctxt =
    let f = make_call0 S.metadata_hash ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

  let protocols ctxt =
    let f = make_call0 S.protocols ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

  let resulting_context_hash ctxt =
    let f = make_call0 S.resulting_context_hash ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

  module Header = struct
    module S = S.Header

    let shell_header ctxt =
      let f = make_call0 S.shell_header ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

    let protocol_data ctxt =
      let f = make_call0 S.protocol_data ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

    let raw_protocol_data ctxt =
      let f = make_call0 S.raw_protocol_data ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()
  end

  module Operations = struct
    let operations ctxt ?(version = S.operations_versions.default)
        ?(force_metadata = false) ?metadata =
      let open Lwt_result_syntax in
      let f = make_call0 S.Operations.operations ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) () ->
        let* (Version_0 | Version_1 | Version_2), operations =
          f
            chain
            block
            (object
               method version = version

               method force_metadata = force_metadata

               method metadata = metadata
            end)
            ()
        in
        return operations

    let operations_in_pass ctxt ?(version = S.operations_versions.default)
        ?(force_metadata = false) ?metadata =
      let open Lwt_result_syntax in
      let f = make_call1 S.Operations.operations_in_pass ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) n ->
        let* (Version_0 | Version_1 | Version_2), operations =
          f
            chain
            block
            n
            (object
               method version = version

               method force_metadata = force_metadata

               method metadata = metadata
            end)
            ()
        in
        return operations

    let operation ctxt ?(version = S.operations_versions.default)
        ?(force_metadata = false) ?metadata =
      let open Lwt_result_syntax in
      let f = make_call2 S.Operations.operation ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) n m ->
        let* (Version_0 | Version_1 | Version_2), operation =
          f
            chain
            block
            n
            m
            (object
               method version = version

               method force_metadata = force_metadata

               method metadata = metadata
            end)
            ()
        in
        return operation
  end

  module Operation_hashes = struct
    module S = S.Operation_hashes

    let operation_hashes ctxt =
      let f = make_call0 S.operation_hashes ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

    let operation_hashes_in_pass ctxt =
      let f = make_call1 S.operation_hashes_in_pass ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) n -> f chain block n () ()

    let operation_hash ctxt =
      let f = make_call2 S.operation_hash ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) n m -> f chain block n m () ()
  end

  module Operation_metadata_hashes = struct
    module S = S.Operation_metadata_hashes

    let root ctxt =
      let f = make_call0 S.root ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

    let operation_metadata_hashes ctxt =
      let f = make_call0 S.operation_metadata_hashes ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()

    let operation_metadata_hashes_in_pass ctxt =
      let f = make_call1 S.operation_metadata_hashes_in_pass ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) n -> f chain block n () ()

    let operation_metadata_hash ctxt =
      let f = make_call2 S.operation_metadata_hash ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) n m -> f chain block n m () ()
  end

  module Context = struct
    module S = S.Context

    let read ctxt =
      let f = make_call1 S.read ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) ?depth path ->
        f
          chain
          block
          path
          (object
             method depth = depth
          end)
          ()

    let merkle_tree ctxt =
      let f = make_call1 S.merkle_tree_v2 ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) ?holey path ->
        f
          chain
          block
          path
          (object
             method holey = holey
          end)
          ()
  end

  module Helpers = struct
    module S = S.Helpers

    module Forge = struct
      module S = S.Forge

      let block_header ctxt =
        let f = make_call0 S.block_header ctxt in
        fun ?(chain = `Main) ?(block = `Head 0) header ->
          f chain block () header
    end

    module Preapply = struct
      module S = S.Preapply

      let block ctxt =
        let f = make_call0 S.block ctxt in
        fun ?(chain = `Main)
            ?(block = `Head 0)
            ?(sort = false)
            ?timestamp
            ~protocol_data
            operations ->
          f
            chain
            block
            (object
               method sort_operations = sort

               method timestamp = timestamp
            end)
            {protocol_data; operations}

      let operations ctxt ?(chain = `Main) ?(block = `Head 0)
          ?(version = S.preapply_versions.default) operations =
        let open Lwt_result_syntax in
        let* (Version_0 | Version_1 | Version_2), preapply_operations =
          make_call0
            S.operations
            ctxt
            chain
            block
            (object
               method version = version
            end)
            operations
        in
        return preapply_operations
    end

    let complete ctxt =
      let f = make_call1 S.complete ctxt in
      fun ?(chain = `Main) ?(block = `Head 0) s -> f chain block s () ()
  end

  let info ctxt ?(version = S.operations_versions.default)
      ?(force_metadata = false) ?metadata =
    let open Lwt_result_syntax in
    let f = make_call0 S.info ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () ->
      let* (Version_0 | Version_1 | Version_2), infos =
        f
          chain
          block
          (object
             method version = version

             method force_metadata = force_metadata

             method metadata = metadata
          end)
          ()
      in
      return infos

  module Mempool = struct
    type t = S.Mempool.t = {
      validated : (Operation_hash.t * Next_proto.operation) list;
      refused : (Next_proto.operation * error list) Operation_hash.Map.t;
      outdated : (Next_proto.operation * error list) Operation_hash.Map.t;
      branch_refused : (Next_proto.operation * error list) Operation_hash.Map.t;
      branch_delayed : (Next_proto.operation * error list) Operation_hash.Map.t;
      unprocessed : Next_proto.operation Operation_hash.Map.t;
    }

    let pending_operations ctxt ?(chain = `Main)
        ?(version = S.Mempool.pending_operations_versions.default)
        ?(validated = true) ?(branch_delayed = true) ?(branch_refused = true)
        ?(refused = true) ?(outdated = true) ?(validation_passes = []) () =
      let open Lwt_result_syntax in
      let* _version, pending_operations =
        Tezos_rpc.Context.make_call1
          (S.Mempool.pending_operations (mempool_path chain_path))
          ctxt
          chain
          (object
             method version = version

             method validated = validated

             method refused = refused

             method outdated = outdated

             method branch_refused = branch_refused

             method branch_delayed = branch_delayed

             method validation_passes = validation_passes
          end)
          ()
      in
      return pending_operations

    let ban_operation ctxt ?(chain = `Main) op_hash =
      let s = S.Mempool.ban_operation (mempool_path chain_path) in
      Tezos_rpc.Context.make_call1 s ctxt chain () op_hash

    let unban_operation ctxt ?(chain = `Main) op_hash =
      let s = S.Mempool.unban_operation (mempool_path chain_path) in
      Tezos_rpc.Context.make_call1 s ctxt chain () op_hash

    let unban_all_operations ctxt ?(chain = `Main) () =
      let s = S.Mempool.unban_all_operations (mempool_path chain_path) in
      Tezos_rpc.Context.make_call1 s ctxt chain () ()

    let monitor_operations ctxt ?(chain = `Main)
        ?(version = S.Mempool.monitor_operations_versions.default)
        ?(validated = true) ?(branch_delayed = true) ?(branch_refused = false)
        ?(refused = false) ?(outdated = false) ?(validation_passes = []) () =
      let open Lwt_result_syntax in
      let s = S.Mempool.monitor_operations (mempool_path chain_path) in
      let* stream, stopper =
        Tezos_rpc.Context.make_streamed_call
          s
          ctxt
          ((), chain)
          (object
             method version = version

             method validated = validated

             method refused = refused

             method outdated = outdated

             method branch_refused = branch_refused

             method branch_delayed = branch_delayed

             method validation_passes = validation_passes
          end)
          ()
      in
      return
        ( Lwt_stream.map
            (fun ( ( Version_0 | Version_1
                   | Version_2
                     (* The same [version] type is used for versioning all the
                        RPC. Even though this version is not supported for this
                        RPC we need to handle it. We rely on the supported
                        version list to fail at parsing for this version *) ),
                   operations ) -> operations)
            stream,
          stopper )

    let request_operations ctxt ?(chain = `Main) ?peer_id () =
      let s = S.Mempool.request_operations (mempool_path chain_path) in
      Tezos_rpc.Context.make_call1
        s
        ctxt
        chain
        (object
           method peer_id = peer_id
        end)
        ()
  end

  let live_blocks ctxt =
    let f = make_call0 S.live_blocks ctxt in
    fun ?(chain = `Main) ?(block = `Head 0) () -> f chain block () ()
end

module Fake_protocol = struct
  let hash = Protocol_hash.zero

  type block_header_data = unit

  let block_header_data_encoding = Data_encoding.empty

  type block_header_metadata = unit

  let block_header_metadata_encoding_with_legacy_attestation_name =
    Data_encoding.empty

  let block_header_metadata_encoding = Data_encoding.empty

  type operation_data = unit

  type operation_receipt = unit

  type operation = {
    shell : Operation.shell_header;
    protocol_data : operation_data;
  }

  let operation_data_encoding = Data_encoding.empty

  let operation_data_encoding_with_legacy_attestation_name =
    operation_data_encoding

  let operation_receipt_encoding = Data_encoding.empty

  let operation_receipt_encoding_with_legacy_attestation_name =
    operation_receipt_encoding

  let operation_data_and_receipt_encoding =
    Data_encoding.conv
      (fun ((), ()) -> ())
      (fun () -> ((), ()))
      Data_encoding.empty

  let operation_data_and_receipt_encoding_with_legacy_attestation_name =
    operation_data_and_receipt_encoding
end

module Empty = Make (Fake_protocol) (Fake_protocol)

let () =
  Printexc.register_printer (function
      | ( Json_schema.Cannot_parse _ | Json_schema.Dangling_reference _
        | Json_schema.Bad_reference _ | Json_schema.Unexpected _
        | Json_schema.Duplicate_definition _ ) as exn ->
          Some
            (Format.asprintf "%a" (fun ppf -> Json_schema.print_error ppf) exn)
      | _ -> None)

let protocols = Empty.protocols
OCaml

Innovation. Community. Security.