package tezos-protocol-013-PtJakart

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

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

(** Tezos Protocol Implementation - Main Entry Points *)

open Alpha_context

type denunciation_kind = Preendorsement | Endorsement | Block

let denunciation_kind_encoding =
  let open Data_encoding in
  string_enum
    [
      ("preendorsement", Preendorsement);
      ("endorsement", Endorsement);
      ("block", Block);
    ]

let pp_denunciation_kind fmt : denunciation_kind -> unit = function
  | Preendorsement -> Format.fprintf fmt "preendorsement"
  | Endorsement -> Format.fprintf fmt "endorsement"
  | Block -> Format.fprintf fmt "baking"

type error +=
  | Not_enough_endorsements of {required : int; provided : int}
  | Wrong_consensus_operation_branch of Block_hash.t * Block_hash.t
  | Invalid_double_baking_evidence of {
      hash1 : Block_hash.t;
      level1 : Raw_level.t;
      round1 : Round.t;
      hash2 : Block_hash.t;
      level2 : Raw_level.t;
      round2 : Round.t;
    }
  | Wrong_level_for_consensus_operation of {
      expected : Raw_level.t;
      provided : Raw_level.t;
    }
  | Wrong_round_for_consensus_operation of {
      expected : Round.t;
      provided : Round.t;
    }
  | Preendorsement_round_too_high of {block_round : Round.t; provided : Round.t}
  | Unexpected_endorsement_in_block
  | Unexpected_preendorsement_in_block
  | Wrong_payload_hash_for_consensus_operation of {
      expected : Block_payload_hash.t;
      provided : Block_payload_hash.t;
    }
  | Wrong_slot_used_for_consensus_operation
  | Consensus_operation_for_future_level of {
      expected : Raw_level.t;
      provided : Raw_level.t;
    }
  | Consensus_operation_for_future_round of {
      expected : Round.t;
      provided : Round.t;
    }
  | Consensus_operation_for_old_level of {
      expected : Raw_level.t;
      provided : Raw_level.t;
    }
  | Consensus_operation_for_old_round of {
      expected : Round.t;
      provided : Round.t;
    }
  | Consensus_operation_on_competing_proposal of {
      expected : Block_payload_hash.t;
      provided : Block_payload_hash.t;
    }
  | Set_deposits_limit_on_unregistered_delegate of Signature.Public_key_hash.t
  | Set_deposits_limit_too_high of {limit : Tez.t; max_limit : Tez.t}
  | Empty_transaction of Contract.t
  | Tx_rollup_feature_disabled
  | Tx_rollup_invalid_transaction_amount
  | Tx_rollup_non_internal_transaction
  | Cannot_transfer_ticket_to_implicit
  | Sc_rollup_feature_disabled
  | Inconsistent_counters
  | Wrong_voting_period of {expected : int32; provided : int32}
  | Internal_operation_replay of Apply_results.packed_internal_contents
  | Invalid_denunciation of denunciation_kind
  | Inconsistent_denunciation of {
      kind : denunciation_kind;
      delegate1 : Signature.Public_key_hash.t;
      delegate2 : Signature.Public_key_hash.t;
    }
  | Unrequired_denunciation
  | Too_early_denunciation of {
      kind : denunciation_kind;
      level : Raw_level.t;
      current : Raw_level.t;
    }
  | Outdated_denunciation of {
      kind : denunciation_kind;
      level : Raw_level.t;
      last_cycle : Cycle.t;
    }
  | Invalid_activation of {pkh : Ed25519.Public_key_hash.t}
  | Multiple_revelation
  | Gas_quota_exceeded_init_deserialize
  | Inconsistent_sources
  | Failing_noop_error
  | Zero_frozen_deposits of Signature.Public_key_hash.t
  | Forbidden_zero_ticket_quantity

let () =
  register_error_kind
    `Permanent
    ~id:"operations.wrong_slot"
    ~title:"Wrong slot"
    ~description:"wrong slot"
    ~pp:(fun ppf () -> Format.fprintf ppf "wrong slot")
    Data_encoding.empty
    (function Wrong_slot_used_for_consensus_operation -> Some () | _ -> None)
    (fun () -> Wrong_slot_used_for_consensus_operation) ;
  register_error_kind
    `Permanent
    ~id:"operation.not_enough_endorsements"
    ~title:"Not enough endorsements"
    ~description:
      "The block being validated does not include the required minimum number \
       of endorsements."
    ~pp:(fun ppf (required, provided) ->
      Format.fprintf
        ppf
        "Wrong number of endorsements (%i), at least %i are expected"
        provided
        required)
    Data_encoding.(obj2 (req "required" int31) (req "provided" int31))
    (function
      | Not_enough_endorsements {required; provided} -> Some (required, provided)
      | _ -> None)
    (fun (required, provided) -> Not_enough_endorsements {required; provided}) ;
  register_error_kind
    `Temporary
    ~id:"operation.wrong_consensus_operation_branch"
    ~title:"Wrong consensus operation branch"
    ~description:
      "Trying to include an endorsement or preendorsement which points to the \
       wrong block.\n\
      \       It should be the predecessor for preendorsements and the \
       grandfather for endorsements."
    ~pp:(fun ppf (e, p) ->
      Format.fprintf
        ppf
        "Wrong branch %a, expected %a"
        Block_hash.pp
        p
        Block_hash.pp
        e)
    Data_encoding.(
      obj2
        (req "expected" Block_hash.encoding)
        (req "provided" Block_hash.encoding))
    (function
      | Wrong_consensus_operation_branch (e, p) -> Some (e, p) | _ -> None)
    (fun (e, p) -> Wrong_consensus_operation_branch (e, p)) ;
  register_error_kind
    `Permanent
    ~id:"block.invalid_double_baking_evidence"
    ~title:"Invalid double baking evidence"
    ~description:
      "A double-baking evidence is inconsistent  (two distinct level)"
    ~pp:(fun ppf (hash1, level1, round1, hash2, level2, round2) ->
      Format.fprintf
        ppf
        "Invalid double-baking evidence (hash: %a and %a, levels/rounds: \
         (%ld,%ld) and (%ld,%ld))"
        Block_hash.pp
        hash1
        Block_hash.pp
        hash2
        (Raw_level.to_int32 level1)
        (Round.to_int32 round1)
        (Raw_level.to_int32 level2)
        (Round.to_int32 round2))
    Data_encoding.(
      obj6
        (req "hash1" Block_hash.encoding)
        (req "level1" Raw_level.encoding)
        (req "round1" Round.encoding)
        (req "hash2" Block_hash.encoding)
        (req "level2" Raw_level.encoding)
        (req "round2" Round.encoding))
    (function
      | Invalid_double_baking_evidence
          {hash1; level1; round1; hash2; level2; round2} ->
          Some (hash1, level1, round1, hash2, level2, round2)
      | _ -> None)
    (fun (hash1, level1, round1, hash2, level2, round2) ->
      Invalid_double_baking_evidence
        {hash1; level1; round1; hash2; level2; round2}) ;
  register_error_kind
    `Permanent
    ~id:"wrong_level_for_consensus_operation"
    ~title:"Wrong level for consensus operation"
    ~description:"Wrong level for consensus operation."
    ~pp:(fun ppf (expected, provided) ->
      Format.fprintf
        ppf
        "Wrong level for consensus operation (expected: %a, provided: %a)."
        Raw_level.pp
        expected
        Raw_level.pp
        provided)
    Data_encoding.(
      obj2
        (req "expected" Raw_level.encoding)
        (req "provided" Raw_level.encoding))
    (function
      | Wrong_level_for_consensus_operation {expected; provided} ->
          Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) ->
      Wrong_level_for_consensus_operation {expected; provided}) ;
  register_error_kind
    `Permanent
    ~id:"wrong_round_for_consensus_operation"
    ~title:"Wrong round for consensus operation"
    ~description:"Wrong round for consensus operation."
    ~pp:(fun ppf (expected, provided) ->
      Format.fprintf
        ppf
        "Wrong round for consensus operation (expected: %a, provided: %a)."
        Round.pp
        expected
        Round.pp
        provided)
    Data_encoding.(
      obj2 (req "expected" Round.encoding) (req "provided" Round.encoding))
    (function
      | Wrong_round_for_consensus_operation {expected; provided} ->
          Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) ->
      Wrong_round_for_consensus_operation {expected; provided}) ;
  register_error_kind
    `Permanent
    ~id:"preendorsement_round_too_high"
    ~title:"Preendorsement round too high"
    ~description:"Preendorsement round too high."
    ~pp:(fun ppf (block_round, provided) ->
      Format.fprintf
        ppf
        "Preendorsement round too high (block_round: %a, provided: %a)."
        Round.pp
        block_round
        Round.pp
        provided)
    Data_encoding.(
      obj2 (req "block_round" Round.encoding) (req "provided" Round.encoding))
    (function
      | Preendorsement_round_too_high {block_round; provided} ->
          Some (block_round, provided)
      | _ -> None)
    (fun (block_round, provided) ->
      Preendorsement_round_too_high {block_round; provided}) ;
  register_error_kind
    `Permanent
    ~id:"wrong_payload_hash_for_consensus_operation"
    ~title:"Wrong payload hash for consensus operation"
    ~description:"Wrong payload hash for consensus operation."
    ~pp:(fun ppf (expected, provided) ->
      Format.fprintf
        ppf
        "Wrong payload hash for consensus operation (expected: %a, provided: \
         %a)."
        Block_payload_hash.pp_short
        expected
        Block_payload_hash.pp_short
        provided)
    Data_encoding.(
      obj2
        (req "expected" Block_payload_hash.encoding)
        (req "provided" Block_payload_hash.encoding))
    (function
      | Wrong_payload_hash_for_consensus_operation {expected; provided} ->
          Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) ->
      Wrong_payload_hash_for_consensus_operation {expected; provided}) ;
  register_error_kind
    `Permanent
    ~id:"unexpected_endorsement_in_block"
    ~title:"Unexpected endorsement in block"
    ~description:"Unexpected endorsement in block."
    ~pp:(fun ppf () -> Format.fprintf ppf "Unexpected endorsement in block.")
    Data_encoding.empty
    (function Unexpected_endorsement_in_block -> Some () | _ -> None)
    (fun () -> Unexpected_endorsement_in_block) ;
  register_error_kind
    `Permanent
    ~id:"unexpected_preendorsement_in_block"
    ~title:"Unexpected preendorsement in block"
    ~description:"Unexpected preendorsement in block."
    ~pp:(fun ppf () -> Format.fprintf ppf "Unexpected preendorsement in block.")
    Data_encoding.empty
    (function Unexpected_preendorsement_in_block -> Some () | _ -> None)
    (fun () -> Unexpected_preendorsement_in_block) ;
  register_error_kind
    `Temporary
    ~id:"consensus_operation_for_future_level"
    ~title:"Consensus operation for future level"
    ~description:"Consensus operation for future level."
    ~pp:(fun ppf (expected, provided) ->
      Format.fprintf
        ppf
        "Consensus operation for future level\n\
        \                            (expected: %a, provided: %a)."
        Raw_level.pp
        expected
        Raw_level.pp
        provided)
    Data_encoding.(
      obj2
        (req "expected" Raw_level.encoding)
        (req "provided" Raw_level.encoding))
    (function
      | Consensus_operation_for_future_level {expected; provided} ->
          Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) ->
      Consensus_operation_for_future_level {expected; provided}) ;
  register_error_kind
    `Temporary
    ~id:"consensus_operation_for_future_round"
    ~title:"Consensus operation for future round"
    ~description:"Consensus operation for future round."
    ~pp:(fun ppf (expected, provided) ->
      Format.fprintf
        ppf
        "Consensus operation for future round (expected: %a, provided: %a)."
        Round.pp
        expected
        Round.pp
        provided)
    Data_encoding.(
      obj2 (req "expected_max" Round.encoding) (req "provided" Round.encoding))
    (function
      | Consensus_operation_for_future_round {expected; provided} ->
          Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) ->
      Consensus_operation_for_future_round {expected; provided}) ;
  register_error_kind
    `Outdated
    ~id:"consensus_operation_for_old_level"
    ~title:"Consensus operation for old level"
    ~description:"Consensus operation for old level."
    ~pp:(fun ppf (expected, provided) ->
      Format.fprintf
        ppf
        "Consensus operation for old level (expected: %a, provided: %a)."
        Raw_level.pp
        expected
        Raw_level.pp
        provided)
    Data_encoding.(
      obj2
        (req "expected" Raw_level.encoding)
        (req "provided" Raw_level.encoding))
    (function
      | Consensus_operation_for_old_level {expected; provided} ->
          Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) ->
      Consensus_operation_for_old_level {expected; provided}) ;
  register_error_kind
    `Branch
    ~id:"consensus_operation_for_old_round"
    ~title:"Consensus operation for old round"
    ~description:"Consensus operation for old round."
    ~pp:(fun ppf (expected, provided) ->
      Format.fprintf
        ppf
        "Consensus operation for old round (expected_min: %a, provided: %a)."
        Round.pp
        expected
        Round.pp
        provided)
    Data_encoding.(
      obj2 (req "expected_min" Round.encoding) (req "provided" Round.encoding))
    (function
      | Consensus_operation_for_old_round {expected; provided} ->
          Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) ->
      Consensus_operation_for_old_round {expected; provided}) ;
  register_error_kind
    `Branch
    ~id:"consensus_operation_on_competing_proposal"
    ~title:"Consensus operation on competing proposal"
    ~description:"Consensus operation on competing proposal."
    ~pp:(fun ppf (expected, provided) ->
      Format.fprintf
        ppf
        "Consensus operation on competing proposal (expected: %a, provided: \
         %a)."
        Block_payload_hash.pp_short
        expected
        Block_payload_hash.pp_short
        provided)
    Data_encoding.(
      obj2
        (req "expected" Block_payload_hash.encoding)
        (req "provided" Block_payload_hash.encoding))
    (function
      | Consensus_operation_on_competing_proposal {expected; provided} ->
          Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) ->
      Consensus_operation_on_competing_proposal {expected; provided}) ;
  register_error_kind
    `Temporary
    ~id:"operation.set_deposits_limit_on_unregistered_delegate"
    ~title:"Set deposits limit on an unregistered delegate"
    ~description:"Cannot set deposits limit on an unregistered delegate."
    ~pp:(fun ppf c ->
      Format.fprintf
        ppf
        "Cannot set a deposits limit on the unregistered delegate %a."
        Signature.Public_key_hash.pp
        c)
    Data_encoding.(obj1 (req "delegate" Signature.Public_key_hash.encoding))
    (function
      | Set_deposits_limit_on_unregistered_delegate c -> Some c | _ -> None)
    (fun c -> Set_deposits_limit_on_unregistered_delegate c) ;
  register_error_kind
    `Permanent
    ~id:"operation.set_deposits_limit_too_high"
    ~title:"Set deposits limit to a too high value"
    ~description:
      "Cannot set deposits limit such that the active stake overflows."
    ~pp:(fun ppf (limit, max_limit) ->
      Format.fprintf
        ppf
        "Cannot set deposits limit to %a as it is higher the allowed maximum \
         %a."
        Tez.pp
        limit
        Tez.pp
        max_limit)
    Data_encoding.(
      obj2 (req "limit" Tez.encoding) (req "max_limit" Tez.encoding))
    (function
      | Set_deposits_limit_too_high {limit; max_limit} -> Some (limit, max_limit)
      | _ -> None)
    (fun (limit, max_limit) -> Set_deposits_limit_too_high {limit; max_limit}) ;
  register_error_kind
    `Branch
    ~id:"contract.empty_transaction"
    ~title:"Empty transaction"
    ~description:"Forbidden to credit 0ꜩ to a contract without code."
    ~pp:(fun ppf contract ->
      Format.fprintf
        ppf
        "Transactions of 0ꜩ towards a contract without code are forbidden \
         (%a)."
        Contract.pp
        contract)
    Data_encoding.(obj1 (req "contract" Contract.encoding))
    (function Empty_transaction c -> Some c | _ -> None)
    (fun c -> Empty_transaction c) ;

  register_error_kind
    `Permanent
    ~id:"operation.tx_rollup_is_disabled"
    ~title:"Tx rollup is disabled"
    ~description:"Cannot originate a tx rollup as it is disabled."
    ~pp:(fun ppf () ->
      Format.fprintf
        ppf
        "Cannot apply a tx rollup operation as it is disabled. This feature \
         will be enabled in a future proposal")
    Data_encoding.unit
    (function Tx_rollup_feature_disabled -> Some () | _ -> None)
    (fun () -> Tx_rollup_feature_disabled) ;

  register_error_kind
    `Permanent
    ~id:"operation.tx_rollup_invalid_transaction_amount"
    ~title:"Transaction amount to a transaction rollup must be zero"
    ~description:
      "Because transaction rollups are outside of the delegation mechanism of \
       Tezos, they cannot own Tez, and therefore transactions targeting a \
       transaction rollup must have its amount field set to zero."
    ~pp:(fun ppf () ->
      Format.fprintf
        ppf
        "Transaction amount to a transaction rollup must be zero.")
    Data_encoding.unit
    (function Tx_rollup_invalid_transaction_amount -> Some () | _ -> None)
    (fun () -> Tx_rollup_invalid_transaction_amount) ;

  register_error_kind
    `Permanent
    ~id:"operation.cannot_transfer_ticket_to_implicit"
    ~title:"Cannot transfer ticket to implicit account"
    ~description:"Cannot transfer ticket to implicit account"
    Data_encoding.unit
    (function Cannot_transfer_ticket_to_implicit -> Some () | _ -> None)
    (fun () -> Cannot_transfer_ticket_to_implicit) ;

  register_error_kind
    `Permanent
    ~id:"operation.tx_rollup_non_internal_transaction"
    ~title:"Non-internal transaction to a transaction rollup"
    ~description:"Non-internal transactions to a tx rollup are forbidden."
    ~pp:(fun ppf () ->
      Format.fprintf ppf "Transaction to a transaction rollup must be internal.")
    Data_encoding.unit
    (function Tx_rollup_non_internal_transaction -> Some () | _ -> None)
    (fun () -> Tx_rollup_non_internal_transaction) ;

  let description =
    "Smart contract rollups will be enabled in a future proposal."
  in
  register_error_kind
    `Permanent
    ~id:"operation.sc_rollup_disabled"
    ~title:"Smart contract rollups are disabled"
    ~description
    ~pp:(fun ppf () -> Format.fprintf ppf "%s" description)
    Data_encoding.unit
    (function Sc_rollup_feature_disabled -> Some () | _ -> None)
    (fun () -> Sc_rollup_feature_disabled) ;

  register_error_kind
    `Permanent
    ~id:"operation.inconsistent_counters"
    ~title:"Inconsistent counters in operation"
    ~description:
      "Inconsistent counters in operation. Counters of an operation must be \
       successive."
    ~pp:(fun ppf () ->
      Format.fprintf
        ppf
        "Inconsistent counters in operation. Counters of an operation must be \
         successive.")
    Data_encoding.empty
    (function Inconsistent_counters -> Some () | _ -> None)
    (fun () -> Inconsistent_counters) ;
  register_error_kind
    `Temporary
    ~id:"operation.wrong_voting_period"
    ~title:"Wrong voting period"
    ~description:
      "Trying to include a proposal or ballot meant for another voting period"
    ~pp:(fun ppf (e, p) ->
      Format.fprintf ppf "Wrong voting period %ld, current is %ld" p e)
    Data_encoding.(
      obj2 (req "current_index" int32) (req "provided_index" int32))
    (function
      | Wrong_voting_period {expected; provided} -> Some (expected, provided)
      | _ -> None)
    (fun (expected, provided) -> Wrong_voting_period {expected; provided}) ;
  register_error_kind
    `Permanent
    ~id:"internal_operation_replay"
    ~title:"Internal operation replay"
    ~description:"An internal operation was emitted twice by a script"
    ~pp:(fun ppf (Apply_results.Internal_contents {nonce; _}) ->
      Format.fprintf
        ppf
        "Internal operation %d was emitted twice by a script"
        nonce)
    Apply_results.internal_contents_encoding
    (function Internal_operation_replay op -> Some op | _ -> None)
    (fun op -> Internal_operation_replay op) ;
  register_error_kind
    `Permanent
    ~id:"block.invalid_denunciation"
    ~title:"Invalid denunciation"
    ~description:"A denunciation is malformed"
    ~pp:(fun ppf kind ->
      Format.fprintf
        ppf
        "Malformed double-%a evidence"
        pp_denunciation_kind
        kind)
    Data_encoding.(obj1 (req "kind" denunciation_kind_encoding))
    (function Invalid_denunciation kind -> Some kind | _ -> None)
    (fun kind -> Invalid_denunciation kind) ;
  register_error_kind
    `Permanent
    ~id:"block.inconsistent_denunciation"
    ~title:"Inconsistent denunciation"
    ~description:
      "A denunciation operation is inconsistent (two distinct delegates)"
    ~pp:(fun ppf (kind, delegate1, delegate2) ->
      Format.fprintf
        ppf
        "Inconsistent double-%a evidence (distinct delegate: %a and %a)"
        pp_denunciation_kind
        kind
        Signature.Public_key_hash.pp_short
        delegate1
        Signature.Public_key_hash.pp_short
        delegate2)
    Data_encoding.(
      obj3
        (req "kind" denunciation_kind_encoding)
        (req "delegate1" Signature.Public_key_hash.encoding)
        (req "delegate2" Signature.Public_key_hash.encoding))
    (function
      | Inconsistent_denunciation {kind; delegate1; delegate2} ->
          Some (kind, delegate1, delegate2)
      | _ -> None)
    (fun (kind, delegate1, delegate2) ->
      Inconsistent_denunciation {kind; delegate1; delegate2}) ;
  register_error_kind
    `Branch
    ~id:"block.unrequired_denunciation"
    ~title:"Unrequired denunciation"
    ~description:"A denunciation is unrequired"
    ~pp:(fun ppf _ ->
      Format.fprintf
        ppf
        "A valid denunciation cannot be applied: the associated delegate has \
         already been denounced for this level.")
    Data_encoding.unit
    (function Unrequired_denunciation -> Some () | _ -> None)
    (fun () -> Unrequired_denunciation) ;
  register_error_kind
    `Temporary
    ~id:"block.too_early_denunciation"
    ~title:"Too early denunciation"
    ~description:"A denunciation is too far in the future"
    ~pp:(fun ppf (kind, level, current) ->
      Format.fprintf
        ppf
        "A double-%a denunciation is too far in the future (current level: %a, \
         given level: %a)"
        pp_denunciation_kind
        kind
        Raw_level.pp
        current
        Raw_level.pp
        level)
    Data_encoding.(
      obj3
        (req "kind" denunciation_kind_encoding)
        (req "level" Raw_level.encoding)
        (req "current" Raw_level.encoding))
    (function
      | Too_early_denunciation {kind; level; current} ->
          Some (kind, level, current)
      | _ -> None)
    (fun (kind, level, current) ->
      Too_early_denunciation {kind; level; current}) ;
  register_error_kind
    `Permanent
    ~id:"block.outdated_denunciation"
    ~title:"Outdated denunciation"
    ~description:"A denunciation is outdated."
    ~pp:(fun ppf (kind, level, last_cycle) ->
      Format.fprintf
        ppf
        "A double-%a is outdated (last acceptable cycle: %a, given level: %a)"
        pp_denunciation_kind
        kind
        Cycle.pp
        last_cycle
        Raw_level.pp
        level)
    Data_encoding.(
      obj3
        (req "kind" denunciation_kind_encoding)
        (req "level" Raw_level.encoding)
        (req "last" Cycle.encoding))
    (function
      | Outdated_denunciation {kind; level; last_cycle} ->
          Some (kind, level, last_cycle)
      | _ -> None)
    (fun (kind, level, last_cycle) ->
      Outdated_denunciation {kind; level; last_cycle}) ;
  register_error_kind
    `Permanent
    ~id:"operation.invalid_activation"
    ~title:"Invalid activation"
    ~description:
      "The given key and secret do not correspond to any existing preallocated \
       contract"
    ~pp:(fun ppf pkh ->
      Format.fprintf
        ppf
        "Invalid activation. The public key %a does not match any commitment."
        Ed25519.Public_key_hash.pp
        pkh)
    Data_encoding.(obj1 (req "pkh" Ed25519.Public_key_hash.encoding))
    (function Invalid_activation {pkh} -> Some pkh | _ -> None)
    (fun pkh -> Invalid_activation {pkh}) ;
  register_error_kind
    `Permanent
    ~id:"block.multiple_revelation"
    ~title:"Multiple revelations were included in a manager operation"
    ~description:
      "A manager operation should not contain more than one revelation"
    ~pp:(fun ppf () ->
      Format.fprintf
        ppf
        "Multiple revelations were included in a manager operation")
    Data_encoding.empty
    (function Multiple_revelation -> Some () | _ -> None)
    (fun () -> Multiple_revelation) ;
  register_error_kind
    `Permanent
    ~id:"gas_exhausted.init_deserialize"
    ~title:"Not enough gas for initial deserialization of script expressions"
    ~description:
      "Gas limit was not high enough to deserialize the transaction parameters \
       or origination script code or initial storage, making the operation \
       impossible to parse within the provided gas bounds."
    Data_encoding.empty
    (function Gas_quota_exceeded_init_deserialize -> Some () | _ -> None)
    (fun () -> Gas_quota_exceeded_init_deserialize) ;
  register_error_kind
    `Permanent
    ~id:"operation.inconsistent_sources"
    ~title:"Inconsistent sources in operation pack"
    ~description:
      "The operation pack includes operations from different sources."
    ~pp:(fun ppf () ->
      Format.pp_print_string
        ppf
        "The operation pack includes operations from different sources.")
    Data_encoding.empty
    (function Inconsistent_sources -> Some () | _ -> None)
    (fun () -> Inconsistent_sources) ;
  register_error_kind
    `Permanent
    ~id:"operation.failing_noop"
    ~title:"Failing_noop operations are not executed by the protocol"
    ~description:
      "The failing_noop operation is an operation that is not and never will \
       be executed by the protocol."
    ~pp:(fun ppf () ->
      Format.fprintf
        ppf
        "The failing_noop operation cannot be executed by the protocol")
    Data_encoding.empty
    (function Failing_noop_error -> Some () | _ -> None)
    (fun () -> Failing_noop_error) ;
  register_error_kind
    `Permanent
    ~id:"delegate.zero_frozen_deposits"
    ~title:"Zero frozen deposits"
    ~description:"The delegate has zero frozen deposits."
    ~pp:(fun ppf delegate ->
      Format.fprintf
        ppf
        "Delegate %a has zero frozen deposits; it is not allowed to \
         bake/preendorse/endorse."
        Signature.Public_key_hash.pp
        delegate)
    Data_encoding.(obj1 (req "delegate" Signature.Public_key_hash.encoding))
    (function Zero_frozen_deposits delegate -> Some delegate | _ -> None)
    (fun delegate -> Zero_frozen_deposits delegate) ;
  register_error_kind
    `Permanent
    ~id:"forbidden_zero_amount_ticket"
    ~title:"Zero ticket amount is not allowed"
    ~description:
      "It is not allowed to use a zero amount ticket in this operation."
    Data_encoding.empty
    (function Forbidden_zero_ticket_quantity -> Some () | _ -> None)
    (fun () -> Forbidden_zero_ticket_quantity)

