Source file RPC.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
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
open Protocol
open Environment
open Alpha_context
type version = Version_0 | Version_1
let string_of_version = function Version_0 -> "0" | Version_1 -> "1"
let version_of_string = function
| "0" -> Ok Version_0
| "1" -> Ok Version_1
| _ -> Error "Cannot parse version (supported versions \"0\" and \"1\")"
let default_operations_version = Version_1
let version_arg =
let open RPC_arg in
make
~descr:
"Supported RPC versions are version '1' (default) that will output \
\"attestation\" in the \"kind\" field and version '0' (deprecated) that \
will output \"endorsement\""
~name:"version"
~destruct:version_of_string
~construct:string_of_version
()
let encoding_versioning ~encoding_name ~latest_encoding ~old_encodings =
let open Data_encoding in
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))
(** The assumed number of blocks between operation-creation time and
the actual time when the operation is included in a block. *)
let default_operation_inclusion_latency = 3
let path = RPC_path.(open_root / "helpers")
let elab_conf =
Script_ir_translator_config.make
~keep_extra_types_for_interpreter_logging:true
module Registration = struct
let patched_services =
ref (RPC_directory.empty : Updater.rpc_context RPC_directory.t)
let register0_fullctxt ~chunked s f =
let open Lwt_result_syntax in
patched_services :=
RPC_directory.register ~chunked !patched_services s (fun ctxt q i ->
let* ctxt = Services_registration.rpc_init ctxt `Head_level in
f ctxt q i)
let register0 ~chunked s f =
register0_fullctxt ~chunked s (fun {context; _} -> f context)
let register0_fullctxt_successor_level ~chunked s f =
let open Lwt_result_syntax in
patched_services :=
RPC_directory.register ~chunked !patched_services s (fun ctxt q i ->
let mode =
if q#successor_level then `Successor_level else `Head_level
in
let* ctxt = Services_registration.rpc_init ctxt mode in
f ctxt q i)
let register0_successor_level ~chunked s f =
register0_fullctxt_successor_level ~chunked s (fun {context; _} ->
f context)
let register0_noctxt ~chunked s f =
patched_services :=
RPC_directory.register ~chunked !patched_services s (fun _ q i -> f q i)
let opt_register0_fullctxt ~chunked s f =
let open Lwt_result_syntax in
patched_services :=
RPC_directory.opt_register ~chunked !patched_services s (fun ctxt q i ->
let* ctxt = Services_registration.rpc_init ctxt `Head_level in
f ctxt q i)
let opt_register0 ~chunked s f =
opt_register0_fullctxt ~chunked s (fun {context; _} -> f context)
let register1_fullctxt ~chunked s f =
let open Lwt_result_syntax in
patched_services :=
RPC_directory.register
~chunked
!patched_services
s
(fun (ctxt, arg) q i ->
let* ctxt = Services_registration.rpc_init ctxt `Head_level in
f ctxt arg q i)
let opt_register1_fullctxt ~chunked s f =
let open Lwt_result_syntax in
patched_services :=
RPC_directory.opt_register
~chunked
!patched_services
s
(fun (ctxt, arg) q i ->
let* ctxt = Services_registration.rpc_init ctxt `Head_level in
f ctxt arg q i)
let register1 ~chunked s f =
register1_fullctxt ~chunked s (fun {context; _} x -> f context x)
let opt_register1 ~chunked s f =
opt_register1_fullctxt ~chunked s (fun {context; _} x -> f context x)
let register2_fullctxt ~chunked s f =
let open Lwt_result_syntax in
patched_services :=
RPC_directory.register
~chunked
!patched_services
s
(fun ((ctxt, arg1), arg2) q i ->
let* ctxt = Services_registration.rpc_init ctxt `Head_level in
f ctxt arg1 arg2 q i)
let register2 ~chunked s f =
register2_fullctxt ~chunked s (fun {context; _} a1 a2 q i ->
f context a1 a2 q i)
let register3_fullctxt ~chunked s f =
let open Lwt_result_syntax in
patched_services :=
RPC_directory.register
~chunked
!patched_services
s
(fun (((ctxt, arg1), arg2), arg3) q i ->
let* ctxt = Services_registration.rpc_init ctxt `Head_level in
f ctxt arg1 arg2 arg3 q i)
let register3 ~chunked s f =
register3_fullctxt ~chunked s (fun {context; _} a1 a2 a3 q i ->
f context a1 a2 a3 q i)
end
let unparsing_mode_encoding =
let open Script_ir_unparser in
let open Data_encoding in
union
~tag_size:`Uint8
[
case
(Tag 0)
~title:"Readable"
(constant "Readable")
(function Readable -> Some () | Optimized | Optimized_legacy -> None)
(fun () -> Readable);
case
(Tag 1)
~title:"Optimized"
(constant "Optimized")
(function Optimized -> Some () | Readable | Optimized_legacy -> None)
(fun () -> Optimized);
case
(Tag 2)
~title:"Optimized_legacy"
(constant "Optimized_legacy")
(function Optimized_legacy -> Some () | Readable | Optimized -> None)
(fun () -> Optimized_legacy);
]
module Scripts = struct
module S = struct
open Data_encoding
let path = RPC_path.(path / "scripts")
type other_contract_description = {
address : Contract_hash.t;
ty : Script.expr;
}
let other_contracts_encoding =
list
(conv
(fun {address; ty} -> (address, ty))
(fun (address, ty) -> {address; ty})
(obj2
(req "address" Contract_hash.encoding)
(req "type" Script.expr_encoding)))
let =
list
(conv
(fun {id; kty; vty; items} -> (id, kty, vty, items))
(fun (id, kty, vty, items) -> {id; kty; vty; items})
(obj4
(req "id" Big_map.Id.encoding)
(req "key_type" Script.expr_encoding)
(req "val_type" Script.expr_encoding)
(req "map_literal" Script.expr_encoding)))
let run_code_input_encoding =
merge_objs
(obj10
(req "script" Script.expr_encoding)
(req "storage" Script.expr_encoding)
(req "input" Script.expr_encoding)
(req "amount" Tez.encoding)
(opt "balance" Tez.encoding)
(req "chain_id" Chain_id.encoding)
(opt "source" Contract.encoding)
(opt "payer" Contract.implicit_encoding)
(opt "self" Contract.originated_encoding)
(dft "entrypoint" Entrypoint.simple_encoding Entrypoint.default))
(obj6
(opt "unparsing_mode" unparsing_mode_encoding)
(opt "gas" Gas.Arith.z_integral_encoding)
(opt "now" Script_timestamp.encoding)
(opt "level" Script_int.n_encoding)
(opt "other_contracts" other_contracts_encoding)
(opt "extra_big_maps" extra_big_maps_encoding))
let run_code_output_encoding =
conv
(fun (storage, operations, lazy_storage_diff) ->
(storage, operations, lazy_storage_diff))
(fun (storage, operations, lazy_storage_diff) ->
(storage, operations, lazy_storage_diff))
(obj3
(req "storage" Script.expr_encoding)
(req
"operations"
(list Apply_internal_results.internal_operation_encoding))
(opt "lazy_storage_diff" Lazy_storage.encoding))
let trace_code_input_encoding = run_code_input_encoding
let trace_encoding : Script_typed_ir.execution_trace encoding =
def "scripted.trace" @@ list
@@ obj3
(req "location" Script.location_encoding)
(req "gas" Gas.Arith.z_fp_encoding)
(req "stack" (list Script.expr_encoding))
let trace_code_output_encoding =
conv
(fun (storage, operations, trace, lazy_storage_diff) ->
(storage, operations, trace, lazy_storage_diff))
(fun (storage, operations, trace, lazy_storage_diff) ->
(storage, operations, trace, lazy_storage_diff))
(obj4
(req "storage" Script.expr_encoding)
(req
"operations"
(list Apply_internal_results.internal_operation_encoding))
(req "trace" trace_encoding)
(opt "lazy_storage_diff" Lazy_storage.encoding))
let stack_encoding =
list
(obj2
(req "type" Script.expr_encoding)
(req "val" Script.expr_encoding))
let run_instr_input_encoding =
merge_objs
(obj10
(req "input" stack_encoding)
(req "code" Script.expr_encoding)
(req "chain_id" Chain_id.encoding)
(opt "gas" Gas.Arith.z_integral_encoding)
(opt "now" Script_timestamp.encoding)
(opt "level" Script_int.n_encoding)
(opt "sender" Contract.encoding)
(opt "source" Contract.implicit_encoding)
(opt "self" Contract.originated_encoding)
(opt "parameter" Script.expr_encoding))
(obj6
(req "amount" Tez.encoding)
(opt "balance" Tez.encoding)
(opt "other_contracts" other_contracts_encoding)
(opt "big_maps" extra_big_maps_encoding)
(opt "unparsing_mode" unparsing_mode_encoding)
(dft "legacy" bool false))
let run_instr_output_encoding =
obj2 (req "output" stack_encoding) (req "gas" Gas.encoding)
let run_tzip4_view_encoding =
let open Data_encoding in
merge_objs
(obj10
(req "contract" Contract.originated_encoding)
(req "entrypoint" Entrypoint.simple_encoding)
(req "input" Script.expr_encoding)
(req "chain_id" Chain_id.encoding)
(opt "source" Contract.encoding)
(opt "payer" Contract.implicit_encoding)
(opt "gas" Gas.Arith.z_integral_encoding)
(req "unparsing_mode" unparsing_mode_encoding)
(opt "now" Script_timestamp.encoding)
(opt "level" Script_int.n_encoding))
(obj2
(opt "other_contracts" other_contracts_encoding)
(opt "extra_big_maps" extra_big_maps_encoding))
let run_script_view_encoding =
let open Data_encoding in
merge_objs
(obj10
(req "contract" Contract.originated_encoding)
(req "view" (string Plain))
(req "input" Script.expr_encoding)
(dft "unlimited_gas" bool false)
(req "chain_id" Chain_id.encoding)
(opt "source" Contract.encoding)
(opt "payer" Contract.implicit_encoding)
(opt "gas" Gas.Arith.z_integral_encoding)
(req "unparsing_mode" unparsing_mode_encoding)
(opt "now" Script_timestamp.encoding))
(obj3
(opt "level" Script_int.n_encoding)
(opt "other_contracts" other_contracts_encoding)
(opt "extra_big_maps" extra_big_maps_encoding))
let normalize_stack_input_encoding =
obj5
(req "input" stack_encoding)
(req "unparsing_mode" unparsing_mode_encoding)
(dft "legacy" bool false)
(opt "other_contracts" other_contracts_encoding)
(opt "extra_big_maps" extra_big_maps_encoding)
let normalize_stack_output_encoding = obj1 (req "output" stack_encoding)
let run_code =
RPC_service.post_service
~description:"Run a Michelson script in the current context"
~query:RPC_query.empty
~input:run_code_input_encoding
~output:run_code_output_encoding
RPC_path.(path / "run_code")
let trace_code =
RPC_service.post_service
~description:
"Run a Michelson script in the current context, keeping a trace"
~query:RPC_query.empty
~input:trace_code_input_encoding
~output:trace_code_output_encoding
RPC_path.(path / "trace_code")
let run_tzip4_view =
RPC_service.post_service
~description:
"Simulate a call to a view following the TZIP-4 standard. See \
https://gitlab.com/tezos/tzip/-/blob/master/proposals/tzip-4/tzip-4.md#view-entrypoints."
~input:run_tzip4_view_encoding
~output:(obj1 (req "data" Script.expr_encoding))
~query:RPC_query.empty
RPC_path.(path / "run_view")
let run_script_view =
RPC_service.post_service
~description:"Simulate a call to a michelson view"
~input:run_script_view_encoding
~output:(obj1 (req "data" Script.expr_encoding))
~query:RPC_query.empty
RPC_path.(path / "run_script_view")
let run_instr =
RPC_service.post_service
~description:"Run a single Michelson instruction"
~query:RPC_query.empty
~input:run_instr_input_encoding
~output:run_instr_output_encoding
RPC_path.(path / "run_instruction")
let typecheck_code =
RPC_service.post_service
~description:"Typecheck a piece of code in the current context"
~query:RPC_query.empty
~input:
(obj4
(req "program" Script.expr_encoding)
(opt "gas" Gas.Arith.z_integral_encoding)
(dft "legacy" bool false)
(dft "show_types" bool true))
~output:
(obj2
(req "type_map" Script_tc_errors_registration.type_map_enc)
(req "gas" Gas.encoding))
RPC_path.(path / "typecheck_code")
let script_size =
RPC_service.post_service
~description:"Compute the size of a script in the current context"
~query:RPC_query.empty
~input:
(obj4
(req "program" Script.expr_encoding)
(req "storage" Script.expr_encoding)
(opt "gas" Gas.Arith.z_integral_encoding)
(dft "legacy" bool false))
~output:(obj1 (req "script_size" int31))
RPC_path.(path / "script_size")
let typecheck_data =
RPC_service.post_service
~description:
"Check that some data expression is well formed and of a given type \
in the current context"
~query:RPC_query.empty
~input:
(obj4
(req "data" Script.expr_encoding)
(req "type" Script.expr_encoding)
(opt "gas" Gas.Arith.z_integral_encoding)
(dft "legacy" bool false))
~output:(obj1 (req "gas" Gas.encoding))
RPC_path.(path / "typecheck_data")
let pack_data =
RPC_service.post_service
~description:
"Computes the serialized version of some data expression using the \
same algorithm as script instruction PACK"
~input:
(obj3
(req "data" Script.expr_encoding)
(req "type" Script.expr_encoding)
(opt "gas" Gas.Arith.z_integral_encoding))
~output:(obj2 (req "packed" (bytes Hex)) (req "gas" Gas.encoding))
~query:RPC_query.empty
RPC_path.(path / "pack_data")
let normalize_data =
RPC_service.post_service
~description:
"Normalizes some data expression using the requested unparsing mode"
~input:
(obj6
(req "data" Script.expr_encoding)
(req "type" Script.expr_encoding)
(req "unparsing_mode" unparsing_mode_encoding)
(dft "legacy" bool false)
(opt "other_contracts" other_contracts_encoding)
(opt "extra_big_maps" extra_big_maps_encoding))
~output:(obj1 (req "normalized" Script.expr_encoding))
~query:RPC_query.empty
RPC_path.(path / "normalize_data")
let normalize_stack =
RPC_service.post_service
~description:
"Normalize a Michelson stack using the requested unparsing mode"
~query:RPC_query.empty
~input:normalize_stack_input_encoding
~output:normalize_stack_output_encoding
RPC_path.(path / "normalize_stack")
let normalize_script =
RPC_service.post_service
~description:
"Normalizes a Michelson script using the requested unparsing mode"
~input:
(obj2
(req "script" Script.expr_encoding)
(req "unparsing_mode" unparsing_mode_encoding))
~output:(obj1 (req "normalized" Script.expr_encoding))
~query:RPC_query.empty
RPC_path.(path / "normalize_script")
let normalize_type =
RPC_service.post_service
~description:
"Normalizes some Michelson type by expanding `pair a b c` as `pair a \
(pair b c)"
~input:(obj1 (req "type" Script.expr_encoding))
~output:(obj1 (req "normalized" Script.expr_encoding))
~query:RPC_query.empty
RPC_path.(path / "normalize_type")
let run_operation_query =
let open RPC_query in
query (fun version ->
object
method version = version
end)
|+ field "version" version_arg default_operations_version (fun t ->
t#version)
|> seal
let operations_encodings =
union
[
case
~title:"operations_encoding"
(Tag 0)
Operation.encoding
Option.some
Fun.id;
case
~title:"operations_encoding_with_legacy_attestation_name"
Json_only
Operation.encoding_with_legacy_attestation_name
Option.some
Fun.id;
]
let run_operation_output_encoding =
encoding_versioning
~encoding_name:"run_operation_output"
~latest_encoding:
(Version_1, Apply_results.operation_data_and_metadata_encoding)
~old_encodings:
[
( Version_0,
Apply_results
.operation_data_and_metadata_encoding_with_legacy_attestation_name
);
]
let run_operation =
RPC_service.post_service
~description:
"Run an operation with the context of the given block and without \
signature checks. Return the operation application result, \
including the consumed gas. This RPC does not support consensus \
operations."
~query:run_operation_query
~input:
(obj2
(req "operation" operations_encodings)
(req "chain_id" Chain_id.encoding))
~output:run_operation_output_encoding
RPC_path.(path / "run_operation")
let simulate_query =
let open RPC_query in
query (fun version successor_level ->
object
method version = version
method successor_level = successor_level
end)
|+ field "version" version_arg default_operations_version (fun t ->
t#version)
|+ flag
~descr:
"If true, the simulation is done on the successor level of the \
current context."
"successor_level"
(fun t -> t#successor_level)
|> seal
let simulate_operation =
RPC_service.post_service
~description:
"Simulate running an operation at some future moment (based on the \
number of blocks given in the `latency` argument), and return the \
operation application result. The result is the same as \
run_operation except for the consumed gas, which depends on the \
contents of the cache at that future moment. This RPC estimates \
future gas consumption by trying to predict the state of the cache \
using some heuristics."
~query:simulate_query
~input:
(obj4
(opt "blocks_before_activation" int32)
(req "operation" operations_encodings)
(req "chain_id" Chain_id.encoding)
(dft "latency" int16 default_operation_inclusion_latency))
~output:run_operation_output_encoding
RPC_path.(path / "simulate_operation")
let entrypoint_type =
RPC_service.post_service
~description:"Return the type of the given entrypoint"
~query:RPC_query.empty
~input:
(obj2
(req "script" Script.expr_encoding)
(dft "entrypoint" Entrypoint.simple_encoding Entrypoint.default))
~output:(obj1 (req "entrypoint_type" Script.expr_encoding))
RPC_path.(path / "entrypoint")
let list_entrypoints =
RPC_service.post_service
~description:"Return the list of entrypoints of the given script"
~query:RPC_query.empty
~input:(obj1 (req "script" Script.expr_encoding))
~output:
(obj2
(dft
"unreachable"
(Data_encoding.list
(obj1
(req
"path"
(Data_encoding.list
Michelson_v1_primitives.prim_encoding))))
[])
(req "entrypoints" (assoc Script.expr_encoding)))
RPC_path.(path / "entrypoints")
end
module type UNPARSING_MODE = sig
val unparsing_mode : Script_ir_unparser.unparsing_mode
end
module Traced_interpreter (Unparsing_mode : UNPARSING_MODE) = struct
type log_element =
| Log :
context
* Script.location
* ('a * 's)
* ('a, 's) Script_typed_ir.stack_ty
-> log_element
let unparse_stack ctxt (stack, stack_ty) =
let open Lwt_result_syntax in
let ctxt = Gas.set_unlimited ctxt in
let rec unparse_stack :
type a s.
(a, s) Script_typed_ir.stack_ty * (a * s) ->
Script.expr list Environment.Error_monad.tzresult Lwt.t = function
| Bot_t, (EmptyCell, EmptyCell) -> return_nil
| Item_t (ty, rest_ty), (v, rest) ->
let* data, _ctxt =
Script_ir_translator.unparse_data
ctxt
Unparsing_mode.unparsing_mode
ty
v
in
let+ rest = unparse_stack (rest_ty, rest) in
data :: rest
in
unparse_stack (stack_ty, stack)
let trace_logger ctxt : Script_typed_ir.logger =
let open Lwt_result_syntax in
Script_interpreter_logging.make
(module struct
let log : log_element list ref = ref []
let log_interp _ ctxt loc sty stack =
log := Log (ctxt, loc, stack, sty) :: !log
let log_entry _ _ctxt _loc _sty _stack = ()
let log_exit _ ctxt loc sty stack =
log := Log (ctxt, loc, stack, sty) :: !log
let log_control _ = ()
let get_log () =
let+ _ctxt, res =
List.fold_left_es
(fun (old_ctxt, l) (Log (ctxt, loc, stack, stack_ty)) ->
let consumed_gas = Gas.consumed ~since:old_ctxt ~until:ctxt in
let+ stack =
Environment.Error_monad.trace
Plugin_errors.Cannot_serialize_log
(unparse_stack ctxt (stack, stack_ty))
in
(ctxt, (loc, consumed_gas, stack) :: l))
(ctxt, [])
(List.rev !log)
in
Some (List.rev res)
end)
let execute ctxt step_constants ~script ~entrypoint ~parameter =
let open Lwt_result_syntax in
let logger = trace_logger ctxt in
let* res =
Script_interpreter.execute
~logger
~cached_script:None
ctxt
Unparsing_mode.unparsing_mode
step_constants
~script
~entrypoint
~parameter
~internal:true
in
let+ trace = logger.get_log () in
let trace = Option.value ~default:[] trace in
(res, trace)
end
let typecheck_data :
legacy:bool ->
context ->
Script.expr * Script.expr ->
context Environment.Error_monad.tzresult Lwt.t =
let open Lwt_result_syntax in
fun ~legacy ctxt (data, exp_ty) ->
let*? Ex_ty exp_ty, ctxt =
Environment.Error_monad.record_trace
(Script_tc_errors.Ill_formed_type (None, exp_ty, 0))
(Script_ir_translator.parse_passable_ty
ctxt
~legacy
(Micheline.root exp_ty))
in
let+ _, ctxt =
Environment.Error_monad.trace_eval
(fun () ->
let exp_ty = Script_ir_unparser.serialize_ty_for_error exp_ty in
Script_tc_errors.Ill_typed_data (None, data, exp_ty))
(let allow_forged_tickets = true in
let allow_forged_lazy_storage_id =
true
in
Script_ir_translator.parse_data
ctxt
~elab_conf:(elab_conf ~legacy ())
~allow_forged_tickets
~allow_forged_lazy_storage_id
exp_ty
(Micheline.root data))
in
ctxt
module Unparse_types = struct
open Micheline
open Michelson_v1_primitives
open Script_typed_ir
let unparse_memo_size ~loc memo_size =
let z = Alpha_context.Sapling.Memo_size.unparse_to_z memo_size in
Int (loc, z)
let rec unparse_ty :
type a ac loc.
loc:loc -> (a, ac) ty -> (loc, Script.prim) Micheline.node =
fun ~loc ty ->
let return (name, args, annot) = Prim (loc, name, args, annot) in
match ty with
| Unit_t -> return (T_unit, [], [])
| Int_t -> return (T_int, [], [])
| Nat_t -> return (T_nat, [], [])
| Signature_t -> return (T_signature, [], [])
| String_t -> return (T_string, [], [])
| Bytes_t -> return (T_bytes, [], [])
| Mutez_t -> return (T_mutez, [], [])
| Bool_t -> return (T_bool, [], [])
| Key_hash_t -> return (T_key_hash, [], [])
| Key_t -> return (T_key, [], [])
| Timestamp_t -> return (T_timestamp, [], [])
| Address_t -> return (T_address, [], [])
| Operation_t -> return (T_operation, [], [])
| Chain_id_t -> return (T_chain_id, [], [])
| Never_t -> return (T_never, [], [])
| Bls12_381_g1_t -> return (T_bls12_381_g1, [], [])
| Bls12_381_g2_t -> return (T_bls12_381_g2, [], [])
| Bls12_381_fr_t -> return (T_bls12_381_fr, [], [])
| Contract_t (ut, _meta) ->
let t = unparse_ty ~loc ut in
return (T_contract, [t], [])
| Pair_t (utl, utr, _meta, _) ->
let annot = [] in
let tl = unparse_ty ~loc utl in
let tr = unparse_ty ~loc utr in
return (T_pair, [tl; tr], annot)
| Or_t (utl, utr, _meta, _) ->
let annot = [] in
let tl = unparse_ty ~loc utl in
let tr = unparse_ty ~loc utr in
return (T_or, [tl; tr], annot)
| Lambda_t (uta, utr, _meta) ->
let ta = unparse_ty ~loc uta in
let tr = unparse_ty ~loc utr in
return (T_lambda, [ta; tr], [])
| Option_t (ut, _meta, _) ->
let annot = [] in
let ut = unparse_ty ~loc ut in
return (T_option, [ut], annot)
| List_t (ut, _meta) ->
let t = unparse_ty ~loc ut in
return (T_list, [t], [])
| Ticket_t (ut, _meta) ->
let t = unparse_ty ~loc ut in
return (T_ticket, [t], [])
| Set_t (ut, _meta) ->
let t = unparse_ty ~loc ut in
return (T_set, [t], [])
| Map_t (uta, utr, _meta) ->
let ta = unparse_ty ~loc uta in
let tr = unparse_ty ~loc utr in
return (T_map, [ta; tr], [])
| Big_map_t (uta, utr, _meta) ->
let ta = unparse_ty ~loc uta in
let tr = unparse_ty ~loc utr in
return (T_big_map, [ta; tr], [])
| Sapling_transaction_t memo_size ->
return (T_sapling_transaction, [unparse_memo_size ~loc memo_size], [])
| Sapling_transaction_deprecated_t memo_size ->
return
( T_sapling_transaction_deprecated,
[unparse_memo_size ~loc memo_size],
[] )
| Sapling_state_t memo_size ->
return (T_sapling_state, [unparse_memo_size ~loc memo_size], [])
| Chest_t -> return (T_chest, [], [])
| Chest_key_t -> return (T_chest_key, [], [])
end
module Normalize_stack = struct
type ex_stack =
| Ex_stack : ('a, 's) Script_typed_ir.stack_ty * 'a * 's -> ex_stack
let rec parse_stack :
context ->
legacy:bool ->
(Script.node * Script.node) list ->
(ex_stack * context) Environment.Error_monad.tzresult Lwt.t =
let open Lwt_result_syntax in
fun ctxt ~legacy l ->
match l with
| [] -> return (Ex_stack (Bot_t, EmptyCell, EmptyCell), ctxt)
| (ty_node, data_node) :: l ->
let*? Ex_ty ty, ctxt =
Script_ir_translator.parse_ty
ctxt
~legacy
~allow_lazy_storage:true
~allow_operation:true
~allow_contract:true
~allow_ticket:true
ty_node
in
let elab_conf = elab_conf ~legacy () in
let* x, ctxt =
Script_ir_translator.parse_data
ctxt
~elab_conf
~allow_forged_tickets:true
~allow_forged_lazy_storage_id:true
ty
data_node
in
let+ Ex_stack (sty, y, st), ctxt = parse_stack ctxt ~legacy l in
(Ex_stack (Item_t (ty, sty), x, (y, st)), ctxt)
let rec unparse_stack :
type a s.
context ->
Script_ir_unparser.unparsing_mode ->
(a, s) Script_typed_ir.stack_ty ->
a ->
s ->
((Script.expr * Script.expr) list * context)
Environment.Error_monad.tzresult
Lwt.t =
let open Lwt_result_syntax in
let loc = Micheline.dummy_location in
fun ctxt unparsing_mode sty x st ->
match (sty, x, st) with
| Bot_t, EmptyCell, EmptyCell -> return ([], ctxt)
| Item_t (ty, sty), x, (y, st) ->
let*? ty_node, ctxt = Script_ir_unparser.unparse_ty ~loc ctxt ty in
let* data_node, ctxt =
Script_ir_translator.unparse_data ctxt unparsing_mode ty x
in
let+ l, ctxt = unparse_stack ctxt unparsing_mode sty y st in
((Micheline.strip_locations ty_node, data_node) :: l, ctxt)
end
let rec pp_instr_name :
type a b c d.
Format.formatter -> (a, b, c, d) Script_typed_ir.kinstr -> unit =
let open Script_typed_ir in
let open Format in
fun fmt -> function
| IDrop _ -> pp_print_string fmt "DROP"
| IDup _ -> pp_print_string fmt "DUP"
| ISwap _ -> pp_print_string fmt "SWAP"
| IPush _ -> pp_print_string fmt "PUSH"
| IUnit _ -> pp_print_string fmt "UNIT"
| ICons_pair _ -> pp_print_string fmt "PAIR"
| ICar _ -> pp_print_string fmt "CAR"
| ICdr _ -> pp_print_string fmt "CDR"
| IUnpair _ -> pp_print_string fmt "UNPAIR"
| ICons_some _ -> pp_print_string fmt "SOME"
| ICons_none _ -> pp_print_string fmt "NONE"
| IIf_none _ -> pp_print_string fmt "IF_NONE"
| IOpt_map _ -> pp_print_string fmt "MAP"
| ICons_left _ -> pp_print_string fmt "LEFT"
| ICons_right _ -> pp_print_string fmt "RIGHT"
| IIf_left _ -> pp_print_string fmt "IF_LEFT"
| ICons_list _ -> pp_print_string fmt "CONS"
| INil _ -> pp_print_string fmt "NIL"
| IIf_cons _ -> pp_print_string fmt "IF_CONS"
| IList_map _ -> pp_print_string fmt "MAP"
| IList_iter _ -> pp_print_string fmt "ITER"
| IList_size _ -> pp_print_string fmt "SIZE"
| IEmpty_set _ -> pp_print_string fmt "EMPTY_SET"
| ISet_iter _ -> pp_print_string fmt "ITER"
| ISet_mem _ -> pp_print_string fmt "MEM"
| ISet_update _ -> pp_print_string fmt "UPDATE"
| ISet_size _ -> pp_print_string fmt "SIZE"
| IEmpty_map _ -> pp_print_string fmt "EMPTY_MAP"
| IMap_map _ -> pp_print_string fmt "MAP"
| IMap_iter _ -> pp_print_string fmt "ITER"
| IMap_mem _ -> pp_print_string fmt "MEM"
| IMap_get _ -> pp_print_string fmt "GET"
| IMap_update _ -> pp_print_string fmt "UPDATE"
| IMap_get_and_update _ -> pp_print_string fmt "GET_AND_UPDATE"
| IMap_size _ -> pp_print_string fmt "SIZE"
| IEmpty_big_map _ -> pp_print_string fmt "EMPTY_BIG_MAP"
| IBig_map_mem _ -> pp_print_string fmt "MEM"
| IBig_map_get _ -> pp_print_string fmt "GET"
| IBig_map_update _ -> pp_print_string fmt "UPDATE"
| IBig_map_get_and_update _ -> pp_print_string fmt "GET_AND_UPDATE"
| IConcat_string _ -> pp_print_string fmt "CONCAT"
| IConcat_string_pair _ -> pp_print_string fmt "CONCAT"
| ISlice_string _ -> pp_print_string fmt "SLICE"
| IString_size _ -> pp_print_string fmt "SIZE"
| IConcat_bytes _ -> pp_print_string fmt "CONCAT"
| IConcat_bytes_pair _ -> pp_print_string fmt "CONCAT"
| ISlice_bytes _ -> pp_print_string fmt "SLICE"
| IBytes_size _ -> pp_print_string fmt "SIZE"
| IBytes_nat _ -> pp_print_string fmt "BYTES"
| INat_bytes _ -> pp_print_string fmt "NAT"
| IBytes_int _ -> pp_print_string fmt "BYTES"
| IInt_bytes _ -> pp_print_string fmt "INT"
| IAdd_seconds_to_timestamp _ -> pp_print_string fmt "ADD"
| IAdd_timestamp_to_seconds _ -> pp_print_string fmt "ADD"
| ISub_timestamp_seconds _ -> pp_print_string fmt "SUB"
| IDiff_timestamps _ -> pp_print_string fmt "DIFF"
| IAdd_tez _ -> pp_print_string fmt "ADD"
| ISub_tez _ -> pp_print_string fmt "SUB_MUTEZ"
| ISub_tez_legacy _ -> pp_print_string fmt "SUB"
| IMul_teznat _ | IMul_nattez _ -> pp_print_string fmt "MUL"
| IEdiv_teznat _ -> pp_print_string fmt "EDIV"
| IEdiv_tez _ -> pp_print_string fmt "EDIV"
| IOr _ -> pp_print_string fmt "OR"
| IAnd _ -> pp_print_string fmt "AND"
| IXor _ -> pp_print_string fmt "XOR"
| INot _ -> pp_print_string fmt "NOT"
| IIs_nat _ -> pp_print_string fmt "ISNAT"
| INeg _ -> pp_print_string fmt "NEG"
| IAbs_int _ -> pp_print_string fmt "ABS"
| IInt_nat _ -> pp_print_string fmt "INT"
| IAdd_int _ | IAdd_nat _ -> pp_print_string fmt "ADD"
| ISub_int _ -> pp_print_string fmt "SUB"
| IMul_int _ | IMul_nat _ -> pp_print_string fmt "MUL"
| IEdiv_int _ | IEdiv_nat _ -> pp_print_string fmt "EDIV"
| ILsl_nat _ -> pp_print_string fmt "LSL"
| ILsl_bytes _ -> pp_print_string fmt "LSL"
| ILsr_nat _ -> pp_print_string fmt "LSR"
| ILsr_bytes _ -> pp_print_string fmt "LSR"
| IOr_nat _ -> pp_print_string fmt "OR"
| IOr_bytes _ -> pp_print_string fmt "OR"
| IAnd_nat _ -> pp_print_string fmt "AND"
| IAnd_int_nat _ -> pp_print_string fmt "AND"
| IAnd_bytes _ -> pp_print_string fmt "AND"
| IXor_nat _ -> pp_print_string fmt "XOR"
| IXor_bytes _ -> pp_print_string fmt "XOR"
| INot_int _ -> pp_print_string fmt "NOT"
| INot_bytes _ -> pp_print_string fmt "NOT"
| IIf _ -> pp_print_string fmt "IF"
| ILoop _ -> pp_print_string fmt "LOOP"
| ILoop_left _ -> pp_print_string fmt "LOOP_LEFT"
| IDip _ -> pp_print_string fmt "DIP"
| IExec _ -> pp_print_string fmt "EXEC"
| IApply _ -> pp_print_string fmt "APPLY"
| ILambda (_, Lam _, _) -> pp_print_string fmt "LAMBDA"
| ILambda (_, LamRec _, _) -> pp_print_string fmt "LAMBDA_REC"
| IFailwith _ -> pp_print_string fmt "FAILWITH"
| ICompare _ -> pp_print_string fmt "COMPARE"
| IEq _ -> pp_print_string fmt "EQ"
| INeq _ -> pp_print_string fmt "NEQ"
| ILt _ -> pp_print_string fmt "LT"
| IGt _ -> pp_print_string fmt "GT"
| ILe _ -> pp_print_string fmt "LE"
| IGe _ -> pp_print_string fmt "GE"
| IAddress _ -> pp_print_string fmt "ADDRESS"
| IContract _ -> pp_print_string fmt "CONTACT"
| IView _ -> pp_print_string fmt "VIEW"
| ITransfer_tokens _ -> pp_print_string fmt "TRANSFER_TOKENS"
| IImplicit_account _ -> pp_print_string fmt "IMPLICIT_ACCOUNT"
| ICreate_contract _ -> pp_print_string fmt "CREATE_CONTRACT"
| ISet_delegate _ -> pp_print_string fmt "SET_DELEGATE"
| INow _ -> pp_print_string fmt "NOW"
| IMin_block_time _ -> pp_print_string fmt "MIN_BLOCK_TIME"
| IBalance _ -> pp_print_string fmt "BALANCE"
| ILevel _ -> pp_print_string fmt "LEVEL"
| ICheck_signature _ -> pp_print_string fmt "CHECK_SIGNATURE"
| IHash_key _ -> pp_print_string fmt "HASH_KEY"
| IPack _ -> pp_print_string fmt "PACK"
| IBlake2b _ -> pp_print_string fmt "BLAKE2B"
| ISha3 _ -> pp_print_string fmt "SHA3"
| ISha256 _ -> pp_print_string fmt "SHA256"
| ISha512 _ -> pp_print_string fmt "SHA512"
| IUnpack _ -> pp_print_string fmt "UNPACK"
| ISource _ -> pp_print_string fmt "SOURCE"
| ISender _ -> pp_print_string fmt "SENDER"
| ISelf _ -> pp_print_string fmt "SELF"
| ISelf_address _ -> pp_print_string fmt "SELF_ADDRESS"
| IAmount _ -> pp_print_string fmt "AMOUNT"
| ISapling_empty_state _ -> pp_print_string fmt "SAPLING_EMPTY_STATE"
| ISapling_verify_update _ | ISapling_verify_update_deprecated _ ->
pp_print_string fmt "SAPLING_VERIFY_UPDATE"
| IDig _ -> pp_print_string fmt "DIG"
| IDug _ -> pp_print_string fmt "DUG"
| IDipn _ -> pp_print_string fmt "DIP"
| IDropn _ -> pp_print_string fmt "DROP"
| IChainId _ -> pp_print_string fmt "CHAIN_ID"
| INever _ -> pp_print_string fmt "NEVER"
| IVoting_power _ -> pp_print_string fmt "VOTING_POWER"
| ITotal_voting_power _ -> pp_print_string fmt "TOTAL_VOTING_POWER"
| IKeccak _ -> pp_print_string fmt "KECCAK"
| IAdd_bls12_381_g1 _ | IAdd_bls12_381_g2 _ | IAdd_bls12_381_fr _ ->
pp_print_string fmt "ADD"
| IMul_bls12_381_g1 _ | IMul_bls12_381_g2 _ | IMul_bls12_381_fr _
| IMul_bls12_381_z_fr _ | IMul_bls12_381_fr_z _ ->
pp_print_string fmt "MUL"
| IInt_bls12_381_fr _ -> pp_print_string fmt "INT"
| INeg_bls12_381_g1 _ | INeg_bls12_381_g2 _ | INeg_bls12_381_fr _ ->
pp_print_string fmt "NEG"
| IPairing_check_bls12_381 _ -> pp_print_string fmt "PAIRING_CHECK"
| IComb _ -> pp_print_string fmt "PAIR"
| IUncomb _ -> pp_print_string fmt "UNPAIR"
| IComb_get _ -> pp_print_string fmt "GET"
| IComb_set _ -> pp_print_string fmt "UPDATE"
| IDup_n _ -> pp_print_string fmt "DUP"
| ITicket _ -> pp_print_string fmt "TICKET"
| ITicket_deprecated _ -> pp_print_string fmt "TICKET_DEPRECATED"
| IRead_ticket _ -> pp_print_string fmt "READ_TICKET"
| ISplit_ticket _ -> pp_print_string fmt "SPLIT_TICKET"
| IJoin_tickets _ -> pp_print_string fmt "JOIN_TICKETS"
| IOpen_chest _ -> pp_print_string fmt "OPEN_CHEST"
| IEmit _ -> pp_print_string fmt "EMIT"
| IHalt _ -> pp_print_string fmt "[halt]"
| ILog (_, _, _, _, instr) ->
Format.fprintf fmt "log/%a" pp_instr_name instr
type Environment.Error_monad.error +=
| Run_operation_does_not_support_consensus_operations
let () =
let description =
"The run_operation RPC does not support consensus operations."
in
Environment.Error_monad.register_error_kind
`Permanent
~id:"run_operation_does_not_support_consensus_operations"
~title:"Run operation does not support consensus operations"
~description
~pp:(fun ppf () -> Format.fprintf ppf "%s" description)
Data_encoding.empty
(function
| Run_operation_does_not_support_consensus_operations -> Some ()
| _ -> None)
(fun () -> Run_operation_does_not_support_consensus_operations)
(** Validate and apply the operation but skip signature checks; do
not support consensus operations.
Return the unchanged operation protocol data, and the operation
receipt ie. metadata containing balance updates, consumed gas,
application success or failure, etc. *)
let run_operation_service rpc_ctxt params (packed_operation, chain_id) =
let open Lwt_result_syntax in
let {Services_registration.context; ; _} = rpc_ctxt in
let*? () =
match packed_operation.protocol_data with
| Operation_data {contents = Single (Preattestation _); _}
| Operation_data {contents = Single (Attestation _); _} ->
Environment.Error_monad.Result_syntax.tzfail
Run_operation_does_not_support_consensus_operations
| _ -> Result_syntax.return_unit
in
let oph = Operation.hash_packed packed_operation in
let validity_state = Validate.begin_no_predecessor_info context chain_id in
let* _validate_operation_state =
Validate.validate_operation
~check_signature:false
validity_state
oph
packed_operation
in
let application_mode =
Apply.Partial_construction {predecessor_fitness = block_header.fitness}
in
let application_state =
Apply.
{
ctxt = context;
chain_id;
mode = application_mode;
op_count = 0;
migration_balance_updates = [];
liquidity_baking_toggle_ema =
Per_block_votes.Liquidity_baking_toggle_EMA.zero;
adaptive_issuance_vote_ema =
Per_block_votes.Adaptive_issuance_launch_EMA.zero;
adaptive_issuance_launch_cycle = None;
implicit_operations_results = [];
}
in
let* _ctxt, op_metadata =
Apply.apply_operation application_state oph packed_operation
in
return (params#version, (packed_operation.protocol_data, op_metadata))
let simulate_operation_service rpc_ctxt params
(blocks_before_activation, op, chain_id, time_in_blocks) =
let open Lwt_result_syntax in
let {Services_registration.context; _} = rpc_ctxt in
let* context =
Cache.Admin.future_cache_expectation
context
~time_in_blocks
?blocks_before_activation
in
run_operation_service
{rpc_ctxt with context}
(object
method version = params#version
end)
(op, chain_id)
let default_from_context ctxt get =
let open Lwt_result_syntax in
function None -> get ctxt | Some x -> return x
type run_code_config = {
balance : Tez.t;
self : Contract_hash.t;
payer : Signature.public_key_hash;
sender : Contract.t;
}
let default_balance = Tez.of_mutez_exn 4_000_000_000_000L
let register () =
let open Lwt_result_syntax in
let originate_dummy_contract ctxt script balance =
let ctxt = Origination_nonce.init ctxt Operation_hash.zero in
let*? ctxt, dummy_contract_hash =
Contract.fresh_contract_from_current_nonce ctxt
in
let dummy_contract = Contract.Originated dummy_contract_hash in
let* ctxt =
Contract.raw_originate
ctxt
~prepaid_bootstrap_storage:false
dummy_contract_hash
~script:(script, None)
in
let+ ctxt, _ =
Token.transfer
~origin:Simulation
ctxt
`Minted
(`Contract dummy_contract)
balance
in
(ctxt, dummy_contract_hash)
in
let originate_dummy_contracts ctxt =
List.fold_left_es
(fun ctxt {S.address; ty} ->
Contract.raw_originate
ctxt
~prepaid_bootstrap_storage:false
address
~script:(View_helpers.make_tzip4_viewer_script ty, None))
ctxt
in
let initialize_big_maps ctxt big_maps =
let* ctxt, (big_map_diff : Lazy_storage.diffs) =
List.fold_left_es
(fun (ctxt, big_map_diff_tl) {S.id; kty; vty; items} ->
let open Script_ir_translator in
let items = Micheline.root items in
let init =
Lazy_storage.(Alloc Big_map.{key_type = kty; value_type = vty})
in
let*? Ex_comparable_ty key_comparable_type, ctxt =
parse_comparable_ty ctxt (Micheline.root kty)
in
let*? Ex_ty value_type, ctxt =
parse_big_map_value_ty ctxt ~legacy:false (Micheline.root vty)
in
let*? map_ty =
Script_typed_ir.map_t (-1) key_comparable_type value_type
in
let* _, ctxt =
parse_data
ctxt
~elab_conf:(Script_ir_translator_config.make ~legacy:false ())
~allow_forged_tickets:true
~allow_forged_lazy_storage_id:true
map_ty
items
in
let items =
match items with
| Micheline.Seq (_, items) -> items
| _ -> assert false
in
let+ ctxt, updates =
List.fold_left_es
(fun (ctxt, acc) key_value ->
let open Micheline in
let key, value =
match key_value with
| Prim (_, Michelson_v1_primitives.D_Elt, [key; value], _)
->
(key, value)
| _ -> assert false
in
let* k, ctxt =
parse_comparable_data ctxt key_comparable_type key
in
let+ key_hash, ctxt = hash_data ctxt key_comparable_type k in
let key = Micheline.strip_locations key in
let value = Some (Micheline.strip_locations value) in
(ctxt, Big_map.{key; key_hash; value} :: acc))
(ctxt, [])
items
in
( ctxt,
Lazy_storage.(
make Big_map id (Update {init; updates = List.rev updates}))
:: big_map_diff_tl ))
(ctxt, [])
big_maps
in
let+ ctxt, _size_change = Lazy_storage.apply ctxt big_map_diff in
ctxt
in
let sender_and_payer ~sender_opt ~payer_opt ~default_sender =
match (sender_opt, payer_opt) with
| None, None ->
(Contract.Originated default_sender, Signature.Public_key_hash.zero)
| Some c, None -> (c, Signature.Public_key_hash.zero)
| None, Some c -> (Contract.Implicit c, c)
| Some sender, Some payer -> (sender, payer)
in
let compute_step_constants ctxt ~balance ~amount ~chain_id ~sender_opt
~payer_opt ~self ~now_opt ~level_opt =
let sender, payer =
sender_and_payer ~sender_opt ~payer_opt ~default_sender:self
in
let now =
match now_opt with None -> Script_timestamp.now ctxt | Some t -> t
in
let level =
match level_opt with
| None ->
(Level.current ctxt).level |> Raw_level.to_int32
|> Script_int.of_int32 |> Script_int.abs
| Some z -> z
in
let open Script_interpreter in
let sender = Destination.Contract sender in
(ctxt, {sender; payer; self; amount; balance; chain_id; now; level})
in
let configure_gas_and_step_constants ctxt ~script ~gas_opt ~balance ~amount
~chain_id ~sender_opt ~payer_opt ~self_opt ~now_opt ~level_opt =
let gas =
match gas_opt with
| Some gas -> gas
| None -> Constants.hard_gas_limit_per_operation ctxt
in
let ctxt = Gas.set_limit ctxt gas in
let+ ctxt, self, balance =
match self_opt with
| None ->
let balance = Option.value ~default:default_balance balance in
let+ ctxt, addr = originate_dummy_contract ctxt script balance in
(ctxt, addr, balance)
| Some addr ->
let+ bal =
default_from_context
ctxt
(fun c -> Contract.get_balance c @@ Contract.Originated addr)
balance
in
(ctxt, addr, bal)
in
compute_step_constants
ctxt
~balance
~amount
~chain_id
~sender_opt
~payer_opt
~self
~now_opt
~level_opt
in
let script_entrypoint_type ctxt expr entrypoint =
let ctxt = Gas.set_unlimited ctxt in
let legacy = false in
let open Script_ir_translator in
let* {arg_type; _}, ctxt = parse_toplevel ctxt expr in
let*? Ex_parameter_ty_and_entrypoints {arg_type; entrypoints}, _ =
parse_parameter_ty_and_entrypoints ctxt ~legacy arg_type
in
let*? r, _ctxt =
Gas_monad.run ctxt
@@ Script_ir_translator.find_entrypoint
~error_details:(Informative ())
arg_type
entrypoints
entrypoint
in
let*? (Ex_ty_cstr {original_type_expr; _}) = r in
return @@ Micheline.strip_locations original_type_expr
in
let script_view_type ctxt contract expr view =
let ctxt = Gas.set_unlimited ctxt in
let open Script_ir_translator in
let* {views; _}, _ = parse_toplevel ctxt expr in
let*? view_name = Script_string.of_string view in
match Script_map.get view_name views with
| None ->
Environment.Error_monad.tzfail
(View_helpers.View_not_found (contract, view))
| Some Script_typed_ir.{input_ty; output_ty; _} ->
return (input_ty, output_ty)
in
Registration.register0
~chunked:true
S.run_code
(fun
ctxt
()
( ( code,
storage,
parameter,
amount,
balance,
chain_id,
sender_opt,
payer_opt,
self_opt,
entrypoint ),
( unparsing_mode,
gas_opt,
now_opt,
level_opt,
other_contracts,
) )
->
let unparsing_mode = Option.value ~default:Readable unparsing_mode in
let other_contracts = Option.value ~default:[] other_contracts in
let* ctxt = originate_dummy_contracts ctxt other_contracts in
let = Option.value ~default:[] extra_big_maps in
let* ctxt = initialize_big_maps ctxt extra_big_maps in
let storage = Script.lazy_expr storage in
let code = Script.lazy_expr code in
let* ctxt, step_constants =
configure_gas_and_step_constants
ctxt
~script:{storage; code}
~gas_opt
~balance
~amount
~chain_id
~sender_opt
~payer_opt
~self_opt
~now_opt
~level_opt
in
let+ ( {
script = _;
code_size = _;
Script_interpreter.storage;
operations;
lazy_storage_diff;
ticket_diffs = _;
ticket_receipt = _;
},
_ ) =
Script_interpreter.execute
ctxt
unparsing_mode
step_constants
~cached_script:None
~script:{storage; code}
~entrypoint
~parameter
~internal:true
in
( storage,
Apply_internal_results.packed_internal_operations operations,
lazy_storage_diff )) ;
Registration.register0
~chunked:true
S.trace_code
(fun
ctxt
()
( ( code,
storage,
parameter,
amount,
balance,
chain_id,
sender_opt,
payer_opt,
self_opt,
entrypoint ),
( unparsing_mode,
gas_opt,
now_opt,
level_opt,
other_contracts,
) )
->
let unparsing_mode = Option.value ~default:Readable unparsing_mode in
let other_contracts = Option.value ~default:[] other_contracts in
let* ctxt = originate_dummy_contracts ctxt other_contracts in
let = Option.value ~default:[] extra_big_maps in
let* ctxt = initialize_big_maps ctxt extra_big_maps in
let storage = Script.lazy_expr storage in
let code = Script.lazy_expr code in
let* ctxt, step_constants =
configure_gas_and_step_constants
ctxt
~script:{storage; code}
~gas_opt
~balance
~amount
~chain_id
~sender_opt
~payer_opt
~self_opt
~now_opt
~level_opt
in
let module Unparsing_mode = struct
let unparsing_mode = unparsing_mode
end in
let module Interp = Traced_interpreter (Unparsing_mode) in
let+ ( ( {
script = _;
code_size = _;
Script_interpreter.storage;
operations;
lazy_storage_diff;
ticket_diffs = _;
ticket_receipt = _;
},
_ctxt ),
trace ) =
Interp.execute
ctxt
step_constants
~script:{storage; code}
~entrypoint
~parameter
in
( storage,
Apply_internal_results.packed_internal_operations operations,
trace,
lazy_storage_diff )) ;
Registration.register0
~chunked:true
S.run_tzip4_view
(fun
ctxt
()
( ( contract_hash,
entrypoint,
input,
chain_id,
sender_opt,
payer_opt,
gas,
unparsing_mode,
now_opt,
level_opt ),
(other_contracts, ) )
->
let other_contracts = Option.value ~default:[] other_contracts in
let* ctxt = originate_dummy_contracts ctxt other_contracts in
let = Option.value ~default:[] extra_big_maps in
let* ctxt = initialize_big_maps ctxt extra_big_maps in
let* ctxt, script_opt = Contract.get_script ctxt contract_hash in
let*? script =
Option.fold
~some:Result_syntax.return
~none:
(Environment.Error_monad.Result_syntax.tzfail
View_helpers.Viewed_contract_has_no_script)
script_opt
in
let*? decoded_script = Script_repr.(force_decode script.code) in
let* view_ty = script_entrypoint_type ctxt decoded_script entrypoint in
let*? ty = View_helpers.extract_view_output_type entrypoint view_ty in
let contract = Contract.Originated contract_hash in
let* balance = Contract.get_balance ctxt contract in
let* ctxt, viewer_contract =
Error_monad.trace View_helpers.View_callback_origination_failed
@@ originate_dummy_contract
ctxt
(View_helpers.make_tzip4_viewer_script ty)
Tez.zero
in
let ctxt, step_constants =
compute_step_constants
ctxt
~balance
~amount:Tez.zero
~chain_id
~sender_opt
~payer_opt
~self:contract_hash
~now_opt
~level_opt
in
let gas =
Option.value
~default:(Constants.hard_gas_limit_per_operation ctxt)
gas
in
let ctxt = Gas.set_limit ctxt gas in
let parameter =
View_helpers.make_view_parameter
(Micheline.root input)
(Contract.Originated viewer_contract)
in
let* ( {
Script_interpreter.operations;
script = _;
code_size = _;
storage = _;
lazy_storage_diff = _;
ticket_diffs = _;
ticket_receipt = _;
},
_ctxt ) =
Script_interpreter.execute
ctxt
unparsing_mode
step_constants
~script
~cached_script:None
~entrypoint
~parameter
~internal:true
in
Lwt.return
(View_helpers.extract_parameter_from_operations
entrypoint
operations
viewer_contract)) ;
Registration.register0
~chunked:true
S.run_script_view
(fun
ctxt
()
( ( contract_hash,
view,
input,
unlimited_gas,
chain_id,
sender_opt,
payer_opt,
gas,
unparsing_mode,
now_opt ),
(level_opt, other_contracts, ) )
->
let other_contracts = Option.value ~default:[] other_contracts in
let* ctxt = originate_dummy_contracts ctxt other_contracts in
let = Option.value ~default:[] extra_big_maps in
let* ctxt = initialize_big_maps ctxt extra_big_maps in
let* ctxt, script_opt = Contract.get_script ctxt contract_hash in
let*? script =
Option.fold
~some:Result_syntax.return
~none:(Error_monad.error View_helpers.Viewed_contract_has_no_script)
script_opt
in
let*? decoded_script = Script_repr.(force_decode script.code) in
let contract = Contract.Originated contract_hash in
let* input_ty, output_ty =
script_view_type ctxt contract_hash decoded_script view
in
let* balance = Contract.get_balance ctxt contract in
let ctxt, step_constants =
compute_step_constants
ctxt
~balance
~amount:Tez.zero
~chain_id
~sender_opt
~payer_opt
~self:contract_hash
~now_opt
~level_opt
in
let max_gas = Gas.fp_of_milligas_int max_int in
let gas =
Option.value
~default:(Constants.hard_gas_limit_per_operation ctxt)
gas
in
let ctxt =
if unlimited_gas then Gas.set_limit ctxt max_gas
else Gas.set_limit ctxt gas
in
let viewer_script =
View_helpers.make_michelson_viewer_script
contract
view
input
input_ty
output_ty
in
let parameter =
Micheline.(strip_locations (Prim (0, Script.D_Unit, [], [])))
in
let* ( {
Script_interpreter.operations = _;
script = _;
code_size = _;
storage;
lazy_storage_diff = _;
ticket_diffs = _;
ticket_receipt = _;
},
_ctxt ) =
Script_interpreter.execute
ctxt
unparsing_mode
step_constants
~script:viewer_script
~cached_script:None
~entrypoint:Entrypoint.default
~parameter
~internal:true
in
let*? value = View_helpers.extract_value_from_storage storage in
return (Micheline.strip_locations value)) ;
Registration.register0
~chunked:false
S.typecheck_code
(fun ctxt () (expr, maybe_gas, legacy, show_types) ->
let ctxt =
match maybe_gas with
| None -> Gas.set_unlimited ctxt
| Some gas -> Gas.set_limit ctxt gas
in
let+ res, ctxt =
Script_ir_translator.typecheck_code ~legacy ~show_types ctxt expr
in
(res, Gas.level ctxt)) ;
Registration.register0
~chunked:false
S.script_size
(fun ctxt () (expr, storage, maybe_gas, legacy) ->
let ctxt =
match maybe_gas with
| None -> Gas.set_unlimited ctxt
| Some gas -> Gas.set_limit ctxt gas
in
let elab_conf = elab_conf ~legacy () in
let code = Script.lazy_expr expr in
let* ( Ex_code
(Code
{code; arg_type; storage_type; views; entrypoints; code_size}),
ctxt ) =
Script_ir_translator.parse_code ~elab_conf ctxt ~code
in
let* storage, _ =
Script_ir_translator.parse_data
~elab_conf
~allow_forged_tickets:true
~allow_forged_lazy_storage_id:true
ctxt
storage_type
(Micheline.root storage)
in
let script =
Script_ir_translator.Ex_script
(Script
{
code;
arg_type;
storage_type;
views;
entrypoints;
code_size;
storage;
})
in
let size, cost = Script_ir_translator.script_size script in
let*? _ctxt = Gas.consume ctxt cost in
return size) ;
Registration.register0
~chunked:false
S.typecheck_data
(fun ctxt () (data, ty, maybe_gas, legacy) ->
let ctxt =
match maybe_gas with
| None -> Gas.set_unlimited ctxt
| Some gas -> Gas.set_limit ctxt gas
in
let+ ctxt = typecheck_data ~legacy ctxt (data, ty) in
Gas.level ctxt) ;
Registration.register0
~chunked:true
S.pack_data
(fun ctxt () (expr, typ, maybe_gas) ->
let open Script_ir_translator in
let ctxt =
match maybe_gas with
| None -> Gas.set_unlimited ctxt
| Some gas -> Gas.set_limit ctxt gas
in
let*? Ex_ty typ, ctxt =
parse_packable_ty ctxt ~legacy:true (Micheline.root typ)
in
let* data, ctxt =
parse_data
ctxt
~elab_conf:(elab_conf ~legacy:true ())
~allow_forged_tickets:true
~allow_forged_lazy_storage_id:true
typ
(Micheline.root expr)
in
let+ bytes, ctxt = Script_ir_translator.pack_data ctxt typ data in
(bytes, Gas.level ctxt)) ;
Registration.register0
~chunked:true
S.normalize_data
(fun
ctxt
()
(expr, typ, unparsing_mode, legacy, other_contracts, )
->
let open Script_ir_translator in
let other_contracts = Option.value ~default:[] other_contracts in
let* ctxt = originate_dummy_contracts ctxt other_contracts in
let = Option.value ~default:[] extra_big_maps in
let* ctxt = initialize_big_maps ctxt extra_big_maps in
let ctxt = Gas.set_unlimited ctxt in
let*? Ex_ty typ, ctxt =
Script_ir_translator.parse_any_ty ctxt ~legacy (Micheline.root typ)
in
let* data, ctxt =
parse_data
ctxt
~elab_conf:(elab_conf ~legacy ())
~allow_forged_tickets:true
~allow_forged_lazy_storage_id:true
typ
(Micheline.root expr)
in
let+ normalized, _ctxt =
Script_ir_translator.unparse_data ctxt unparsing_mode typ data
in
normalized) ;
Registration.register0
~chunked:true
S.normalize_stack
(fun
ctxt
()
(stack, unparsing_mode, legacy, other_contracts, )
->
let ctxt = Gas.set_unlimited ctxt in
let nodes =
List.map (fun (a, b) -> (Micheline.root a, Micheline.root b)) stack
in
let other_contracts = Option.value ~default:[] other_contracts in
let* ctxt = originate_dummy_contracts ctxt other_contracts in
let = Option.value ~default:[] extra_big_maps in
let* ctxt = initialize_big_maps ctxt extra_big_maps in
let* Normalize_stack.Ex_stack (st_ty, x, st), ctxt =
Normalize_stack.parse_stack ctxt ~legacy nodes
in
let+ normalized, _ctxt =
Normalize_stack.unparse_stack ctxt unparsing_mode st_ty x st
in
normalized) ;
Registration.register0
~chunked:true
S.normalize_script
(fun ctxt () (script, unparsing_mode) ->
let ctxt = Gas.set_unlimited ctxt in
let+ normalized, _ctxt =
Script_ir_translator.unparse_code
ctxt
unparsing_mode
(Micheline.root script)
in
normalized) ;
Registration.register0 ~chunked:true S.normalize_type (fun ctxt () typ ->
let open Script_typed_ir in
let ctxt = Gas.set_unlimited ctxt in
let*? Ex_ty typ, _ctxt =
Script_ir_translator.parse_ty
ctxt
~legacy:true
~allow_lazy_storage:true
~allow_operation:true
~allow_contract:true
~allow_ticket:true
(Micheline.root typ)
in
let normalized = Unparse_types.unparse_ty ~loc:() typ in
return @@ Micheline.strip_locations normalized) ;
Registration.register0
~chunked:true
S.run_instr
(fun
ctxt
()
( ( input,
code,
chain_id,
gas_opt,
now_opt,
level_opt,
sender_opt,
source_opt,
self_opt,
parameter_opt ),
( amount,
balance,
other_contracts,
,
unparsing_mode,
legacy ) )
->
let unparsing_mode = Option.value ~default:Readable unparsing_mode in
let other_contracts = Option.value ~default:[] other_contracts in
let* ctxt = originate_dummy_contracts ctxt other_contracts in
let = Option.value ~default:[] extra_big_maps in
let* ctxt = initialize_big_maps ctxt extra_big_maps in
let parameter =
Option.value
~default:
(Micheline.strip_locations
(Prim (0, Michelson_v1_primitives.T_unit, [], [])))
parameter_opt
in
let*? Ex_parameter_ty_and_entrypoints {arg_type; entrypoints}, ctxt =
Script_ir_translator.parse_parameter_ty_and_entrypoints
ctxt
~legacy
(Micheline.root parameter)
in
let* ctxt, step_constants =
configure_gas_and_step_constants
ctxt
~script:(View_helpers.make_tzip4_viewer_script parameter)
~gas_opt
~balance
~amount
~chain_id
~sender_opt
~payer_opt:source_opt
~self_opt
~now_opt
~level_opt
in
let input_nodes =
List.map (fun (a, b) -> (Micheline.root a, Micheline.root b)) input
in
let* Normalize_stack.Ex_stack (st_ty, x, st), ctxt =
Normalize_stack.parse_stack ctxt ~legacy input_nodes
in
let* j, ctxt =
Script_ir_translator.parse_instr
~elab_conf:(Script_ir_translator_config.make ~legacy ())
(Script_tc_context.toplevel
~storage_type:Script_typed_ir.unit_t
~param_type:arg_type
~entrypoints)
ctxt
(Micheline.root code)
st_ty
in
match j with
| Failed {descr} -> (
let impossible_stack_ty =
Script_typed_ir.(Item_t (never_t, Bot_t))
in
let descr = descr impossible_stack_ty in
let descr = Script_ir_translator.close_descr descr in
let* absurd =
Script_interpreter.Internals.step_descr
None
ctxt
step_constants
descr
x
st
in
match absurd with _ -> .)
| Typed descr ->
let descr = Script_ir_translator.close_descr descr in
let* y, output_st, _ctxt =
Script_interpreter.Internals.step_descr
None
ctxt
step_constants
descr
x
st
in
let+ output, ctxt =
Normalize_stack.unparse_stack
ctxt
unparsing_mode
descr.kaft
y
output_st
in
(output, Gas.level ctxt)) ;
Registration.register0_fullctxt
~chunked:true
S.run_operation
run_operation_service ;
Registration.register0_fullctxt_successor_level
~chunked:true
S.simulate_operation
simulate_operation_service ;
Registration.register0
~chunked:true
S.entrypoint_type
(fun ctxt () (expr, entrypoint) ->
script_entrypoint_type ctxt expr entrypoint) ;
Registration.register0 ~chunked:true S.list_entrypoints (fun ctxt () expr ->
let ctxt = Gas.set_unlimited ctxt in
let legacy = false in
let open Script_ir_translator in
let* {arg_type; _}, ctxt = parse_toplevel ctxt expr in
let*? Ex_parameter_ty_and_entrypoints {arg_type; entrypoints}, _ =
parse_parameter_ty_and_entrypoints ctxt ~legacy arg_type
in
return
@@
let unreachable_entrypoint, map =
Script_ir_translator.list_entrypoints_uncarbonated
arg_type
entrypoints
in
( unreachable_entrypoint,
Entrypoint.Map.fold
(fun entry (_ex_ty, original_type_expr) acc ->
( Entrypoint.to_string entry,
Micheline.strip_locations original_type_expr )
:: acc)
map
[] ))
let run_code ~unparsing_mode ~gas ~entrypoint ~balance ~other_contracts
~ ~script ~storage ~input ~amount ~chain_id ~sender ~payer
~self ~now ~level ctxt block =
RPC_context.make_call0
S.run_code
ctxt
block
()
( ( script,
storage,
input,
amount,
balance,
chain_id,
sender,
payer,
self,
entrypoint ),
(unparsing_mode, gas, now, level, other_contracts, extra_big_maps) )
let trace_code ~unparsing_mode ~gas ~entrypoint ~balance ~other_contracts
~ ~script ~storage ~input ~amount ~chain_id ~sender ~payer
~self ~now ~level ctxt block =
RPC_context.make_call0
S.trace_code
ctxt
block
()
( ( script,
storage,
input,
amount,
balance,
chain_id,
sender,
payer,
self,
entrypoint ),
(unparsing_mode, gas, now, level, other_contracts, extra_big_maps) )
let run_tzip4_view ~gas ~other_contracts ~ ~contract ~entrypoint
~input ~chain_id ~now ~level ~sender ~payer ~unparsing_mode ctxt block =
RPC_context.make_call0
S.run_tzip4_view
ctxt
block
()
( ( contract,
entrypoint,
input,
chain_id,
sender,
payer,
gas,
unparsing_mode,
now,
level ),
(other_contracts, extra_big_maps) )
(** [run_script_view] is an helper function to call the corresponding
RPC. *)
let run_script_view ~gas ~other_contracts ~ ~contract ~view
~input ~unlimited_gas ~chain_id ~now ~level ~sender ~payer ~unparsing_mode
ctxt block =
RPC_context.make_call0
S.run_script_view
ctxt
block
()
( ( contract,
view,
input,
unlimited_gas,
chain_id,
sender,
payer,
gas,
unparsing_mode,
now ),
(level, other_contracts, extra_big_maps) )
let run_instr ~gas ~legacy ~input ~code ~chain_id ~now ~level ~unparsing_mode
~source ~sender ~self ~parameter ~amount ~balance ~other_contracts
~ ctxt block =
RPC_context.make_call0
S.run_instr
ctxt
block
()
( (input, code, chain_id, gas, now, level, sender, source, self, parameter),
( amount,
balance,
other_contracts,
extra_big_maps,
unparsing_mode,
legacy ) )
let typecheck_code ~gas ~legacy ~script ~show_types ctxt block =
RPC_context.make_call0
S.typecheck_code
ctxt
block
()
(script, gas, legacy, show_types)
let script_size ~gas ~legacy ~script ~storage ctxt block =
RPC_context.make_call0
S.script_size
ctxt
block
()
(script, storage, gas, legacy)
let typecheck_data ~gas ~legacy ~data ~ty ctxt block =
RPC_context.make_call0 S.typecheck_data ctxt block () (data, ty, gas, legacy)
let pack_data ~gas ~data ~ty ctxt block =
RPC_context.make_call0 S.pack_data ctxt block () (data, ty, gas)
let normalize_data ~legacy ~other_contracts ~ ~data ~ty
~unparsing_mode ctxt block =
RPC_context.make_call0
S.normalize_data
ctxt
block
()
(data, ty, unparsing_mode, legacy, other_contracts, extra_big_maps)
let normalize_stack ~legacy ~other_contracts ~ ~stack
~unparsing_mode ctxt block =
RPC_context.make_call0
S.normalize_stack
ctxt
block
()
(stack, unparsing_mode, legacy, other_contracts, extra_big_maps)
let normalize_script ~script ~unparsing_mode ctxt block =
RPC_context.make_call0
S.normalize_script
ctxt
block
()
(script, unparsing_mode)
let normalize_type ~ty ctxt block =
RPC_context.make_call0 S.normalize_type ctxt block () ty
let run_operation ~op ~chain_id ?(version = default_operations_version) ctxt
block =
let open Lwt_result_syntax in
let* (Version_0 | Version_1), run_operation =
RPC_context.make_call0
S.run_operation
ctxt
block
(object
method version = version
end)
(op, chain_id)
in
return run_operation
let simulate_operation ~op ~chain_id ~latency
?(version = default_operations_version) ?(successor_level = false)
?blocks_before_activation ctxt block =
let open Lwt_result_syntax in
let* (Version_0 | Version_1), simulate_operation =
RPC_context.make_call0
S.simulate_operation
ctxt
block
(object
method version = version
method successor_level = successor_level
end)
(blocks_before_activation, op, chain_id, latency)
in
return simulate_operation
let entrypoint_type ~script ~entrypoint ctxt block =
RPC_context.make_call0 S.entrypoint_type ctxt block () (script, entrypoint)
let list_entrypoints ctxt block ~script =
RPC_context.make_call0 S.list_entrypoints ctxt block () script
end
module Contract = struct
let ticket_balances_encoding =
let open Data_encoding in
list
(merge_objs Ticket_token.unparsed_token_encoding (obj1 (req "amount" n)))
module S = struct
let path =
(RPC_path.(open_root / "context" / "contracts")
: RPC_context.t RPC_path.context)
let get_storage_normalized =
let open Data_encoding in
RPC_service.post_service
~description:
"Access the data of the contract and normalize it using the \
requested unparsing mode."
~input:(obj1 (req "unparsing_mode" unparsing_mode_encoding))
~query:RPC_query.empty
~output:(option Script.expr_encoding)
RPC_path.(path /: Contract.rpc_arg / "storage" / "normalized")
let get_script_normalized =
let open Data_encoding in
RPC_service.post_service
~description:
"Access the script of the contract and normalize it using the \
requested unparsing mode."
~input:
(obj2
(req "unparsing_mode" unparsing_mode_encoding)
(dft "normalize_types" bool false))
~query:RPC_query.empty
~output:(option Script.encoding)
RPC_path.(path /: Contract.rpc_arg / "script" / "normalized")
let get_used_storage_space =
let open Data_encoding in
RPC_service.get_service
~description:"Access the used storage space of the contract."
~query:RPC_query.empty
~output:(option z)
RPC_path.(path /: Contract.rpc_arg / "storage" / "used_space")
let get_paid_storage_space =
let open Data_encoding in
RPC_service.get_service
~description:"Access the paid storage space of the contract."
~query:RPC_query.empty
~output:(option z)
RPC_path.(path /: Contract.rpc_arg / "storage" / "paid_space")
let ticket_balance =
let open Data_encoding in
RPC_service.post_service
~description:
"Access the contract's balance of ticket with specified ticketer, \
content type, and content."
~query:RPC_query.empty
~input:Ticket_token.unparsed_token_encoding
~output:n
RPC_path.(path /: Contract.rpc_arg / "ticket_balance")
let all_ticket_balances =
RPC_service.get_service
~description:
"Access the complete list of tickets owned by the given contract by \
scanning the contract's storage."
~query:RPC_query.empty
~output:ticket_balances_encoding
RPC_path.(path /: Contract.rpc_arg / "all_ticket_balances")
end
let get_contract contract f =
let open Lwt_result_syntax in
match contract with
| Contract.Implicit _ -> return_none
| Contract.Originated contract -> f contract
let register () =
let open Lwt_result_syntax in
Registration.register1
~chunked:true
S.get_storage_normalized
(fun ctxt contract () unparsing_mode ->
get_contract contract @@ fun contract ->
let* ctxt, script = Contract.get_script ctxt contract in
match script with
| None -> return_none
| Some script ->
let ctxt = Gas.set_unlimited ctxt in
let open Script_ir_translator in
let* Ex_script (Script {storage; storage_type; _}), ctxt =
parse_script
ctxt
~elab_conf:(elab_conf ~legacy:true ())
~allow_forged_tickets_in_storage:true
~allow_forged_lazy_storage_id_in_storage:true
script
in
let+ storage, _ctxt =
unparse_data ctxt unparsing_mode storage_type storage
in
Some storage) ;
Registration.register1
~chunked:true
S.get_script_normalized
(fun ctxt contract () (unparsing_mode, normalize_types) ->
get_contract contract @@ fun contract ->
let* ctxt, script = Contract.get_script ctxt contract in
match script with
| None -> return_none
| Some script ->
let ctxt = Gas.set_unlimited ctxt in
let+ script, _ctxt =
Script_ir_translator.parse_and_unparse_script_unaccounted
ctxt
~legacy:true
~allow_forged_tickets_in_storage:true
~allow_forged_lazy_storage_id_in_storage:true
unparsing_mode
~normalize_types
script
in
Some script) ;
Registration.register1
~chunked:false
S.get_used_storage_space
(fun ctxt contract () () ->
get_contract contract @@ fun _ ->
let+ x = Contract.used_storage_space ctxt contract in
Some x) ;
Registration.register1
~chunked:false
S.get_paid_storage_space
(fun ctxt contract () () ->
get_contract contract @@ fun _ ->
let+ x = Contract.paid_storage_space ctxt contract in
Some x) ;
Registration.register1
~chunked:false
S.ticket_balance
(fun ctxt contract () Ticket_token.{ticketer; contents_type; contents} ->
let* ticket_hash, ctxt =
Ticket_balance_key.make
ctxt
~owner:(Contract contract)
~ticketer
~contents_type:(Micheline.root contents_type)
~contents:(Micheline.root contents)
in
let+ amount, _ctxt = Ticket_balance.get_balance ctxt ticket_hash in
Option.value amount ~default:Z.zero) ;
Registration.opt_register1
~chunked:false
S.all_ticket_balances
(fun ctxt contract () () ->
get_contract contract @@ fun contract ->
let* ctxt, script = Contract.get_script ctxt contract in
match script with
| None -> return_none
| Some script ->
let* Ex_script (Script {storage; storage_type; _}), ctxt =
Script_ir_translator.parse_script
ctxt
~elab_conf:(elab_conf ~legacy:true ())
~allow_forged_tickets_in_storage:true
~allow_forged_lazy_storage_id_in_storage:true
script
in
let*? has_tickets, ctxt =
Ticket_scanner.type_has_tickets ctxt storage_type
in
let* ticket_token_map, ctxt =
Ticket_accounting.ticket_balances_of_value
ctxt
~include_lazy:true
has_tickets
storage
in
let+ ticket_balances, _ctxt =
Ticket_token_map.fold_es
ctxt
(fun ctxt acc ex_token amount ->
let+ unparsed_token, ctxt =
Ticket_token_unparser.unparse ctxt ex_token
in
((unparsed_token, amount) :: acc, ctxt))
[]
ticket_token_map
in
Some ticket_balances)
let get_storage_normalized ctxt block ~contract ~unparsing_mode =
RPC_context.make_call1
S.get_storage_normalized
ctxt
block
(Contract.Originated contract)
()
unparsing_mode
let get_script_normalized ctxt block ~contract ~unparsing_mode
~normalize_types =
RPC_context.make_call1
S.get_script_normalized
ctxt
block
(Contract.Originated contract)
()
(unparsing_mode, normalize_types)
let get_used_storage_space ctxt block ~contract =
RPC_context.make_call1
S.get_used_storage_space
ctxt
block
(Contract.Originated contract)
()
()
let get_paid_storage_space ctxt block ~contract =
RPC_context.make_call1
S.get_paid_storage_space
ctxt
block
(Contract.Originated contract)
()
()
let get_ticket_balance ctxt block contract key =
RPC_context.make_call1 S.ticket_balance ctxt block contract () key
let get_all_ticket_balances ctxt block contract =
RPC_context.make_call1
S.all_ticket_balances
ctxt
block
(Contract.Originated contract)
()
()
end
module Big_map = struct
module S = struct
let path =
(RPC_path.(open_root / "context" / "big_maps")
: RPC_context.t RPC_path.context)
let big_map_get_normalized =
let open Data_encoding in
RPC_service.post_service
~description:
"Access the value associated with a key in a big map, normalize the \
output using the requested unparsing mode."
~query:RPC_query.empty
~input:(obj1 (req "unparsing_mode" unparsing_mode_encoding))
~output:Script.expr_encoding
RPC_path.(
path /: Big_map.Id.rpc_arg /: Script_expr_hash.rpc_arg / "normalized")
end
let register () =
let open Lwt_result_syntax in
Registration.register2
~chunked:true
S.big_map_get_normalized
(fun ctxt id key () unparsing_mode ->
let open Script_ir_translator in
let ctxt = Gas.set_unlimited ctxt in
let* ctxt, types = Big_map.exists ctxt id in
match types with
| None -> raise Not_found
| Some (_, value_type) -> (
let*? Ex_ty value_type, ctxt =
parse_big_map_value_ty
ctxt
~legacy:true
(Micheline.root value_type)
in
let* _ctxt, value = Big_map.get_opt ctxt id key in
match value with
| None -> raise Not_found
| Some value ->
let* value, ctxt =
parse_data
ctxt
~elab_conf:(elab_conf ~legacy:true ())
~allow_forged_tickets:true
~allow_forged_lazy_storage_id:true
value_type
(Micheline.root value)
in
let+ value, _ctxt =
unparse_data ctxt unparsing_mode value_type value
in
value))
let big_map_get_normalized ctxt block id key ~unparsing_mode =
RPC_context.make_call2
S.big_map_get_normalized
ctxt
block
id
key
()
unparsing_mode
end
module Sc_rollup = struct
open Data_encoding
module S = struct
let prefix : RPC_context.t RPC_path.context =
RPC_path.(open_root / "context" / "smart_rollups")
let path_sc_rollup : (RPC_context.t, RPC_context.t * Sc_rollup.t) RPC_path.t
=
RPC_path.(prefix / "smart_rollup" /: Sc_rollup.Address.rpc_arg)
let path_sc_rollups : RPC_context.t RPC_path.context =
RPC_path.(prefix / "all")
let kind =
RPC_service.get_service
~description:"Kind of smart rollup"
~query:RPC_query.empty
~output:Sc_rollup.Kind.encoding
RPC_path.(path_sc_rollup / "kind")
let genesis_info =
RPC_service.get_service
~description:
"Genesis information (level and commitment hash) for a smart rollup"
~query:RPC_query.empty
~output:Sc_rollup.Commitment.genesis_info_encoding
RPC_path.(path_sc_rollup / "genesis_info")
let last_cemented_commitment_hash_with_level =
RPC_service.get_service
~description:
"Level and hash of the last cemented commitment for a smart rollup"
~query:RPC_query.empty
~output:
(obj2
(req "hash" Sc_rollup.Commitment.Hash.encoding)
(req "level" Raw_level.encoding))
RPC_path.(path_sc_rollup / "last_cemented_commitment_hash_with_level")
let staked_on_commitment =
RPC_service.get_service
~description:
"The newest commitment on which the operator has staked on for a \
smart rollup. Note that is can return a commitment that is before \
the last cemented one."
~query:RPC_query.empty
~output:
(option
(merge_objs
(obj1 (req "hash" Sc_rollup.Commitment.Hash.encoding))
Sc_rollup.Commitment.encoding))
RPC_path.(
path_sc_rollup / "staker" /: Sc_rollup.Staker.rpc_arg
/ "staked_on_commitment")
let commitment =
RPC_service.get_service
~description:"Commitment for a smart rollup from its hash"
~query:RPC_query.empty
~output:Sc_rollup.Commitment.encoding
RPC_path.(
path_sc_rollup / "commitment" /: Sc_rollup.Commitment.Hash.rpc_arg)
let dal_slot_subscriptions =
RPC_service.get_service
~description:
"List of slot indices to which a rollup is subscribed to at a given \
level"
~query:RPC_query.empty
~output:(Data_encoding.list Dal.Slot_index.encoding)
RPC_path.(
path_sc_rollup / "dal_slot_subscriptions" /: Raw_level.rpc_arg)
let ongoing_refutation_games =
let output =
Sc_rollup.(
Data_encoding.(
list
(obj3
(req "game" Game.encoding)
(req "alice" Staker.encoding)
(req "bob" Staker.encoding))))
in
RPC_service.get_service
~description:"Ongoing refutation games for a given staker"
~query:RPC_query.empty
~output
RPC_path.(
path_sc_rollup / "staker" /: Sc_rollup.Staker.rpc_arg / "games")
let commitments =
let output =
Data_encoding.(option (list Sc_rollup.Commitment.Hash.encoding))
in
RPC_service.get_service
~description:
"List of commitments associated to a rollup for a given inbox level"
~query:RPC_query.empty
~output
RPC_path.(
path_sc_rollup / "inbox_level" /: Raw_level.rpc_arg / "commitments")
let stakers_ids =
let output = Data_encoding.list Sc_rollup.Staker.Index.encoding in
RPC_service.get_service
~description:"List of stakers indexes staking on a given commitment"
~query:RPC_query.empty
~output
RPC_path.(
path_sc_rollup / "commitment" /: Sc_rollup.Commitment.Hash.rpc_arg
/ "stakers_indexes")
let staker_id =
let output = Sc_rollup.Staker.Index.encoding in
RPC_service.get_service
~description:
"Staker index associated to a public key hash for a given rollup"
~query:RPC_query.empty
~output
RPC_path.(
path_sc_rollup / "staker" /: Sc_rollup.Staker.rpc_arg / "index")
let stakers =
let output = Data_encoding.list Sc_rollup.Staker.encoding in
RPC_service.get_service
~description:"List of active stakers' public key hashes of a rollup"
~query:RPC_query.empty
~output
RPC_path.(path_sc_rollup / "stakers")
let conflicts =
let output =
Sc_rollup.(Data_encoding.list Refutation_storage.conflict_encoding)
in
RPC_service.get_service
~description:"List of stakers in conflict with the given staker"
~query:RPC_query.empty
~output
RPC_path.(
path_sc_rollup / "staker" /: Sc_rollup.Staker.rpc_arg / "conflicts")
let timeout =
let output = Data_encoding.option Sc_rollup.Game.timeout_encoding in
RPC_service.get_service
~description:"Returns the timeout of players."
~query:RPC_query.empty
~output
RPC_path.(
path_sc_rollup / "staker1" /: Sc_rollup.Staker.rpc_arg_staker1
/ "staker2" /: Sc_rollup.Staker.rpc_arg_staker2 / "timeout")
let timeout_reached =
let output = Data_encoding.option Sc_rollup.Game.game_result_encoding in
RPC_service.get_service
~description:
"Returns whether the timeout creates a result for the game."
~query:RPC_query.empty
~output
RPC_path.(
path_sc_rollup / "staker1" /: Sc_rollup.Staker.rpc_arg_staker1
/ "staker2" /: Sc_rollup.Staker.rpc_arg_staker2 / "timeout_reached")
let can_be_cemented =
let output = Data_encoding.bool in
RPC_service.get_service
~description:
"Returns true if and only if the provided commitment can be cemented."
~query:RPC_query.empty
~output
RPC_path.(
path_sc_rollup / "commitment" /: Sc_rollup.Commitment.Hash.rpc_arg
/ "can_be_cemented")
let root =
RPC_service.get_service
~description:"List of all originated smart rollups"
~query:RPC_query.empty
~output:(Data_encoding.list Sc_rollup.Address.encoding)
path_sc_rollups
let inbox =
RPC_service.get_service
~description:"Inbox for the smart rollups"
~query:RPC_query.empty
~output:Sc_rollup.Inbox.encoding
RPC_path.(path_sc_rollups / "inbox")
let ticket_balance =
let open Data_encoding in
RPC_service.post_service
~description:
"Access the smart rollup's balance of ticket with specified \
ticketer, content type, and content."
~query:RPC_query.empty
~input:Ticket_token.unparsed_token_encoding
~output:n
RPC_path.(path_sc_rollup / "ticket_balance")
let whitelist =
RPC_service.get_service
~description:
"Whitelist for private smart rollups. If the output is None then the \
rollup is public."
~query:RPC_query.empty
~output:Data_encoding.(option Sc_rollup.Whitelist.encoding)
RPC_path.(path_sc_rollup / "whitelist")
let last_whitelist_update =
RPC_service.get_service
~description:
"Last whitelist update for private smart rollups. If the output is \
None then the rollup is public."
~query:RPC_query.empty
~output:
Data_encoding.(
option Sc_rollup.Whitelist.last_whitelist_update_encoding)
RPC_path.(path_sc_rollup / "last_whitelist_update")
end
let kind ctxt block sc_rollup_address =
RPC_context.make_call1 S.kind ctxt block sc_rollup_address ()
let register_inbox () =
let open Lwt_result_syntax in
Registration.register0 ~chunked:true S.inbox (fun ctxt () () ->
let+ inbox, _ctxt = Sc_rollup.Inbox.get_inbox ctxt in
inbox)
let register_whitelist () =
Registration.register1 ~chunked:true S.whitelist (fun ctxt address () () ->
Sc_rollup.Whitelist.find_whitelist_uncarbonated ctxt address)
let register_last_whitelist_update () =
let open Lwt_result_syntax in
Registration.register1
~chunked:true
S.last_whitelist_update
(fun ctxt address () () ->
let* ctxt, is_private = Sc_rollup.Whitelist.is_private ctxt address in
if is_private then
let* _ctxt, last_whitelist_update =
Sc_rollup.Whitelist.get_last_whitelist_update ctxt address
in
return_some last_whitelist_update
else return_none)
let register_kind () =
let open Lwt_result_syntax in
Registration.opt_register1 ~chunked:true S.kind @@ fun ctxt address () () ->
let+ _ctxt, kind = Alpha_context.Sc_rollup.kind ctxt address in
Some kind
let register_genesis_info () =
let open Lwt_result_syntax in
Registration.register1 ~chunked:true S.genesis_info
@@ fun ctxt address () () ->
let+ _ctxt, genesis_info =
Alpha_context.Sc_rollup.genesis_info ctxt address
in
genesis_info
let register_last_cemented_commitment_hash_with_level () =
let open Lwt_result_syntax in
Registration.register1
~chunked:false
S.last_cemented_commitment_hash_with_level
@@ fun ctxt address () () ->
let+ last_cemented_commitment, level, _ctxt =
Alpha_context.Sc_rollup.Commitment
.last_cemented_commitment_hash_with_level
ctxt
address
in
(last_cemented_commitment, level)
let register_staked_on_commitment () =
let open Lwt_result_syntax in
Registration.register2 ~chunked:false S.staked_on_commitment
@@ fun ctxt address staker () () ->
let* ctxt, commitment_hash =
Alpha_context.Sc_rollup.Stake_storage.find_staker ctxt address staker
in
match commitment_hash with
| None -> return_none
| Some commitment_hash ->
let+ commitment, _ctxt =
Alpha_context.Sc_rollup.Commitment.get_commitment
ctxt
address
commitment_hash
in
Some (commitment_hash, commitment)
let register_commitment () =
let open Lwt_result_syntax in
Registration.register2 ~chunked:false S.commitment
@@ fun ctxt address commitment_hash () () ->
let+ commitment, _ =
Alpha_context.Sc_rollup.Commitment.get_commitment
ctxt
address
commitment_hash
in
commitment
let register_root () =
Registration.register0 ~chunked:true S.root (fun context () () ->
Sc_rollup.list_unaccounted context)
let register_ongoing_refutation_games () =
let open Lwt_result_syntax in
Registration.register2
~chunked:false
S.ongoing_refutation_games
(fun context rollup staker () () ->
let open Sc_rollup.Game.Index in
let open Sc_rollup.Refutation_storage in
let+ game, _ = get_ongoing_games_for_staker context rollup staker in
List.map (fun (game, index) -> (game, index.alice, index.bob)) game)
let register_commitments () =
Registration.register2
~chunked:false
S.commitments
(fun context rollup inbox_level () () ->
Sc_rollup.Stake_storage.commitments_uncarbonated
context
~rollup
~inbox_level)
let register_stakers_ids () =
Registration.register2
~chunked:false
S.stakers_ids
(fun context rollup commitment () () ->
Sc_rollup.Stake_storage.stakers_ids_uncarbonated
context
~rollup
~commitment)
let register_staker_id () =
Registration.register2
~chunked:false
S.staker_id
(fun context rollup pkh () () ->
Sc_rollup.Stake_storage.staker_id_uncarbonated context ~rollup ~pkh)
let register_stakers () =
let open Lwt_result_syntax in
Registration.register1 ~chunked:false S.stakers (fun context rollup () () ->
let*! stakers_pkhs =
Sc_rollup.Stake_storage.stakers_pkhs_uncarbonated context ~rollup
in
return stakers_pkhs)
let register_conflicts () =
Registration.register2
~chunked:false
S.conflicts
(fun context rollup staker () () ->
Sc_rollup.Refutation_storage.conflicting_stakers_uncarbonated
context
rollup
staker)
let register_timeout () =
let open Lwt_result_syntax in
Registration.register3
~chunked:false
S.timeout
(fun context rollup staker1 staker2 () () ->
let index = Sc_rollup.Game.Index.make staker1 staker2 in
let*! res =
Sc_rollup.Refutation_storage.get_timeout context rollup index
in
match res with
| Ok (timeout, _context) -> return_some timeout
| Error _ -> return_none)
let register_timeout_reached () =
let open Lwt_result_syntax in
Registration.register3
~chunked:false
S.timeout_reached
(fun context rollup staker1 staker2 () () ->
let index = Sc_rollup.Game.Index.make staker1 staker2 in
let*! res = Sc_rollup.Refutation_storage.timeout context rollup index in
match res with
| Ok (game_result, _context) -> return_some game_result
| Error _ -> return_none)
let register_can_be_cemented () =
let open Lwt_result_syntax in
Registration.register2
~chunked:false
S.can_be_cemented
(fun context rollup commitment_hash () () ->
let*! res = Sc_rollup.Stake_storage.cement_commitment context rollup in
match res with
| Ok (_context, _cemented_commitment, cemented_commitment_hash)
when Sc_rollup.Commitment.Hash.equal
commitment_hash
cemented_commitment_hash ->
return_true
| Ok _ | Error _ -> return_false)
let register_ticket_balance () =
Registration.register1
~chunked:false
S.ticket_balance
(fun ctxt sc_rollup () Ticket_token.{ticketer; contents_type; contents} ->
let open Lwt_result_syntax in
let* ticket_hash, ctxt =
Ticket_balance_key.make
ctxt
~owner:(Sc_rollup sc_rollup)
~ticketer
~contents_type:(Micheline.root contents_type)
~contents:(Micheline.root contents)
in
let* amount, _ctxt = Ticket_balance.get_balance ctxt ticket_hash in
return @@ Option.value amount ~default:Z.zero)
let register () =
register_kind () ;
register_inbox () ;
register_whitelist () ;
register_last_whitelist_update () ;
register_genesis_info () ;
register_last_cemented_commitment_hash_with_level () ;
register_staked_on_commitment () ;
register_commitment () ;
register_root () ;
register_ongoing_refutation_games () ;
register_commitments () ;
register_stakers_ids () ;
register_staker_id () ;
register_stakers () ;
register_conflicts () ;
register_timeout () ;
register_timeout_reached () ;
register_can_be_cemented () ;
register_ticket_balance ()
let list ctxt block = RPC_context.make_call0 S.root ctxt block () ()
let inbox ctxt block = RPC_context.make_call0 S.inbox ctxt block () ()
let whitelist ctxt block sc_rollup_address =
RPC_context.make_call1 S.whitelist ctxt block sc_rollup_address () ()
let last_whitelist_update ctxt block sc_rollup_address =
RPC_context.make_call1
S.last_whitelist_update
ctxt
block
sc_rollup_address
()
()
let genesis_info ctxt block sc_rollup_address =
RPC_context.make_call1 S.genesis_info ctxt block sc_rollup_address () ()
let last_cemented_commitment_hash_with_level ctxt block sc_rollup_address =
RPC_context.make_call1
S.last_cemented_commitment_hash_with_level
ctxt
block
sc_rollup_address
()
()
let staked_on_commitment ctxt block sc_rollup_address staker =
RPC_context.make_call2
S.staked_on_commitment
ctxt
block
sc_rollup_address
staker
()
()
let commitment ctxt block sc_rollup_address commitment_hash =
RPC_context.make_call2
S.commitment
ctxt
block
sc_rollup_address
commitment_hash
()
()
let ongoing_refutation_games ctxt block sc_rollup_address staker =
RPC_context.make_call2
S.ongoing_refutation_games
ctxt
block
sc_rollup_address
staker
()
()
let commitments ctxt rollup inbox_level =
RPC_context.make_call2 S.commitments ctxt rollup inbox_level
let stakers_ids ctxt rollup commitment =
RPC_context.make_call2 S.stakers_ids ctxt rollup commitment
let staker_id ctxt rollup pkh =
RPC_context.make_call2 S.staker_id ctxt rollup pkh
let stakers ctxt rollup = RPC_context.make_call1 S.stakers ctxt rollup
let conflicts ctxt block sc_rollup_address staker =
RPC_context.make_call2 S.conflicts ctxt block sc_rollup_address staker () ()
let timeout_reached ctxt block sc_rollup_address staker1 staker2 =
RPC_context.make_call3
S.timeout_reached
ctxt
block
sc_rollup_address
staker1
staker2
()
()
let can_be_cemented ctxt block sc_rollup_address commitment_hash =
RPC_context.make_call2
S.can_be_cemented
ctxt
block
sc_rollup_address
commitment_hash
()
()
let get_ticket_balance ctxt block sc_rollup key =
RPC_context.make_call1 S.ticket_balance ctxt block sc_rollup () key
end
type Environment.Error_monad.error +=
let () =
Environment.Error_monad.register_error_kind
`Permanent
~id:"published_slot_headers_not_initialized"
~title:"The published slot headers bucket not initialized in the context"
~description:
"The published slot headers bucket is not initialized in the context"
~pp:(fun ppf level ->
Format.fprintf
ppf
"The published slot headers bucket is not initialized in the context \
at level %a"
Raw_level.pp
level)
Data_encoding.(obj1 (req "level" Raw_level.encoding))
(function
| Published_slot_headers_not_initialized level -> Some level | _ -> None)
(fun level -> Published_slot_headers_not_initialized level)
module Dal = struct
let path : RPC_context.t RPC_path.context =
RPC_path.(open_root / "context" / "dal")
module S = struct
let dal_commitments_history =
let output = Data_encoding.option Dal.Slots_history.encoding in
let query = RPC_query.(seal @@ query ()) in
RPC_service.get_service
~description:
"Returns the (currently last) DAL skip list cell if DAL is enabled, \
or [None] otherwise."
~output
~query
RPC_path.(path / "commitments_history")
let level_query =
RPC_query.(
query (fun level -> level)
|+ opt_field "level" Raw_level.rpc_arg (fun t -> t)
|> seal)
type shards_query = {
level : Raw_level.t option;
delegates : Signature.Public_key_hash.t list;
}
let shards_query =
let open RPC_query in
query (fun level delegates -> {level; delegates})
|+ opt_field "level" Raw_level.rpc_arg (fun t -> t.level)
|+ multi_field "delegates" Signature.Public_key_hash.rpc_arg (fun t ->
t.delegates)
|> seal
type shards_assignment = {
delegate : Signature.Public_key_hash.t;
indexes : int list;
}
let shards_assignment_encoding =
let open Data_encoding in
conv
(fun {delegate; indexes} -> (delegate, indexes))
(fun (delegate, indexes) -> {delegate; indexes})
(obj2
(req "delegate" Signature.Public_key_hash.encoding)
(req "indexes" (list int16)))
type shards_output = shards_assignment list
let shards =
RPC_service.get_service
~description:
"Get the shards assignment for a given level (the default is the \
current level) and given delegates (the default is all delegates)"
~query:shards_query
~output:(Data_encoding.list shards_assignment_encoding)
RPC_path.(path / "shards")
let =
let output = Data_encoding.(list Dal.Slot.Header.encoding) in
RPC_service.get_service
~description:"Get the published slots headers for the given level"
~query:level_query
~output
RPC_path.(path / "published_slot_headers")
end
let register_dal_commitments_history () =
let open Lwt_result_syntax in
Registration.register0
~chunked:false
S.dal_commitments_history
(fun ctxt () () ->
if (Constants.parametric ctxt).dal.feature_enable then
let+ result = Dal.Slots_storage.get_slot_headers_history ctxt in
Option.some result
else return_none)
let dal_commitments_history ctxt block =
RPC_context.make_call0 S.dal_commitments_history ctxt block () ()
let dal_shards ctxt block ?level ?(delegates = []) () =
RPC_context.make_call0 S.shards ctxt block {level; delegates} ()
let register_shards () =
Registration.register0 ~chunked:true S.shards @@ fun ctxt q () ->
let open Lwt_result_syntax in
let*? level_opt =
Option.map_e (Level.from_raw_with_offset ctxt ~offset:0l) q.level
in
let level = Option.value level_opt ~default:(Level.current ctxt) in
let* _ctxt, map = Dal_services.shards ctxt ~level in
let query_delegates = Signature.Public_key_hash.Set.of_list q.delegates in
let all_delegates =
Signature.Public_key_hash.Set.is_empty query_delegates
in
Signature.Public_key_hash.Map.fold
(fun delegate indexes acc ->
if
all_delegates
|| Signature.Public_key_hash.Set.mem delegate query_delegates
then ({delegate; indexes} : S.shards_assignment) :: acc
else acc)
map
[]
|> return
let ctxt block ?level () =
RPC_context.make_call0 S.published_slot_headers ctxt block level ()
let () =
let open Lwt_result_syntax in
Registration.register0 ~chunked:true S.published_slot_headers
@@ fun ctxt level () ->
let level = Option.value level ~default:(Level.current ctxt).level in
let* result = Dal.Slot.find_slot_headers ctxt level in
match result with
| Some l -> return l
| None ->
Environment.Error_monad.tzfail
@@ Published_slot_headers_not_initialized level
let register () =
register_dal_commitments_history () ;
register_shards () ;
register_published_slot_headers ()
end
module Forge = struct
module S = struct
open Data_encoding
let path = RPC_path.(path / "forge")
let operations_encoding =
union
[
case
~title:"operations_encoding"
(Tag 0)
Operation.unsigned_encoding
Option.some
Fun.id;
case
~title:"operations_encoding_with_legacy_attestation_name"
Json_only
Operation.unsigned_encoding_with_legacy_attestation_name
Option.some
Fun.id;
]
let operations =
RPC_service.post_service
~description:"Forge an operation"
~query:RPC_query.empty
~input:operations_encoding
~output:(bytes Hex)
RPC_path.(path / "operations")
let empty_proof_of_work_nonce =
Bytes.make Constants_repr.proof_of_work_nonce_size '\000'
let protocol_data =
RPC_service.post_service
~description:"Forge the protocol-specific part of a block header"
~query:RPC_query.empty
~input:
(obj5
(req "payload_hash" Block_payload_hash.encoding)
(req "payload_round" Round.encoding)
(opt "nonce_hash" Nonce_hash.encoding)
(dft
"proof_of_work_nonce"
(Fixed.bytes
Hex
Alpha_context.Constants.proof_of_work_nonce_size)
empty_proof_of_work_nonce)
Per_block_votes.(
dft
"per_block_votes"
per_block_votes_encoding
{
liquidity_baking_vote = Per_block_vote_pass;
adaptive_issuance_vote = Per_block_vote_pass;
}))
~output:(obj1 (req "protocol_data" (bytes Hex)))
RPC_path.(path / "protocol_data")
end
let register () =
let open Lwt_result_syntax in
Registration.register0_noctxt
~chunked:true
S.operations
(fun () operation ->
return
(Data_encoding.Binary.to_bytes_exn
Operation.unsigned_encoding
operation)) ;
Registration.register0_noctxt
~chunked:true
S.protocol_data
(fun
()
( payload_hash,
payload_round,
seed_nonce_hash,
proof_of_work_nonce,
per_block_votes )
->
return
(Data_encoding.Binary.to_bytes_exn
Block_header.contents_encoding
{
payload_hash;
payload_round;
seed_nonce_hash;
proof_of_work_nonce;
per_block_votes;
}))
module Manager = struct
let operations ctxt block ~branch ~source ?sourcePubKey ~counter ~fee
~gas_limit ~storage_limit operations =
let open Lwt_result_syntax in
let*! result = Contract_services.manager_key ctxt block source in
match result with
| Error _ as e -> Lwt.return e
| Ok revealed ->
let ops =
List.map
(fun (Manager operation) ->
Contents
(Manager_operation
{source; counter; operation; fee; gas_limit; storage_limit}))
operations
in
let ops =
match (sourcePubKey, revealed) with
| None, _ | _, Some _ -> ops
| Some pk, None ->
let operation = Reveal pk in
Contents
(Manager_operation
{source; counter; operation; fee; gas_limit; storage_limit})
:: ops
in
let*? ops = Environment.wrap_tzresult @@ Operation.of_list ops in
RPC_context.make_call0 S.operations ctxt block () ({branch}, ops)
let reveal ctxt block ~branch ~source ~sourcePubKey ~counter ~fee () =
operations
ctxt
block
~branch
~source
~sourcePubKey
~counter
~fee
~gas_limit:Gas.Arith.zero
~storage_limit:Z.zero
[]
let transaction ctxt block ~branch ~source ?sourcePubKey ~counter ~amount
~destination ?(entrypoint = Entrypoint.default) ?parameters ~gas_limit
~storage_limit ~fee () =
let parameters =
Option.fold
~some:Script.lazy_expr
~none:Script.unit_parameter
parameters
in
operations
ctxt
block
~branch
~source
?sourcePubKey
~counter
~fee
~gas_limit
~storage_limit
[Manager (Transaction {amount; parameters; destination; entrypoint})]
let origination ctxt block ~branch ~source ?sourcePubKey ~counter ~balance
?delegatePubKey ~script ~gas_limit ~storage_limit ~fee () =
operations
ctxt
block
~branch
~source
?sourcePubKey
~counter
~fee
~gas_limit
~storage_limit
[
Manager
(Origination {delegate = delegatePubKey; script; credit = balance});
]
let delegation ctxt block ~branch ~source ?sourcePubKey ~counter ~fee
delegate =
operations
ctxt
block
~branch
~source
?sourcePubKey
~counter
~fee
~gas_limit:Gas.Arith.zero
~storage_limit:Z.zero
[Manager (Delegation delegate)]
end
let operation ctxt block ~branch operation =
RPC_context.make_call0
S.operations
ctxt
block
()
({branch}, Contents_list (Single operation))
let attestation ctxt b ~branch ~consensus_content ?dal_content () =
operation ctxt b ~branch (Attestation {consensus_content; dal_content})
let proposals ctxt b ~branch ~source ~period ~proposals () =
operation ctxt b ~branch (Proposals {source; period; proposals})
let ballot ctxt b ~branch ~source ~period ~proposal ~ballot () =
operation ctxt b ~branch (Ballot {source; period; proposal; ballot})
let failing_noop ctxt b ~branch ~message () =
operation ctxt b ~branch (Failing_noop message)
let seed_nonce_revelation ctxt block ~branch ~level ~nonce () =
operation ctxt block ~branch (Seed_nonce_revelation {level; nonce})
let vdf_revelation ctxt block ~branch ~solution () =
operation ctxt block ~branch (Vdf_revelation {solution})
let double_baking_evidence ctxt block ~branch ~bh1 ~bh2 () =
operation ctxt block ~branch (Double_baking_evidence {bh1; bh2})
let double_attestation_evidence ctxt block ~branch ~op1 ~op2 () =
operation ctxt block ~branch (Double_attestation_evidence {op1; op2})
let double_preattestation_evidence ctxt block ~branch ~op1 ~op2 () =
operation ctxt block ~branch (Double_preattestation_evidence {op1; op2})
let empty_proof_of_work_nonce =
Bytes.make Constants_repr.proof_of_work_nonce_size '\000'
let protocol_data ctxt block ?(payload_hash = Block_payload_hash.zero)
?(payload_round = Round.zero) ?seed_nonce_hash
?(proof_of_work_nonce = empty_proof_of_work_nonce)
~liquidity_baking_toggle_vote ~adaptive_issuance_vote () =
RPC_context.make_call0
S.protocol_data
ctxt
block
()
( payload_hash,
payload_round,
seed_nonce_hash,
proof_of_work_nonce,
{
liquidity_baking_vote = liquidity_baking_toggle_vote;
adaptive_issuance_vote;
} )
end
module Parse = struct
module S = struct
open Data_encoding
let path = RPC_path.(path / "parse")
let operations_query =
let open RPC_query in
query (fun version ->
object
method version = version
end)
|+ field "version" version_arg default_operations_version (fun t ->
t#version)
|> seal
let parse_operations_encoding =
encoding_versioning
~encoding_name:"parse_operations"
~latest_encoding:(Version_1, list (dynamic_size Operation.encoding))
~old_encodings:
[
( Version_0,
list
(dynamic_size Operation.encoding_with_legacy_attestation_name)
);
]
let operations =
RPC_service.post_service
~description:"Parse operations"
~query:operations_query
~input:
(obj2
(req "operations" (list (dynamic_size Operation.raw_encoding)))
(opt "check_signature" bool))
~output:parse_operations_encoding
RPC_path.(path / "operations")
let block =
RPC_service.post_service
~description:"Parse a block"
~query:RPC_query.empty
~input:Block_header.raw_encoding
~output:Block_header.protocol_data_encoding
RPC_path.(path / "block")
end
let parse_protocol_data protocol_data =
match
Data_encoding.Binary.of_bytes_opt
Block_header.protocol_data_encoding
protocol_data
with
| None -> Stdlib.failwith "Cant_parse_protocol_data"
| Some protocol_data -> protocol_data
let parse_operation (op : Operation.raw) =
let open Result_syntax in
match
Data_encoding.Binary.of_bytes_opt
Operation.protocol_data_encoding
op.proto
with
| Some protocol_data -> return {shell = op.shell; protocol_data}
| None -> Environment.Error_monad.error Plugin_errors.Cannot_parse_operation
let register () =
let open Lwt_result_syntax in
Registration.register0
~chunked:true
S.operations
(fun _ctxt params (operations, check) ->
let* ops =
List.map_es
(fun raw ->
let*? op = parse_operation raw in
let () =
match check with
| Some true -> ()
| Some false | None -> ()
in
return op)
operations
in
let version = params#version in
return (version, ops)) ;
Registration.register0_noctxt ~chunked:false S.block (fun () raw_block ->
return @@ parse_protocol_data raw_block.protocol_data)
let operations ctxt block ?(version = default_operations_version) ?check
operations =
let open Lwt_result_syntax in
let*! v =
RPC_context.make_call0
S.operations
ctxt
block
(object
method version = version
end)
(operations, check)
in
match v with
| Error e -> tzfail e
| Ok ((Version_0 | Version_1), parse_operation) -> return parse_operation
let block ctxt block shell protocol_data =
RPC_context.make_call0
S.block
ctxt
block
()
({shell; protocol_data} : Block_header.raw)
end
let estimated_time round_durations ~current_level ~current_round
~current_timestamp ~level ~round =
let open Result_syntax in
if Level.(level <= current_level) then return_none
else
let* round_start_at_next_level =
Round.timestamp_of_round
round_durations
~round
~predecessor_timestamp:current_timestamp
~predecessor_round:current_round
in
let step = Round.round_duration round_durations Round.zero in
let diff = Level.diff level current_level in
let* delay = Period.mult (Int32.pred diff) step in
let* timestamp = Timestamp.(round_start_at_next_level +? delay) in
return_some timestamp
let requested_levels ~default_level ctxt cycles levels =
match (levels, cycles) with
| [], [] -> [default_level]
| levels, cycles ->
List.sort_uniq
Level.compare
(List.rev_append
(List.rev_map (Level.from_raw ctxt) levels)
(List.concat_map (Level.levels_in_cycle ctxt) cycles))
module Baking_rights = struct
type t = {
level : Raw_level.t;
delegate : public_key_hash;
consensus_key : public_key_hash;
round : Round.t;
timestamp : Timestamp.t option;
}
let encoding =
let open Data_encoding in
conv
(fun {level; delegate; consensus_key; round; timestamp} ->
(level, delegate, round, timestamp, consensus_key))
(fun (level, delegate, round, timestamp, consensus_key) ->
{level; delegate; consensus_key; round; timestamp})
(obj5
(req "level" Raw_level.encoding)
(req "delegate" Signature.Public_key_hash.encoding)
(req "round" Round.encoding)
(opt "estimated_time" Timestamp.encoding)
(req "consensus_key" Signature.Public_key_hash.encoding))
let default_max_round = 64
module S = struct
open Data_encoding
let path = RPC_path.(open_root / "helpers" / "baking_rights")
type baking_rights_query = {
levels : Raw_level.t list;
cycle : Cycle.t option;
delegates : Signature.Public_key_hash.t list;
consensus_keys : Signature.Public_key_hash.t list;
max_round : int option;
all : bool;
}
let baking_rights_query =
let open RPC_query in
query (fun levels cycle delegates consensus_keys max_round all ->
{levels; cycle; delegates; consensus_keys; max_round; all})
|+ multi_field "level" Raw_level.rpc_arg (fun t -> t.levels)
|+ opt_field "cycle" Cycle.rpc_arg (fun t -> t.cycle)
|+ multi_field "delegate" Signature.Public_key_hash.rpc_arg (fun t ->
t.delegates)
|+ multi_field "consensus_key" Signature.Public_key_hash.rpc_arg (fun t ->
t.consensus_keys)
|+ opt_field "max_round" RPC_arg.uint (fun t -> t.max_round)
|+ flag "all" (fun t -> t.all)
|> seal
let baking_rights =
RPC_service.get_service
~description:
(Format.sprintf
"Retrieves the list of delegates allowed to bake a block.\n\
By default, it gives the best baking opportunities (in terms of \
rounds) for bakers that have at least one opportunity below the \
%dth round for the next block.\n\
Parameters `level` and `cycle` can be used to specify the \
(valid) level(s) in the past or future at which the baking \
rights have to be returned.\n\
Parameter `delegate` can be used to restrict the results to the \
given delegates. Parameter `consensus_key` can be used to \
restrict the results to the given consensus_keys. If parameter \
`all` is set, all the baking opportunities for each baker at \
each level are returned, instead of just the first one.\n\
Returns the list of baking opportunities up to round %d. Also \
returns the minimal timestamps that correspond to these \
opportunities. The timestamps are omitted for levels in the \
past, and are only estimates for levels higher that the next \
block's, based on the hypothesis that all predecessor blocks \
were baked at the first round."
default_max_round
default_max_round)
~query:baking_rights_query
~output:(list encoding)
path
end
let baking_rights_at_level ctxt max_round level =
let open Lwt_result_syntax in
let* current_round = Round.get ctxt in
let current_level = Level.current ctxt in
let current_timestamp = Timestamp.current ctxt in
let round_durations = Alpha_context.Constants.round_durations ctxt in
let rec loop ctxt acc round =
if Round.(round > max_round) then
return (ctxt, List.rev acc)
else
let* ( ctxt,
_slot,
{Consensus_key.consensus_pkh; delegate; consensus_pk = _} ) =
Stake_distribution.baking_rights_owner ctxt level ~round
in
let*? timestamp =
estimated_time
round_durations
~current_level
~current_round
~current_timestamp
~level
~round
in
let acc =
{
level = level.level;
delegate;
consensus_key = consensus_pkh;
round;
timestamp;
}
:: acc
in
loop ctxt acc (Round.succ round)
in
loop ctxt [] Round.zero
let remove_duplicated_delegates rights =
List.rev @@ fst
@@ List.fold_left
(fun (acc, previous) r ->
if
Signature.Public_key_hash.Set.exists
(Signature.Public_key_hash.equal r.delegate)
previous
then (acc, previous)
else (r :: acc, Signature.Public_key_hash.Set.add r.delegate previous))
([], Signature.Public_key_hash.Set.empty)
rights
let register () =
let open Lwt_result_syntax in
Registration.register0 ~chunked:true S.baking_rights (fun ctxt q () ->
let cycles = match q.cycle with None -> [] | Some cycle -> [cycle] in
let levels =
requested_levels
~default_level:(Level.succ ctxt (Level.current ctxt))
ctxt
cycles
q.levels
in
let*? max_round =
Round.of_int
(match q.max_round with
| None -> default_max_round
| Some max_round ->
Compare.Int.min
max_round
(Constants.consensus_committee_size ctxt))
in
let+ _ctxt, rights =
List.fold_left_map_es
(fun ctxt l -> baking_rights_at_level ctxt max_round l)
ctxt
levels
in
let rights =
if q.all then List.concat rights
else List.concat_map remove_duplicated_delegates rights
in
let rights =
match q.delegates with
| [] -> rights
| _ :: _ as delegates ->
let is_requested p =
List.exists
(Signature.Public_key_hash.equal p.delegate)
delegates
in
List.filter is_requested rights
in
let rights =
match q.consensus_keys with
| [] -> rights
| _ :: _ as delegates ->
let is_requested p =
List.exists
(Signature.Public_key_hash.equal p.consensus_key)
delegates
in
List.filter is_requested rights
in
rights)
let get ctxt ?(levels = []) ?cycle ?(delegates = []) ?(consensus_keys = [])
?(all = false) ?max_round block =
RPC_context.make_call0
S.baking_rights
ctxt
block
{levels; cycle; delegates; consensus_keys; max_round; all}
()
end
module Attestation_rights = struct
type delegate_rights = {
delegate : Signature.Public_key_hash.t;
consensus_key : Signature.Public_key_hash.t;
first_slot : Slot.t;
attestation_power : int;
}
type t = {
level : Raw_level.t;
delegates_rights : delegate_rights list;
estimated_time : Time.t option;
}
let delegate_rights_encoding =
let open Data_encoding in
conv
(fun {delegate; consensus_key; first_slot; attestation_power} ->
(delegate, first_slot, attestation_power, consensus_key))
(fun (delegate, first_slot, attestation_power, consensus_key) ->
{delegate; first_slot; attestation_power; consensus_key})
(obj4
(req "delegate" Signature.Public_key_hash.encoding)
(req "first_slot" Slot.encoding)
(req "attestation_power" uint16)
(req "consensus_key" Signature.Public_key_hash.encoding))
let encoding =
let open Data_encoding in
conv
(fun {level; delegates_rights; estimated_time} ->
(level, delegates_rights, estimated_time))
(fun (level, delegates_rights, estimated_time) ->
{level; delegates_rights; estimated_time})
(obj3
(req "level" Raw_level.encoding)
(req "delegates" (list delegate_rights_encoding))
(opt "estimated_time" Timestamp.encoding))
module S = struct
open Data_encoding
let attestation_path = RPC_path.(path / "attestation_rights")
type attestation_rights_query = {
levels : Raw_level.t list;
cycle : Cycle.t option;
delegates : Signature.Public_key_hash.t list;
consensus_keys : Signature.Public_key_hash.t list;
}
let attestation_rights_query =
let open RPC_query in
query (fun levels cycle delegates consensus_keys ->
{levels; cycle; delegates; consensus_keys})
|+ multi_field "level" Raw_level.rpc_arg (fun t -> t.levels)
|+ opt_field "cycle" Cycle.rpc_arg (fun t -> t.cycle)
|+ multi_field "delegate" Signature.Public_key_hash.rpc_arg (fun t ->
t.delegates)
|+ multi_field "consensus_key" Signature.Public_key_hash.rpc_arg (fun t ->
t.consensus_keys)
|> seal
let attestation_rights =
RPC_service.get_service
~description:
"Retrieves the delegates allowed to attest a block.\n\
By default, it gives the attestation power for delegates that have \
at least one attestation slot for the next block.\n\
Parameters `level` and `cycle` can be used to specify the (valid) \
level(s) in the past or future at which the attestation rights have \
to be returned. Parameter `delegate` can be used to restrict the \
results to the given delegates.\n\
Parameter `consensus_key` can be used to restrict the results to \
the given consensus_keys. \n\
Returns the smallest attestation slots and the attestation power. \
Also returns the minimal timestamp that corresponds to attestation \
at the given level. The timestamps are omitted for levels in the \
past, and are only estimates for levels higher that the next \
block's, based on the hypothesis that all predecessor blocks were \
baked at the first round."
~query:attestation_rights_query
~output:(list encoding)
attestation_path
end
let attestation_rights_at_level ctxt level =
let open Lwt_result_syntax in
let* ctxt, rights = Baking.attesting_rights_by_first_slot ctxt level in
let* current_round = Round.get ctxt in
let current_level = Level.current ctxt in
let current_timestamp = Timestamp.current ctxt in
let round_durations = Alpha_context.Constants.round_durations ctxt in
let*? estimated_time =
estimated_time
round_durations
~current_level
~current_round
~current_timestamp
~level
~round:Round.zero
in
let rights =
Slot.Map.fold
(fun first_slot
( {
Consensus_key.delegate;
consensus_pk = _;
consensus_pkh = consensus_key;
},
attestation_power,
_dal_power )
acc ->
{delegate; consensus_key; first_slot; attestation_power} :: acc)
rights
[]
in
return
(ctxt, {level = level.level; delegates_rights = rights; estimated_time})
let get_attestation_rights ctxt (q : S.attestation_rights_query) =
let open Lwt_result_syntax in
let cycles = match q.cycle with None -> [] | Some cycle -> [cycle] in
let levels =
requested_levels ~default_level:(Level.current ctxt) ctxt cycles q.levels
in
let+ _ctxt, rights_per_level =
List.fold_left_map_es attestation_rights_at_level ctxt levels
in
let rights_per_level =
match (q.consensus_keys, q.delegates) with
| [], [] -> rights_per_level
| _, _ ->
let is_requested p =
List.exists
(Signature.Public_key_hash.equal p.consensus_key)
q.consensus_keys
|| List.exists
(Signature.Public_key_hash.equal p.delegate)
q.delegates
in
List.filter_map
(fun rights_at_level ->
match
List.filter is_requested rights_at_level.delegates_rights
with
| [] -> None
| delegates_rights -> Some {rights_at_level with delegates_rights})
rights_per_level
in
rights_per_level
let register () =
Registration.register0 ~chunked:true S.attestation_rights (fun ctxt q () ->
get_attestation_rights ctxt q)
let get ctxt ?(levels = []) ?cycle ?(delegates = []) ?(consensus_keys = [])
block =
RPC_context.make_call0
S.attestation_rights
ctxt
block
{levels; cycle; delegates; consensus_keys}
()
end
module Validators = struct
type t = {
level : Raw_level.t;
delegate : Signature.Public_key_hash.t;
consensus_key : Signature.public_key_hash;
slots : Slot.t list;
}
let encoding =
let open Data_encoding in
conv
(fun {level; delegate; consensus_key; slots} ->
(level, delegate, slots, consensus_key))
(fun (level, delegate, slots, consensus_key) ->
{level; delegate; consensus_key; slots})
(obj4
(req "level" Raw_level.encoding)
(req "delegate" Signature.Public_key_hash.encoding)
(req "slots" (list Slot.encoding))
(req "consensus_key" Signature.Public_key_hash.encoding))
module S = struct
open Data_encoding
let path = RPC_path.(path / "validators")
type validators_query = {
levels : Raw_level.t list;
delegates : Signature.Public_key_hash.t list;
consensus_keys : Signature.Public_key_hash.t list;
}
let validators_query =
let open RPC_query in
query (fun levels delegates consensus_keys ->
{levels; delegates; consensus_keys})
|+ multi_field "level" Raw_level.rpc_arg (fun t -> t.levels)
|+ multi_field "delegate" Signature.Public_key_hash.rpc_arg (fun t ->
t.delegates)
|+ multi_field "consensus_key" Signature.Public_key_hash.rpc_arg (fun t ->
t.consensus_keys)
|> seal
let validators =
RPC_service.get_service
~description:
"Retrieves the level, the attestation slots and the public key hash \
of each delegate allowed to attest a block.\n\
By default, it provides this information for the next level.\n\
Parameter `level` can be used to specify the (valid) level(s) in \
the past or future at which the attestation rights have to be \
returned. Parameter `delegate` can be used to restrict the results \
results to the given delegates. Parameter `consensus_key` can be \
used to restrict the results to the given consensus_keys.\n"
~query:validators_query
~output:(list encoding)
path
end
let add_attestation_slots_at_level (ctxt, acc) level =
let open Lwt_result_syntax in
let+ ctxt, rights = Baking.attesting_rights ctxt level in
( ctxt,
Signature.Public_key_hash.Map.fold
(fun _pkh {Baking.delegate; consensus_key; slots} acc ->
{level = level.level; delegate; consensus_key; slots} :: acc)
rights
acc )
let register () =
let open Lwt_result_syntax in
Registration.register0 ~chunked:true S.validators (fun ctxt q () ->
let levels =
requested_levels ~default_level:(Level.current ctxt) ctxt [] q.levels
in
let+ _ctxt, rights =
List.fold_left_es
add_attestation_slots_at_level
(ctxt, [])
(List.rev levels)
in
let rights =
match q.delegates with
| [] -> rights
| _ :: _ as delegates ->
let is_requested p =
List.exists
(Signature.Public_key_hash.equal p.delegate)
delegates
in
List.filter is_requested rights
in
let rights =
match q.consensus_keys with
| [] -> rights
| _ :: _ as delegates ->
let is_requested p =
List.exists
(Signature.Public_key_hash.equal p.consensus_key)
delegates
in
List.filter is_requested rights
in
rights)
let get ctxt ?(levels = []) ?(delegates = []) ?(consensus_keys = []) block =
RPC_context.make_call0
S.validators
ctxt
block
{levels; delegates; consensus_keys}
()
end
module Delegates = struct
let check_delegate_registered ctxt pkh =
let open Lwt_result_syntax in
let*! result = Delegate.registered ctxt pkh in
if result then return_unit
else Environment.Error_monad.tzfail (Delegate_services.Not_registered pkh)
module S = struct
let path =
RPC_path.(
open_root / "context" / "delegates" /: Signature.Public_key_hash.rpc_arg)
let info =
RPC_service.get_service
~description:"Everything about a delegate."
~query:RPC_query.empty
~output:Delegate_services.info_encoding
path
let delegated_balance =
RPC_service.get_service
~description:
"Returns the sum (in mutez) of all balances of all the contracts \
that delegate to a given delegate. This excludes the delegate's own \
balance, its frozen deposits and its frozen bonds."
~query:RPC_query.empty
~output:Tez.encoding
RPC_path.(path / "delegated_balance")
end
let unstake_requests ctxt pkh =
let open Lwt_result_syntax in
let* result = Unstake_requests.prepare_finalize_unstake ctxt pkh in
match result with
| None -> return_none
| Some {finalizable; unfinalizable} ->
let* unfinalizable =
Unstake_requests.For_RPC
.apply_slash_to_unstaked_unfinalizable_stored_requests
ctxt
unfinalizable
in
return_some Unstake_requests.{finalizable; unfinalizable}
let overrided_delegated_balance ctxt pkh =
let open Lwt_result_syntax in
let* full_balance = Delegate.For_RPC.full_balance ctxt pkh in
let* unstake_requests = unstake_requests ctxt (Implicit pkh) in
let* unstake_requests_to_other_delegates =
match unstake_requests with
| None -> return Tez.zero
| Some {finalizable; unfinalizable} ->
let* finalizable_sum =
List.fold_left_es
(fun acc (delegate, _, (amount : Tez.t)) ->
if Signature.Public_key_hash.(delegate <> pkh) then
Lwt.return Tez.(acc +? amount)
else return acc)
Tez.zero
finalizable
in
let* unfinalizable_sum =
if Signature.Public_key_hash.(unfinalizable.delegate <> pkh) then
List.fold_left_es
(fun acc (_, (amount : Tez.t)) ->
Lwt.return Tez.(acc +? amount))
Tez.zero
unfinalizable.requests
else return Tez.zero
in
Lwt.return Tez.(finalizable_sum +? unfinalizable_sum)
in
let* staking_balance = Delegate.For_RPC.staking_balance ctxt pkh in
let*? self_staking_balance =
Tez.(full_balance -? unstake_requests_to_other_delegates)
in
let*? sum = Tez.(staking_balance -? self_staking_balance) in
return sum
let info ctxt pkh =
let open Lwt_result_syntax in
let open Delegate_services in
let* () = check_delegate_registered ctxt pkh in
let* full_balance = Delegate.For_RPC.full_balance ctxt pkh in
let* current_frozen_deposits = Delegate.current_frozen_deposits ctxt pkh in
let* frozen_deposits = Delegate.initial_frozen_deposits ctxt pkh in
let* staking_balance = Delegate.For_RPC.staking_balance ctxt pkh in
let* frozen_deposits_limit = Delegate.frozen_deposits_limit ctxt pkh in
let*! delegated_contracts = Delegate.delegated_contracts ctxt pkh in
let* delegated_balance = overrided_delegated_balance ctxt pkh in
let* min_delegated_in_current_cycle =
Delegate.For_RPC.min_delegated_in_current_cycle ctxt pkh
in
let* total_delegated_stake =
Staking_pseudotokens.For_RPC.get_frozen_deposits_staked_tez
ctxt
~delegate:pkh
in
let* staking_denominator =
Staking_pseudotokens.For_RPC.get_frozen_deposits_pseudotokens
ctxt
~delegate:pkh
in
let* deactivated = Delegate.deactivated ctxt pkh in
let* grace_period = Delegate.last_cycle_before_deactivation ctxt pkh in
let*! pending_denunciations =
Delegate.For_RPC.has_pending_denunciations ctxt pkh
in
let* voting_info = Vote.get_delegate_info ctxt pkh in
let* consensus_key = Delegate.Consensus_key.active_pubkey ctxt pkh in
let+ pendings = Delegate.Consensus_key.pending_updates ctxt pkh in
let pending_consensus_keys =
List.map (fun (cycle, pkh, _) -> (cycle, pkh)) pendings
in
{
full_balance;
current_frozen_deposits;
frozen_deposits;
staking_balance;
frozen_deposits_limit;
delegated_contracts;
delegated_balance;
min_delegated_in_current_cycle;
total_delegated_stake;
staking_denominator;
deactivated;
grace_period;
pending_denunciations;
voting_info;
active_consensus_key = consensus_key.consensus_pkh;
pending_consensus_keys;
}
let register () =
let open Lwt_result_syntax in
Registration.register1 ~chunked:false S.info (fun ctxt pkh () () ->
info ctxt pkh) ;
Registration.register1
~chunked:false
S.delegated_balance
(fun ctxt pkh () () ->
let* () = check_delegate_registered ctxt pkh in
overrided_delegated_balance ctxt pkh)
let delegated_balance ctxt block pkh =
RPC_context.make_call1 S.delegated_balance ctxt block pkh () ()
let info ctxt block pkh = RPC_context.make_call1 S.info ctxt block pkh () ()
end
module Staking = struct
let path =
RPC_path.(
open_root / "context" / "delegates" /: Signature.Public_key_hash.rpc_arg)
let stakers_encoding =
let open Data_encoding in
let staker_enconding =
obj2
(req "staker" Alpha_context.Contract.implicit_encoding)
(req "frozen_deposits" Tez.encoding)
in
list staker_enconding
module S = struct
let stakers =
RPC_service.get_service
~description:
"Returns the list of accounts that stake to a given delegate \
together with their share of the frozen deposits."
~query:RPC_query.empty
~output:stakers_encoding
RPC_path.(path / "stakers")
let is_forbidden =
RPC_service.get_service
~description:
"Returns true if the delegate is forbidden to participate in \
consensus."
~query:RPC_query.empty
~output:Data_encoding.bool
RPC_path.(path / "is_forbidden")
end
let contract_stake ctxt ~delegator_contract ~delegate =
let open Alpha_context in
let open Lwt_result_syntax in
let* staked_balance =
Staking_pseudotokens.For_RPC.staked_balance
ctxt
~contract:delegator_contract
~delegate
in
if not Tez.(staked_balance = zero) then
let delegator_pkh =
match delegator_contract with
| Contract.Implicit pkh -> pkh
| Contract.Originated _ -> assert false
in
return @@ Some (delegator_pkh, staked_balance)
else return_none
let check_is_forbidden ctxt pkh =
let open Lwt_result_syntax in
return @@ Delegate.is_forbidden_delegate ctxt pkh
let register () =
Registration.register1 ~chunked:false S.is_forbidden (fun ctxt pkh () () ->
check_is_forbidden ctxt pkh) ;
Registration.register1 ~chunked:true S.stakers (fun ctxt pkh () () ->
let open Lwt_result_syntax in
let* () = Delegates.check_delegate_registered ctxt pkh in
let*! delegators = Delegate.delegated_contracts ctxt pkh in
List.filter_map_es
(fun delegator_contract ->
contract_stake ctxt ~delegator_contract ~delegate:pkh)
delegators)
let stakers ctxt block pkh =
RPC_context.make_call1 S.stakers ctxt block pkh () ()
end
module S = struct
open Data_encoding
type level_query = {offset : int32}
let level_query : level_query RPC_query.t =
let open RPC_query in
query (fun offset -> {offset})
|+ field "offset" RPC_arg.int32 0l (fun t -> t.offset)
|> seal
let current_level =
RPC_service.get_service
~description:
"Returns the level of the interrogated block, or the one of a block \
located `offset` blocks after it in the chain. For instance, the next \
block if `offset` is 1. The offset cannot be negative."
~query:level_query
~output:Level.encoding
RPC_path.(path / "current_level")
let levels_in_current_cycle =
RPC_service.get_service
~description:"Levels of a cycle"
~query:level_query
~output:
(obj2 (req "first" Raw_level.encoding) (req "last" Raw_level.encoding))
RPC_path.(path / "levels_in_current_cycle")
let round =
RPC_service.get_service
~description:
"Returns the round of the interrogated block, or the one of a block \
located `offset` blocks after in the chain (or before when negative). \
For instance, the next block if `offset` is 1."
~query:RPC_query.empty
~output:Round.encoding
RPC_path.(path / "round")
end
type Environment.Error_monad.error += Negative_level_offset
let () =
Environment.Error_monad.register_error_kind
`Permanent
~id:"negative_level_offset"
~title:"The specified level offset is negative"
~description:"The specified level offset is negative"
~pp:(fun ppf () ->
Format.fprintf ppf "The specified level offset should be positive.")
Data_encoding.unit
(function Negative_level_offset -> Some () | _ -> None)
(fun () -> Negative_level_offset)
let register () =
let open Lwt_result_syntax in
Scripts.register () ;
Forge.register () ;
Parse.register () ;
Contract.register () ;
Big_map.register () ;
Baking_rights.register () ;
Attestation_rights.register () ;
Validators.register () ;
Sc_rollup.register () ;
Dal.register () ;
Staking.register () ;
Delegates.register () ;
Registration.register0 ~chunked:false S.current_level (fun ctxt q () ->
if q.offset < 0l then Environment.Error_monad.tzfail Negative_level_offset
else
Lwt.return
(Level.from_raw_with_offset
ctxt
~offset:q.offset
(Level.current ctxt).level)) ;
Registration.opt_register0
~chunked:true
S.levels_in_current_cycle
(fun ctxt q () ->
let rev_levels = Level.levels_in_current_cycle ctxt ~offset:q.offset () in
match rev_levels with
| [] -> return_none
| [level] -> return_some (level.level, level.level)
| last :: default_first :: rest ->
let first = List.last default_first rest in
return_some (first.level, last.level)) ;
Registration.register0 ~chunked:false S.round (fun ctxt () () ->
Round.get ctxt)
let current_level ctxt ?(offset = 0l) block =
RPC_context.make_call0 S.current_level ctxt block {offset} ()
let levels_in_current_cycle ctxt ?(offset = 0l) block =
RPC_context.make_call0 S.levels_in_current_cycle ctxt block {offset} ()
let rpc_services =
register () ;
RPC_directory.merge
~strategy:`Pick_right
rpc_services
!Registration.patched_services