open Apply_results

let assert_tx_rollup_feature_enabled ctxt =
  let level = (Level.current ctxt).level in
  Raw_level.of_int32 @@ Constants.tx_rollup_sunset_level ctxt >>?= fun sunset ->
  fail_when Raw_level.(sunset <= level) Tx_rollup_feature_disabled
  >>=? fun () ->
  fail_unless (Constants.tx_rollup_enable ctxt) Tx_rollup_feature_disabled

let assert_sc_rollup_feature_enabled ctxt =
  fail_unless (Constants.sc_rollup_enable ctxt) Sc_rollup_feature_disabled

let update_script_storage_and_ticket_balances ctxt ~self storage
    lazy_storage_diff ticket_diffs operations =
  Contract.update_script_storage ctxt self storage lazy_storage_diff
  >>=? fun ctxt ->
  Ticket_accounting.update_ticket_balances ctxt ~self ~ticket_diffs operations

let apply_delegation ~ctxt ~source ~delegate ~before_operation =
  Delegate.set ctxt source delegate >|=? fun ctxt ->
  ( ctxt,
    Delegation_result
      {consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt},
    [] )

type execution_arg =
  | Typed_arg :
      Script.location * ('a, _) Script_typed_ir.ty * 'a
      -> execution_arg
  | Untyped_arg : Script.expr -> execution_arg

let apply_transaction_to_implicit ~ctxt ~contract ~parameter ~entrypoint
    ~before_operation ~balance_updates ~allocated_destination_contract =
  let is_unit =
    match parameter with
    | Typed_arg (_, Unit_t, ()) -> true
    | Typed_arg _ -> false
    | Untyped_arg parameter -> (
        match Micheline.root parameter with
        | Prim (_, Michelson_v1_primitives.D_Unit, [], _) -> true
        | _ -> false)
  in
  ( (if Entrypoint.is_default entrypoint then Result.return_unit
    else error (Script_tc_errors.No_such_entrypoint entrypoint))
  >>? fun () ->
    if is_unit then
      (* Only allow [Unit] parameter to implicit accounts. *)
      ok ctxt
    else error (Script_interpreter.Bad_contract_parameter contract) )
  >|? fun ctxt ->
  let result =
    Transaction_result
      (Transaction_to_contract_result
         {
           storage = None;
           lazy_storage_diff = None;
           balance_updates;
           originated_contracts = [];
           consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
           storage_size = Z.zero;
           paid_storage_size_diff = Z.zero;
           allocated_destination_contract;
         })
  in
  (ctxt, result)

let apply_transaction_to_smart_contract ~ctxt ~source ~contract ~amount
    ~entrypoint ~before_operation ~payer ~chain_id ~mode ~internal ~script_ir
    ~script ~parameter ~cache_key ~balance_updates
    ~allocated_destination_contract =
  (* Token.transfer which is being called before already loads this value into
     the Irmin cache, so no need to burn gas for it. *)
  Contract.get_balance ctxt contract >>=? fun balance ->
  let now = Script_timestamp.now ctxt in
  let level =
    (Level.current ctxt).level |> Raw_level.to_int32 |> Script_int.of_int32
    |> Script_int.abs
  in
  let step_constants =
    let open Script_interpreter in
    {
      source;
      payer = Contract.implicit_contract payer;
      self = contract;
      amount;
      chain_id;
      balance;
      now;
      level;
    }
  in
  let execute =
    match parameter with
    | Untyped_arg parameter -> Script_interpreter.execute ~parameter
    | Typed_arg (location, parameter_ty, parameter) ->
        Script_interpreter.execute_with_typed_parameter
          ~location
          ~parameter_ty
          ~parameter
  in
  let cached_script = Some script_ir in
  execute ctxt ~cached_script mode step_constants ~script ~entrypoint ~internal
  >>=? fun ( {
               script = updated_cached_script;
               code_size = updated_size;
               storage;
               lazy_storage_diff;
               operations;
               ticket_diffs;
             },
             ctxt ) ->
  update_script_storage_and_ticket_balances
    ctxt
    ~self:contract
    storage
    lazy_storage_diff
    ticket_diffs
    operations
  >>=? fun (ticket_table_size_diff, ctxt) ->
  Ticket_balance.adjust_storage_space ctxt ~storage_diff:ticket_table_size_diff
  >>=? fun (ticket_paid_storage_diff, ctxt) ->
  Fees.record_paid_storage_space ctxt contract
  >>=? fun (ctxt, new_size, contract_paid_storage_size_diff) ->
  Contract.originated_from_current_nonce ~since:before_operation ~until:ctxt
  >>=? fun originated_contracts ->
  Lwt.return
    ( Script_cache.update
        ctxt
        cache_key
        ({script with storage = Script.lazy_expr storage}, updated_cached_script)
        updated_size
    >|? fun ctxt ->
      let result =
        Transaction_result
          (Transaction_to_contract_result
             {
               storage = Some storage;
               lazy_storage_diff;
               balance_updates;
               originated_contracts;
               consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
               storage_size = new_size;
               paid_storage_size_diff =
                 Z.add contract_paid_storage_size_diff ticket_paid_storage_diff;
               allocated_destination_contract;
             })
      in
      (ctxt, result, operations) )

let apply_transaction ~ctxt ~parameter ~source ~contract ~amount ~entrypoint
    ~before_operation ~payer ~chain_id ~mode ~internal =
  (match Contract.is_implicit contract with
  | None ->
      (if Tez.(amount = zero) then
       (* Detect potential call to non existent contract. *)
       Contract.must_exist ctxt contract
      else return_unit)
      >>=? fun () ->
      (* Since the contract is originated, nothing will be allocated
         or the next transfer of tokens will fail. *)
      return_false
  | Some _ ->
      (* Transfers of zero to implicit accounts are forbidden. *)
      error_when Tez.(amount = zero) (Empty_transaction contract) >>?= fun () ->
      (* If the implicit contract is not yet allocated at this point then
         the next transfer of tokens will allocate it. *)
      Contract.allocated ctxt contract >|=? not)
  >>=? fun allocated_destination_contract ->
  Token.transfer ctxt (`Contract source) (`Contract contract) amount
  >>=? fun (ctxt, balance_updates) ->
  Script_cache.find ctxt contract >>=? fun (ctxt, cache_key, script) ->
  match script with
  | None ->
      apply_transaction_to_implicit
        ~ctxt
        ~contract
        ~parameter
        ~entrypoint
        ~before_operation
        ~balance_updates
        ~allocated_destination_contract
      >>?= fun (ctxt, result) -> return (ctxt, result, [])
  | Some (script, script_ir) ->
      apply_transaction_to_smart_contract
        ~ctxt
        ~source
        ~contract
        ~amount
        ~entrypoint
        ~before_operation
        ~payer
        ~chain_id
        ~mode
        ~internal
        ~script_ir
        ~script
        ~parameter
        ~cache_key
        ~balance_updates
        ~allocated_destination_contract

let ex_ticket_size :
    context -> Ticket_scanner.ex_ticket -> (context * int) tzresult Lwt.t =
 fun ctxt (Ex_ticket (ty, ticket)) ->
  (* type *)
  Script_typed_ir.ticket_t Micheline.dummy_location ty >>?= fun ty ->
  Script_ir_translator.unparse_ty ~loc:Micheline.dummy_location ctxt ty
  >>?= fun (ty', ctxt) ->
  let (ty_nodes, ty_size) = Script_typed_ir_size.node_size ty' in
  let ty_size = Saturation_repr.to_int ty_size in
  let ty_size_cost = Script_typed_ir_size_costs.nodes_cost ~nodes:ty_nodes in
  Gas.consume ctxt ty_size_cost >>?= fun ctxt ->
  (* contents *)
  let (val_nodes, val_size) = Script_typed_ir_size.value_size ty ticket in
  let val_size = Saturation_repr.to_int val_size in
  let val_size_cost = Script_typed_ir_size_costs.nodes_cost ~nodes:val_nodes in
  Gas.consume ctxt val_size_cost >>?= fun ctxt ->
  (* gas *)
  return (ctxt, ty_size + val_size)

let apply_transaction_to_tx_rollup ~ctxt ~parameters_ty ~parameters ~amount
    ~entrypoint ~payer ~dst_rollup ~since =
  assert_tx_rollup_feature_enabled ctxt >>=? fun () ->
  fail_unless Tez.(amount = zero) Tx_rollup_invalid_transaction_amount
  >>=? fun () ->
  if Entrypoint.(entrypoint = Tx_rollup.deposit_entrypoint) then
    (* If the ticket deposit fails on L2 for some reason
       (e.g. [Balance_overflow] in the recipient), then it is
       returned to [payer]. As [payer] is implicit, it cannot own
       tickets directly. Therefore, erroneous deposits are
       returned using the L2 withdrawal mechanism: a failing
       deposit emits a withdrawal that can be executed by
       [payer]. *)
    Tx_rollup_parameters.get_deposit_parameters parameters_ty parameters
    >>?= fun {ex_ticket; l2_destination} ->
    ex_ticket_size ctxt ex_ticket >>=? fun (ctxt, ticket_size) ->
    let limit = Constants.tx_rollup_max_ticket_payload_size ctxt in
    fail_when
      Compare.Int.(ticket_size > limit)
      (Tx_rollup_errors_repr.Ticket_payload_size_limit_exceeded
         {payload_size = ticket_size; limit})
    >>=? fun () ->
    let (ex_token, ticket_amount) =
      Ticket_token.token_and_amount_of_ex_ticket ex_ticket
    in
    Ticket_balance_key.of_ex_token ctxt ~owner:(Tx_rollup dst_rollup) ex_token
    >>=? fun (ticket_hash, ctxt) ->
    Option.value_e
      ~error:(Error_monad.trace_of_error Tx_rollup_invalid_transaction_amount)
      (Option.bind
         (Script_int.to_int64 ticket_amount)
         Tx_rollup_l2_qty.of_int64)
    >>?= fun ticket_amount ->
    error_when
      Tx_rollup_l2_qty.(ticket_amount <= zero)
      Forbidden_zero_ticket_quantity
    >>?= fun () ->
    let (deposit, message_size) =
      Tx_rollup_message.make_deposit
        payer
        l2_destination
        ticket_hash
        ticket_amount
    in
    Tx_rollup_state.get ctxt dst_rollup >>=? fun (ctxt, state) ->
    Tx_rollup_state.burn_cost ~limit:None state message_size >>?= fun cost ->
    Token.transfer
      ctxt
      (`Contract (Contract.implicit_contract payer))
      `Burned
      cost
    >>=? fun (ctxt, balance_updates) ->
    Tx_rollup_inbox.append_message ctxt dst_rollup state deposit
    >>=? fun (ctxt, state, paid_storage_size_diff) ->
    Tx_rollup_state.update ctxt dst_rollup state >>=? fun ctxt ->
    let result =
      Transaction_result
        (Transaction_to_tx_rollup_result
           {
             balance_updates;
             consumed_gas = Gas.consumed ~since ~until:ctxt;
             ticket_hash;
             paid_storage_size_diff;
           })
    in
    return (ctxt, result, [])
  else fail (Script_tc_errors.No_such_entrypoint entrypoint)

let apply_origination ~ctxt ~storage_type ~storage ~unparsed_code ~contract
    ~delegate ~source ~credit ~before_operation =
  Script_ir_translator.collect_lazy_storage ctxt storage_type storage
  >>?= fun (to_duplicate, ctxt) ->
  let to_update = Script_ir_translator.no_lazy_storage_id in
  Script_ir_translator.extract_lazy_storage_diff
    ctxt
    Optimized
    storage_type
    storage
    ~to_duplicate
    ~to_update
    ~temporary:false
  >>=? fun (storage, lazy_storage_diff, ctxt) ->
  Script_ir_translator.unparse_data ctxt Optimized storage_type storage
  >>=? fun (storage, ctxt) ->
  Gas.consume ctxt (Script.strip_locations_cost storage) >>?= fun ctxt ->
  let storage = Script.lazy_expr (Micheline.strip_locations storage) in
  (* Normalize code to avoid #843 *)
  Script_ir_translator.unparse_code
    ctxt
    Optimized
    (Micheline.root unparsed_code)
  >>=? fun (code, ctxt) ->
  Gas.consume ctxt (Script.strip_locations_cost code) >>?= fun ctxt ->
  let code = Script.lazy_expr (Micheline.strip_locations code) in
  let script = {Script.code; storage} in
  Contract.raw_originate
    ctxt
    ~prepaid_bootstrap_storage:false
    contract
    ~script:(script, lazy_storage_diff)
  >>=? fun ctxt ->
  (match delegate with
  | None -> return ctxt
  | Some delegate -> Delegate.init ctxt contract delegate)
  >>=? fun ctxt ->
  Token.transfer ctxt (`Contract source) (`Contract contract) credit
  >>=? fun (ctxt, balance_updates) ->
  Fees.record_paid_storage_space ctxt contract
  >|=? fun (ctxt, size, paid_storage_size_diff) ->
  let result =
    Origination_result
      {
        lazy_storage_diff;
        balance_updates;
        originated_contracts = [contract];
        consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
        storage_size = size;
        paid_storage_size_diff;
      }
  in
  (ctxt, result, [])

(**

   Retrieving the source code of a contract from its address is costly
   because it requires I/Os. For this reason, we put the corresponding
   Micheline expression in the cache.

   Elaborating a Micheline node into the well-typed script abstract
   syntax tree is also a costly operation. The result of this operation
   is cached as well.

*)

let prepare_apply_manager_operation_content ~ctxt ~source
    ~gas_consumed_in_precheck =
  let before_operation =
    (* This context is not used for backtracking. Only to compute
         gas consumption and originations for the operation result. *)
    ctxt
  in
  Contract.must_exist ctxt source >>=? fun () ->
  Gas.consume ctxt Michelson_v1_gas.Cost_of.manager_operation >>?= fun ctxt ->
  (match gas_consumed_in_precheck with
  | None -> Ok ctxt
  | Some gas -> Gas.consume ctxt gas)
  >>?= fun ctxt ->
  let consume_deserialization_gas = Script.When_needed in
  (* [note]: deserialization gas has already been accounted for in the gas
     consumed by the precheck and the lazy_exprs have been forced. *)
  return (ctxt, before_operation, consume_deserialization_gas)

let apply_internal_manager_operation_content :
    type kind.
    context ->
    Script_ir_translator.unparsing_mode ->
    payer:public_key_hash ->
    source:Contract.t ->
    chain_id:Chain_id.t ->
    gas_consumed_in_precheck:Gas.cost option ->
    kind Script_typed_ir.manager_operation ->
    (context
    * kind successful_manager_operation_result
    * Script_typed_ir.packed_internal_operation list)
    tzresult
    Lwt.t =
 fun ctxt mode ~payer ~source ~chain_id ~gas_consumed_in_precheck operation ->
  prepare_apply_manager_operation_content
    ~ctxt
    ~source
    ~gas_consumed_in_precheck
  >>=? fun (ctxt, before_operation, consume_deserialization_gas) ->
  match operation with
  | Transaction
      {
        transaction =
          {amount; parameters = _; destination = Contract contract; entrypoint};
        location;
        parameters_ty;
        parameters = typed_parameters;
      } ->
      apply_transaction
        ~ctxt
        ~parameter:(Typed_arg (location, parameters_ty, typed_parameters))
        ~source
        ~contract
        ~amount
        ~entrypoint
        ~before_operation
        ~payer
        ~chain_id
        ~mode
        ~internal:true
      >|=? fun (ctxt, manager_result, operations) ->
      ( ctxt,
        (manager_result : kind successful_manager_operation_result),
        operations )
  | Transaction
      {
        transaction =
          {amount; destination = Tx_rollup dst; entrypoint; parameters = _};
        location = _;
        parameters_ty;
        parameters;
      } ->
      apply_transaction_to_tx_rollup
        ~ctxt
        ~parameters_ty
        ~parameters
        ~amount
        ~entrypoint
        ~payer
        ~dst_rollup:dst
        ~since:before_operation
  | Origination
      {
        origination = {delegate; script; credit};
        preorigination = contract;
        storage_type;
        storage;
      } ->
      Script.force_decode_in_context
        ~consume_deserialization_gas
        ctxt
        script.Script.code
      >>?= fun (unparsed_code, ctxt) ->
      apply_origination
        ~ctxt
        ~storage_type
        ~storage
        ~unparsed_code
        ~contract
        ~delegate
        ~source
        ~credit
        ~before_operation
  | Delegation delegate ->
      apply_delegation ~ctxt ~source ~delegate ~before_operation

let apply_external_manager_operation_content :
    type kind.
    context ->
    Script_ir_translator.unparsing_mode ->
    source:public_key_hash ->
    chain_id:Chain_id.t ->
    gas_consumed_in_precheck:Gas.cost option ->
    kind manager_operation ->
    (context
    * kind successful_manager_operation_result
    * Script_typed_ir.packed_internal_operation list)
    tzresult
    Lwt.t =
 fun ctxt mode ~source ~chain_id ~gas_consumed_in_precheck operation ->
  let source_contract = Contract.implicit_contract source in
  prepare_apply_manager_operation_content
    ~ctxt
    ~source:source_contract
    ~gas_consumed_in_precheck
  >>=? fun (ctxt, before_operation, consume_deserialization_gas) ->
  match operation with
  | Reveal _ ->
      return
        (* No-op: action already performed by `precheck_manager_contents`. *)
        ( ctxt,
          (Reveal_result
             {consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt}
            : kind successful_manager_operation_result),
          [] )
  | Transaction
      {amount; parameters; destination = Contract contract; entrypoint} ->
      Script.force_decode_in_context
        ~consume_deserialization_gas
        ctxt
        parameters
      >>?= fun (parameters, ctxt) ->
      apply_transaction
        ~ctxt
        ~parameter:(Untyped_arg parameters)
        ~source:source_contract
        ~contract
        ~amount
        ~entrypoint
        ~before_operation
        ~payer:source
        ~chain_id
        ~mode
        ~internal:false
  | Transaction {destination = Tx_rollup _; _} ->
      fail Tx_rollup_non_internal_transaction
  | Tx_rollup_dispatch_tickets
      {
        tx_rollup;
        level;
        context_hash;
        message_index;
        message_result_path;
        tickets_info;
      } ->
      Tx_rollup_state.get ctxt tx_rollup >>=? fun (ctxt, state) ->
      Tx_rollup_commitment.get_finalized ctxt tx_rollup state level
      >>=? fun (ctxt, commitment) ->
      Tx_rollup_reveal.mem ctxt tx_rollup level ~message_position:message_index
      >>=? fun (ctxt, already_revealed) ->
      error_when
        already_revealed
        Tx_rollup_errors.Withdrawals_already_dispatched
      >>?= fun () ->
      (* The size of the list [tickets_info] is bounded by a
         parametric constant, and checked in precheck. *)
      List.fold_left_es
        (fun (acc_withdraw, acc, ctxt)
             Tx_rollup_reveal.{contents; ty; ticketer; amount; claimer} ->
          error_when
            Tx_rollup_l2_qty.(amount <= zero)
            Forbidden_zero_ticket_quantity
          >>?= fun () ->
          Tx_rollup_ticket.parse_ticket
            ~consume_deserialization_gas
            ~ticketer
            ~contents
            ~ty
            ctxt
          >>=? fun (ctxt, ticket_token) ->
          Tx_rollup_ticket.make_withdraw_order
            ctxt
            tx_rollup
            ticket_token
            claimer
            amount
          >>=? fun (ctxt, withdrawal) ->
          return
            (withdrawal :: acc_withdraw, (withdrawal, ticket_token) :: acc, ctxt))
        ([], [], ctxt)
        tickets_info
      >>=? fun (rev_withdraw_list, rev_ex_token_and_hash_list, ctxt) ->
      Tx_rollup_hash.withdraw_list ctxt (List.rev rev_withdraw_list)
      >>?= fun (ctxt, withdraw_list_hash) ->
      Tx_rollup_commitment.check_message_result
        ctxt
        commitment.commitment
        (`Result {context_hash; withdraw_list_hash})
        ~path:message_result_path
        ~index:message_index
      >>?= fun ctxt ->
      Tx_rollup_reveal.record
        ctxt
        tx_rollup
        level
        ~message_position:message_index
      >>=? fun ctxt ->
      let adjust_ticket_balance (ctxt, acc_diff)
          ( Tx_rollup_withdraw.
              {claimer; amount; ticket_hash = tx_rollup_ticket_hash},
            ticket_token ) =
        let amount = Tx_rollup_l2_qty.to_z amount in
        Ticket_balance_key.of_ex_token
          ctxt
          ~owner:(Contract (Contract.implicit_contract claimer))
          ticket_token
        >>=? fun (claimer_ticket_hash, ctxt) ->
        Tx_rollup_ticket.transfer_ticket_with_hashes
          ctxt
          ~src_hash:tx_rollup_ticket_hash
          ~dst_hash:claimer_ticket_hash
          amount
        >>=? fun (ctxt, diff) -> return (ctxt, Z.(add acc_diff diff))
      in
      List.fold_left_es
        adjust_ticket_balance
        (ctxt, Z.zero)
        rev_ex_token_and_hash_list
      >>=? fun (ctxt, paid_storage_size_diff) ->
      let result =
        Tx_rollup_dispatch_tickets_result
          {
            balance_updates = [];
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            paid_storage_size_diff;
          }
      in
      return (ctxt, result, [])
  | Transfer_ticket {contents; ty; ticketer; amount; destination; entrypoint} ->
      (* The encoding ensures that the amount is in a natural number. Here is
         mainly to check that it is non-zero.*)
      error_when Compare.Z.(amount <= Z.zero) Forbidden_zero_ticket_quantity
      >>?= fun () ->
      error_when
        (Option.is_some @@ Contract.is_implicit destination)
        Cannot_transfer_ticket_to_implicit
      >>?= fun () ->
      Tx_rollup_ticket.parse_ticket_and_operation
        ~consume_deserialization_gas
        ~ticketer
        ~contents
        ~ty
        ~source:source_contract
        ~destination:(Contract destination)
        ~entrypoint
        ~amount
        ctxt
      >>=? fun (ctxt, ticket_token, op) ->
      Tx_rollup_ticket.transfer_ticket
        ctxt
        ~src:(Contract source_contract)
        ~dst:(Contract destination)
        ticket_token
        amount
      >>=? fun (ctxt, paid_storage_size_diff) ->
      let result =
        Transfer_ticket_result
          {
            balance_updates = [];
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            paid_storage_size_diff;
          }
      in
      return (ctxt, result, [op])
  | Origination {delegate; script; credit} ->
      (* Internal originations have their address generated in the interpreter
         so that the script can use it immediately.
         The address of external originations is generated here. *)
      Contract.fresh_contract_from_current_nonce ctxt
      >>?= fun (ctxt, contract) ->
      Script.force_decode_in_context
        ~consume_deserialization_gas
        ctxt
        script.Script.storage
      >>?= fun (_unparsed_storage, ctxt) ->
      Script_ir_translator.parse_script
        ctxt
        ~legacy:false
        ~allow_forged_in_storage:false
        script
      >>=? fun (Ex_script parsed_script, ctxt) ->
      Script.force_decode_in_context
        ~consume_deserialization_gas
        ctxt
        script.Script.code
      >>?= fun (unparsed_code, ctxt) ->
      let (Script {storage_type; views; storage; _}) = parsed_script in
      let views_result =
        Script_ir_translator.parse_views ctxt ~legacy:false storage_type views
      in
      trace
        (Script_tc_errors.Ill_typed_contract (unparsed_code, []))
        views_result
      >>=? fun (_typed_views, ctxt) ->
      apply_origination
        ~ctxt
        ~storage_type
        ~storage
        ~unparsed_code
        ~contract
        ~delegate
        ~source:source_contract
        ~credit
        ~before_operation
  | Delegation delegate ->
      apply_delegation ~ctxt ~source:source_contract ~delegate ~before_operation
  | Register_global_constant {value} ->
      (* Decode the value and consume gas appropriately *)
      Script.force_decode_in_context ~consume_deserialization_gas ctxt value
      >>?= fun (expr, ctxt) ->
      (* Set the key to the value in storage. *)
      Global_constants_storage.register ctxt expr
      >>=? fun (ctxt, address, size) ->
      (* The burn and the reporting of the burn are calculated differently.

         [Fees.record_global_constant_storage_space] does the actual burn
         based on the size of the constant registered, and this causes a
         change in account balance.

         On the other hand, the receipt is calculated
         with the help of [Fees.cost_of_bytes], and is included in block metadata
         and the client output. The receipt is also used during simulation,
         letting the client automatically set an appropriate storage limit.
         TODO : is this concern still honored by the token management
         refactoring ? *)
      let (ctxt, paid_size) =
        Fees.record_global_constant_storage_space ctxt size
      in
      let result =
        Register_global_constant_result
          {
            balance_updates = [];
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            size_of_constant = paid_size;
            global_address = address;
          }
      in
      return (ctxt, result, [])
  | Set_deposits_limit limit ->
      (match limit with
      | None -> Result.return_unit
      | Some limit ->
          let frozen_deposits_percentage =
            Constants.frozen_deposits_percentage ctxt
          in
          let max_limit =
            Tez.of_mutez_exn
              Int64.(
                mul (of_int frozen_deposits_percentage) Int64.(div max_int 100L))
          in
          error_when
            Tez.(limit > max_limit)
            (Set_deposits_limit_too_high {limit; max_limit}))
      >>?= fun () ->
      Delegate.registered ctxt source >>=? fun is_registered ->
      error_unless
        is_registered
        (Set_deposits_limit_on_unregistered_delegate source)
      >>?= fun () ->
      Delegate.set_frozen_deposits_limit ctxt source limit >>= fun ctxt ->
      return
        ( ctxt,
          Set_deposits_limit_result
            {consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt},
          [] )
  | Tx_rollup_origination ->
      Tx_rollup.originate ctxt >>=? fun (ctxt, originated_tx_rollup) ->
      let result =
        Tx_rollup_origination_result
          {
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            originated_tx_rollup;
            balance_updates = [];
          }
      in
      return (ctxt, result, [])
  | Tx_rollup_submit_batch {tx_rollup; content; burn_limit} ->
      let (message, message_size) = Tx_rollup_message.make_batch content in
      Tx_rollup_state.get ctxt tx_rollup >>=? fun (ctxt, state) ->
      Tx_rollup_inbox.append_message ctxt tx_rollup state message
      >>=? fun (ctxt, state, paid_storage_size_diff) ->
      Tx_rollup_state.burn_cost ~limit:burn_limit state message_size
      >>?= fun cost ->
      Token.transfer ctxt (`Contract source_contract) `Burned cost
      >>=? fun (ctxt, balance_updates) ->
      Tx_rollup_state.update ctxt tx_rollup state >>=? fun ctxt ->
      let result =
        Tx_rollup_submit_batch_result
          {
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            balance_updates;
            paid_storage_size_diff;
          }
      in
      return (ctxt, result, [])
  | Tx_rollup_commit {tx_rollup; commitment} ->
      Tx_rollup_state.get ctxt tx_rollup >>=? fun (ctxt, state) ->
      ( Tx_rollup_commitment.has_bond ctxt tx_rollup source
      >>=? fun (ctxt, pending) ->
        if not pending then
          let bond_id = Bond_id.Tx_rollup_bond_id tx_rollup in
          Token.transfer
            ctxt
            (`Contract source_contract)
            (`Frozen_bonds (source_contract, bond_id))
            (Constants.tx_rollup_commitment_bond ctxt)
        else return (ctxt, []) )
      >>=? fun (ctxt, balance_updates) ->
      Tx_rollup_commitment.add_commitment ctxt tx_rollup state source commitment
      >>=? fun (ctxt, state, to_slash) ->
      (match to_slash with
      | Some pkh ->
          let committer = Contract.implicit_contract pkh in
          Tx_rollup_commitment.slash_bond ctxt tx_rollup pkh
          >>=? fun (ctxt, slashed) ->
          if slashed then
            let bid = Bond_id.Tx_rollup_bond_id tx_rollup in
            Token.balance ctxt (`Frozen_bonds (committer, bid))
            >>=? fun (ctxt, burn) ->
            Token.transfer
              ctxt
              (`Frozen_bonds (committer, bid))
              `Tx_rollup_rejection_punishments
              burn
          else return (ctxt, [])
      | None -> return (ctxt, []))
      >>=? fun (ctxt, burn_update) ->
      Tx_rollup_state.update ctxt tx_rollup state >>=? fun ctxt ->
      let result =
        Tx_rollup_commit_result
          {
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            balance_updates = burn_update @ balance_updates;
          }
      in
      return (ctxt, result, [])
  | Tx_rollup_return_bond {tx_rollup} ->
      Tx_rollup_commitment.remove_bond ctxt tx_rollup source >>=? fun ctxt ->
      let bond_id = Bond_id.Tx_rollup_bond_id tx_rollup in
      Token.balance ctxt (`Frozen_bonds (source_contract, bond_id))
      >>=? fun (ctxt, bond) ->
      Token.transfer
        ctxt
        (`Frozen_bonds (source_contract, bond_id))
        (`Contract source_contract)
        bond
      >>=? fun (ctxt, balance_updates) ->
      let result =
        Tx_rollup_return_bond_result
          {
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            balance_updates;
          }
      in
      return (ctxt, result, [])
  | Tx_rollup_finalize_commitment {tx_rollup} ->
      Tx_rollup_state.get ctxt tx_rollup >>=? fun (ctxt, state) ->
      Tx_rollup_commitment.finalize_commitment ctxt tx_rollup state
      >>=? fun (ctxt, state, level) ->
      Tx_rollup_state.update ctxt tx_rollup state >>=? fun ctxt ->
      let result =
        Tx_rollup_finalize_commitment_result
          {
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            balance_updates = [];
            level;
          }
      in
      return (ctxt, result, [])
  | Tx_rollup_remove_commitment {tx_rollup} ->
      Tx_rollup_state.get ctxt tx_rollup >>=? fun (ctxt, state) ->
      Tx_rollup_commitment.remove_commitment ctxt tx_rollup state
      >>=? fun (ctxt, state, level) ->
      Tx_rollup_state.update ctxt tx_rollup state >>=? fun ctxt ->
      let result =
        Tx_rollup_remove_commitment_result
          {
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            balance_updates = [];
            level;
          }
      in
      return (ctxt, result, [])
  | Tx_rollup_rejection
      {
        proof;
        tx_rollup;
        level;
        message;
        message_position;
        message_path;
        message_result_hash;
        message_result_path;
        previous_message_result;
        previous_message_result_path;
      } ->
      Tx_rollup_state.get ctxt tx_rollup >>=? fun (ctxt, state) ->
      (* Check [level] *)
      Tx_rollup_state.check_level_can_be_rejected state level >>?= fun () ->
      Tx_rollup_commitment.get ctxt tx_rollup state level
      >>=? fun (ctxt, commitment) ->
      (* Check [message] *)
      error_when
        Compare.Int.(
          message_position < 0
          || commitment.commitment.messages.count <= message_position)
        (Tx_rollup_errors.Wrong_message_position
           {
             level = commitment.commitment.level;
             position = message_position;
             length = commitment.commitment.messages.count;
           })
      >>?= fun () ->
      Tx_rollup_inbox.check_message_hash
        ctxt
        level
        tx_rollup
        ~position:message_position
        message
        message_path
      >>=? fun ctxt ->
      (* Check message result paths *)
      Tx_rollup_commitment.check_agreed_and_disputed_results
        ctxt
        tx_rollup
        state
        commitment
        ~agreed_result:previous_message_result
        ~agreed_result_path:previous_message_result_path
        ~disputed_result:message_result_hash
        ~disputed_result_path:message_result_path
        ~disputed_position:message_position
      >>=? fun ctxt ->
      (* Check [proof] *)
      let parameters =
        Tx_rollup_l2_apply.
          {
            tx_rollup_max_withdrawals_per_batch =
              Constants.tx_rollup_max_withdrawals_per_batch ctxt;
          }
      in
      Tx_rollup_l2_verifier.verify_proof
        ctxt
        parameters
        message
        proof
        ~agreed:previous_message_result
        ~rejected:message_result_hash
        ~max_proof_size:
          (Alpha_context.Constants.tx_rollup_rejection_max_proof_size ctxt)
      >>=? fun ctxt ->
      (* Proof is correct, removing *)
      Tx_rollup_commitment.reject_commitment ctxt tx_rollup state level
      >>=? fun (ctxt, state) ->
      (* Bond slashing, and removing *)
      Tx_rollup_commitment.slash_bond ctxt tx_rollup commitment.committer
      >>=? fun (ctxt, slashed) ->
      (if slashed then
       let committer = Contract.implicit_contract commitment.committer in
       let bid = Bond_id.Tx_rollup_bond_id tx_rollup in
       Token.balance ctxt (`Frozen_bonds (committer, bid))
       >>=? fun (ctxt, burn) ->
       Tez.(burn /? 2L) >>?= fun reward ->
       Token.transfer
         ctxt
         (`Frozen_bonds (committer, bid))
         `Tx_rollup_rejection_punishments
         burn
       >>=? fun (ctxt, burn_update) ->
       Token.transfer
         ctxt
         `Tx_rollup_rejection_rewards
         (`Contract source_contract)
         reward
       >>=? fun (ctxt, reward_update) ->
       return (ctxt, burn_update @ reward_update)
      else return (ctxt, []))
      >>=? fun (ctxt, balance_updates) ->
      (* Update state and conclude *)
      Tx_rollup_state.update ctxt tx_rollup state >>=? fun ctxt ->
      let result =
        Tx_rollup_rejection_result
          {
            consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;
            balance_updates;
          }
      in
      return (ctxt, result, [])
  | Sc_rollup_originate {kind; boot_sector} ->
      Sc_rollup_operations.originate ctxt ~kind ~boot_sector
      >>=? fun ({address; size}, ctxt) ->
      let consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt in
      let result =
        Sc_rollup_originate_result
          {address; consumed_gas; size; balance_updates = []}
      in
      return (ctxt, result, [])
  | Sc_rollup_add_messages {rollup; messages} ->
      Sc_rollup.add_messages ctxt rollup messages
      >>=? fun (inbox_after, _size, ctxt) ->
      let consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt in
      let result = Sc_rollup_add_messages_result {consumed_gas; inbox_after} in
      return (ctxt, result, [])
  | Sc_rollup_cement {rollup; commitment} ->
      Sc_rollup.cement_commitment ctxt rollup commitment >>=? fun ctxt ->
      let consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt in
      let result = Sc_rollup_cement_result {consumed_gas} in
      return (ctxt, result, [])
  | Sc_rollup_publish {rollup; commitment} ->
      Sc_rollup.publish_commitment ctxt rollup source commitment
      >>=? fun (staked_hash, ctxt) ->
      let consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt in
      let result = Sc_rollup_publish_result {staked_hash; consumed_gas} in
      return (ctxt, result, [])

type success_or_failure = Success of context | Failure

let apply_internal_manager_operations ctxt mode ~payer ~chain_id ops =
  let[@coq_struct "ctxt"] rec apply ctxt applied worklist =
    match worklist with
    | [] -> Lwt.return (Success ctxt, List.rev applied)
    | Script_typed_ir.Internal_operation ({source; operation; nonce} as op)
      :: rest -> (
        let op_res = Apply_results.contents_of_internal_operation op in
        (if internal_nonce_already_recorded ctxt nonce then
         fail (Internal_operation_replay (Internal_contents op_res))
        else
          let ctxt = record_internal_nonce ctxt nonce in
          apply_internal_manager_operation_content
            ctxt
            mode
            ~source
            ~payer
            ~chain_id
            ~gas_consumed_in_precheck:None
            operation)
        >>= function
        | Error errors ->
            let result =
              pack_internal_manager_operation_result
                op
                (Failed (Script_typed_ir.manager_kind op.operation, errors))
            in
            let skipped =
              List.rev_map
                (fun (Script_typed_ir.Internal_operation op) ->
                  pack_internal_manager_operation_result
                    op
                    (Skipped (Script_typed_ir.manager_kind op.operation)))
                rest
            in
            Lwt.return (Failure, List.rev (skipped @ result :: applied))
        | Ok (ctxt, result, emitted) ->
            apply
              ctxt
              (pack_internal_manager_operation_result op (Applied result)
               :: applied)
              (emitted @ rest))
  in
  apply ctxt [] ops

let precheck_manager_contents (type kind) ctxt (op : kind Kind.manager contents)
    ~(only_batch : bool) : (context * precheck_result) tzresult Lwt.t =
  let[@coq_match_with_default] (Manager_operation
                                 {
                                   source;
                                   fee;
                                   counter;
                                   operation;
                                   gas_limit;
                                   storage_limit;
                                 }) =
    op
  in
  (if only_batch then
   (* Gas.consume_limit_in_block will only raise a "temporary" error, however
      when the precheck is called on a batch in isolation (like e.g. in the
      mempool) it must "refuse" operations whose total gas_limit (the sum of
      the gas_limits of each operation) is already above the block limit. We
      add the "permanent" error Gas.Gas_limit_too_high on top of the trace to
      this effect. *)
   record_trace Gas.Gas_limit_too_high
  else fun errs -> errs)
  @@ Gas.consume_limit_in_block ctxt gas_limit
  >>?= fun ctxt ->
  let ctxt = Gas.set_limit ctxt gas_limit in
  let ctxt_before = ctxt in
  Fees.check_storage_limit ctxt ~storage_limit >>?= fun () ->
  let source_contract = Contract.implicit_contract source in
  Contract.must_be_allocated ctxt source_contract >>=? fun () ->
  Contract.check_counter_increment ctxt source counter >>=? fun () ->
  let consume_deserialization_gas = Script.Always in
  (* We want to always consume the deserialization gas here, independently of
     the internal state of the lazy_exprs in the arguments. Otherwise we might
     risk getting different results if the operation has already been
     deserialized before (e.g. when retrieve in JSON format). *)
  (match operation with
  | Reveal pk -> Contract.reveal_manager_key ctxt source pk
  | Transaction {parameters; destination; _} ->
      (* Precheck is only called for non-internal operations
       * and rollup transactions must be internal. *)
      fail_when
        (match destination with Tx_rollup _ -> true | _ -> false)
        Tx_rollup_non_internal_transaction
      >>=? fun () ->
      Lwt.return
      @@ record_trace Gas_quota_exceeded_init_deserialize
      @@ (* Fail early if not enough gas for complete deserialization
             cost or if deserialization fails. The gas consumed here is
            "replayed" in [apply_manager_contents]. *)
      ( Script.force_decode_in_context
          ~consume_deserialization_gas
          ctxt
          parameters
      >|? fun (_arg, ctxt) -> ctxt )
  | Origination {script; _} ->
      Lwt.return
      @@ record_trace Gas_quota_exceeded_init_deserialize
      @@ (* See comment in the Transaction branch *)
      ( Script.force_decode_in_context
          ~consume_deserialization_gas
          ctxt
          script.code
      >>? fun (_code, ctxt) ->
        Script.force_decode_in_context
          ~consume_deserialization_gas
          ctxt
          script.storage
        >|? fun (_storage, ctxt) -> ctxt )
  | Register_global_constant {value} ->
      Lwt.return
      @@ record_trace Gas_quota_exceeded_init_deserialize
      @@ (* See comment in the Transaction branch *)
      ( Script.force_decode_in_context ~consume_deserialization_gas ctxt value
      >|? fun (_value, ctxt) -> ctxt )
  | Delegation _ | Set_deposits_limit _ -> return ctxt
  | Tx_rollup_origination ->
      assert_tx_rollup_feature_enabled ctxt >|=? fun () -> ctxt
  | Tx_rollup_submit_batch {content; _} ->
      assert_tx_rollup_feature_enabled ctxt >>=? fun () ->
      let size_limit = Constants.tx_rollup_hard_size_limit_per_message ctxt in
      let (_message, message_size) = Tx_rollup_message.make_batch content in
      Tx_rollup_gas.hash_cost message_size >>?= fun cost ->
      Gas.consume ctxt cost >>?= fun ctxt ->
      fail_unless
        Compare.Int.(message_size <= size_limit)
        Tx_rollup_errors.Message_size_exceeds_limit
      >>=? fun () -> return ctxt
  | Tx_rollup_commit _ | Tx_rollup_return_bond _
  | Tx_rollup_finalize_commitment _ | Tx_rollup_remove_commitment _ ->
      assert_tx_rollup_feature_enabled ctxt >>=? fun () -> return ctxt
  | Transfer_ticket {contents; ty; _} ->
      assert_tx_rollup_feature_enabled ctxt >>=? fun () ->
      Lwt.return
      @@ record_trace Gas_quota_exceeded_init_deserialize
      @@ (* See comment in the Transaction branch *)
      ( Script.force_decode_in_context ~consume_deserialization_gas ctxt contents
      >>? fun (_contents, ctxt) ->
        Script.force_decode_in_context ~consume_deserialization_gas ctxt ty
        >|? fun (_ty, ctxt) -> ctxt )
  | Tx_rollup_dispatch_tickets {tickets_info; message_result_path; _} ->
      assert_tx_rollup_feature_enabled ctxt >>=? fun () ->
      let Constants.
            {
              tx_rollup_max_messages_per_inbox;
              tx_rollup_max_withdrawals_per_batch;
              _;
            } =
        Constants.parametric ctxt
      in
      Tx_rollup_errors.check_path_depth
        `Commitment
        (Tx_rollup_commitment.Merkle.path_depth message_result_path)
        ~count_limit:tx_rollup_max_messages_per_inbox
      >>?= fun () ->
      error_when
        Compare.List_length_with.(tickets_info = 0)
        Tx_rollup_errors.No_withdrawals_to_dispatch
      >>?= fun () ->
      error_when
        Compare.List_length_with.(
          tickets_info > tx_rollup_max_withdrawals_per_batch)
        Tx_rollup_errors.Too_many_withdrawals
      >>?= fun () ->
      record_trace Gas_quota_exceeded_init_deserialize
      @@ (* See comment in the Transaction branch *)
      List.fold_left_e
        (fun ctxt Tx_rollup_reveal.{contents; ty; _} ->
          Script.force_decode_in_context
            ~consume_deserialization_gas
            ctxt
            contents
          >>? fun (_contents, ctxt) ->
          Script.force_decode_in_context ~consume_deserialization_gas ctxt ty
          >|? fun (_ty, ctxt) -> ctxt)
        ctxt
        tickets_info
      >>?= fun ctxt -> return ctxt
  | Tx_rollup_rejection
      {message_path; message_result_path; previous_message_result_path; _} ->
      assert_tx_rollup_feature_enabled ctxt >>=? fun () ->
      let Constants.{tx_rollup_max_messages_per_inbox; _} =
        Constants.parametric ctxt
      in
      Tx_rollup_errors.check_path_depth
        `Inbox
        (Tx_rollup_inbox.Merkle.path_depth message_path)
        ~count_limit:tx_rollup_max_messages_per_inbox
      >>?= fun () ->
      Tx_rollup_errors.check_path_depth
        `Commitment
        (Tx_rollup_commitment.Merkle.path_depth message_result_path)
        ~count_limit:tx_rollup_max_messages_per_inbox
      >>?= fun () ->
      Tx_rollup_errors.check_path_depth
        `Commitment
        (Tx_rollup_commitment.Merkle.path_depth previous_message_result_path)
        ~count_limit:tx_rollup_max_messages_per_inbox
      >>?= fun () -> return ctxt
  | Sc_rollup_originate _ | Sc_rollup_add_messages _ | Sc_rollup_cement _
  | Sc_rollup_publish _ ->
      assert_sc_rollup_feature_enabled ctxt >|=? fun () -> ctxt)
  >>=? fun ctxt ->
  Contract.increment_counter ctxt source >>=? fun ctxt ->
  Token.transfer ctxt (`Contract source_contract) `Block_fees fee
  >|=? fun (ctxt, balance_updates) ->
  let consumed_gas = Gas.consumed ~since:ctxt_before ~until:ctxt in
  (ctxt, {balance_updates; consumed_gas})

(** [burn_storage_fees ctxt smopr storage_limit payer] burns the storage fees
    associated to an operation result [smopr].
    Returns an updated context, an updated storage limit with the space consumed
    by the operation subtracted, and [smopr] with the relevant balance updates
    included. *)
let burn_storage_fees :
    type kind.
    context ->
    kind successful_manager_operation_result ->
    storage_limit:Z.t ->
    payer:public_key_hash ->
    (context * Z.t * kind successful_manager_operation_result) tzresult Lwt.t =
 fun ctxt smopr ~storage_limit ~payer ->
  let payer = `Contract (Contract.implicit_contract payer) in
  match smopr with
  | Transaction_result (Transaction_to_contract_result payload) ->
      let consumed = payload.paid_storage_size_diff in
      Fees.burn_storage_fees ctxt ~storage_limit ~payer consumed
      >>=? fun (ctxt, storage_limit, storage_bus) ->
      (if payload.allocated_destination_contract then
       Fees.burn_origination_fees ctxt ~storage_limit ~payer
      else return (ctxt, storage_limit, []))
      >>=? fun (ctxt, storage_limit, origination_bus) ->
      let balance_updates =
        storage_bus @ payload.balance_updates @ origination_bus
      in
      return
        ( ctxt,
          storage_limit,
          Transaction_result
            (Transaction_to_contract_result
               {
                 storage = payload.storage;
                 lazy_storage_diff = payload.lazy_storage_diff;
                 balance_updates;
                 originated_contracts = payload.originated_contracts;
                 consumed_gas = payload.consumed_gas;
                 storage_size = payload.storage_size;
                 paid_storage_size_diff = payload.paid_storage_size_diff;
                 allocated_destination_contract =
                   payload.allocated_destination_contract;
               }) )
  | Transaction_result (Transaction_to_tx_rollup_result payload) ->
      let consumed = payload.paid_storage_size_diff in
      Fees.burn_storage_fees ctxt ~storage_limit ~payer consumed
      >>=? fun (ctxt, storage_limit, storage_bus) ->
      let balance_updates = storage_bus @ payload.balance_updates in
      return
        ( ctxt,
          storage_limit,
          Transaction_result
            (Transaction_to_tx_rollup_result {payload with balance_updates}) )
  | Origination_result payload ->
      let consumed = payload.paid_storage_size_diff in
      Fees.burn_storage_fees ctxt ~storage_limit ~payer consumed
      >>=? fun (ctxt, storage_limit, storage_bus) ->
      Fees.burn_origination_fees ctxt ~storage_limit ~payer
      >>=? fun (ctxt, storage_limit, origination_bus) ->
      let balance_updates =
        storage_bus @ origination_bus @ payload.balance_updates
      in
      return
        ( ctxt,
          storage_limit,
          Origination_result
            {
              lazy_storage_diff = payload.lazy_storage_diff;
              balance_updates;
              originated_contracts = payload.originated_contracts;
              consumed_gas = payload.consumed_gas;
              storage_size = payload.storage_size;
              paid_storage_size_diff = payload.paid_storage_size_diff;
            } )
  | Reveal_result _ | Delegation_result _ -> return (ctxt, storage_limit, smopr)
  | Register_global_constant_result payload ->
      let consumed = payload.size_of_constant in
      Fees.burn_storage_fees ctxt ~storage_limit ~payer consumed
      >>=? fun (ctxt, storage_limit, storage_bus) ->
      let balance_updates = storage_bus @ payload.balance_updates in
      return
        ( ctxt,
          storage_limit,
          Register_global_constant_result
            {
              balance_updates;
              consumed_gas = payload.consumed_gas;
              size_of_constant = payload.size_of_constant;
              global_address = payload.global_address;
            } )
  | Set_deposits_limit_result _ -> return (ctxt, storage_limit, smopr)
  | Tx_rollup_origination_result payload ->
      Fees.burn_tx_rollup_origination_fees ctxt ~storage_limit ~payer
      >>=? fun (ctxt, storage_limit, origination_bus) ->
      let balance_updates = origination_bus @ payload.balance_updates in
      return
        ( ctxt,
          storage_limit,
          Tx_rollup_origination_result {payload with balance_updates} )
  | Tx_rollup_return_bond_result _ | Tx_rollup_remove_commitment_result _
  | Tx_rollup_rejection_result _ | Tx_rollup_finalize_commitment_result _
  | Tx_rollup_commit_result _ ->
      return (ctxt, storage_limit, smopr)
  | Transfer_ticket_result payload ->
      let consumed = payload.paid_storage_size_diff in
      Fees.burn_storage_fees ctxt ~storage_limit ~payer consumed
      >>=? fun (ctxt, storage_limit, storage_bus) ->
      let balance_updates = payload.balance_updates @ storage_bus in
      return
        ( ctxt,
          storage_limit,
          Transfer_ticket_result {payload with balance_updates} )
  | Tx_rollup_submit_batch_result payload ->
      let consumed = payload.paid_storage_size_diff in
      Fees.burn_storage_fees ctxt ~storage_limit ~payer consumed
      >>=? fun (ctxt, storage_limit, storage_bus) ->
      let balance_updates = storage_bus @ payload.balance_updates in
      return
        ( ctxt,
          storage_limit,
          Tx_rollup_submit_batch_result {payload with balance_updates} )
  | Tx_rollup_dispatch_tickets_result payload ->
      let consumed = payload.paid_storage_size_diff in
      Fees.burn_storage_fees ctxt ~storage_limit ~payer consumed
      >>=? fun (ctxt, storage_limit, storage_bus) ->
      let balance_updates = storage_bus @ payload.balance_updates in
      return
        ( ctxt,
          storage_limit,
          Tx_rollup_dispatch_tickets_result {payload with balance_updates} )
  | Sc_rollup_originate_result payload ->
      Fees.burn_sc_rollup_origination_fees
        ctxt
        ~storage_limit
        ~payer
        payload.size
      >>=? fun (ctxt, storage_limit, balance_updates) ->
      let result = Sc_rollup_originate_result {payload with balance_updates} in
      return (ctxt, storage_limit, result)
  | Sc_rollup_add_messages_result _ -> return (ctxt, storage_limit, smopr)
  | Sc_rollup_cement_result _ -> return (ctxt, storage_limit, smopr)
  | Sc_rollup_publish_result _ -> return (ctxt, storage_limit, smopr)

let apply_manager_contents (type kind) ctxt mode chain_id
    ~gas_consumed_in_precheck (op : kind Kind.manager contents) :
    (success_or_failure
    * kind manager_operation_result
    * packed_internal_manager_operation_result list)
    Lwt.t =
  let[@coq_match_with_default] (Manager_operation
                                 {
                                   source;
                                   operation;
                                   gas_limit;
                                   storage_limit;
                                   _;
                                 }) =
    op
  in
  (* We do not expose the internal scaling to the users. Instead, we multiply
       the specified gas limit by the internal scaling. *)
  let ctxt = Gas.set_limit ctxt gas_limit in
  apply_external_manager_operation_content
    ctxt
    mode
    ~source
    ~gas_consumed_in_precheck
    ~chain_id
    operation
  >>= function
  | Ok (ctxt, operation_results, internal_operations) -> (
      apply_internal_manager_operations
        ctxt
        mode
        ~payer:source
        ~chain_id
        internal_operations
      >>= function
      | (Success ctxt, internal_operations_results) -> (
          burn_storage_fees ctxt operation_results ~storage_limit ~payer:source
          >>= function
          | Ok (ctxt, storage_limit, operation_results) -> (
              List.fold_left_es
                (fun (ctxt, storage_limit, res) imopr ->
                  let (Internal_manager_operation_result (op, mopr)) = imopr in
                  match mopr with
                  | Applied smopr ->
                      burn_storage_fees ctxt smopr ~storage_limit ~payer:source
                      >>=? fun (ctxt, storage_limit, smopr) ->
                      let imopr =
                        Internal_manager_operation_result (op, Applied smopr)
                      in
                      return (ctxt, storage_limit, imopr :: res)
                  | _ -> return (ctxt, storage_limit, imopr :: res))
                (ctxt, storage_limit, [])
                internal_operations_results
              >|= function
              | Ok (ctxt, _, internal_operations_results) ->
                  ( Success ctxt,
                    Applied operation_results,
                    List.rev internal_operations_results )
              | Error errors ->
                  ( Failure,
                    Backtracked (operation_results, Some errors),
                    internal_operations_results ))
          | Error errors ->
              Lwt.return
                ( Failure,
                  Backtracked (operation_results, Some errors),
                  internal_operations_results ))
      | (Failure, internal_operations_results) ->
          Lwt.return
            (Failure, Applied operation_results, internal_operations_results))
  | Error errors ->
      Lwt.return (Failure, Failed (manager_kind operation, errors), [])

let skipped_operation_result :
    type kind. kind manager_operation -> kind manager_operation_result =
  function
  | operation -> (
      match operation with
      | Reveal _ ->
          Applied
            (Reveal_result {consumed_gas = Gas.Arith.zero}
              : kind successful_manager_operation_result)
      | _ -> Skipped (manager_kind operation))

let rec mark_skipped :
    type kind.
    payload_producer:Signature.Public_key_hash.t ->
    Level.t ->
    kind Kind.manager prechecked_contents_list ->
    kind Kind.manager contents_result_list =
 fun ~payload_producer level prechecked_contents_list ->
  match[@coq_match_with_default] prechecked_contents_list with
  | PrecheckedSingle
      {
        contents = Manager_operation {operation; _};
        result = {balance_updates; _};
      } ->
      Single_result
        (Manager_operation_result
           {
             balance_updates;
             operation_result = skipped_operation_result operation;
             internal_operation_results = [];
           })
  | PrecheckedCons
      ( {
          contents = Manager_operation {operation; _};
          result = {balance_updates; _};
        },
        rest ) ->
      Cons_result
        ( Manager_operation_result
            {
              balance_updates;
              operation_result = skipped_operation_result operation;
              internal_operation_results = [];
            },
          mark_skipped ~payload_producer level rest )

(** Check that counters are consistent, i.e. that they are successive within a
    batch. Fail with a {b permanent} error otherwise.
    TODO: https://gitlab.com/tezos/tezos/-/issues/2301
    Remove when format of operation is changed to save space.
 *)
let check_counters_consistency contents_list =
  let check_counter ~previous_counter counter =
    match previous_counter with
    | None -> return_unit
    | Some previous_counter ->
        let expected = Z.succ previous_counter in
        if Compare.Z.(expected = counter) then return_unit
        else fail Inconsistent_counters
  in
  let rec check_counters_rec :
      type kind.
      counter option -> kind Kind.manager contents_list -> unit tzresult Lwt.t =
   fun previous_counter contents_list ->
    match[@coq_match_with_default] contents_list with
    | Single (Manager_operation {counter; _}) ->
        check_counter ~previous_counter counter
    | Cons (Manager_operation {counter; _}, rest) ->
        check_counter ~previous_counter counter >>=? fun () ->
        check_counters_rec (Some counter) rest
  in
  check_counters_rec None contents_list

(** Returns an updated context, and a list of prechecked contents containing
    balance updates for fees related to each manager operation in
    [contents_list]. *)
let precheck_manager_contents_list ctxt contents_list ~mempool_mode =
  let rec rec_precheck_manager_contents_list :
      type kind.
      context ->
      kind Kind.manager contents_list ->
      (context * kind Kind.manager prechecked_contents_list) tzresult Lwt.t =
   fun ctxt contents_list ->
    match contents_list with
    | Single contents ->
        precheck_manager_contents ctxt contents ~only_batch:mempool_mode
        >>=? fun (ctxt, result) ->
        return (ctxt, PrecheckedSingle {contents; result})
    | Cons (contents, rest) ->
        precheck_manager_contents ctxt contents ~only_batch:mempool_mode
        >>=? fun (ctxt, result) ->
        rec_precheck_manager_contents_list ctxt rest
        >>=? fun (ctxt, results_rest) ->
        return (ctxt, PrecheckedCons ({contents; result}, results_rest))
  in
  let ctxt = if mempool_mode then Gas.reset_block_gas ctxt else ctxt in
  check_counters_consistency contents_list >>=? fun () ->
  rec_precheck_manager_contents_list ctxt contents_list

let find_manager_public_key ctxt (op : _ Kind.manager contents_list) =
  (* Currently, the [op] only contains one signature, so
     all operations are required to be from the same manager. This may
     change in the future, allowing several managers to group-sign a
     sequence of transactions. *)
  let check_same_manager (source, source_key) manager =
    match manager with
    | None -> ok (source, source_key)
    | Some (manager, manager_key) ->
        if Signature.Public_key_hash.equal source manager then
          (* Consistency will be checked by
             [reveal_manager_key] in [precheck_manager_contents]. *)
          ok (source, Option.either manager_key source_key)
        else error Inconsistent_sources
  in
  let rec find_source :
      type kind.
      kind Kind.manager contents_list ->
      (Signature.public_key_hash * Signature.public_key option) option ->
      (Signature.public_key_hash * Signature.public_key option) tzresult =
   fun contents_list manager ->
    let source (type kind) = function[@coq_match_with_default]
      | (Manager_operation {source; operation = Reveal key; _} :
          kind Kind.manager contents) ->
          (source, Some key)
      | Manager_operation {source; _} -> (source, None)
    in
    match contents_list with
    | Single op -> check_same_manager (source op) manager
    | Cons (op, rest) ->
        check_same_manager (source op) manager >>? fun manager ->
        find_source rest (Some manager)
  in
  find_source op None >>?= fun (source, source_key) ->
  match source_key with
  | Some key -> return key
  | None -> Contract.get_manager_key ctxt source

let check_manager_signature ctxt chain_id (op : _ Kind.manager contents_list)
    raw_operation =
  find_manager_public_key ctxt op >>=? fun public_key ->
  Lwt.return (Operation.check_signature public_key chain_id raw_operation)

let rec apply_manager_contents_list_rec :
    type kind.
    context ->
    Script_ir_translator.unparsing_mode ->
    payload_producer:public_key_hash ->
    Chain_id.t ->
    kind Kind.manager prechecked_contents_list ->
    (success_or_failure * kind Kind.manager contents_result_list) Lwt.t =
 fun ctxt mode ~payload_producer chain_id prechecked_contents_list ->
  let level = Level.current ctxt in
  match[@coq_match_with_default] prechecked_contents_list with
  | PrecheckedSingle
      {
        contents = Manager_operation _ as op;
        result = {consumed_gas; balance_updates};
      } ->
      apply_manager_contents
        ctxt
        mode
        chain_id
        ~gas_consumed_in_precheck:(Some (Gas.cost_of_gas consumed_gas))
        op
      >|= fun (ctxt_result, operation_result, internal_operation_results) ->
      let result =
        Manager_operation_result
          {balance_updates; operation_result; internal_operation_results}
      in
      (ctxt_result, Single_result result)
  | PrecheckedCons
      ( {
          contents = Manager_operation _ as op;
          result = {consumed_gas; balance_updates};
        },
        rest ) -> (
      apply_manager_contents
        ctxt
        mode
        chain_id
        ~gas_consumed_in_precheck:(Some (Gas.cost_of_gas consumed_gas))
        op
      >>= function
      | (Failure, operation_result, internal_operation_results) ->
          let result =
            Manager_operation_result
              {balance_updates; operation_result; internal_operation_results}
          in
          Lwt.return
            ( Failure,
              Cons_result (result, mark_skipped ~payload_producer level rest) )
      | (Success ctxt, operation_result, internal_operation_results) ->
          let result =
            Manager_operation_result
              {balance_updates; operation_result; internal_operation_results}
          in
          apply_manager_contents_list_rec
            ctxt
            mode
            ~payload_producer
            chain_id
            rest
          >|= fun (ctxt_result, results) ->
          (ctxt_result, Cons_result (result, results)))

let mark_backtracked results =
  let rec mark_contents_list :
      type kind.
      kind Kind.manager contents_result_list ->
      kind Kind.manager contents_result_list = function
    | Single_result (Manager_operation_result op) ->
        Single_result
          (Manager_operation_result
             {
               balance_updates = op.balance_updates;
               operation_result =
                 mark_manager_operation_result op.operation_result;
               internal_operation_results =
                 List.map
                   mark_internal_operation_results
                   op.internal_operation_results;
             })
    | Cons_result (Manager_operation_result op, rest) ->
        Cons_result
          ( Manager_operation_result
              {
                balance_updates = op.balance_updates;
                operation_result =
                  mark_manager_operation_result op.operation_result;
                internal_operation_results =
                  List.map
                    mark_internal_operation_results
                    op.internal_operation_results;
              },
            mark_contents_list rest )
  and mark_internal_operation_results
      (Internal_manager_operation_result (kind, result)) =
    Internal_manager_operation_result
      (kind, mark_manager_operation_result result)
  and mark_manager_operation_result :
      type kind. kind manager_operation_result -> kind manager_operation_result
      = function
    | (Failed _ | Skipped _ | Backtracked _) as result -> result
    | Applied (Reveal_result _) as result -> result
    | Applied result -> Backtracked (result, None)
  in
  mark_contents_list results
  [@@coq_axiom_with_reason "non-top-level mutual recursion"]

type apply_mode =
  | Application of {
      predecessor_block : Block_hash.t;
      payload_hash : Block_payload_hash.t;
      locked_round : Round.t option;
      predecessor_level : Level.t;
      predecessor_round : Round.t;
      round : Round.t;
    } (* Both partial and normal *)
  | Full_construction of {
      predecessor_block : Block_hash.t;
      payload_hash : Block_payload_hash.t;
      predecessor_level : Level.t;
      predecessor_round : Round.t;
      round : Round.t;
    }
  | Partial_construction of {
      predecessor_level : Level.t;
      predecessor_round : Round.t;
      grand_parent_round : Round.t;
    }

let get_predecessor_level = function
  | Application {predecessor_level; _}
  | Full_construction {predecessor_level; _}
  | Partial_construction {predecessor_level; _} ->
      predecessor_level

let record_operation (type kind) ctxt (operation : kind operation) : context =
  match operation.protocol_data.contents with
  | Single (Preendorsement _) -> ctxt
  | Single (Endorsement _) -> ctxt
  | Single
      ( Failing_noop _ | Proposals _ | Ballot _ | Seed_nonce_revelation _
      | Double_endorsement_evidence _ | Double_preendorsement_evidence _
      | Double_baking_evidence _ | Activate_account _ | Manager_operation _ )
  | Cons (Manager_operation _, _) ->
      let hash = Operation.hash operation in
      record_non_consensus_operation_hash ctxt hash

type 'consensus_op_kind expected_consensus_content = {
  payload_hash : Block_payload_hash.t;
  branch : Block_hash.t;
  level : Level.t;
  round : Round.t;
}

(* The [Alpha_context] is modified only in [Full_construction] mode
   when we check a preendorsement if the [preendorsement_quorum_round]
   was not set. *)
let compute_expected_consensus_content (type consensus_op_kind)
    ~(current_level : Level.t) ~(proposal_level : Level.t) (ctxt : context)
    (application_mode : apply_mode)
    (operation_kind : consensus_op_kind consensus_operation_type)
    (operation_round : Round.t) (operation_level : Raw_level.t) :
    (context * consensus_op_kind expected_consensus_content) tzresult Lwt.t =
  match operation_kind with
  | Endorsement -> (
      match Consensus.endorsement_branch ctxt with
      | None -> (
          match application_mode with
          | Application _ | Full_construction _ ->
              fail Unexpected_endorsement_in_block
          | Partial_construction _ ->
              fail
                (Consensus_operation_for_future_level
                   {expected = proposal_level.level; provided = operation_level})
          )
      | Some (branch, payload_hash) -> (
          match application_mode with
          | Application {predecessor_round; _}
          | Full_construction {predecessor_round; _}
          | Partial_construction {predecessor_round; _} ->
              return
                ( ctxt,
                  {
                    payload_hash;
                    branch;
                    level = proposal_level;
                    round = predecessor_round;
                  } )))
  | Preendorsement -> (
      match application_mode with
      | Application {locked_round = None; _} ->
          fail Unexpected_preendorsement_in_block
      | Application
          {
            payload_hash;
            predecessor_block = branch;
            locked_round = Some locked_round;
            _;
          } ->
          return
            ( ctxt,
              {
                payload_hash;
                branch;
                level = current_level;
                round = locked_round;
              } )
      | Partial_construction {predecessor_round; _} -> (
          match Consensus.endorsement_branch ctxt with
          | None ->
              fail
                (Consensus_operation_for_future_level
                   {expected = proposal_level.level; provided = operation_level})
          | Some (branch, payload_hash) ->
              return
                ( ctxt,
                  {
                    payload_hash;
                    branch;
                    level = proposal_level;
                    round = predecessor_round;
                  } ))
      | Full_construction {payload_hash; predecessor_block = branch; _} ->
          let (ctxt', round) =
            match Consensus.get_preendorsements_quorum_round ctxt with
            | None ->
                ( Consensus.set_preendorsements_quorum_round ctxt operation_round,
                  operation_round )
            | Some round -> (ctxt, round)
          in
          return (ctxt', {payload_hash; branch; level = current_level; round}))

let check_level (apply_mode : apply_mode) ~expected ~provided =
  match apply_mode with
  | Application _ | Full_construction _ ->
      error_unless
        (Raw_level.equal expected provided)
        (Wrong_level_for_consensus_operation {expected; provided})
  | Partial_construction _ ->
      (* Valid grand parent's endorsements were treated by
         [validate_grand_parent_endorsement]. *)
      error_when
        Raw_level.(expected > provided)
        (Consensus_operation_for_old_level {expected; provided})
      >>? fun () ->
      error_when
        Raw_level.(expected < provided)
        (Consensus_operation_for_future_level {expected; provided})

let check_payload_hash (apply_mode : apply_mode) ~expected ~provided =
  match apply_mode with
  | Application _ | Full_construction _ ->
      error_unless
        (Block_payload_hash.equal expected provided)
        (Wrong_payload_hash_for_consensus_operation {expected; provided})
  | Partial_construction _ ->
      error_unless
        (Block_payload_hash.equal expected provided)
        (Consensus_operation_on_competing_proposal {expected; provided})

let check_operation_branch ~expected ~provided =
  error_unless
    (Block_hash.equal expected provided)
    (Wrong_consensus_operation_branch (expected, provided))

let check_round (type kind) (operation_kind : kind consensus_operation_type)
    (apply_mode : apply_mode) ~(expected : Round.t) ~(provided : Round.t) :
    unit tzresult =
  match apply_mode with
  | Partial_construction _ ->
      error_when
        Round.(expected > provided)
        (Consensus_operation_for_old_round {expected; provided})
      >>? fun () ->
      error_when
        Round.(expected < provided)
        (Consensus_operation_for_future_round {expected; provided})
  | Full_construction {round; _} | Application {round; _} ->
      (match operation_kind with
      | Preendorsement ->
          error_when
            Round.(round <= provided)
            (Preendorsement_round_too_high {block_round = round; provided})
      | Endorsement -> Result.return_unit)
      >>? fun () ->
      error_unless
        (Round.equal expected provided)
        (Wrong_round_for_consensus_operation {expected; provided})

let check_consensus_content (type kind) (apply_mode : apply_mode)
    (content : consensus_content) (operation_branch : Block_hash.t)
    (operation_kind : kind consensus_operation_type)
    (expected_content : kind expected_consensus_content) : unit tzresult =
  let expected_level = expected_content.level.level in
  let provided_level = content.level in
  let expected_round = expected_content.round in
  let provided_round = content.round in
  check_level apply_mode ~expected:expected_level ~provided:provided_level
  >>? fun () ->
  check_round
    operation_kind
    apply_mode
    ~expected:expected_round
    ~provided:provided_round
  >>? fun () ->
  check_operation_branch
    ~expected:expected_content.branch
    ~provided:operation_branch
  >>? fun () ->
  check_payload_hash
    apply_mode
    ~expected:expected_content.payload_hash
    ~provided:content.block_payload_hash

(* Validate the 'operation.shell.branch' field of the operation. It MUST point
   to the grandfather: the block hash used in the payload_hash. Otherwise we could produce
   a preendorsement pointing to the direct proposal. This preendorsement wouldn't be able to
   propagate for a subsequent proposal using it as a locked_round evidence. *)
let validate_consensus_contents (type kind) ctxt chain_id
    (operation_kind : kind consensus_operation_type)
    (operation : kind operation) (apply_mode : apply_mode)
    (content : consensus_content) :
    (context * public_key_hash * int) tzresult Lwt.t =
  let current_level = Level.current ctxt in
  let proposal_level = get_predecessor_level apply_mode in
  let slot_map =
    match operation_kind with
    | Preendorsement -> Consensus.allowed_preendorsements ctxt
    | Endorsement -> Consensus.allowed_endorsements ctxt
  in
  compute_expected_consensus_content
    ~current_level
    ~proposal_level
    ctxt
    apply_mode
    operation_kind
    content.round
    content.level
  >>=? fun (ctxt, expected_content) ->
  check_consensus_content
    apply_mode
    content
    operation.shell.branch
    operation_kind
    expected_content
  >>?= fun () ->
  match Slot.Map.find content.slot slot_map with
  | None -> fail Wrong_slot_used_for_consensus_operation
  | Some (delegate_pk, delegate_pkh, voting_power) ->
      Delegate.frozen_deposits ctxt delegate_pkh >>=? fun frozen_deposits ->
      fail_unless
        Tez.(frozen_deposits.current_amount > zero)
        (Zero_frozen_deposits delegate_pkh)
      >>=? fun () ->
      Operation.check_signature delegate_pk chain_id operation >>?= fun () ->
      return (ctxt, delegate_pkh, voting_power)

let apply_manager_contents_list ctxt mode ~payload_producer chain_id
    prechecked_contents_list =
  apply_manager_contents_list_rec
    ctxt
    mode
    ~payload_producer
    chain_id
    prechecked_contents_list
  >>= fun (ctxt_result, results) ->
  match ctxt_result with
  | Failure -> Lwt.return (ctxt (* backtracked *), mark_backtracked results)
  | Success ctxt ->
      Lazy_storage.cleanup_temporaries ctxt >|= fun ctxt -> (ctxt, results)

let check_denunciation_age ctxt kind given_level =
  let max_slashing_period = Constants.max_slashing_period ctxt in
  let current_cycle = (Level.current ctxt).cycle in
  let given_cycle = (Level.from_raw ctxt given_level).cycle in
  let last_slashable_cycle = Cycle.add given_cycle max_slashing_period in
  fail_when
    Cycle.(given_cycle > current_cycle)
    (Too_early_denunciation
       {kind; level = given_level; current = (Level.current ctxt).level})
  >>=? fun () ->
  fail_unless
    Cycle.(last_slashable_cycle > current_cycle)
    (Outdated_denunciation
       {kind; level = given_level; last_cycle = last_slashable_cycle})

let punish_delegate ctxt delegate level mistake mk_result ~payload_producer =
  let (already_slashed, punish) =
    match mistake with
    | `Double_baking ->
        ( Delegate.already_slashed_for_double_baking,
          Delegate.punish_double_baking )
    | `Double_endorsing ->
        ( Delegate.already_slashed_for_double_endorsing,
          Delegate.punish_double_endorsing )
  in
  already_slashed ctxt delegate level >>=? fun slashed ->
  fail_when slashed Unrequired_denunciation >>=? fun () ->
  punish ctxt delegate level >>=? fun (ctxt, burned, punish_balance_updates) ->
  (match Tez.(burned /? 2L) with
  | Ok reward ->
      Token.transfer
        ctxt
        `Double_signing_evidence_rewards
        (`Contract (Contract.implicit_contract payload_producer))
        reward
  | Error _ -> (* reward is Tez.zero *) return (ctxt, []))
  >|=? fun (ctxt, reward_balance_updates) ->
  let balance_updates = reward_balance_updates @ punish_balance_updates in
  (ctxt, Single_result (mk_result balance_updates))

let punish_double_endorsement_or_preendorsement (type kind) ctxt ~chain_id
    ~preendorsement ~(op1 : kind Kind.consensus Operation.t)
    ~(op2 : kind Kind.consensus Operation.t) ~payload_producer :
    (context
    * kind Kind.double_consensus_operation_evidence contents_result_list)
    tzresult
    Lwt.t =
  let mk_result (balance_updates : Receipt.balance_updates) :
      kind Kind.double_consensus_operation_evidence contents_result =
    match op1.protocol_data.contents with
    | Single (Preendorsement _) ->
        Double_preendorsement_evidence_result balance_updates
    | Single (Endorsement _) ->
        Double_endorsement_evidence_result balance_updates
  in
  match (op1.protocol_data.contents, op2.protocol_data.contents) with
  | (Single (Preendorsement e1), Single (Preendorsement e2))
  | (Single (Endorsement e1), Single (Endorsement e2)) ->
      let kind = if preendorsement then Preendorsement else Endorsement in
      let op1_hash = Operation.hash op1 in
      let op2_hash = Operation.hash op2 in
      fail_unless
        (Raw_level.(e1.level = e2.level)
        && Round.(e1.round = e2.round)
        && (not
              (Block_payload_hash.equal
                 e1.block_payload_hash
                 e2.block_payload_hash))
        && (* we require an order on hashes to avoid the existence of
              equivalent evidences *)
        Operation_hash.(op1_hash < op2_hash))
        (Invalid_denunciation kind)
      >>=? fun () ->
      (* Disambiguate: levels are equal *)
      let level = Level.from_raw ctxt e1.level in
      check_denunciation_age ctxt kind level.level >>=? fun () ->
      Stake_distribution.slot_owner ctxt level e1.slot
      >>=? fun (ctxt, (delegate1_pk, delegate1)) ->
      Stake_distribution.slot_owner ctxt level e2.slot
      >>=? fun (ctxt, (_delegate2_pk, delegate2)) ->
      fail_unless
        (Signature.Public_key_hash.equal delegate1 delegate2)
        (Inconsistent_denunciation {kind; delegate1; delegate2})
      >>=? fun () ->
      let (delegate_pk, delegate) = (delegate1_pk, delegate1) in
      Operation.check_signature delegate_pk chain_id op1 >>?= fun () ->
      Operation.check_signature delegate_pk chain_id op2 >>?= fun () ->
      punish_delegate
        ctxt
        delegate
        level
        `Double_endorsing
        mk_result
        ~payload_producer

let punish_double_baking ctxt chain_id bh1 bh2 ~payload_producer =
  let hash1 = Block_header.hash bh1 in
  let hash2 = Block_header.hash bh2 in
  Fitness.from_raw bh1.shell.fitness >>?= fun bh1_fitness ->
  let round1 = Fitness.round bh1_fitness in
  Fitness.from_raw bh2.shell.fitness >>?= fun bh2_fitness ->
  let round2 = Fitness.round bh2_fitness in
  ( Raw_level.of_int32 bh1.shell.level >>?= fun level1 ->
    Raw_level.of_int32 bh2.shell.level >>?= fun level2 ->
    fail_unless
      (Compare.Int32.(bh1.shell.level = bh2.shell.level)
      && Round.(round1 = round2)
      && (* we require an order on hashes to avoid the existence of
            equivalent evidences *)
      Block_hash.(hash1 < hash2))
      (Invalid_double_baking_evidence
         {hash1; level1; round1; hash2; level2; round2}) )
  >>=? fun () ->
  Raw_level.of_int32 bh1.shell.level >>?= fun raw_level ->
  check_denunciation_age ctxt Block raw_level >>=? fun () ->
  let level = Level.from_raw ctxt raw_level in
  let committee_size = Constants.consensus_committee_size ctxt in
  Round.to_slot round1 ~committee_size >>?= fun slot1 ->
  Stake_distribution.slot_owner ctxt level slot1
  >>=? fun (ctxt, (delegate1_pk, delegate1)) ->
  Round.to_slot round2 ~committee_size >>?= fun slot2 ->
  Stake_distribution.slot_owner ctxt level slot2
  >>=? fun (ctxt, (_delegate2_pk, delegate2)) ->
  fail_unless
    Signature.Public_key_hash.(delegate1 = delegate2)
    (Inconsistent_denunciation {kind = Block; delegate1; delegate2})
  >>=? fun () ->
  let (delegate_pk, delegate) = (delegate1_pk, delegate1) in
  Block_header.check_signature bh1 chain_id delegate_pk >>?= fun () ->
  Block_header.check_signature bh2 chain_id delegate_pk >>?= fun () ->
  punish_delegate
    ctxt
    delegate
    level
    `Double_baking
    ~payload_producer
    (fun balance_updates -> Double_baking_evidence_result balance_updates)

let is_parent_endorsement ctxt ~proposal_level ~grand_parent_round
    (operation : 'a operation) (operation_content : consensus_content) =
  match Consensus.grand_parent_branch ctxt with
  | None -> false
  | Some (great_grand_parent_hash, grand_parent_payload_hash) ->
      (* Check level *)
      Raw_level.(proposal_level.Level.level = succ operation_content.level)
      (* Check round *)
      && Round.(grand_parent_round = operation_content.round)
      (* Check payload *)
      && Block_payload_hash.(
           grand_parent_payload_hash = operation_content.block_payload_hash)
      && (* Check branch *)
      Block_hash.(great_grand_parent_hash = operation.shell.branch)

let validate_grand_parent_endorsement ctxt chain_id
    (op : Kind.endorsement operation) =
  match op.protocol_data.contents with
  | Single (Endorsement e) ->
      let level = Level.from_raw ctxt e.level in
      Stake_distribution.slot_owner ctxt level e.slot
      >>=? fun (ctxt, (delegate_pk, pkh)) ->
      Operation.check_signature delegate_pk chain_id op >>?= fun () ->
      Consensus.record_grand_parent_endorsement ctxt pkh >>?= fun ctxt ->
      return
        ( ctxt,
          Single_result
            (Endorsement_result
               {
                 balance_updates = [];
                 delegate = pkh;
                 endorsement_power =
                   0 (* dummy endorsement power: this will never be used *);
               }) )

let apply_contents_list (type kind) ctxt chain_id (apply_mode : apply_mode) mode
    ~payload_producer (operation : kind operation)
    (contents_list : kind contents_list) :
    (context * kind contents_result_list) tzresult Lwt.t =
  let mempool_mode =
    match apply_mode with
    | Partial_construction _ -> true
    | Full_construction _ | Application _ -> false
  in
  match[@coq_match_with_default] contents_list with
  | Single (Preendorsement consensus_content) ->
      validate_consensus_contents
        ctxt
        chain_id
        Preendorsement
        operation
        apply_mode
        consensus_content
      >>=? fun (ctxt, delegate, voting_power) ->
      Consensus.record_preendorsement
        ctxt
        ~initial_slot:consensus_content.slot
        ~power:voting_power
        consensus_content.round
      >>?= fun ctxt ->
      return
        ( ctxt,
          Single_result
            (Preendorsement_result
               {
                 balance_updates = [];
                 delegate;
                 preendorsement_power = voting_power;
               }) )
  | Single (Endorsement consensus_content) -> (
      let proposal_level = get_predecessor_level apply_mode in
      match apply_mode with
      | Partial_construction {grand_parent_round; _}
        when is_parent_endorsement
               ctxt
               ~proposal_level
               ~grand_parent_round
               operation
               consensus_content ->
          validate_grand_parent_endorsement ctxt chain_id operation
      | _ ->
          validate_consensus_contents
            ctxt
            chain_id
            Endorsement
            operation
            apply_mode
            consensus_content
          >>=? fun (ctxt, delegate, voting_power) ->
          Consensus.record_endorsement
            ctxt
            ~initial_slot:consensus_content.slot
            ~power:voting_power
          >>?= fun ctxt ->
          return
            ( ctxt,
              Single_result
                (Endorsement_result
                   {
                     balance_updates = [];
                     delegate;
                     endorsement_power = voting_power;
                   }) ))
  | Single (Seed_nonce_revelation {level; nonce}) ->
      let level = Level.from_raw ctxt level in
      Nonce.reveal ctxt level nonce >>=? fun ctxt ->
      let tip = Constants.seed_nonce_revelation_tip ctxt in
      let contract = Contract.implicit_contract payload_producer in
      Token.transfer ctxt `Revelation_rewards (`Contract contract) tip
      >|=? fun (ctxt, balance_updates) ->
      (ctxt, Single_result (Seed_nonce_revelation_result balance_updates))
  | Single (Double_preendorsement_evidence {op1; op2}) ->
      punish_double_endorsement_or_preendorsement
        ctxt
        ~preendorsement:true
        ~chain_id
        ~op1
        ~op2
        ~payload_producer
  | Single (Double_endorsement_evidence {op1; op2}) ->
      punish_double_endorsement_or_preendorsement
        ctxt
        ~preendorsement:false
        ~chain_id
        ~op1
        ~op2
        ~payload_producer
  | Single (Double_baking_evidence {bh1; bh2}) ->
      punish_double_baking ctxt chain_id bh1 bh2 ~payload_producer
  | Single (Activate_account {id = pkh; activation_code}) ->
      let blinded_pkh =
        Blinded_public_key_hash.of_ed25519_pkh activation_code pkh
      in
      let src = `Collected_commitments blinded_pkh in
      Token.allocated ctxt src >>=? fun (ctxt, src_exists) ->
      fail_unless src_exists (Invalid_activation {pkh}) >>=? fun () ->
      let contract = Contract.implicit_contract (Signature.Ed25519 pkh) in
      Token.balance ctxt src >>=? fun (ctxt, amount) ->
      Token.transfer ctxt src (`Contract contract) amount
      >>=? fun (ctxt, bupds) ->
      return (ctxt, Single_result (Activate_account_result bupds))
  | Single (Proposals {source; period; proposals}) ->
      Delegate.pubkey ctxt source >>=? fun delegate ->
      Operation.check_signature delegate chain_id operation >>?= fun () ->
      Voting_period.get_current ctxt >>=? fun {index = current_period; _} ->
      error_unless
        Compare.Int32.(current_period = period)
        (Wrong_voting_period {expected = current_period; provided = period})
      >>?= fun () ->
      Amendment.record_proposals ctxt source proposals >|=? fun ctxt ->
      (ctxt, Single_result Proposals_result)
  | Single (Ballot {source; period; proposal; ballot}) ->
      Delegate.pubkey ctxt source >>=? fun delegate ->
      Operation.check_signature delegate chain_id operation >>?= fun () ->
      Voting_period.get_current ctxt >>=? fun {index = current_period; _} ->
      error_unless
        Compare.Int32.(current_period = period)
        (Wrong_voting_period {expected = current_period; provided = period})
      >>?= fun () ->
      Amendment.record_ballot ctxt source proposal ballot >|=? fun ctxt ->
      (ctxt, Single_result Ballot_result)
  | Single (Failing_noop _) ->
      (* Failing_noop _ always fails *)
      fail Failing_noop_error
  | Single (Manager_operation _) as op ->
      (* Use the initial context, the contract may be deleted by the
         fee transfer in [precheck_manager_contents] *)
      find_manager_public_key ctxt op >>=? fun public_key ->
      precheck_manager_contents_list ctxt op ~mempool_mode
      >>=? fun (ctxt, prechecked_contents_list) ->
      Operation.check_signature public_key chain_id operation >>?= fun () ->
      apply_manager_contents_list
        ctxt
        mode
        ~payload_producer
        chain_id
        prechecked_contents_list
      >|= ok
  | Cons (Manager_operation _, _) as op ->
      (* Use the initial context, the contract may be deleted by the
         fee transfer in [precheck_manager_contents] *)
      find_manager_public_key ctxt op >>=? fun public_key ->
      precheck_manager_contents_list ctxt op ~mempool_mode
      >>=? fun (ctxt, prechecked_contents_list) ->
      Operation.check_signature public_key chain_id operation >>?= fun () ->
      apply_manager_contents_list
        ctxt
        mode
        ~payload_producer
        chain_id
        prechecked_contents_list
      >|= ok

let apply_operation ctxt chain_id (apply_mode : apply_mode) mode
    ~payload_producer hash operation =
  let ctxt = Origination_nonce.init ctxt hash in
  let ctxt = record_operation ctxt operation in
  apply_contents_list
    ctxt
    chain_id
    apply_mode
    mode
    ~payload_producer
    operation
    operation.protocol_data.contents
  >|=? fun (ctxt, result) ->
  let ctxt = Gas.set_unlimited ctxt in
  let ctxt = Origination_nonce.unset ctxt in
  (ctxt, {contents = result})

let may_start_new_cycle ctxt =
  match Level.dawn_of_a_new_cycle ctxt with
  | None -> return (ctxt, [], [])
  | Some last_cycle ->
      Seed.cycle_end ctxt last_cycle >>=? fun (ctxt, unrevealed) ->
      Delegate.cycle_end ctxt last_cycle unrevealed
      >>=? fun (ctxt, balance_updates, deactivated) ->
      Bootstrap.cycle_end ctxt last_cycle >|=? fun ctxt ->
      (ctxt, balance_updates, deactivated)

let init_allowed_consensus_operations ctxt ~endorsement_level
    ~preendorsement_level =
  Delegate.prepare_stake_distribution ctxt >>=? fun ctxt ->
  (if Level.(endorsement_level = preendorsement_level) then
   Baking.endorsing_rights_by_first_slot ctxt endorsement_level
   >>=? fun (ctxt, slots) ->
   let consensus_operations = slots in
   return (ctxt, consensus_operations, consensus_operations)
  else
    Baking.endorsing_rights_by_first_slot ctxt endorsement_level
    >>=? fun (ctxt, endorsements_slots) ->
    let endorsements = endorsements_slots in
    Baking.endorsing_rights_by_first_slot ctxt preendorsement_level
    >>=? fun (ctxt, preendorsements_slots) ->
    let preendorsements = preendorsements_slots in
    return (ctxt, endorsements, preendorsements))
  >>=? fun (ctxt, allowed_endorsements, allowed_preendorsements) ->
  return
    (Consensus.initialize_consensus_operation
       ctxt
       ~allowed_endorsements
       ~allowed_preendorsements)

let apply_liquidity_baking_subsidy ctxt ~toggle_vote =
  Liquidity_baking.on_subsidy_allowed
    ctxt
    ~toggle_vote
    (fun ctxt liquidity_baking_cpmm_contract ->
      let ctxt =
        (* We set a gas limit of 1/20th the block limit, which is ~10x
           actual usage here in Granada. Gas consumed is reported in
           the Transaction receipt, but not counted towards the block
           limit. The gas limit is reset to unlimited at the end of
           this function.*)
        Gas.set_limit
          ctxt
          (Gas.Arith.integral_exn
             (Z.div
                (Gas.Arith.integral_to_z
                   (Constants.hard_gas_limit_per_block ctxt))
                (Z.of_int 20)))
      in
      let backtracking_ctxt = ctxt in
      (let liquidity_baking_subsidy = Constants.liquidity_baking_subsidy ctxt in
       (* credit liquidity baking subsidy to CPMM contract *)
       Token.transfer
         ~origin:Subsidy
         ctxt
         `Liquidity_baking_subsidies
         (`Contract liquidity_baking_cpmm_contract)
         liquidity_baking_subsidy
       >>=? fun (ctxt, balance_updates) ->
       Script_cache.find ctxt liquidity_baking_cpmm_contract
       >>=? fun (ctxt, cache_key, script) ->
       match script with
       | None -> fail (Script_tc_errors.No_such_entrypoint Entrypoint.default)
       | Some (script, script_ir) -> (
           (* Token.transfer which is being called above already loads this
              value into the Irmin cache, so no need to burn gas for it. *)
           Contract.get_balance ctxt liquidity_baking_cpmm_contract
           >>=? fun balance ->
           let now = Script_timestamp.now ctxt in
           let level =
             (Level.current ctxt).level |> Raw_level.to_int32
             |> Script_int.of_int32 |> Script_int.abs
           in
           let step_constants =
             let open Script_interpreter in
             (* Using dummy values for source, payer, and chain_id
                since they are not used within the CPMM default
                entrypoint. *)
             {
               source = liquidity_baking_cpmm_contract;
               payer = liquidity_baking_cpmm_contract;
               self = liquidity_baking_cpmm_contract;
               amount = liquidity_baking_subsidy;
               balance;
               chain_id = Chain_id.zero;
               now;
               level;
             }
           in
           let parameter =
             Micheline.strip_locations
               Michelson_v1_primitives.(Prim (0, D_Unit, [], []))
           in
           (*
                 Call CPPM default entrypoint with parameter Unit.
                 This is necessary for the CPMM's xtz_pool in storage to
                 increase since it cannot use BALANCE due to a transfer attack.

                 Mimicks a transaction.

                 There is no:
                 - storage burn (extra storage is free)
                 - fees (the operation is mandatory)
          *)
           Script_interpreter.execute
             ctxt
             Optimized
             step_constants
             ~script
             ~parameter
             ~cached_script:(Some script_ir)
             ~entrypoint:Entrypoint.default
             ~internal:false
           >>=? fun ( {
                        script = updated_cached_script;
                        code_size = updated_size;
                        storage;
                        lazy_storage_diff;
                        operations;
                        ticket_diffs;
                      },
                      ctxt ) ->
           match operations with
           | _ :: _ ->
               (* No internal operations are expected here. Something bad may be happening. *)
               return (backtracking_ctxt, [])
           | [] ->
               (* update CPMM storage *)
               update_script_storage_and_ticket_balances
                 ctxt
                 ~self:liquidity_baking_cpmm_contract
                 storage
                 lazy_storage_diff
                 ticket_diffs
                 operations
               >>=? fun (ticket_table_size_diff, ctxt) ->
               Fees.record_paid_storage_space
                 ctxt
                 liquidity_baking_cpmm_contract
               >>=? fun (ctxt, new_size, paid_storage_size_diff) ->
               Ticket_balance.adjust_storage_space
                 ctxt
                 ~storage_diff:ticket_table_size_diff
               >>=? fun (ticket_paid_storage_diff, ctxt) ->
               let consumed_gas =
                 Gas.consumed ~since:backtracking_ctxt ~until:ctxt
               in
               Script_cache.update
                 ctxt
                 cache_key
                 ( {script with storage = Script.lazy_expr storage},
                   updated_cached_script )
                 updated_size
               >>?= fun ctxt ->
               let result =
                 Transaction_result
                   (Transaction_to_contract_result
                      {
                        storage = Some storage;
                        lazy_storage_diff;
                        balance_updates;
                        (* At this point in application the
                           origination nonce has not been initialized
                           so it's not possible to originate new
                           contracts. We've checked above that none
                           were originated. *)
                        originated_contracts = [];
                        consumed_gas;
                        storage_size = new_size;
                        paid_storage_size_diff =
                          Z.add paid_storage_size_diff ticket_paid_storage_diff;
                        allocated_destination_contract = false;
                      })
               in
               let ctxt = Gas.set_unlimited ctxt in
               return (ctxt, [Successful_manager_result result])))
      >|= function
      | Ok (ctxt, results) -> Ok (ctxt, results)
      | Error _ ->
          (* Do not fail if something bad happens during CPMM contract call. *)
          let ctxt = Gas.set_unlimited backtracking_ctxt in
          Ok (ctxt, []))

type 'a full_construction = {
  ctxt : t;
  protocol_data : 'a;
  payload_producer : Signature.public_key_hash;
  block_producer : Signature.public_key_hash;
  round : Round.t;
  implicit_operations_results : packed_successful_manager_operation_result list;
  liquidity_baking_toggle_ema : Liquidity_baking.Toggle_EMA.t;
}

let begin_full_construction ctxt ~predecessor_timestamp ~predecessor_level
    ~predecessor_round ~round protocol_data =
  let round_durations = Constants.round_durations ctxt in
  let timestamp = Timestamp.current ctxt in
  Block_header.check_timestamp
    round_durations
    ~timestamp
    ~round
    ~predecessor_timestamp
    ~predecessor_round
  >>?= fun () ->
  let current_level = Level.current ctxt in
  Stake_distribution.baking_rights_owner ctxt current_level ~round
  >>=? fun (ctxt, _slot, (_block_producer_pk, block_producer)) ->
  Delegate.frozen_deposits ctxt block_producer >>=? fun frozen_deposits ->
  fail_unless
    Tez.(frozen_deposits.current_amount > zero)
    (Zero_frozen_deposits block_producer)
  >>=? fun () ->
  Stake_distribution.baking_rights_owner
    ctxt
    current_level
    ~round:protocol_data.Block_header.payload_round
  >>=? fun (ctxt, _slot, (_payload_producer_pk, payload_producer)) ->
  init_allowed_consensus_operations
    ctxt
    ~endorsement_level:predecessor_level
    ~preendorsement_level:current_level
  >>=? fun ctxt ->
  let toggle_vote = protocol_data.liquidity_baking_toggle_vote in
  apply_liquidity_baking_subsidy ctxt ~toggle_vote
  >|=? fun ( ctxt,
             liquidity_baking_operations_results,
             liquidity_baking_toggle_ema ) ->
  {
    ctxt;
    protocol_data;
    payload_producer;
    block_producer;
    round;
    implicit_operations_results = liquidity_baking_operations_results;
    liquidity_baking_toggle_ema;
  }

let begin_partial_construction ctxt ~predecessor_level ~toggle_vote =
  (* In the mempool, only consensus operations for [predecessor_level]
     (that is, head's level) are allowed, contrary to block validation
     where endorsements are for the previous level and
     preendorsements, if any, for the block's level. *)
  init_allowed_consensus_operations
    ctxt
    ~endorsement_level:predecessor_level
    ~preendorsement_level:predecessor_level
  >>=? fun ctxt -> apply_liquidity_baking_subsidy ctxt ~toggle_vote

let begin_application ctxt chain_id (block_header : Block_header.t) fitness
    ~predecessor_timestamp ~predecessor_level ~predecessor_round =
  let round = Fitness.round fitness in
  let current_level = Level.current ctxt in
  Stake_distribution.baking_rights_owner ctxt current_level ~round
  >>=? fun (ctxt, _slot, (block_producer_pk, block_producer)) ->
  let timestamp = block_header.shell.timestamp in
  Block_header.begin_validate_block_header
    ~block_header
    ~chain_id
    ~predecessor_timestamp
    ~predecessor_round
    ~fitness
    ~timestamp
    ~delegate_pk:block_producer_pk
    ~round_durations:(Constants.round_durations ctxt)
    ~proof_of_work_threshold:(Constants.proof_of_work_threshold ctxt)
    ~expected_commitment:current_level.expected_commitment
  >>?= fun () ->
  Delegate.frozen_deposits ctxt block_producer >>=? fun frozen_deposits ->
  fail_unless
    Tez.(frozen_deposits.current_amount > zero)
    (Zero_frozen_deposits block_producer)
  >>=? fun () ->
  Stake_distribution.baking_rights_owner
    ctxt
    current_level
    ~round:block_header.protocol_data.contents.payload_round
  >>=? fun (ctxt, _slot, (payload_producer_pk, _payload_producer)) ->
  init_allowed_consensus_operations
    ctxt
    ~endorsement_level:predecessor_level
    ~preendorsement_level:current_level
  >>=? fun ctxt ->
  let toggle_vote =
    block_header.Block_header.protocol_data.contents
      .liquidity_baking_toggle_vote
  in
  apply_liquidity_baking_subsidy ctxt ~toggle_vote
  >|=? fun ( ctxt,
             liquidity_baking_operations_results,
             liquidity_baking_toggle_ema ) ->
  ( ctxt,
    payload_producer_pk,
    block_producer,
    liquidity_baking_operations_results,
    liquidity_baking_toggle_ema )

type finalize_application_mode =
  | Finalize_full_construction of {
      level : Raw_level.t;
      predecessor_round : Round.t;
    }
  | Finalize_application of Fitness.t

let compute_payload_hash (ctxt : context) ~(predecessor : Block_hash.t)
    ~(payload_round : Round.t) : Block_payload_hash.t =
  let non_consensus_operations = non_consensus_operations ctxt in
  let operations_hash = Operation_list_hash.compute non_consensus_operations in
  Block_payload.hash ~predecessor payload_round operations_hash

let are_endorsements_required ctxt ~level =
  First_level_of_protocol.get ctxt >|=? fun first_level ->
  (* NB: the first level is the level of the migration block. There
     are no endorsements for this block. Therefore the block at the
     next level cannot contain endorsements. *)
  let level_position_in_protocol = Raw_level.diff level first_level in
  Compare.Int32.(level_position_in_protocol > 1l)

let check_minimum_endorsements ~endorsing_power ~minimum =
  error_when
    Compare.Int.(endorsing_power < minimum)
    (Not_enough_endorsements {required = minimum; provided = endorsing_power})

let finalize_application_check_validity ctxt (mode : finalize_application_mode)
    protocol_data ~round ~predecessor ~endorsing_power ~consensus_threshold
    ~required_endorsements =
  (if required_endorsements then
   check_minimum_endorsements ~endorsing_power ~minimum:consensus_threshold
  else Result.return_unit)
  >>?= fun () ->
  let block_payload_hash =
    compute_payload_hash
      ctxt
      ~predecessor
      ~payload_round:protocol_data.Block_header.payload_round
  in
  let locked_round_evidence =
    Option.map
      (fun (preendorsement_round, preendorsement_count) ->
        Block_header.{preendorsement_round; preendorsement_count})
      (Consensus.locked_round_evidence ctxt)
  in
  (match mode with
  | Finalize_application fitness -> ok fitness
  | Finalize_full_construction {level; predecessor_round} ->
      let locked_round =
        match locked_round_evidence with
        | None -> None
        | Some {preendorsement_round; _} -> Some preendorsement_round
      in
      Fitness.create ~level ~round ~predecessor_round ~locked_round)
  >>?= fun fitness ->
  let checkable_payload_hash : Block_header.checkable_payload_hash =
    match mode with
    | Finalize_application _ -> Expected_payload_hash block_payload_hash
    | Finalize_full_construction _ -> (
        match locked_round_evidence with
        | Some _ -> Expected_payload_hash block_payload_hash
        | None ->
            (* In full construction, when there is no locked round
               evidence (and thus no preendorsements), the baker cannot
               know the payload hash before selecting the operations. We
               may dismiss checking the initially given
               payload_hash. However, to be valid, the baker must patch
               the resulting block header with the actual payload
               hash. *)
            No_check)
  in
  Block_header.finalize_validate_block_header
    ~block_header_contents:protocol_data
    ~round
    ~fitness
    ~checkable_payload_hash
    ~locked_round_evidence
    ~consensus_threshold
  >>?= fun () -> return (fitness, block_payload_hash)

let record_endorsing_participation ctxt =
  let validators = Consensus.allowed_endorsements ctxt in
  Slot.Map.fold_es
    (fun initial_slot (_delegate_pk, delegate, power) ctxt ->
      let participation =
        if Slot.Set.mem initial_slot (Consensus.endorsements_seen ctxt) then
          Delegate.Participated
        else Delegate.Didn't_participate
      in
      Delegate.record_endorsing_participation
        ctxt
        ~delegate
        ~participation
        ~endorsing_power:power)
    validators
    ctxt

let finalize_application ctxt (mode : finalize_application_mode) protocol_data
    ~payload_producer ~block_producer liquidity_baking_toggle_ema
    implicit_operations_results ~round ~predecessor ~migration_balance_updates =
  (* Then we finalize the consensus. *)
  let level = Level.current ctxt in
  let block_endorsing_power = Consensus.current_endorsement_power ctxt in
  let consensus_threshold = Constants.consensus_threshold ctxt in
  are_endorsements_required ctxt ~level:level.level
  >>=? fun required_endorsements ->
  finalize_application_check_validity
    ctxt
    mode
    protocol_data
    ~round
    ~predecessor
    ~endorsing_power:block_endorsing_power
    ~consensus_threshold
    ~required_endorsements
  >>=? fun (fitness, block_payload_hash) ->
  (* from this point nothing should fail *)
  (* We mark the endorsement branch as the grand parent branch when
     accessible. This will not be present before the first two blocks
     of tenderbake. *)
  (match Consensus.endorsement_branch ctxt with
  | Some predecessor_branch ->
      Consensus.store_grand_parent_branch ctxt predecessor_branch >>= return
  | None -> return ctxt)
  >>=? fun ctxt ->
  (* We mark the current payload hash as the predecessor one => this
     will only be accessed by the successor block now. *)
  Consensus.store_endorsement_branch ctxt (predecessor, block_payload_hash)
  >>= fun ctxt ->
  Round.update ctxt round >>=? fun ctxt ->
  (* end of level  *)
  (match protocol_data.Block_header.seed_nonce_hash with
  | None -> return ctxt
  | Some nonce_hash ->
      Nonce.record_hash ctxt {nonce_hash; delegate = block_producer})
  >>=? fun ctxt ->
  (if required_endorsements then
   record_endorsing_participation ctxt >>=? fun ctxt ->
   Baking.bonus_baking_reward ctxt ~endorsing_power:block_endorsing_power
   >>?= fun rewards_bonus -> return (ctxt, Some rewards_bonus)
  else return (ctxt, None))
  >>=? fun (ctxt, reward_bonus) ->
  let baking_reward = Constants.baking_reward_fixed_portion ctxt in
  Delegate.record_baking_activity_and_pay_rewards_and_fees
    ctxt
    ~payload_producer
    ~block_producer
    ~baking_reward
    ~reward_bonus
  >>=? fun (ctxt, baking_receipts) ->
  (* end of cycle *)
  (if Level.may_snapshot_rolls ctxt then Stake_distribution.snapshot ctxt
  else return ctxt)
  >>=? fun ctxt ->
  may_start_new_cycle ctxt
  >>=? fun (ctxt, cycle_end_balance_updates, deactivated) ->
  Amendment.may_start_new_voting_period ctxt >>=? fun ctxt ->
  let balance_updates =
    migration_balance_updates @ baking_receipts @ cycle_end_balance_updates
  in
  let consumed_gas =
    Gas.Arith.sub
      (Gas.Arith.fp @@ Constants.hard_gas_limit_per_block ctxt)
      (Gas.block_level ctxt)
  in
  Voting_period.get_rpc_current_info ctxt >|=? fun voting_period_info ->
  let receipt =
    Apply_results.
      {
        proposer = payload_producer;
        baker = block_producer;
        level_info = level;
        voting_period_info;
        nonce_hash = protocol_data.seed_nonce_hash;
        consumed_gas;
        deactivated;
        balance_updates;
        liquidity_baking_toggle_ema;
        implicit_operations_results;
      }
  in
  (ctxt, fitness, receipt)

let value_of_key ctxt k = Cache.Admin.value_of_key ctxt k
OCaml

Innovation. Community. Security.